import Foundation // MARK: Accounts and connections public enum AccountKind: String, Codable, CaseIterable, Sendable { case checking, savings, credit, investment, loan, crypto, property, other public var title: String { switch self { case .checking: "Checking" case .savings: "Savings" case .credit: "Credit card" case .investment: "Investment" case .loan: "Loan" case .crypto: "Crypto" case .property: "Property" case .other: "Other" } } public var group: AccountGroup { switch self { case .checking, .savings: .cash case .credit: .credit case .investment, .crypto: .investments case .loan: .loans case .property, .other: .other } } public var isLiability: Bool { self == .credit || self == .loan } /// Best guess from a bank's own words ("Sapphire Card", "Roth IRA", "Adv Plus Banking"). /// Matches whole words, so an account number like "5401" never reads as a 401(k). public static func guess(from text: String) -> AccountKind { let words = text.lowercased() .replacingOccurrences(of: "(k)", with: "k").replacingOccurrences(of: "(b)", with: "b") .split { !$0.isLetter && !$0.isNumber } .filter { !$0.allSatisfy(\.isNumber) } let padded = " " + words.joined(separator: " ") + " " func has(_ phrases: String...) -> Bool { phrases.contains { padded.contains(" \($0) ") } } if has("credit card", "card", "visa", "mastercard", "amex", "american express", "sapphire", "cash rewards", "rewards card", "signature") { return .credit } if has("mortgage", "loan", "auto loan", "student loan", "heloc", "line of credit") { return .loan } if has("crypto", "bitcoin", "coinbase", "btc", "eth", "ethereum") { return .crypto } if has("brokerage", "ira", "rollover", "401k", "403b", "457b", "529", "invest", "investment", "investments", "investing", "roth", "hsa", "retirement", "stock", "stocks", "cma", "self directed", "merrill", "edge", "fidelity", "vanguard", "schwab", "robinhood", "etrade", "sep") { return .investment } if has("saving", "savings", "money market", "mma", "cd", "certificate") { return .savings } if has("checking", "chequing", "debit", "spend", "spending", "banking", "everyday", "share draft") { return .checking } return .other } } public enum AccountGroup: String, Codable, CaseIterable, Sendable { case cash, credit, investments, loans, other public var title: String { switch self { case .cash: "Cash" case .credit: "Credit" case .investments: "Investments" case .loans: "Loans" case .other: "Other" } } } public enum SourceKind: String, Codable, CaseIterable, Sendable { case simplefin, plaid, financekit, csv, manual, coinbase /// Pulled live by the Mac's bank sync. public var syncs: Bool { self == .simplefin || self == .plaid || self == .coinbase } public var title: String { switch self { case .simplefin: "SimpleFIN Bridge" case .plaid: "Plaid (your keys)" case .coinbase: "Coinbase (your read-only key)" case .financekit: "Apple Wallet" case .csv: "CSV import" case .manual: "Manual" } } } /// One bank link. Its secret (SimpleFIN access URL, Plaid access token) lives in the Keychain under /// the connection's ID, never here. public struct Connection: Codable, Identifiable, Hashable, Sendable { public var id: String public var kind: SourceKind public var name: String public var createdAt: Date public var lastSyncAt: Date? public var lastError: String? /// Plaid only: "sandbox" or "production", and the /transactions/sync cursor (not a secret). public var plaidEnvironment: String? public var plaidCursor: String? public init(id: String = UUID().uuidString, kind: SourceKind, name: String, createdAt: Date = .now, plaidEnvironment: String? = nil) { self.id = id; self.kind = kind; self.name = name; self.createdAt = createdAt self.plaidEnvironment = plaidEnvironment } } public struct Account: Codable, Identifiable, Hashable, Sendable { public var id: String public var connectionID: String public var name: String public var institution: String public var kind: AccountKind /// Signed the way it counts toward net worth: assets positive, money owed negative. public var balance: Decimal public var available: Decimal? public var currency: String public var balanceDate: Date public var hidden: Bool = false public var nickname: String? /// True once the user picked the type by hand; bank syncs then keep it. public var kindChosen: Bool? /// True once the account's first 90 days have been pulled. An account linked after the first sync /// would otherwise only get the two weeks each later sync re-reads. public var historyLoaded: Bool? /// Positions in a brokerage account, when the connector sends them (SimpleFIN Bridge does). public var holdings: [Holding]? public init(id: String, connectionID: String, name: String, institution: String, kind: AccountKind, balance: Decimal, available: Decimal? = nil, currency: String = "USD", balanceDate: Date = .now) { self.id = id; self.connectionID = connectionID; self.name = name; self.institution = institution self.kind = kind; self.balance = balance; self.available = available; self.currency = currency self.balanceDate = balanceDate } public var displayName: String { nickname ?? name } } /// One position in an investment account. public struct Holding: Codable, Hashable, Identifiable, Sendable { public var id: String public var symbol: String? public var name: String public var shares: Decimal? public var marketValue: Decimal public var costBasis: Decimal? public init(id: String, symbol: String?, name: String, shares: Decimal?, marketValue: Decimal, costBasis: Decimal?) { self.id = id; self.symbol = symbol; self.name = name; self.shares = shares; self.marketValue = marketValue; self.costBasis = costBasis } /// Gain since purchase, when the cost basis is known. public var gain: Decimal? { costBasis.map { marketValue - $0 } } } /// A day's closing balance for one account, used for the net worth chart. public struct BalancePoint: Codable, Hashable, Sendable { public var accountID: String public var day: String public var balance: Decimal public init(accountID: String, day: String, balance: Decimal) { self.accountID = accountID; self.day = day; self.balance = balance } } // MARK: Transactions /// What the bank sent. Never edited by the user; edits live in `TransactionEdit` so a re-sync can't /// overwrite them ("user edits win over bank data"). public struct Transaction: Codable, Identifiable, Hashable, Sendable { public var id: String public var accountID: String public var day: String /// Negative is money out, positive is money in. public var amount: Decimal public var description: String public var payee: String? public var bankCategory: String? public var pending: Bool public var importedAt: Date public init(id: String, accountID: String, day: String, amount: Decimal, description: String, payee: String? = nil, bankCategory: String? = nil, pending: Bool = false, importedAt: Date = .now) { self.id = id; self.accountID = accountID; self.day = day; self.amount = amount; self.description = description self.payee = payee; self.bankCategory = bankCategory; self.pending = pending; self.importedAt = importedAt } } public struct Split: Codable, Hashable, Identifiable, Sendable { public var id: String public var amount: Decimal public var categoryID: String public var note: String? public init(id: String = UUID().uuidString, amount: Decimal, categoryID: String, note: String? = nil) { self.id = id; self.amount = amount; self.categoryID = categoryID; self.note = note } } /// The user's changes to one transaction, from the Mac, the iPhone or an agent. Nil fields keep the /// bank's (or a rule's) value. Two-way iCloud sync merges these per transaction: the newest wins. public struct TransactionEdit: Codable, Hashable, Sendable { public var transactionID: String public var name: String? public var categoryID: String? public var note: String? public var tags: [String]? public var reviewed: Bool? public var splits: [Split]? public var excluded: Bool? /// The purchase this credit refunds, once the user accepts the match. public var refundOf: String? public var updatedAt: Date public var device: String public init(transactionID: String, updatedAt: Date = .now, device: String = DeviceName.current) { self.transactionID = transactionID; self.updatedAt = updatedAt; self.device = device } /// Field by field, so a phone that only marked a row reviewed doesn't erase the Mac's note. public func merged(over older: TransactionEdit) -> TransactionEdit { var out = older if let name { out.name = name } if let categoryID { out.categoryID = categoryID } if let note { out.note = note } if let tags { out.tags = tags } if let reviewed { out.reviewed = reviewed } if let splits { out.splits = splits } if let excluded { out.excluded = excluded } if let refundOf { out.refundOf = refundOf } out.updatedAt = max(updatedAt, older.updatedAt) out.device = updatedAt >= older.updatedAt ? device : older.device return out } } /// A transaction as the app shows it: bank data, then rules, then the user's edits on top. public struct LedgerEntry: Identifiable, Hashable, Sendable { public let transaction: Transaction public var name: String public var categoryID: String public var note: String? public var tags: [String] public var reviewed: Bool public var splits: [Split] public var excluded: Bool public var ruleID: String? public var edited: Bool /// True when the user picked the category by hand (not a rule or Bucksley's guess). public var categoryChosen: Bool = false public var refundOf: String? public var id: String { transaction.id } public var day: String { transaction.day } public var amount: Decimal { transaction.amount } public var accountID: String { transaction.accountID } /// Category amounts, honoring splits. Splits carry positive amounts of the outflow. public var parts: [(categoryID: String, amount: Decimal)] { guard !splits.isEmpty else { return [(categoryID, amount)] } let sign: Decimal = amount < 0 ? -1 : 1 return splits.map { ($0.categoryID, $0.amount * sign) } } } // MARK: Categories, rules, budgets, recurring public enum CategoryKind: String, Codable, CaseIterable, Sendable { case expense, income, transfer } public struct CategoryGroup: Codable, Identifiable, Hashable, Sendable { public var id: String public var name: String public init(id: String, name: String) { self.id = id; self.name = name } } public struct Category: Codable, Identifiable, Hashable, Sendable { public var id: String public var name: String public var symbol: String public var groupID: String public var colorIndex: Int public var kind: CategoryKind /// The user's own emoji; nil falls back to the starter emoji for built-in categories. public var emoji: String? /// Spending the person can't easily change, such as rent, insurance or utilities. Smart budgets set /// these at what's actually spent and never cut them. Nil uses Bucksley's guess from the name. public var fixed: Bool? public init(id: String, name: String, symbol: String, groupID: String, colorIndex: Int, kind: CategoryKind = .expense, emoji: String? = nil, fixed: Bool? = nil) { self.id = id; self.name = name; self.symbol = symbol; self.groupID = groupID; self.colorIndex = colorIndex; self.kind = kind; self.emoji = emoji; self.fixed = fixed } /// Whether smart budgets treat this as fixed spending. public var isFixed: Bool { if let fixed { return fixed } if Defaults.fixedIDs.contains(id) { return true } let words = name.lowercased() return Defaults.fixedWords.contains { words.contains($0) } } /// What every pill, row and budget shows beside the name. public var icon: String { emoji ?? Defaults.emoji[id] ?? "🏷️" } } /// "When the name contains X (and the amount is in range, on this account), set these." public struct Rule: Codable, Identifiable, Hashable, Sendable { public var id: String public var matchText: String public var minAmount: Decimal? public var maxAmount: Decimal? public var accountID: String? public var setCategoryID: String? public var rename: String? public var addTags: [String] public var markReviewed: Bool public var enabled: Bool public init(id: String = UUID().uuidString, matchText: String, minAmount: Decimal? = nil, maxAmount: Decimal? = nil, accountID: String? = nil, setCategoryID: String? = nil, rename: String? = nil, addTags: [String] = [], markReviewed: Bool = false, enabled: Bool = true) { self.id = id; self.matchText = matchText; self.minAmount = minAmount; self.maxAmount = maxAmount self.accountID = accountID; self.setCategoryID = setCategoryID; self.rename = rename self.addTags = addTags; self.markReviewed = markReviewed; self.enabled = enabled } public func matches(_ tx: Transaction) -> Bool { guard enabled, !matchText.isEmpty else { return false } let haystack = [tx.description, tx.payee ?? ""].joined(separator: " ").lowercased() guard haystack.contains(matchText.lowercased()) else { return false } let size = abs(tx.amount) if let minAmount, size < minAmount { return false } if let maxAmount, size > maxAmount { return false } if let accountID, tx.accountID != accountID { return false } return true } } /// A monthly budget on one category, or on a whole category group when `categoryID` is a group's ID. /// A group budget covers its member categories as they are grouped today, in every month. public struct Budget: Codable, Identifiable, Hashable, Sendable { public var categoryID: String public var amount: Decimal public var rollover: Bool /// First month the budget counts for rollover, "yyyy-MM". public var startMonth: String /// A different amount for particular months ("yyyy-MM" → amount), like a bigger December. public var monthAmounts: [String: Decimal]? public var id: String { categoryID } public init(categoryID: String, amount: Decimal, rollover: Bool = false, startMonth: String = MonthKey.current) { self.categoryID = categoryID; self.amount = amount; self.rollover = rollover; self.startMonth = startMonth } /// What this budget allows in a month, honoring a one-month change. public func amount(for month: String) -> Decimal { monthAmounts?[month] ?? amount } } public enum Cadence: String, Codable, CaseIterable, Sendable { case weekly, biweekly, monthly, quarterly, yearly public var days: Int { switch self { case .weekly: 7; case .biweekly: 14; case .monthly: 30; case .quarterly: 91; case .yearly: 365 } } public var title: String { rawValue.capitalized } } public enum RecurringStatus: String, Codable, Sendable { case detected, confirmed, dismissed } public struct RecurringItem: Identifiable, Hashable, Sendable { public var id: String public var name: String public var cadence: Cadence public var amount: Decimal public var lastDay: String public var nextDay: String public var categoryID: String public var count: Int public var status: RecurringStatus } // MARK: Agents and settings public struct AgentAction: Codable, Identifiable, Hashable, Sendable { public var id: String public var at: Date public var client: String public var tool: String public var summary: String public init(client: String, tool: String, summary: String, at: Date = .now) { id = UUID().uuidString; self.at = at; self.client = client; self.tool = tool; self.summary = summary } } public enum AskProvider: String, Codable, CaseIterable, Sendable { case apple, claude, openai case claudeCode = "claude-code", codex /// Gemini through the Antigravity CLI (`agy`). It answers from the summary only, with no tools. case gemini public var title: String { switch self { case .apple: "Apple Intelligence" case .claude: "Claude API key" case .openai: "OpenAI API key" case .claudeCode: "Claude Code" case .codex: "Codex" case .gemini: "Gemini" } } /// An agent installed on this Mac, signed in with the person's own account. public var isAgent: Bool { self == .claudeCode || self == .codex || self == .gemini } /// The agent reads more through Bucksley's read-only MCP tools. public var usesTools: Bool { self == .claudeCode || self == .codex } /// The company that gets the question. public var company: String { switch self { case .apple: "Apple" case .claude, .claudeCode: "Anthropic" case .openai, .codex: "OpenAI" case .gemini: "Google" } } } public struct Settings: Codable, Hashable, Sendable { public var agentsCanWrite = false public var agentsCanSetKeys = false public var askProvider: AskProvider = .apple public var claudeModel = "claude-opus-5-5" public var openAIModel = "gpt-6.1-sol" /// Model for each installed agent ("claude-code", "codex"); missing uses the agent's default. public var agentModels: [String: String]? public var shareWithIPhone = true public var lastSyncAt: Date? public var lastSharedAt: Date? /// Bank sync runs this often while the Mac app is open. public var syncEveryHours = 6 public init() {} /// The model to ask for with this answer source. public func model(for provider: AskProvider) -> String? { switch provider { case .apple: nil case .claude: claudeModel case .openai: openAIModel case .claudeCode, .codex, .gemini: agentModels?[provider.rawValue] } } } public struct Workspace: Codable, Sendable { public var connections: [Connection] = [] public var accounts: [Account] = [] public var groups: [CategoryGroup] = Defaults.groups public var categories: [Category] = Defaults.categories public var rules: [Rule] = [] public var budgets: [Budget] = [] public var recurring: [String: RecurringStatus] = [:] public var settings = Settings() public var agentLog: [AgentAction] = [] public init() {} public func category(_ id: String?) -> Category? { categories.first { $0.id == id } } public func account(_ id: String) -> Account? { accounts.first { $0.id == id } } public enum CodingKeys: String, CodingKey { case connections, accounts, groups, categories, rules, budgets, recurring, settings, agentLog } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) connections = try c.decodeIfPresent([Connection].self, forKey: .connections) ?? [] accounts = try c.decodeIfPresent([Account].self, forKey: .accounts) ?? [] groups = try c.decodeIfPresent([CategoryGroup].self, forKey: .groups) ?? Defaults.groups categories = try c.decodeIfPresent([Category].self, forKey: .categories) ?? Defaults.categories rules = try c.decodeIfPresent([Rule].self, forKey: .rules) ?? [] budgets = try c.decodeIfPresent([Budget].self, forKey: .budgets) ?? [] recurring = try c.decodeIfPresent([String: RecurringStatus].self, forKey: .recurring) ?? [:] settings = try c.decodeIfPresent(Settings.self, forKey: .settings) ?? Settings() agentLog = try c.decodeIfPresent([AgentAction].self, forKey: .agentLog) ?? [] } } public enum BucksleyError: LocalizedError, Sendable { case missing(String), notAllowed(String), network(String), invalid(String) public var errorDescription: String? { switch self { case .missing(let s), .notAllowed(let s), .network(let s), .invalid(let s): s } } } // MARK: Days, months and money public enum DayKey { static let formatter: DateFormatter = { let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.locale = Locale(identifier: "en_US_POSIX") f.timeZone = .current; f.dateFormat = "yyyy-MM-dd"; return f }() public static func from(_ date: Date) -> String { formatter.string(from: date) } public static func date(_ key: String) -> Date? { formatter.date(from: key) } public static var today: String { from(.now) } public static func adding(_ days: Int, to key: String) -> String { guard let d = date(key), let out = Calendar.current.date(byAdding: .day, value: days, to: d) else { return key } return from(out) } public static func between(_ a: String, _ b: String) -> Int { guard let x = date(a), let y = date(b) else { return 0 } return Calendar.current.dateComponents([.day], from: x, to: y).day ?? 0 } /// The last `n` days ending today, oldest first. public static func lastDays(_ n: Int, endingOn end: String = today) -> [String] { (0.. String { String(day.prefix(7)) } public static func adding(_ months: Int, to month: String) -> String { guard let d = DayKey.date(month + "-01"), let out = Calendar.current.date(byAdding: .month, value: months, to: d) else { return month } return String(DayKey.from(out).prefix(7)) } public static func days(in month: String) -> Int { guard let d = DayKey.date(month + "-01") else { return 30 } return Calendar.current.range(of: .day, in: .month, for: d)?.count ?? 30 } public static func title(_ month: String) -> String { guard let d = DayKey.date(month + "-01") else { return month } return d.formatted(.dateTime.month(.wide).year()) } } public enum DeviceName { public static var current: String { #if os(macOS) Host.current().localizedName ?? "Mac" #else "iPhone" #endif } } public extension Decimal { /// Parsed from the decimal text, which avoids the binary noise NSDecimalNumber.doubleValue adds. var double: Double { Double(description) ?? NSDecimalNumber(decimal: self).doubleValue } init(cents: Int) { self = Decimal(cents) / 100 } /// Parses "1,234.56", "-12.30", "(45.00)" and "$9.99". init?(money text: String) { var t = text.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "$", with: "").replacingOccurrences(of: ",", with: "") var negative = false if t.hasPrefix("(") && t.hasSuffix(")") { negative = true; t = String(t.dropFirst().dropLast()) } guard !t.isEmpty, let value = Decimal(string: t, locale: Locale(identifier: "en_US_POSIX")) else { return nil } self = negative ? -value : value } func rounded(_ places: Int = 2) -> Decimal { var input = self, out = Decimal() NSDecimalRound(&out, &input, places, .bankers) return out } } public enum Money { public static func format(_ value: Decimal, cents: Bool = true, signed: Bool = false, currency: String = "USD") -> String { let style = Decimal.FormatStyle.Currency(code: currency).precision(.fractionLength(cents ? 2 : 0)) let text = abs(value).formatted(style) if value < 0 { return "−" + text } return signed && value > 0 ? "+" + text : text } /// "$142.4k", "$1.2M" for chart axes and tight cards. public static func short(_ value: Decimal) -> String { let v = value.double, a = Swift.abs(v), sign = v < 0 ? "−" : "" switch a { case 1_000_000...: return sign + "$" + String(format: "%.1fM", a / 1_000_000) case 10_000...: return sign + "$" + String(format: "%.0fk", a / 1_000) case 1_000...: return sign + "$" + String(format: "%.1fk", a / 1_000) default: return sign + "$" + String(format: "%.0f", a) } } } public func abs(_ value: Decimal) -> Decimal { value < 0 ? -value : value }