import Foundation import Testing import CryptoKit @testable import BucksleyKit private func month(_ back: Int) -> String { MonthKey.adding(-back, to: MonthKey.current) } private func day(_ back: Int, _ d: Int) -> String { month(back) + String(format: "-%02d", d) } @Suite struct CashFlow { @Test func incomeSpendAndSavingsRatePerMonth() throws { let store = try tempStore() try store.upsert([ tx("p1", day(1, 1), 4000, "ACME PAYROLL DIRECT DEP"), tx("g1", day(1, 3), -300, "SAFEWAY GROCERY"), tx("d1", day(1, 9), -100, "CHIPOTLE RESTAURANT"), tx("x1", day(1, 15), -1000, "CHASE CREDIT CARD PAYMENT"), // a transfer: neither income nor spend tx("r1", day(1, 20), 50, "SAFEWAY GROCERY") // a refund lowers groceries ]) let flow = try store.ledger().cashFlow(months: 3) #expect(flow.count == 3 && flow.last?.month == MonthKey.current) let last = try #require(flow.first { $0.month == month(1) }) #expect(last.income == 4000) #expect(last.spend == 350) #expect(last.net == 3650) #expect(abs(Decimal(last.savingsRate!) - Decimal(0.9125)) < Decimal(0.0001)) let avg = try store.ledger().cashFlowAverages(flow) #expect(avg.income == 4000) // months with no activity don't count } } @Suite struct Flags { @Test func duplicatesPriceIncreasesAndBigCharges() throws { let store = try tempStore() let t = DayKey.today var txs = [ tx("dup1", DayKey.adding(-3, to: t), -42.50, "BLUE BOTTLE COFFEE"), tx("dup2", DayKey.adding(-2, to: t), -42.50, "BLUE BOTTLE COFFEE"), tx("new1", DayKey.adding(-1, to: t), -640, "APEX FURNITURE OUTLET") ] // Steady monthly Netflix that just went up. for (i, back) in [120, 90, 60, 30].enumerated() { txs.append(tx("n\(i)", DayKey.adding(-back, to: t), -15.49, "NETFLIX.COM")) } txs.append(tx("n9", t, -17.99, "NETFLIX.COM")) // A usually-small merchant with a big charge. for (i, back) in [80, 60, 40, 20].enumerated() { txs.append(tx("s\(i)", DayKey.adding(-back, to: t), -12, "CORNER DELI")) } txs.append(tx("s9", DayKey.adding(-1, to: t), -96, "CORNER DELI")) try store.upsert(txs) let flags = try store.ledger().flags() let byID = Dictionary(flags.map { ($0.entryID, $0.kind) }, uniquingKeysWith: { a, _ in a }) #expect(byID["dup2"] == .duplicate && byID["dup1"] == nil) #expect(byID["n9"] == .priceChange) #expect(byID["s9"] == .aboveUsual) #expect(byID["new1"] == .newMerchant) #expect(byID["n3"] == nil) } @Test func reviewingClearsAFlagAndFlaggedComeFirst() throws { let store = try tempStore() let t = DayKey.today try store.upsert([tx("small", t, -4, "SOME SHOP"), tx("big", DayKey.adding(-5, to: t), -700, "NEW PLACE INC")]) #expect(try store.ledger().prioritizedReviewQueue().first?.id == "big") try store.edit("big") { $0.reviewed = true } #expect(try store.ledger().flags().isEmpty) } } @Suite struct Refunds { @Test func creditFromTheSameMerchantMatchesThePurchase() throws { let store = try tempStore() let t = DayKey.today try store.upsert([ tx("buy", DayKey.adding(-20, to: t), -89.99, "REI COOP OUTDOOR"), tx("back", DayKey.adding(-5, to: t), 89.99, "REI COOP OUTDOOR"), tx("pay", DayKey.adding(-4, to: t), 2000, "ACME PAYROLL DIRECT DEP") ]) let matches = try store.ledger().refundMatches() #expect(matches == [Ledger.RefundMatch(refundID: "back", purchaseID: "buy")]) // Accepting: the credit takes the purchase's category and the link; then it's no longer suggested. let purchase = try #require(try store.ledger().entry("buy")) try store.edit("back") { $0.refundOf = "buy"; $0.categoryID = purchase.categoryID } let after = try store.ledger() #expect(after.refundMatches().isEmpty) #expect(after.entry("back")?.categoryID == purchase.categoryID && after.entry("back")?.refundOf == "buy") } } @Suite struct Suggestions { @Test func historyPicksTheCategoryTheUserChoseBefore() throws { let store = try tempStore() try store.upsert([tx("a", day(1, 2), -30, "ZORBLAX LLC"), tx("b", day(0, 1), -31, "ZORBLAX LLC")]) try store.edit("a") { $0.categoryID = "health" } let s = try store.ledger().historySuggestions() #expect(s.map(\.entryID) == ["b"] && s.first?.categoryID == "health") } } @Suite struct Budgets2 { @Test func groupBudgetsAndMonthOverridesDontDoubleCount() throws { let store = try tempStore() let m = MonthKey.current try store.upsert([tx("g", m + "-01", -200, "SAFEWAY GROCERY"), tx("e", m + "-01", -50, "PG&E UTILITY BILL", category: "mcc:4900")]) try store.update { ws in var group = Budget(categoryID: "essentials", amount: 1000) group.monthAmounts = [m: 1200] ws.budgets = [group, Budget(categoryID: "groceries", amount: 400), Budget(categoryID: "dining", amount: 300)] } let ledger = try store.ledger() let essentials = try #require(ledger.budgetStatus().first { $0.id == "essentials" }) #expect(essentials.allowed == 1200) #expect(essentials.spent == ledger.spent("groceries", month: m) + ledger.spent("utilities", month: m)) #expect(ledger.isCoveredByGroupBudget("groceries") && !ledger.isCoveredByGroupBudget("dining")) let totals = ledger.budgetTotals() #expect(totals.budgeted == 1500) // essentials 1200 + dining 300; groceries sits inside essentials #expect(ledger.budgetName("essentials") == "Essentials") } @Test func rolloverUsesEachMonthsOwnAmount() throws { let store = try tempStore() try store.update { ws in var b = Budget(categoryID: "dining", amount: 100, rollover: true, startMonth: month(2)) b.monthAmounts = [month(2): 300] ws.budgets = [b] } let status = try #require(try store.ledger().budgetStatus().first) #expect(status.carried == 400) // 300 + 100 unspent } } @Suite struct Rules2 { @Test func previewShowsMatchesAndHandEditedOnes() throws { let store = try tempStore() 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")]) try store.edit("2") { $0.categoryID = "travel" } var rule = Rule(matchText: "uber", setCategoryID: "transport"); rule.enabled = false let preview = try store.ledger().preview(rule) #expect(Set(preview.matches.map(\.id)) == ["1", "2"]) #expect(preview.editedByHand.map(\.id) == ["2"]) } } @Suite struct Recaps { @Test func factsAndFigureGuard() throws { let store = try tempStore() try store.upsert([ tx("p", day(1, 1), 5000, "ACME PAYROLL DIRECT DEP"), tx("g", day(1, 4), -400, "SAFEWAY GROCERY"), tx("d", day(1, 6), -250, "CHIPOTLE RESTAURANT"), tx("d0", day(2, 6), -100, "CHIPOTLE RESTAURANT"), tx("p0", day(2, 1), 5000, "ACME PAYROLL DIRECT DEP") ]) let recap = try #require(try store.ledger().recap()) #expect(recap.spend == 650 && recap.income == 5000 && recap.net == 4350) #expect(recap.facts.contains("$4,350")) #expect(recap.movers.first?.change == 400 || recap.movers.contains { $0.change == 150 }) #expect(AskBucksley.recapFiguresAreValid("You kept $4,350 this month, nice.", recap: recap)) #expect(!AskBucksley.recapFiguresAreValid("You kept $4,999 this month.", recap: recap)) } } @Suite struct Exports { @Test func csvRoundTripsThroughTheImporter() throws { let store = try tempStore() try store.upsert([tx("1", day(0, 1), -12.5, "BLUE BOTTLE, COFFEE"), tx("2", day(0, 2), 3000, "ACME PAYROLL DIRECT DEP")]) try store.edit("1") { $0.note = "with \"Sam\""; $0.tags = ["work"] } let csv = Backup.csv(try store.ledger()) let parsed = try CSVImport.parse(csv, connectionID: "c", categories: Defaults.categories) #expect(parsed.transactions.count == 2) #expect(parsed.transactions.contains { $0.amount == -12.5 && $0.description.lowercased().contains("blue bottle") }) #expect(parsed.edits.contains { $0.note == "with \"Sam\"" && $0.tags == ["work"] }) } @Test func backupRestoresEverythingAndSavesTheOldData() throws { let store = try tempStore() try store.upsert([tx("1", day(0, 1), -12.5, "BLUE BOTTLE COFFEE")]) try store.update { $0.budgets = [Budget(categoryID: "dining", amount: 200)]; $0.connections = [Connection(kind: .plaid, name: "Bank")] ; $0.connections[0].plaidCursor = "abc" } let backup = try Backup.make(from: store) #expect(!String(decoding: backup, as: UTF8.self).contains("abc")) try store.upsert([tx("2", day(0, 2), -5, "LATER")]) try store.update { $0.budgets = [] } let saved = try Backup.restore(backup, into: store) #expect(FileManager.default.fileExists(atPath: saved.path)) #expect(try store.transactions().map(\.id) == ["1"]) #expect(try store.load().budgets.first?.amount == 200) #expect(throws: BucksleyError.self) { try Backup.read(Data("{}".utf8)) } } } @Suite struct CoinbaseTests { @Test func walletsBecomeCryptoHoldingsAndCash() async throws { let wallets = """ {"data":[ {"id":"w1","name":"BTC Wallet","type":"wallet","currency":{"code":"BTC","name":"Bitcoin"},"balance":{"amount":"0.5","currency":"BTC"}}, {"id":"w2","name":"USD Wallet","type":"fiat","currency":{"code":"USD","name":"US Dollar"},"balance":{"amount":"1234.56","currency":"USD"}}, {"id":"w3","name":"ETH Wallet","type":"wallet","currency":{"code":"ETH","name":"Ethereum"},"balance":{"amount":"0","currency":"ETH"}}, {"id":"w4","name":"ZZZ Wallet","type":"wallet","currency":{"code":"ZZZ","name":"Mystery"},"balance":{"amount":"7","currency":"ZZZ"}} ],"pagination":{"next_uri":null}} """ let rates = #"{"data":{"currency":"USD","rates":{"BTC":"0.00001","ETH":"0.0003"}}}"# let key = Coinbase.Key(name: "organizations/o/apiKeys/k", privateKey: P256.Signing.PrivateKey().pemRepresentation) let http = StubHTTP { req in if req.url!.path == "/v2/accounts" { #expect(req.value(forHTTPHeaderField: "Authorization")?.hasPrefix("Bearer ey") == true) return (200, wallets) } #expect(req.value(forHTTPHeaderField: "Authorization") == nil) return (200, rates) } let pull = try await Coinbase(key: key, http: http).pull(connectionID: "cb") let crypto = try #require(pull.accounts.first { $0.kind == .crypto }) #expect(crypto.balance == 50_000) #expect(crypto.holdings?.map(\.symbol) == ["BTC"]) #expect(pull.accounts.first { $0.id == "cb.usd" }?.balance == Decimal(string: "1234.56")) #expect(pull.warnings.first?.contains("ZZZ") == true) } @Test func jwtCarriesTheRequestAndVerifies() throws { let pk = P256.Signing.PrivateKey() let jwt = try Coinbase(key: .init(name: "kname", privateKey: pk.pemRepresentation)).jwt(method: "GET", path: "/v2/accounts") let parts = jwt.split(separator: ".").map(String.init) #expect(parts.count == 3) func decode(_ s: String) -> Data { var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/"); while b.count % 4 != 0 { b += "=" }; return Data(base64Encoded: b)! } let payload = try JSONSerialization.jsonObject(with: decode(parts[1])) as! [String: Any] #expect(payload["uri"] as? String == "GET api.coinbase.com/v2/accounts" && payload["sub"] as? String == "kname") let sig = try P256.Signing.ECDSASignature(rawRepresentation: decode(parts[2])) #expect(pk.publicKey.isValidSignature(sig, for: Data((parts[0] + "." + parts[1]).utf8))) // Ed25519 keys as Coinbase downloads them (base64 of seed + public key). let ed = Curve25519.Signing.PrivateKey() let edKey = (ed.rawRepresentation + ed.publicKey.rawRepresentation).base64EncodedString() let edJWT = try Coinbase(key: .init(name: "id", privateKey: edKey)).jwt(method: "GET", path: "/v2/accounts") let ep = edJWT.split(separator: ".").map(String.init) #expect(ed.publicKey.isValidSignature(decode(ep[2]), for: Data((ep[0] + "." + ep[1]).utf8))) #expect(Coinbase.Key(json: #"{"name":"n","privateKey":"-----BEGIN \("")EC PRIVATE KEY-----\nabc\n-----END EC PRIVATE KEY-----\n"}"#)?.privateKey.contains("\n") == true) } } @Suite struct CoinbaseSignInTests { @Test func signInSavesTheRefreshTokenAndEachSyncRotatesIt() async throws { let store = try tempStore() 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}}"# let rates = #"{"data":{"currency":"USD","rates":{}}}"# let counter = Counter() let http = StubHTTP { req in switch req.url!.path { case "/coinbase/token": let body = try! JSONSerialization.jsonObject(with: req.httpBody!) as! [String: String] let n = counter.next() if body["grant_type"] == "authorization_code" { #expect(body["code"] == "c0de" && body["code_verifier"] == "v") } else { #expect(body["refresh_token"] == "r\(n - 1)") } return (200, #"{"access_token":"a\#(n)","refresh_token":"r\#(n)","expires_in":3600}"#) case "/v2/accounts": #expect(req.value(forHTTPHeaderField: "Authorization")?.hasPrefix("Bearer a") == true) return (200, wallets) default: return (200, rates) } } let sync = BankSync(store: store, http: http) let connection = try await sync.connectCoinbase(signInCode: "c0de", verifier: "v") #expect(Keychain.get(.connection(connection.id))?.contains("r1") == true) _ = try await sync.sync(connection) #expect(Keychain.get(.connection(connection.id))?.contains("r2") == true) #expect(try store.load().accounts.first { $0.name == "Coinbase Cash" }?.balance == 50) } @Test func callbackStateMustMatch() throws { let request = CoinbaseSignIn.Request(url: URL(string: "https://x")!, state: "s1", verifier: "v") #expect(try CoinbaseSignIn.code(from: URL(string: "bucksley://coinbase/callback?code=abc&state=s1")!, expecting: request) == "abc") #expect(throws: BucksleyError.self) { try CoinbaseSignIn.code(from: URL(string: "bucksley://coinbase/callback?code=abc&state=nope")!, expecting: request) } } } final class Counter: @unchecked Sendable { private var n = 0 private let lock = NSLock() func next() -> Int { lock.lock(); defer { lock.unlock() }; n += 1; return n } } @Suite struct HistoryBackfill { /// An account that shows up after the first sync gets its 90 days once, not just the two weeks each /// later sync re-reads. @Test func anAccountLinkedLaterGetsItsHistory() async throws { Keychain.memory = Keychain.memory ?? [:] let store = try tempStore() let now = Date(timeIntervalSince1970: 1795600000) var connection = Connection(kind: .simplefin, name: "SimpleFIN") connection.lastSyncAt = now.addingTimeInterval(-86_400) try Keychain.set("https://u:p@bridge.example/simplefin", for: .connection(connection.id)) try store.update { $0.connections = [connection] } let old = Int(now.timeIntervalSince1970) - 60 * 86_400 let http = StubHTTP { req in let start = Int(URLComponents(url: req.url!, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "start-date" }!.value!)! let end = Int(URLComponents(url: req.url!, resolvingAgainstBaseURL: false)!.queryItems!.first { $0.name == "end-date" }!.value!)! let tx = (start...end).contains(old) ? #"[{"id":"T-OLD","posted":\#(old),"amount":"120","description":"Dividend"}]"# : "[]" return (200, #"{"errors":[],"accounts":[{"org":{"name":"Merrill Lynch"},"id":"ACT-IRA","name":"IRA-Edge- 5Z05","currency":"USD","balance":"1000","balance-date":1795600000,"transactions":\#(tx)}]}"#) } let sync = BankSync(store: store, http: http) _ = try await sync.sync(connection, now: now) #expect(try store.load().accounts.first?.historyLoaded == true) #expect(try store.ledger().entries.contains { $0.transaction.description == "Dividend" }) } }