Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/TradingAgents/TradingAPIPanels.swift10// Description : The webhooks of the trading API (list, creation to an11// https address only, enabling, signing-secret rotation,12// deletion, deliveries with their real state) and the usage13// panel (calls per key, rate limits, state of the API and of14// its services, server capabilities). A delivery is15// "delivered" only when the server says so.16// Module : Features17// Repository : https://git.spboucher.ai/sp-wallet-macos18// Created : 2026-11-1819// Last Modified : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import SPWalletCore9596struct WebhooksView: View {97 let model: AppModel98 let store: TradingAPIStore99 @State private var url = ""100 @State private var label = ""101 @State private var events: Set<String> = []102 @State private var confirmDelete: Webhook?103 @State private var confirmRotate: Webhook?104105 private var urlProblem: String? {106 let t = url.trimmingCharacters(in: .whitespaces)107 guard !t.isEmpty else { return "Entrez l’adresse du récepteur." }108 guard let u = URL(string: t), u.scheme == "https", u.host?.isEmpty == false else { return "Adresse https complète requise (les adresses non chiffrées sont refusées)." }109 if events.isEmpty { return "Choisissez au moins un événement." }110 return nil111 }112113 var body: some View {114 Card("Webhooks") {115 if let w = store.webhooks {116 if w.webhooks.isEmpty { Text("Aucun webhook.").foregroundStyle(.secondary) }117 ForEach(w.webhooks) { h in118 VStack(alignment: .leading, spacing: 4) {119 HStack(spacing: 8) {120 Image(systemName: h.enabled ? "circle.fill" : "circle").font(.caption2).foregroundStyle(h.enabled ? Theme.positive : .secondary)121 Text(h.label?.isEmpty == false ? h.label! : "Webhook").fontWeight(.medium)122 Text(h.enabled ? "activé" : "désactivé").font(.caption).foregroundStyle(.secondary)123 Spacer()124 Button(h.enabled ? "Désactiver" : "Activer") { Task { await store.setWebhook(h, enabled: !h.enabled) } }125 Button("Nouveau secret…") { confirmRotate = h }126 Button("Supprimer", role: .destructive) { confirmDelete = h }127 }.disabled(!model.canOperate || store.busy != nil)128 Text(h.url).font(Theme.monoSmall).textSelection(.enabled)129 Text("Événements : \(h.events.joined(separator: ", "))").font(.caption).foregroundStyle(.secondary)130 Text("Créé \(Fmt.date(AgentText.ms(h.createdAt))) · dernière livraison réussie : \(h.lastOkAt.map { Fmt.relative(AgentText.ms($0)) } ?? "aucune")\(h.failures.map { $0 > 0 ? " · \($0) échec(s)" : "" } ?? "")\(h.hasSecret == false ? " · SANS secret de signature" : "")").font(.caption).foregroundStyle(.secondary)131 if let e = h.lastError { Text("Dernière erreur : \(e)").font(.caption).foregroundStyle(Theme.warning).textSelection(.enabled) }132 }133 Divider()134 }135 if let s = w.signature { Text("Signature des livraisons : \(s)").font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }136 if let r = w.retry { Text("Nouvelles tentatives : \(r.attempts) au plus, après \(r.backoffSec.map { "\(Int($0)) s" }.joined(separator: ", ")).").font(.caption).foregroundStyle(.secondary) }137 } else { Unavailable(what: "Webhooks", error: store.errors["webhooks"]) }138 }139 .confirmationDialog("Supprimer ce webhook ?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }), titleVisibility: .visible, presenting: confirmDelete) { h in140 Button("Supprimer", role: .destructive) { Task { await store.deleteWebhook(h) } }141 Button("Annuler", role: .cancel) {}142 } message: { h in Text("Plus aucun événement ne sera envoyé à \(h.url).") }143 .confirmationDialog("Générer un nouveau secret de signature ?", isPresented: Binding(get: { confirmRotate != nil }, set: { if !$0 { confirmRotate = nil } }), titleVisibility: .visible, presenting: confirmRotate) { h in144 Button("Générer un nouveau secret") { Task { await store.rotateWebhookSecret(h) } }145 Button("Annuler", role: .cancel) {}146 } message: { _ in Text("L’ancien secret cesse immédiatement de vérifier les livraisons. Le nouveau ne sera affiché qu’une seule fois.") }147148 if let w = store.webhooks {149 Card("Nouveau webhook") {150 Form {151 TextField("Adresse du récepteur (https)", text: $url, prompt: Text("https://exemple.org/webhook"))152 TextField("Libellé", text: $label)153 }.formStyle(.grouped).scrollDisabled(true)154 Text("Événements").font(.callout.weight(.medium))155 ForEach(w.events, id: \.event) { e in156 Toggle(isOn: Binding(get: { events.contains(e.event) }, set: { if $0 { events.insert(e.event) } else { events.remove(e.event) } })) {157 VStack(alignment: .leading, spacing: 1) {158 Text(e.event + (e.emitted ? "" : " — pas encore émis par ce serveur")).font(Theme.monoSmall).foregroundStyle(e.emitted ? Color.primary : Color.secondary)159 Text(e.description).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)160 }161 }.toggleStyle(.checkbox)162 }163 HStack {164 if let p = urlProblem, !url.isEmpty || !events.isEmpty { Text(p).font(.callout).foregroundStyle(.secondary) }165 Spacer()166 Button("Créer le webhook") { Task { if await store.createWebhook(url: url.trimmingCharacters(in: .whitespaces), events: events.sorted(), label: label.trimmingCharacters(in: .whitespaces)) { url = ""; label = ""; events = [] } } }167 .buttonStyle(.borderedProminent).disabled(urlProblem != nil || !model.canOperate || store.busy != nil)168 }169 Text("Un webhook n’envoie que des notifications : il ne donne aucune autorité. Son secret de signature sera affiché une seule fois à la création.").font(.caption).foregroundStyle(.secondary)170 }171 Card("Livraisons récentes") {172 if w.deliveries.isEmpty { Text("Aucune livraison.").foregroundStyle(.secondary) }173 else {174 Table(w.deliveries) {175 TableColumn("Créée") { x in Text(Fmt.dateSeconds(AgentText.ms(x.createdAt))).monospacedDigit() }.width(150)176 TableColumn("Événement") { x in Text(x.event).font(Theme.monoSmall) }.width(170)177 TableColumn("État") { x in Text(x.state == "delivered" ? "livrée" : x.state == "failed" ? "échouée" : x.state == "pending" ? "en attente" : x.state).foregroundStyle(x.state == "delivered" ? Theme.positive : x.state == "failed" ? Theme.negative : Theme.warning) }.width(90)178 TableColumn("Tentatives") { x in Text(x.attempts.map(String.init) ?? "—") }.width(70)179 TableColumn("HTTP") { x in Text(x.lastStatus.map(String.init) ?? "—") }.width(50)180 TableColumn("Détail") { x in Text(x.lastError ?? (x.deliveredAt.map { "livrée \(Fmt.dateSeconds(AgentText.ms($0)))" } ?? (x.nextAttemptAt.map { "prochaine tentative \(Fmt.relative(AgentText.ms($0)))" } ?? ""))).lineLimit(1).help(x.lastError ?? "") }181 }.frame(height: min(CGFloat(w.deliveries.count) * 28 + 34, 340))182 }183 }184 }185 }186}187188struct APIUsageView: View {189 let store: TradingAPIStore190191 var body: some View {192 Card("État de l’API") {193 if let s = store.status {194 Field(label: "Version", value: "\(s.api.version) · préfixe \(s.api.prefix)")195 Field(label: "Opérations", value: "\(s.api.implemented) implémentées sur \(s.api.operations)\(s.api.notImplemented.isEmpty ? "" : " — non implémentées : \(s.api.notImplemented.joined(separator: ", "))")")196 if let k = s.keys { Field(label: "Clés", value: "\(k.active) active(s) sur \(k.total)") }197 Field(label: "Limites de cadence", value: "\(s.rateLimits.defaultPerMin) requêtes/min par défaut · \(s.rateLimits.maxPerMin) au plus · \(s.rateLimits.failedAuthPerMinPerAddress) échecs d’authentification/min par adresse")198 Field(label: "En-têtes de cadence", value: s.rateLimits.headers.joined(separator: ", "), mono: true)199 Divider()200 ForEach(s.services) { x in201 HStack(alignment: .firstTextBaseline, spacing: 8) {202 Image(systemName: x.ok ? "checkmark.circle.fill" : "xmark.octagon.fill").foregroundStyle(x.ok ? Theme.positive : Theme.negative)203 Text(x.id).font(Theme.monoSmall).frame(width: 170, alignment: .leading)204 Text(x.detail + (x.lastOkAt.map { " · dernier succès \(Fmt.relative(AgentText.ms($0)))" } ?? "")).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)205 }206 }207 if let c = s.capabilities, !c.isEmpty {208 DisclosureGroup("Capacités et verrous du serveur (\(c.count))") { VStack(alignment: .leading, spacing: 6) { ForEach(c) { l in LockRow(name: l.id, open: l.on, reason: l.why) } }.padding(.top, 6) }209 }210 Text("État lu \(Fmt.relative(AgentText.ms(s.ts))).").font(.caption).foregroundStyle(.secondary)211 } else { Unavailable(what: "État", error: store.errors["status"]) }212 }213 Card("Utilisation par clé") {214 if let u = store.usage {215 if u.perKey.isEmpty { Text("Aucun appel enregistré.").foregroundStyle(.secondary) }216 ForEach(u.perKey, id: \.keyId) { k in217 HStack(alignment: .firstTextBaseline, spacing: 10) {218 Text(k.keyId).font(Theme.monoSmall).frame(width: 170, alignment: .leading).textSelection(.enabled)219 Text("\(k.calls24h) appel(s) en 24 h · \(k.errors24h) erreur(s) · \(k.rateLimited24h) refus de cadence · \(k.callsLastMinute) dans la dernière minute\(k.p95Ms.map { " · p95 \($0) ms" } ?? "") · dernier \(k.lastAt.map { Fmt.relative(AgentText.ms($0)) } ?? "—")").font(.callout).monospacedDigit().fixedSize(horizontal: false, vertical: true)220 }221 }222 Text("Sont enregistrés : méthode, modèle de route, statut et latence — jamais un corps, une requête ou un en-tête. Conservation : \(u.retentionDays) jour(s).").font(.caption).foregroundStyle(.secondary)223 if !u.items.isEmpty {224 Table(u.items) {225 TableColumn("Date") { x in Text(Fmt.dateSeconds(AgentText.ms(x.ts))).monospacedDigit() }.width(150)226 TableColumn("Clé") { x in Text(x.keyId).font(.caption) }.width(140)227 TableColumn("Appel") { x in Text("\(x.method) \(x.route)").font(Theme.monoSmall).lineLimit(1) }228 TableColumn("Statut") { x in Text(String(x.status)).foregroundStyle(x.status >= 400 ? Theme.negative : .primary) }.width(60)229 TableColumn("Latence") { x in Text(x.latencyMs.map { "\($0) ms" } ?? "—").monospacedDigit() }.width(80)230 }.frame(height: min(CGFloat(u.items.count) * 28 + 34, 380))231 }232 } else { Unavailable(what: "Utilisation", error: store.errors["usage"]) }233 }234 }235}236