import Foundation /// Getting data out and back in: a transactions CSV anyone can open (in the Copilot Money export /// layout, so Bucksley and other apps can import it) and a full backup that restores everything. /// Neither ever holds a credential: bank keys and tokens stay in the Keychain. public enum Backup { // MARK: CSV export public static let csvHeader = ["date", "name", "amount", "status", "category", "parent category", "excluded", "tags", "type", "account", "account mask", "note", "recurring"] /// Every transaction as the app shows it. Amounts are positive for spending, like Copilot's export. public static func csv(_ ledger: Ledger) -> String { let ws = ledger.workspace let recurringKeys = Set(ledger.recurring().filter { $0.status != .dismissed }.map(\.id)) var lines = [csvHeader.joined(separator: ",")] for e in ledger.entries.sorted(by: { ($0.day, $0.id) > ($1.day, $1.id) }) { let category = ws.category(e.categoryID) let kind = category?.kind ?? .expense let account = ws.account(e.accountID) let row = [e.day, e.name, (-e.amount).description, e.transaction.pending ? "pending" : "posted", category?.name ?? e.categoryID, ws.groups.first { $0.id == category?.groupID }?.name ?? "", e.excluded ? "true" : "false", e.tags.joined(separator: ","), kind == .income ? "income" : kind == .transfer ? "internal transfer" : "regular", account?.displayName ?? "", "", e.note ?? "", recurringKeys.contains(Ledger.recurringKey(e.name)) ? e.name : ""] lines.append(row.map(field).joined(separator: ",")) } return lines.joined(separator: "\n") + "\n" } static func field(_ text: String) -> String { guard text.contains(where: { $0 == "," || $0 == "\"" || $0 == "\n" }) else { return text } return "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" } // MARK: Full backup /// One JSON file with the whole local store and a format version. public struct File: Codable, Sendable { public static let currentFormat = 1 public var app = "Bucksley" public var format = File.currentFormat public var createdAt: Date public var device: String public var workspace: Workspace public var transactions: [Transaction] public var edits: [String: TransactionEdit] public var balances: [BalancePoint] } public static func make(from store: WorkspaceStore, now: Date = .now) throws -> Data { var ws = try store.load() // The sync cursor belongs to this Mac's link with Plaid; a restored copy re-reads instead. for i in ws.connections.indices { ws.connections[i].plaidCursor = nil } let file = File(createdAt: now, device: DeviceName.current, workspace: ws, transactions: try store.transactions(), edits: try store.edits(), balances: try store.balances()) let e = JSONEncoder.bucksley; e.outputFormatting = [.sortedKeys, .prettyPrinted] return try e.encode(file) } public static func read(_ data: Data) throws -> File { let file: File do { file = try JSONDecoder.bucksley.decode(File.self, from: data) } catch { throw BucksleyError.invalid("That isn't a Bucksley backup.") } guard file.app == "Bucksley" else { throw BucksleyError.invalid("That isn't a Bucksley backup.") } guard file.format <= File.currentFormat else { throw BucksleyError.invalid("That backup is from a newer Bucksley. Update Bucksley, then restore it.") } return file } /// Replaces everything with the backup. A backup of the current data is saved first, in /// Bucksley's folder, and its URL returned so nothing is ever lost to a restore. @discardableResult public static func restore(_ data: Data, into store: WorkspaceStore, now: Date = .now) throws -> URL { let file = try read(data) let safety = store.folder.appendingPathComponent("Backups", isDirectory: true) try FileManager.default.createDirectory(at: safety, withIntermediateDirectories: true) let stamp = ISO8601DateFormatter().string(from: now).replacingOccurrences(of: ":", with: "-") let saved = safety.appendingPathComponent("Before restore \(stamp).bucksley-backup.json") try make(from: store, now: now).write(to: saved, options: .atomic) var ws = file.workspace for i in ws.connections.indices { ws.connections[i].plaidCursor = nil } try store.replaceAll(workspace: ws, transactions: file.transactions, edits: file.edits, balances: file.balances) return saved } public static func fileName(now: Date = .now) -> String { "Bucksley \(DayKey.from(now)).bucksley-backup.json" } }