Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Ops/AlertsModels.swift3// Description: Models of the alerts layer (services/api/src/alerts/routes.ts, store.ts; packages/core/src/alert-catalog.ts):4// the in-app alert rows, the owner's switches and thresholds, the outgoing webhook, the Web Push devices.5// An alert is a KIND and PARAMETERS — never a sentence: the sentence is rendered here, in the device's language,6// with the backend's own templates (AlertCatalog.swift, generated). The webhook secret is write-only: the server7// shows it once when it is generated and afterwards only reports that one exists.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213public enum AlertSeverity: Sendable, Hashable, Codable, Comparable {14 case info, warning, critical15 /** A severity added by a newer server: shown verbatim. */16 case unknown(String)1718 public var rawValue: String {19 switch self { case .info: "info"; case .warning: "warning"; case .critical: "critical"; case .unknown(let s): s }20 }21 public init(rawValue: String) {22 switch rawValue { case "info": self = .info; case "warning": self = .warning; case "critical": self = .critical; default: self = .unknown(rawValue) }23 }24 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }25 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }26 /** info < warning < critical; an unknown severity sorts with `warning` (never below what it could be hiding, never treated as critical). */27 private var rank: Int { switch self { case .info: 0; case .warning, .unknown: 1; case .critical: 2 } }28 public static func < (a: AlertSeverity, b: AlertSeverity) -> Bool { a.rank < b.rank }29}3031public enum AlertGroup: Sendable, Hashable, Codable, CaseIterable {32 case transfers, agents, derivatives, security, system33 case unknown(String)3435 public static let allCases: [AlertGroup] = [.transfers, .agents, .derivatives, .security, .system]36 public var rawValue: String {37 switch self {38 case .transfers: "transfers"; case .agents: "agents"; case .derivatives: "derivatives"; case .security: "security"; case .system: "system"39 case .unknown(let s): s40 }41 }42 public init(rawValue: String) { self = AlertGroup.allCases.first { $0.rawValue == rawValue } ?? .unknown(rawValue) }43 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }44 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }45}4647public enum AlertLocale: String, Sendable, Codable, CaseIterable { case fr, en }4849/** One entry of the catalogue (`AlertDef`). `title`, `body` and `priv` are `[fr, en]`. */50public struct AlertDefinition: Sendable, Hashable {51 public let kind: AlertKind52 public let group: AlertGroup53 /** The DEFAULT severity of the kind. A row carries its own (`WalletAlert.severity`), which is the one to show. */54 public let severity: AlertSeverity55 /** Default state of the owner's switch. */56 public let defaultOn: Bool57 /** Not switchable (the cap summary, the test notification, the kill switch). */58 public let fixed: Bool59 public let title: [String]60 public let body: [String]61 /** Lock-screen wording used when "show details" is off: names, networks and counts only. */62 public let priv: [String]?63}6465/** Rendering of alerts with the backend's templates (`renderAlert`, `safeParams`, `alertPath` of alert-catalog.ts). */66public enum AlertCatalog {67 public static func definition(_ kind: AlertKind) -> AlertDefinition? { byKind[kind] }68 private static let byKind: [AlertKind: AlertDefinition] = Dictionary(uniqueKeysWithValues: definitions.map { ($0.kind, $0) })6970 /** Only the parameters that may leave the server (or reach a lock screen) without "show details". */71 public static func safe(_ params: [String: JSONValue]) -> [String: JSONValue] {72 var out: [String: JSONValue] = [:]73 for k in safeParams { if let v = params[k] { out[k] = v } }74 return out75 }7677 /**78 Title and body of an alert in one language. `detail: false` gives the lock-screen wording (no amount, price, address or79 reason text). A kind this catalogue does not know renders as its raw kind and an empty body — exactly as the backend does;80 nothing is guessed.81 */82 public static func render(_ kind: AlertKind, params: [String: JSONValue], locale: AlertLocale, detail: Bool = true) -> (title: String, body: String) {83 guard let def = byKind[kind] else { return (kind.rawValue, "") }84 let i = locale == .fr ? 0 : 185 let template = detail ? def.body[i] : (def.priv?[i] ?? "")86 return (def.title[i], fill(template, detail ? params : safe(params), i))87 }8889 private static func word(_ v: JSONValue?, _ i: Int) -> String {90 let s: String91 switch v {92 case nil, .null?: return "—"93 case .string(let x)?: s = x94 case .int(let x)?: s = String(x)95 case .double(let x)?: s = x == x.rounded() && abs(x) < 1e15 ? String(Int64(x)) : String(x)96 case .bool(let x)?: s = x ? "true" : "false"97 case .array?, .object?: return "—" // AlertParams are scalars; anything else is not printable98 }99 if s.isEmpty { return "—" }100 guard s.hasPrefix("@") else { return s }101 let key = String(s.dropFirst())102 return vocabulary[key]?[i] ?? key103 }104105 private static func fill(_ template: String, _ p: [String: JSONValue], _ i: Int) -> String {106 var out = "", rest = Substring(template)107 while let open = rest.firstIndex(of: "{") {108 out += rest[..<open]109 let after = rest[rest.index(after: open)...]110 if let close = after.firstIndex(of: "}"), close > after.startIndex, after[..<close].allSatisfy({ $0.isASCII && $0.isLetter }) {111 out += word(p[String(after[..<close])], i)112 rest = after[after.index(after: close)...]113 } else { out += "{"; rest = after }114 }115 out += rest116 return out.split(whereSeparator: \.isWhitespace).joined(separator: " ")117 }118119 /**120 The web path the backend opens for an alert (`alertPath`). The native apps map it to their own navigation; it is ported so121 both clients land on the same screen for the same alert.122 */123 public static func path(kind: AlertKind, subject: AlertSubject?) -> String {124 if let s = subject {125 if s.type == "agent", let id = s.id, !id.isEmpty { return "/agents/\(id)" }126 if s.type == "plan", let id = s.id, !id.isEmpty { return "/plan/\(id)" }127 if s.type == "account" { return "/futures?v=accounts" }128 if s.type == "proposal" || s.type == "deposit" { return "/activity" }129 }130 switch byKind[kind]?.group {131 case .security?: return "/security"132 case .system?: return "/monitor"133 case .agents?: return "/agents"134 case .derivatives?: return "/futures?v=accounts"135 case .transfers?: return "/activity"136 default: return "/alerts"137 }138 }139}140141/** What an alert is about: `proposal`, `agent`, `account`, `network`, `deposit`, `plan` or `none` (kept as text: the server may add types). */142public struct AlertSubject: Codable, Sendable, Hashable {143 public let type: String144 public let id: String?145 public let network: String?146 public init(type: String, id: String? = nil, network: String? = nil) { self.type = type; self.id = id; self.network = network }147}148149/** What the dispatcher decided for the notification of a row (`alerts.delivery`). It never changes whether the row exists in the app. */150public enum AlertDelivery: Sendable, Hashable, Codable {151 /** Not looked at yet by the dispatcher. */152 case pending153 /** No device and no webhook: the alert only exists in the app. */154 case inApp155 /** Older than one hour when the dispatcher saw it: not notified. */156 case stale157 /** Held back by the quiet hours (criticals are never held back). */158 case quiet159 /** Held back by the hourly cap; a `system.alerts_capped` summary follows. */160 case capped161 /** Handed to the push services and/or the webhook (see `channels` for the outcome). */162 case sent163 case unknown(String)164165 public var rawValue: String {166 switch self { case .pending: "pending"; case .inApp: "inapp"; case .stale: "stale"; case .quiet: "quiet"; case .capped: "capped"; case .sent: "sent"; case .unknown(let s): s }167 }168 public init(rawValue: String) {169 switch rawValue {170 case "pending": self = .pending; case "inapp": self = .inApp; case "stale": self = .stale; case "quiet": self = .quiet171 case "capped": self = .capped; case "sent": self = .sent; default: self = .unknown(rawValue)172 }173 }174 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }175 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }176}177178/** Outcome per channel of a `sent` alert; empty for the others. */179public struct AlertChannels: Codable, Sendable, Hashable {180 public struct Push: Codable, Sendable, Hashable { public let sent: Int; public let failed: Int; public let removed: Int }181 public struct Webhook: Codable, Sendable, Hashable { public let ok: Bool; public let status: Int }182 public let push: Push?183 public let webhook: Webhook?184}185186/** One alert row as GET /alerts serves it (`view` in alerts/routes.ts). Named `WalletAlert` so that it never collides with SwiftUI's `Alert`. */187public struct WalletAlert: Codable, Sendable, Hashable, Identifiable {188 public let id: Int64189 /** When the event happened (the server sends epoch milliseconds). */190 public let ts: Date191 public let kind: AlertKind192 /** The severity of THIS row (a rule may raise or lower the kind's default). */193 public let severity: AlertSeverity194 public let group: AlertGroup195 /** Codes, names and already formatted numbers; `count` is always present (a digest counts its occurrences). Values of the form `@word` are vocabulary. */196 public let params: [String: JSONValue]197 public let subject: AlertSubject?198 public let count: Int199 /** nil = unread. */200 public let readAt: Date?201 public let delivery: AlertDelivery202 public let channels: AlertChannels?203204 public var isRead: Bool { readAt != nil }205 /** The sentence to show, from the backend's own templates. */206 public func text(locale: AlertLocale, detail: Bool = true) -> (title: String, body: String) { AlertCatalog.render(kind, params: params, locale: locale, detail: detail) }207 public var path: String { AlertCatalog.path(kind: kind, subject: subject) }208}209210/** The unread counters; `lastId` is the highest alert id on the server (0 when there is none) — what a poller compares to know that something new exists. */211public struct AlertUnread: Codable, Sendable, Hashable {212 public let unread: Int213 public let critical: Int214 public let lastId: Int64215}216217public struct AlertPage: Codable, Sendable, Hashable {218 public let items: [WalletAlert]219 public let unread: Int220 public let critical: Int221 public let lastId: Int64222 public var counters: AlertUnread { AlertUnread(unread: unread, critical: critical, lastId: lastId) }223 /** The `before` of the next (older) page; nil when this page is empty. */224 public var nextBefore: Int64? { items.last?.id }225}226227public struct AlertListQuery: Sendable, Equatable {228 /** 1…200 (server default 50). */229 public var limit: Int?230 /** Only alerts with an id below this one (paging towards the past). */231 public var before: Int64?232 public var severity: AlertSeverity?233 public var group: AlertGroup?234 public var unreadOnly: Bool235 public init(limit: Int? = nil, before: Int64? = nil, severity: AlertSeverity? = nil, group: AlertGroup? = nil, unreadOnly: Bool = false) {236 self.limit = limit; self.before = before; self.severity = severity; self.group = group; self.unreadOnly = unreadOnly237 }238}239240// MARK: owner settings241242public struct AlertQuietHours: Codable, Sendable, Hashable {243 public var enabled: Bool244 /** `HH:MM`, 24 h. */245 public var start: String246 public var end: String247 /** IANA time zone. */248 public var tz: String249}250251public struct AlertThresholds: Codable, Sendable, Hashable {252 /** A transfer or swap still not final after this many minutes (5…1440). */253 public var stuckMinutes: Int254 public var bridgeStuckMinutes: Int255 /** At most one "order filled" notification per agent per this many minutes (0 = one per order). */256 public var agentDigestMinutes: Int257 public var staleBars: Int258 public var signalFailures: Int259 /** Absolute funding payment, USD. */260 public var fundingUsd: Double261 public var diskFreePct: Double262 public var backupHours: Int263 public var feedDebounceSec: Int264 public var unknownOrderSec: Int265}266267/** The webhook as the server stores it: there is NO secret here — it lives in a file on the API host and is never returned by a read. */268public struct AlertWebhookSettings: Codable, Sendable, Hashable {269 public var enabled: Bool270 /** https only; "" when none is set. */271 public var url: String272 /** Amounts, prices and reason texts in the calls. Off by default. */273 public var details: Bool274}275276public struct AlertSettings: Codable, Sendable, Hashable {277 /** One switch per switchable kind (the raw kind string → on/off). Fixed kinds are not listed. */278 public var rules: [String: Bool]279 public var quiet: AlertQuietHours280 /** Amounts, prices and reasons in push notifications (lock screen). Off by default. */281 public var showDetails: Bool282 /** Push notifications and webhook calls per hour, criticals excepted (1…500). */283 public var capPerHour: Int284 public var thresholds: AlertThresholds285 public var webhook: AlertWebhookSettings286287 public func isOn(_ kind: AlertKind) -> Bool? { rules[kind.rawValue] }288}289290/** The kinds the server knows, as GET /alerts/settings lists them (the server's catalogue, which may be newer than this app's). */291public struct AlertKindInfo: Codable, Sendable, Hashable {292 public let kind: AlertKind293 public let group: AlertGroup294 public let severity: AlertSeverity295 public let defaultOn: Bool296 public let fixed: Bool297 enum CodingKeys: String, CodingKey { case kind, group, severity, defaultOn = "default", fixed }298}299300public struct AlertSettingsView: Codable, Sendable, Hashable {301 public struct WebhookState: Codable, Sendable, Hashable {302 /** Whether a webhook secret exists on the server. The secret itself is never part of any read. */303 public let secretSet: Bool304 }305 public let settings: AlertSettings306 public let kinds: [AlertKindInfo]307 public let webhook: WebhookState308 /** Exactly what a webhook call contains with the present "details" setting (shown before the webhook is enabled). */309 public let webhookSample: JSONValue?310}311312/** A partial update (PUT /alerts/settings merges it over the stored settings). Only the fields set here are sent. */313public struct AlertSettingsPatch: Encodable, Sendable, Equatable {314 public struct Quiet: Encodable, Sendable, Equatable {315 public var enabled: Bool?; public var start: String?; public var end: String?; public var tz: String?316 public init(enabled: Bool? = nil, start: String? = nil, end: String? = nil, tz: String? = nil) { self.enabled = enabled; self.start = start; self.end = end; self.tz = tz }317 }318 public struct Thresholds: Encodable, Sendable, Equatable {319 public var stuckMinutes: Int?; public var bridgeStuckMinutes: Int?; public var agentDigestMinutes: Int?; public var staleBars: Int?; public var signalFailures: Int?320 public var fundingUsd: Double?; public var diskFreePct: Double?; public var backupHours: Int?; public var feedDebounceSec: Int?; public var unknownOrderSec: Int?321 public init() {}322 }323 /** URL and switches only: the secret is generated by the server (`AlertsAPI.rotateWebhookSecret`), never sent by a client. */324 public struct Webhook: Encodable, Sendable, Equatable {325 public var enabled: Bool?; public var url: String?; public var details: Bool?326 public init(enabled: Bool? = nil, url: String? = nil, details: Bool? = nil) { self.enabled = enabled; self.url = url; self.details = details }327 }328 /** Raw kind → on/off. The server refuses an unknown or a fixed kind (`bad_request`). */329 public var rules: [String: Bool]?330 public var quiet: Quiet?331 public var showDetails: Bool?332 public var capPerHour: Int?333 public var thresholds: Thresholds?334 public var webhook: Webhook?335 public init(rules: [String: Bool]? = nil, quiet: Quiet? = nil, showDetails: Bool? = nil, capPerHour: Int? = nil, thresholds: Thresholds? = nil, webhook: Webhook? = nil) {336 self.rules = rules; self.quiet = quiet; self.showDetails = showDetails; self.capPerHour = capPerHour; self.thresholds = thresholds; self.webhook = webhook337 }338 public static func rule(_ kind: AlertKind, on: Bool) -> AlertSettingsPatch { AlertSettingsPatch(rules: [kind.rawValue: on]) }339}340341/**342 The answer of POST /alerts/webhook/secret: the new shared secret, returned ONCE. Deliberately not `Encodable` and not `Hashable`:343 it is shown to the owner and dropped — never cached, never written to the offline store, never logged.344 */345public struct AlertWebhookSecret: Decodable, Sendable {346 public let secret: String347}348349public struct AlertWebhookTestResult: Codable, Sendable, Hashable {350 public let ok: Bool351 /** HTTP status of the receiver; 0 when no answer was received. */352 public let status: Int353 public let error: String?354}355356// MARK: Web Push devices357358/** The server's VAPID public key (RFC 8292), public by design. Web Push only. */359public struct PushPublicKey: Codable, Sendable, Hashable { public let publicKey: String }360361/** One subscribed browser (`subView`): the endpoint and its keys are never returned, only the push service's host and the last 12 characters. */362public struct PushSubscription: Codable, Sendable, Hashable, Identifiable {363 public let id: String364 public let label: String365 public let locale: String366 /** Host of the browser's push service (`web.push.apple.com`, `fcm.googleapis.com`…). */367 public let service: String368 public let endpointTail: String369 public let ua: String370 public let createdAt: Date?371 public let lastOkAt: Date?372 public let lastError: String?373 public let failures: Int374}375376/**377 A Web Push subscription (RFC 8030 / 8291) as a BROWSER creates it. The server only accepts endpoints of the browsers' push378 services and encrypts for these keys. A native app has no such endpoint: there is no APNs device-token route on this server.379 */380public struct WebPushSubscriptionRequest: Encodable, Sendable, Equatable {381 public struct Keys: Encodable, Sendable, Equatable { public let p256dh: String; public let auth: String; public init(p256dh: String, auth: String) { self.p256dh = p256dh; self.auth = auth } }382 public let endpoint: String383 public let keys: Keys384 public let label: String?385 public let locale: AlertLocale?386 public init(endpoint: String, keys: Keys, label: String? = nil, locale: AlertLocale? = nil) { self.endpoint = endpoint; self.keys = keys; self.label = label; self.locale = locale }387}388389public struct PushTestResult: Codable, Sendable, Hashable {390 public struct Device: Codable, Sendable, Hashable, Identifiable {391 public let id: String392 public let ok: Bool393 public let status: Int394 /** The push service no longer knows this subscription: the server removed it. */395 public let removed: Bool396 public let error: String?397 }398 public let results: [Device]399}400401/** One event of the alerts SSE stream (GET /alerts/stream): the unread counters now, then at every change. */402public enum AlertStreamEvent: Sendable, Equatable {403 case unread(AlertUnread)404405 /** nil for comments, keep-alives and event names this version does not know. */406 public init?(_ e: ServerSentEvent) {407 guard e.event == "unread", let u = try? APICoding.decoder().decode(AlertUnread.self, from: Data(e.data.utf8)) else { return nil }408 self = .unread(u)409 }410}411