SPB Git

Repository Public

LocalStores.swift 4.4 KB 103 lines swift

1//2//  VQuant iOS3//  File: Core/Stores/LocalStores.swift4//  Description: Device-local state shared by the app, its widgets and its intents: the watchlist, the widget snapshot,5//               and the catalogue of quantitative operations the agent runs on the server.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213/// 1.0 kept the watchlist on the device in this JSON file of the app-group container. Since 2.0 the watchlist is a14/// synced `watchlist` object of the account; this type remains for the one-time migration of the file and for the15/// symbol rules (`normalise`).16struct WatchlistFile: Sendable {17    struct Entry: Codable, Hashable, Sendable, Identifiable {18        var symbol: String19        var name: String?20        var addedAt: Date21        var id: String { symbol }22    }23    static let defaults = ["^GSPC", "^IXIC", "AAPL", "MSFT", "NVDA"]24    let url: URL2526    func load() -> [Entry] {27        guard let data = try? Data(contentsOf: url), let list = try? JSONDecoder().decode([Entry].self, from: data) else { return [] }28        return list29    }30    func save(_ list: [Entry]) {31        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)32        if let data = try? JSONEncoder().encode(list) { try? data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) }33    }3435    static func normalise(_ raw: String) -> String? {36        let s = raw.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()37        guard !s.isEmpty, s.count <= 20, s.allSatisfy({ $0.isLetter || $0.isNumber || "^.-=".contains($0) }) else { return nil }38        return s39    }40    static func adding(_ symbol: String, name: String?, to list: [Entry], now: Date = Date()) -> [Entry] {41        guard let s = normalise(symbol), !list.contains(where: { $0.symbol == s }) else { return list }42        return list + [Entry(symbol: s, name: name, addedAt: now)]43    }44    static func removing(_ symbol: String, from list: [Entry]) -> [Entry] { list.filter { $0.symbol != symbol.uppercased() } }45}4647/// What the app leaves for its widgets after each refresh: real values with the time they were fetched. A widget48/// never shows a number without that time.49struct WidgetSnapshot: Codable, Sendable, Equatable {50    struct Row: Codable, Sendable, Equatable, Identifiable {51        var symbol: String52        var name: String?53        var price: Double54        var changePercent: Double?55        var id: String { symbol }56    }57    struct Job: Codable, Sendable, Equatable, Identifiable {58        var id: String59        var query: String60        var status: String61        var step: String62        var startedAt: Date63    }64    /// A research workspace of the account (2.0): the studies the agent keeps on the server.65    struct Study: Codable, Sendable, Equatable, Identifiable {66        var id: String67        var title: String68        var updatedAt: Date69    }70    var fetchedAt: Date71    var indices: [Row] = []72    var watchlist: [Row] = []73    var jobs: [Job] = []74    var portfolioValue: Double?75    var portfolioDayPercent: Double?76    var signedIn: Bool = true77    // 2.0 — optional so a snapshot written by 1.0 still decodes.78    /// Name of the synced watchlist the rows come from.79    var watchlistName: String?80    var research: [Study]? = []81    /// Approval requests of the research agent waiting for the person.82    var pendingApprovals: Int?8384    static func load(from url: URL) -> WidgetSnapshot? {85        guard let d = try? Data(contentsOf: url) else { return nil }86        return try? JSONDecoder().decode(WidgetSnapshot.self, from: d)87    }88    func save(to url: URL) {89        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)90        if let d = try? JSONEncoder().encode(self) { try? d.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) }91    }92}9394enum SharedContainer {95    static let appGroup = "group.ai.spboucher.vquant"96    static var directory: URL {97        FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)98            ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]99    }100    static var watchlistURL: URL { directory.appendingPathComponent("watchlist.json") }101    static var snapshotURL: URL { directory.appendingPathComponent("widget-snapshot.json") }102}103
Files main
Menu

Theme