Bucksley / app · bucksley.ai / Sources / BucksleyKit / Backup.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Getting data out and back in: a transactions CSV anyone can open (in the Copilot Money export |
| 4 | /// layout, so Bucksley and other apps can import it) and a full backup that restores everything. |
| 5 | /// Neither ever holds a credential: bank keys and tokens stay in the Keychain. |
| 6 | public enum Backup { |
| 7 | |
| 8 | // MARK: CSV export |
| 9 | |
| 10 | public static let csvHeader = ["date", "name", "amount", "status", "category", "parent category", "excluded", "tags", "type", "account", "account mask", "note", "recurring"] |
| 11 | |
| 12 | /// Every transaction as the app shows it. Amounts are positive for spending, like Copilot's export. |
| 13 | public static func csv(_ ledger: Ledger) -> String { |
| 14 | let ws = ledger.workspace |
| 15 | let recurringKeys = Set(ledger.recurring().filter { $0.status != .dismissed }.map(\.id)) |
| 16 | var lines = [csvHeader.joined(separator: ",")] |
| 17 | for e in ledger.entries.sorted(by: { ($0.day, $0.id) > ($1.day, $1.id) }) { |
| 18 | let category = ws.category(e.categoryID) |
| 19 | let kind = category?.kind ?? .expense |
| 20 | let account = ws.account(e.accountID) |
| 21 | let row = [e.day, e.name, (-e.amount).description, e.transaction.pending ? "pending" : "posted", |
| 22 | category?.name ?? e.categoryID, ws.groups.first { $0.id == category?.groupID }?.name ?? "", |
| 23 | e.excluded ? "true" : "false", e.tags.joined(separator: ","), |
| 24 | kind == .income ? "income" : kind == .transfer ? "internal transfer" : "regular", |
| 25 | account?.displayName ?? "", "", e.note ?? "", recurringKeys.contains(Ledger.recurringKey(e.name)) ? e.name : ""] |
| 26 | lines.append(row.map(field).joined(separator: ",")) |
| 27 | } |
| 28 | return lines.joined(separator: "\n") + "\n" |
| 29 | } |
| 30 | |
| 31 | static func field(_ text: String) -> String { |
| 32 | guard text.contains(where: { $0 == "," || $0 == "\"" || $0 == "\n" }) else { return text } |
| 33 | return "\"" + text.replacingOccurrences(of: "\"", with: "\"\"") + "\"" |
| 34 | } |
| 35 | |
| 36 | // MARK: Full backup |
| 37 | |
| 38 | /// One JSON file with the whole local store and a format version. |
| 39 | public struct File: Codable, Sendable { |
| 40 | public static let currentFormat = 1 |
| 41 | public var app = "Bucksley" |
| 42 | public var format = File.currentFormat |
| 43 | public var createdAt: Date |
| 44 | public var device: String |
| 45 | public var workspace: Workspace |
| 46 | public var transactions: [Transaction] |
| 47 | public var edits: [String: TransactionEdit] |
| 48 | public var balances: [BalancePoint] |
| 49 | } |
| 50 | |
| 51 | public static func make(from store: WorkspaceStore, now: Date = .now) throws -> Data { |
| 52 | var ws = try store.load() |
| 53 | // The sync cursor belongs to this Mac's link with Plaid; a restored copy re-reads instead. |
| 54 | for i in ws.connections.indices { ws.connections[i].plaidCursor = nil } |
| 55 | let file = File(createdAt: now, device: DeviceName.current, workspace: ws, transactions: try store.transactions(), |
| 56 | edits: try store.edits(), balances: try store.balances()) |
| 57 | let e = JSONEncoder.bucksley; e.outputFormatting = [.sortedKeys, .prettyPrinted] |
| 58 | return try e.encode(file) |
| 59 | } |
| 60 | |
| 61 | public static func read(_ data: Data) throws -> File { |
| 62 | let file: File |
| 63 | do { file = try JSONDecoder.bucksley.decode(File.self, from: data) } |
| 64 | catch { throw BucksleyError.invalid("That isn't a Bucksley backup.") } |
| 65 | guard file.app == "Bucksley" else { throw BucksleyError.invalid("That isn't a Bucksley backup.") } |
| 66 | guard file.format <= File.currentFormat else { throw BucksleyError.invalid("That backup is from a newer Bucksley. Update Bucksley, then restore it.") } |
| 67 | return file |
| 68 | } |
| 69 | |
| 70 | /// Replaces everything with the backup. A backup of the current data is saved first, in |
| 71 | /// Bucksley's folder, and its URL returned so nothing is ever lost to a restore. |
| 72 | @discardableResult |
| 73 | public static func restore(_ data: Data, into store: WorkspaceStore, now: Date = .now) throws -> URL { |
| 74 | let file = try read(data) |
| 75 | let safety = store.folder.appendingPathComponent("Backups", isDirectory: true) |
| 76 | try FileManager.default.createDirectory(at: safety, withIntermediateDirectories: true) |
| 77 | let stamp = ISO8601DateFormatter().string(from: now).replacingOccurrences(of: ":", with: "-") |
| 78 | let saved = safety.appendingPathComponent("Before restore \(stamp).bucksley-backup.json") |
| 79 | try make(from: store, now: now).write(to: saved, options: .atomic) |
| 80 | var ws = file.workspace |
| 81 | for i in ws.connections.indices { ws.connections[i].plaidCursor = nil } |
| 82 | try store.replaceAll(workspace: ws, transactions: file.transactions, edits: file.edits, balances: file.balances) |
| 83 | return saved |
| 84 | } |
| 85 | |
| 86 | public static func fileName(now: Date = .now) -> String { "Bucksley \(DayKey.from(now)).bucksley-backup.json" } |
| 87 | } |