Bucksley / app · bucksley.ai / Tests / BucksleyKitTests / InsightsTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | import CryptoKit |
| 4 | @testable import BucksleyKit |
| 5 | |
| 6 | private func month(_ back: Int) -> String { MonthKey.adding(-back, to: MonthKey.current) } |
| 7 | private func day(_ back: Int, _ d: Int) -> String { month(back) + String(format: "-%02d", d) } |
| 8 | |
| 9 | @Suite struct CashFlow { |
| 10 | @Test func incomeSpendAndSavingsRatePerMonth() throws { |
| 11 | let store = try tempStore() |
| 12 | try store.upsert([ |
| 13 | tx("p1", day(1, 1), 4000, "ACME PAYROLL DIRECT DEP"), |
| 14 | tx("g1", day(1, 3), -300, "SAFEWAY GROCERY"), |
| 15 | tx("d1", day(1, 9), -100, "CHIPOTLE RESTAURANT"), |
| 16 | tx("x1", day(1, 15), -1000, "CHASE CREDIT CARD PAYMENT"), // a transfer: neither income nor spend |
| 17 | tx("r1", day(1, 20), 50, "SAFEWAY GROCERY") // a refund lowers groceries |
| 18 | ]) |
| 19 | let flow = try store.ledger().cashFlow(months: 3) |
| 20 | #expect(flow.count == 3 && flow.last?.month == MonthKey.current) |
| 21 | let last = try #require(flow.first { $0.month == month(1) }) |
| 22 | #expect(last.income == 4000) |
| 23 | #expect(last.spend == 350) |
| 24 | #expect(last.net == 3650) |
| 25 | #expect(abs(Decimal(last.savingsRate!) - Decimal(0.9125)) < Decimal(0.0001)) |
| 26 | let avg = try store.ledger().cashFlowAverages(flow) |
| 27 | #expect(avg.income == 4000) // months with no activity don't count |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | @Suite struct Flags { |
| 32 | @Test func duplicatesPriceIncreasesAndBigCharges() throws { |
| 33 | let store = try tempStore() |
| 34 | let t = DayKey.today |
| 35 | var txs = [ |
| 36 | tx("dup1", DayKey.adding(-3, to: t), -42.50, "BLUE BOTTLE COFFEE"), |
| 37 | tx("dup2", DayKey.adding(-2, to: t), -42.50, "BLUE BOTTLE COFFEE"), |
| 38 | tx("new1", DayKey.adding(-1, to: t), -640, "APEX FURNITURE OUTLET") |
| 39 | ] |
| 40 | // Steady monthly Netflix that just went up. |
| 41 | for (i, back) in [120, 90, 60, 30].enumerated() { txs.append(tx("n\(i)", DayKey.adding(-back, to: t), -15.49, "NETFLIX.COM")) } |
| 42 | txs.append(tx("n9", t, -17.99, "NETFLIX.COM")) |
| 43 | // A usually-small merchant with a big charge. |
| 44 | for (i, back) in [80, 60, 40, 20].enumerated() { txs.append(tx("s\(i)", DayKey.adding(-back, to: t), -12, "CORNER DELI")) } |
| 45 | txs.append(tx("s9", DayKey.adding(-1, to: t), -96, "CORNER DELI")) |
| 46 | try store.upsert(txs) |
| 47 | let flags = try store.ledger().flags() |
| 48 | let byID = Dictionary(flags.map { ($0.entryID, $0.kind) }, uniquingKeysWith: { a, _ in a }) |
| 49 | #expect(byID["dup2"] == .duplicate && byID["dup1"] == nil) |
| 50 | #expect(byID["n9"] == .priceChange) |
| 51 | #expect(byID["s9"] == .aboveUsual) |
| 52 | #expect(byID["new1"] == .newMerchant) |
| 53 | #expect(byID["n3"] == nil) |
| 54 | } |
| 55 | |
| 56 | @Test func reviewingClearsAFlagAndFlaggedComeFirst() throws { |
| 57 | let store = try tempStore() |
| 58 | let t = DayKey.today |
| 59 | try store.upsert([tx("small", t, -4, "SOME SHOP"), tx("big", DayKey.adding(-5, to: t), -700, "NEW PLACE INC")]) |
| 60 | #expect(try store.ledger().prioritizedReviewQueue().first?.id == "big") |
| 61 | try store.edit("big") { $0.reviewed = true } |
| 62 | #expect(try store.ledger().flags().isEmpty) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | @Suite struct Refunds { |
| 67 | @Test func creditFromTheSameMerchantMatchesThePurchase() throws { |
| 68 | let store = try tempStore() |
| 69 | let t = DayKey.today |
| 70 | try store.upsert([ |
| 71 | tx("buy", DayKey.adding(-20, to: t), -89.99, "REI COOP OUTDOOR"), |
| 72 | tx("back", DayKey.adding(-5, to: t), 89.99, "REI COOP OUTDOOR"), |
| 73 | tx("pay", DayKey.adding(-4, to: t), 2000, "ACME PAYROLL DIRECT DEP") |
| 74 | ]) |
| 75 | let matches = try store.ledger().refundMatches() |
| 76 | #expect(matches == [Ledger.RefundMatch(refundID: "back", purchaseID: "buy")]) |
| 77 | // Accepting: the credit takes the purchase's category and the link; then it's no longer suggested. |
| 78 | let purchase = try #require(try store.ledger().entry("buy")) |
| 79 | try store.edit("back") { $0.refundOf = "buy"; $0.categoryID = purchase.categoryID } |
| 80 | let after = try store.ledger() |
| 81 | #expect(after.refundMatches().isEmpty) |
| 82 | #expect(after.entry("back")?.categoryID == purchase.categoryID && after.entry("back")?.refundOf == "buy") |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | @Suite struct Suggestions { |
| 87 | @Test func historyPicksTheCategoryTheUserChoseBefore() throws { |
| 88 | let store = try tempStore() |
| 89 | try store.upsert([tx("a", day(1, 2), -30, "ZORBLAX LLC"), tx("b", day(0, 1), -31, "ZORBLAX LLC")]) |
| 90 | try store.edit("a") { $0.categoryID = "health" } |
| 91 | let s = try store.ledger().historySuggestions() |
| 92 | #expect(s.map(\.entryID) == ["b"] && s.first?.categoryID == "health") |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | @Suite struct Budgets2 { |
| 97 | @Test func groupBudgetsAndMonthOverridesDontDoubleCount() throws { |
| 98 | let store = try tempStore() |
| 99 | let m = MonthKey.current |
| 100 | try store.upsert([tx("g", m + "-01", -200, "SAFEWAY GROCERY"), tx("e", m + "-01", -50, "PG&E UTILITY BILL", category: "mcc:4900")]) |
| 101 | try store.update { ws in |
| 102 | var group = Budget(categoryID: "essentials", amount: 1000) |
| 103 | group.monthAmounts = [m: 1200] |
| 104 | ws.budgets = [group, Budget(categoryID: "groceries", amount: 400), Budget(categoryID: "dining", amount: 300)] |
| 105 | } |
| 106 | let ledger = try store.ledger() |
| 107 | let essentials = try #require(ledger.budgetStatus().first { $0.id == "essentials" }) |
| 108 | #expect(essentials.allowed == 1200) |
| 109 | #expect(essentials.spent == ledger.spent("groceries", month: m) + ledger.spent("utilities", month: m)) |
| 110 | #expect(ledger.isCoveredByGroupBudget("groceries") && !ledger.isCoveredByGroupBudget("dining")) |
| 111 | let totals = ledger.budgetTotals() |
| 112 | #expect(totals.budgeted == 1500) // essentials 1200 + dining 300; groceries sits inside essentials |
| 113 | #expect(ledger.budgetName("essentials") == "Essentials") |
| 114 | } |
| 115 | |
| 116 | @Test func rolloverUsesEachMonthsOwnAmount() throws { |
| 117 | let store = try tempStore() |
| 118 | try store.update { ws in |
| 119 | var b = Budget(categoryID: "dining", amount: 100, rollover: true, startMonth: month(2)) |
| 120 | b.monthAmounts = [month(2): 300] |
| 121 | ws.budgets = [b] |
| 122 | } |
| 123 | let status = try #require(try store.ledger().budgetStatus().first) |
| 124 | #expect(status.carried == 400) // 300 + 100 unspent |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | @Suite struct Rules2 { |
| 129 | @Test func previewShowsMatchesAndHandEditedOnes() throws { |
| 130 | let store = try tempStore() |
| 131 | try store.upsert([tx("1", day(0, 1), -20, "UBER TRIP"), tx("2", day(0, 2), -25, "UBER TRIP"), tx("3", day(0, 2), -9, "LYFT RIDE")]) |
| 132 | try store.edit("2") { $0.categoryID = "travel" } |
| 133 | var rule = Rule(matchText: "uber", setCategoryID: "transport"); rule.enabled = false |
| 134 | let preview = try store.ledger().preview(rule) |
| 135 | #expect(Set(preview.matches.map(\.id)) == ["1", "2"]) |
| 136 | #expect(preview.editedByHand.map(\.id) == ["2"]) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | @Suite struct Recaps { |
| 141 | @Test func factsAndFigureGuard() throws { |
| 142 | let store = try tempStore() |
| 143 | try store.upsert([ |
| 144 | tx("p", day(1, 1), 5000, "ACME PAYROLL DIRECT DEP"), tx("g", day(1, 4), -400, "SAFEWAY GROCERY"), |
| 145 | tx("d", day(1, 6), -250, "CHIPOTLE RESTAURANT"), tx("d0", day(2, 6), -100, "CHIPOTLE RESTAURANT"), |
| 146 | tx("p0", day(2, 1), 5000, "ACME PAYROLL DIRECT DEP") |
| 147 | ]) |
| 148 | let recap = try #require(try store.ledger().recap()) |
| 149 | #expect(recap.spend == 650 && recap.income == 5000 && recap.net == 4350) |
| 150 | #expect(recap.facts.contains("$4,350")) |
| 151 | #expect(recap.movers.first?.change == 400 || recap.movers.contains { $0.change == 150 }) |
| 152 | #expect(AskBucksley.recapFiguresAreValid("You kept $4,350 this month, nice.", recap: recap)) |
| 153 | #expect(!AskBucksley.recapFiguresAreValid("You kept $4,999 this month.", recap: recap)) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | @Suite struct Exports { |
| 158 | @Test func csvRoundTripsThroughTheImporter() throws { |
| 159 | let store = try tempStore() |
| 160 | try store.upsert([tx("1", day(0, 1), -12.5, "BLUE BOTTLE, COFFEE"), tx("2", day(0, 2), 3000, "ACME PAYROLL DIRECT DEP")]) |
| 161 | try store.edit("1") { $0.note = "with \"Sam\""; $0.tags = ["work"] } |
| 162 | let csv = Backup.csv(try store.ledger()) |
| 163 | let parsed = try CSVImport.parse(csv, connectionID: "c", categories: Defaults.categories) |
| 164 | #expect(parsed.transactions.count == 2) |
| 165 | #expect(parsed.transactions.contains { $0.amount == -12.5 && $0.description.lowercased().contains("blue bottle") }) |
| 166 | #expect(parsed.edits.contains { $0.note == "with \"Sam\"" && $0.tags == ["work"] }) |
| 167 | } |
| 168 | |
| 169 | @Test func backupRestoresEverythingAndSavesTheOldData() throws { |
| 170 | let store = try tempStore() |
| 171 | try store.upsert([tx("1", day(0, 1), -12.5, "BLUE BOTTLE COFFEE")]) |
| 172 | try store.update { $0.budgets = [Budget(categoryID: "dining", amount: 200)]; $0.connections = [Connection(kind: .plaid, name: "Bank")] ; $0.connections[0].plaidCursor = "abc" } |
| 173 | let backup = try Backup.make(from: store) |
| 174 | #expect(!String(decoding: backup, as: UTF8.self).contains("abc")) |
| 175 | try store.upsert([tx("2", day(0, 2), -5, "LATER")]) |
| 176 | try store.update { $0.budgets = [] } |
| 177 | let saved = try Backup.restore(backup, into: store) |
| 178 | #expect(FileManager.default.fileExists(atPath: saved.path)) |
| 179 | #expect(try store.transactions().map(\.id) == ["1"]) |
| 180 | #expect(try store.load().budgets.first?.amount == 200) |
| 181 | #expect(throws: BucksleyError.self) { try Backup.read(Data("{}".utf8)) } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | @Suite struct CoinbaseTests { |
| 186 | @Test func walletsBecomeCryptoHoldingsAndCash() async throws { |
| 187 | let wallets = """ |
| 188 | {"data":[ |
| 189 | {"id":"w1","name":"BTC Wallet","type":"wallet","currency":{"code":"BTC","name":"Bitcoin"},"balance":{"amount":"0.5","currency":"BTC"}}, |
| 190 | {"id":"w2","name":"USD Wallet","type":"fiat","currency":{"code":"USD","name":"US Dollar"},"balance":{"amount":"1234.56","currency":"USD"}}, |
| 191 | {"id":"w3","name":"ETH Wallet","type":"wallet","currency":{"code":"ETH","name":"Ethereum"},"balance":{"amount":"0","currency":"ETH"}}, |
| 192 | {"id":"w4","name":"ZZZ Wallet","type":"wallet","currency":{"code":"ZZZ","name":"Mystery"},"balance":{"amount":"7","currency":"ZZZ"}} |
| 193 | ],"pagination":{"next_uri":null}} |
| 194 | """ |
| 195 | let rates = #"{"data":{"currency":"USD","rates":{"BTC":"0.00001","ETH":"0.0003"}}}"# |
| 196 | let key = Coinbase.Key(name: "organizations/o/apiKeys/k", privateKey: P256.Signing.PrivateKey().pemRepresentation) |
| 197 | let http = StubHTTP { req in |
| 198 | if req.url!.path == "/v2/accounts" { |
| 199 | #expect(req.value(forHTTPHeaderField: "Authorization")?.hasPrefix("Bearer ey") == true) |
| 200 | return (200, wallets) |
| 201 | } |
| 202 | #expect(req.value(forHTTPHeaderField: "Authorization") == nil) |
| 203 | return (200, rates) |
| 204 | } |
| 205 | let pull = try await Coinbase(key: key, http: http).pull(connectionID: "cb") |
| 206 | let crypto = try #require(pull.accounts.first { $0.kind == .crypto }) |
| 207 | #expect(crypto.balance == 50_000) |
| 208 | #expect(crypto.holdings?.map(\.symbol) == ["BTC"]) |
| 209 | #expect(pull.accounts.first { $0.id == "cb.usd" }?.balance == Decimal(string: "1234.56")) |
| 210 | #expect(pull.warnings.first?.contains("ZZZ") == true) |
| 211 | } |
| 212 | |
| 213 | @Test func jwtCarriesTheRequestAndVerifies() throws { |
| 214 | let pk = P256.Signing.PrivateKey() |
| 215 | let jwt = try Coinbase(key: .init(name: "kname", privateKey: pk.pemRepresentation)).jwt(method: "GET", path: "/v2/accounts") |
| 216 | let parts = jwt.split(separator: ".").map(String.init) |
| 217 | #expect(parts.count == 3) |
| 218 | func decode(_ s: String) -> Data { var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/"); while b.count % 4 != 0 { b += "=" }; return Data(base64Encoded: b)! } |
| 219 | let payload = try JSONSerialization.jsonObject(with: decode(parts[1])) as! [String: Any] |
| 220 | #expect(payload["uri"] as? String == "GET api.coinbase.com/v2/accounts" && payload["sub"] as? String == "kname") |
| 221 | let sig = try P256.Signing.ECDSASignature(rawRepresentation: decode(parts[2])) |
| 222 | #expect(pk.publicKey.isValidSignature(sig, for: Data((parts[0] + "." + parts[1]).utf8))) |
| 223 | // Ed25519 keys as Coinbase downloads them (base64 of seed + public key). |
| 224 | let ed = Curve25519.Signing.PrivateKey() |
| 225 | let edKey = (ed.rawRepresentation + ed.publicKey.rawRepresentation).base64EncodedString() |
| 226 | let edJWT = try Coinbase(key: .init(name: "id", privateKey: edKey)).jwt(method: "GET", path: "/v2/accounts") |
| 227 | let ep = edJWT.split(separator: ".").map(String.init) |
| 228 | #expect(ed.publicKey.isValidSignature(decode(ep[2]), for: Data((ep[0] + "." + ep[1]).utf8))) |
| 229 | #expect(Coinbase.Key(json: #"{"name":"n","privateKey":"-----BEGIN \("")EC PRIVATE KEY-----\nabc\n-----END EC PRIVATE KEY-----\n"}"#)?.privateKey.contains("\n") == true) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | @Suite struct CoinbaseSignInTests { |
| 234 | @Test func signInSavesTheRefreshTokenAndEachSyncRotatesIt() async throws { |
| 235 | let store = try tempStore() |
| 236 | let wallets = #"{"data":[{"id":"w2","name":"USD Wallet","type":"fiat","currency":{"code":"USD","name":"US Dollar"},"balance":{"amount":"50","currency":"USD"}}],"pagination":{"next_uri":null}}"# |
| 237 | let rates = #"{"data":{"currency":"USD","rates":{}}}"# |
| 238 | let counter = Counter() |
| 239 | let http = StubHTTP { req in |
| 240 | switch req.url!.path { |
| 241 | case "/coinbase/token": |
| 242 | let body = try! JSONSerialization.jsonObject(with: req.httpBody!) as! [String: String] |
| 243 | let n = counter.next() |
| 244 | if body["grant_type"] == "authorization_code" { #expect(body["code"] == "c0de" && body["code_verifier"] == "v") } |
| 245 | else { #expect(body["refresh_token"] == "r\(n - 1)") } |
| 246 | return (200, #"{"access_token":"a\#(n)","refresh_token":"r\#(n)","expires_in":3600}"#) |
| 247 | case "/v2/accounts": |
| 248 | #expect(req.value(forHTTPHeaderField: "Authorization")?.hasPrefix("Bearer a") == true) |
| 249 | return (200, wallets) |
| 250 | default: return (200, rates) |
| 251 | } |
| 252 | } |
| 253 | let sync = BankSync(store: store, http: http) |
| 254 | let connection = try await sync.connectCoinbase(signInCode: "c0de", verifier: "v") |
| 255 | #expect(Keychain.get(.connection(connection.id))?.contains("r1") == true) |
| 256 | _ = try await sync.sync(connection) |
| 257 | #expect(Keychain.get(.connection(connection.id))?.contains("r2") == true) |
| 258 | #expect(try store.load().accounts.first { $0.name == "Coinbase Cash" }?.balance == 50) |
| 259 | } |
| 260 | |
| 261 | @Test func callbackStateMustMatch() throws { |
| 262 | let request = CoinbaseSignIn.Request(url: URL(string: "https://x")!, state: "s1", verifier: "v") |
| 263 | #expect(try CoinbaseSignIn.code(from: URL(string: "bucksley://coinbase/callback?code=abc&state=s1")!, expecting: request) == "abc") |
| 264 | #expect(throws: BucksleyError.self) { try CoinbaseSignIn.code(from: URL(string: "bucksley://coinbase/callback?code=abc&state=nope")!, expecting: request) } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | final class Counter: @unchecked Sendable { |
| 269 | private var n = 0 |
| 270 | private let lock = NSLock() |
| 271 | func next() -> Int { lock.lock(); defer { lock.unlock() }; n += 1; return n } |
| 272 | } |
| 273 | |
| 274 | @Suite struct HistoryBackfill { |
| 275 | /// An account that shows up after the first sync gets its 90 days once, not just the two weeks each |
| 276 | /// later sync re-reads. |
| 277 | @Test func anAccountLinkedLaterGetsItsHistory() async throws { |
| 278 | Keychain.memory = Keychain.memory ?? [:] |
| 279 | let store = try tempStore() |
| 280 | let now = Date(timeIntervalSince1970: 1795600000) |
| 281 | var connection = Connection(kind: .simplefin, name: "SimpleFIN") |
| 282 | connection.lastSyncAt = now.addingTimeInterval(-86_400) |
| 283 | try Keychain.set("https://u:p@bridge.example/simplefin", for: .connection(connection.id)) |
| 284 | try store.update { $0.connections = [connection] } |
| 285 | let old = Int(now.timeIntervalSince1970) - 60 * 86_400 |
| 286 | let http = StubHTTP { req in |
| 287 | let start = Int(URLComponents(url: req.url!, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "start-date" }!.value!)! |
| 288 | let end = Int(URLComponents(url: req.url!, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "end-date" }!.value!)! |
| 289 | let tx = (start...end).contains(old) ? #"[{"id":"T-OLD","posted":\#(old),"amount":"120","description":"Dividend"}]"# : "[]" |
| 290 | return (200, #"{"errors":[],"accounts":[{"org":{"name":"Merrill Lynch"},"id":"ACT-IRA","name":"IRA-Edge- 5Z05","currency":"USD","balance":"1000","balance-date":1795600000,"transactions":\#(tx)}]}"#) |
| 291 | } |
| 292 | let sync = BankSync(store: store, http: http) |
| 293 | _ = try await sync.sync(connection, now: now) |
| 294 | #expect(try store.load().accounts.first?.historyLoaded == true) |
| 295 | #expect(try store.ledger().entries.contains { $0.transaction.description == "Dividend" }) |
| 296 | } |
| 297 | } |