SPB Git

Repository Public

AlertsText.swift 9.9 KB 149 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/AlertsText.swift3// Description: French labels of the alerts centre: severities, the catalogue's groups, the subjects an alert can be about, delivery states and parameter names. The sentence of an alert always comes from the Core's catalogue (the backend's own templates); nothing here rewrites its meaning.4import SwiftUI5import SPWalletCore67enum AlertsText {8    static func severity(_ s: AlertSeverity) -> String {9        switch s { case .info: "Information"; case .warning: "Avertissement"; case .critical: "Critique"; case .unknown(let r): "Gravité « \(r) »" }10    }11    static func color(_ s: AlertSeverity) -> Color {12        switch s { case .info: .blue; case .warning, .unknown: Theme.warning; case .critical: Theme.negative }13    }14    static func symbol(_ s: AlertSeverity) -> String {15        switch s { case .info: "info.circle.fill"; case .warning, .unknown: "exclamationmark.triangle.fill"; case .critical: "exclamationmark.octagon.fill" }16    }17    static func group(_ g: AlertGroup) -> String {18        switch g {19        case .transfers: "Transactions"; case .agents: "Agents"; case .derivatives: "Dérivés"; case .security: "Sécurité"; case .system: "Système"20        case .unknown(let r): r21        }22    }23    static func delivery(_ d: AlertDelivery) -> String {24        switch d {25        case .pending: "Pas encore examinée par le serveur pour la notification"26        case .inApp: "Dans l’app seulement (aucun appareil ni webhook configuré sur le serveur)"27        case .stale: "Non notifiée : datait de plus d’une heure quand le serveur l’a examinée"28        case .quiet: "Retenue par les heures calmes"29        case .capped: "Retenue par le plafond horaire"30        case .sent: "Remise aux canaux du serveur (push web, webhook)"31        case .unknown(let r): r32        }33    }34    static func subject(_ s: AlertSubject) -> String {35        let what: String36        switch s.type {37        case "proposal": what = "Opération"; case "agent": what = "Agent"; case "account": what = "Compte de dérivés"; case "network": what = "Réseau"38        case "deposit": what = "Dépôt"; case "plan": what = "Plan"; case "none": return "—"39        default: what = s.type40        }41        return [what, s.id, s.network.map { "réseau \($0)" }].compactMap { $0 }.joined(separator: " · ")42    }43    /// Where the same alert opens in the app (the Core ports the backend's `alertPath`).44    static func destination(_ path: String) -> String {45        if path.hasPrefix("/agents") { return "Agents de trading" }46        if path.hasPrefix("/plan") { return "Échange (plans)" }47        if path.hasPrefix("/futures") { return "Dérivés (comptes)" }48        if path.hasPrefix("/activity") { return "Activité" }49        if path.hasPrefix("/security") { return "Sécurité" }50        if path.hasPrefix("/monitor") { return "Supervision (cet écran)" }51        return "Alertes"52    }5354    private static let params: [String: String] = [55        "agent": "Agent", "account": "Compte", "network": "Réseau", "to": "Vers", "from": "De", "what": "Objet", "mode": "Mode", "scope": "Portée", "count": "Occurrences",56        "minutes": "Minutes", "hours": "Heures", "seconds": "Secondes", "bars": "Barres", "interval": "Intervalle", "instrument": "Instrument", "name": "Nom", "loop": "Boucle",57        "pct": "Pourcentage", "positions": "Positions", "state": "État", "reason": "Motif", "amount": "Montant", "symbol": "Actif", "toSymbol": "Actif reçu", "size": "Taille",58        "price": "Prix", "side": "Sens", "steps": "Étapes", "step": "Étape", "ip": "Adresse IP", "seq": "Séquence", "pnl": "Résultat", "label": "Libellé", "device": "Appareil",59        "detail": "Détail", "clientId": "Identifiant client",60    ]61    static func param(_ key: String) -> String { params[key] ?? key }62    /// A parameter as served. `@word` values are vocabulary codes of the backend: the sentence above shows their translation; here the code is shown without its marker.63    static func value(_ v: JSONValue) -> String {64        if case .string(let s) = v { return s.hasPrefix("@") ? String(s.dropFirst()) : (s.isEmpty ? "—" : s) }65        return v.displayText66    }6768    /// Title and body in French. A kind this version does not know is shown as its raw code, with nothing guessed.69    static func sentence(_ a: WalletAlert, detail: Bool = true) -> (title: String, body: String) {70        guard AlertCatalog.definition(a.kind) != nil else { return ("Alerte de type « \(a.kind.rawValue) »", "") }71        return a.text(locale: .fr, detail: detail)72    }73}7475/// What an alert is about, finer than the catalogue's five groups. Derived from the catalogue's kinds only; two subjects76/// (insufficient balance, high fees) have no kind of their own on the server and are recognised from the reason it returned.77enum AlertsTheme: String, CaseIterable, Identifiable {78    case transactions, positions, orders, errors, insufficientBalance, highFees, rpc, signerFailure, limitExceeded, liquidation, agentState, signerState, security, system79    var id: String { rawValue }8081    var label: String {82        switch self {83        case .transactions: "Transactions"; case .positions: "Positions"; case .orders: "Ordres"; case .errors: "Erreurs et échecs"84        case .insufficientBalance: "Solde insuffisant"; case .highFees: "Frais élevés"; case .rpc: "Panne RPC / connecteur"; case .signerFailure: "Panne du signataire"85        case .limitExceeded: "Limite dépassée"; case .liquidation: "Liquidation possible"; case .agentState: "État des agents"; case .signerState: "État du signataire"86        case .security: "Sécurité du compte"; case .system: "Système"87        }88    }89    var derivedFromReason: Bool { self == .insufficientBalance || self == .highFees }9091    static func of(_ a: WalletAlert) -> Set<AlertsTheme> {92        var out: Set<AlertsTheme> = []93        switch a.kind {94        case .transferConfirmed, .swapConfirmed, .bridgeConfirmed, .transferStuck, .depositReceived, .planStepReady, .planPaused, .planDone: out = [.transactions]95        case .transferFailed, .swapFailed, .bridgeFailed: out = [.transactions, .errors]96        case .agentOrderFilled: out = [.orders, .agentState]97        case .derivPaperFilled, .derivLiveFilled: out = [.orders]98        case .derivOrderRejected, .derivOrderUnknown: out = [.orders, .errors]99        case .derivPositionOpened, .derivPositionClosed, .derivFunding, .derivDivergence, .derivDivergenceCleared: out = [.positions]100        case .derivMarginWarning, .derivPaperLiquidation, .derivLiveLiquidation: out = [.liquidation, .positions]101        case .derivLossLimit, .derivHalt: out = [.limitExceeded]102        case .agentStoppedLoss, .agentStoppedMandate, .agentMmBreaker, .agentMmRateBudget: out = [.limitExceeded, .agentState]103        case .agentStopped, .agentMmHalted, .agentMmDeadManSwitch, .agentMmSessionEnded, .agentMandateRevoked, .mandateExpiring, .agentResearchSubmitted: out = [.agentState]104        case .agentMmSignerRefusals: out = [.agentState, .signerFailure]105        case .agentDataStale: out = [.agentState, .rpc]106        case .agentSignalFailures, .agentResearchFailed: out = [.agentState, .errors]107        case .derivAssetTableMismatch: out = [.errors]108        case .securitySignerUnreachable, .securityPinMismatch: out = [.signerFailure, .signerState]109        case .securitySignerRefused: out = [.signerFailure]110        case .securitySignerBack, .securitySignerHalted, .securitySignerUnhalted: out = [.signerState]111        case .securityPasskeyAdded, .securityNewDevice, .securityLoginFailed, .securityKillSwitchOn, .securityKillSwitchOff, .securityAuditBroken, .securityPolicyChanged: out = [.security]112        case .connDown, .connUp: out = [.rpc]113        case .systemWorkerFailing: out = [.system, .errors]114        case .systemApiRestarted, .systemBackupMissing, .systemDiskLow, .systemLabSandboxUnavailable, .systemLabSandboxBack, .systemLabSandboxOff, .systemAlertsCapped, .systemTest: out = [.system]115        case .unknown: out = []116        }117        // no dedicated kind on the server: read from the reason text it returned with a failure or a refusal118        if out.contains(.errors) || out.contains(.signerFailure) {119            let reason = ["reason", "detail"].compactMap { a.params[$0]?.stringValue?.lowercased() }.joined(separator: " ")120            if ["insufficient", "not enough", "balance", "solde", "funds"].contains(where: reason.contains) { out.insert(.insufficientBalance) }121            if ["fee", "gas", "frais"].contains(where: reason.contains) { out.insert(.highFees) }122            if ["limit", "limite", "cap ", "ceiling", "plafond"].contains(where: reason.contains) { out.insert(.limitExceeded) }123        }124        return out125    }126}127128/// The owner's choice of which new alerts raise a macOS notification (this Mac only; the server's own switches are in Réglages).129enum AlertsNotifyLevel: String, CaseIterable, Identifiable {130    case off, critical, warning, info131    var id: String { rawValue }132    var label: String {133        switch self { case .off: "Aucune"; case .critical: "Critiques seulement"; case .warning: "Avertissements et critiques"; case .info: "Toutes (information comprise)" }134    }135    func allows(_ s: AlertSeverity) -> Bool {136        switch self { case .off: false; case .critical: s >= .critical; case .warning: s >= .warning; case .info: true }137    }138    private static let key = "alertsNotifyLevel", detailKey = "alertsNotifyDetails"139    static var stored: AlertsNotifyLevel {140        get { UserDefaults.standard.string(forKey: key).flatMap(AlertsNotifyLevel.init(rawValue:)) ?? .warning }141        set { UserDefaults.standard.set(newValue.rawValue, forKey: key) }142    }143    /// Amounts, prices and reasons in the notification text. Off by default, as on the server: a notification can be read on a locked screen.144    static var showDetails: Bool {145        get { UserDefaults.standard.bool(forKey: detailKey) }146        set { UserDefaults.standard.set(newValue, forKey: detailKey) }147    }148}149
Files main
Menu

Theme