Bucksley / app · bucksley.ai / Sources / BucksleyKit / Model.swift
| 1 | import Foundation |
| 2 | |
| 3 | // MARK: Accounts and connections |
| 4 | |
| 5 | public enum AccountKind: String, Codable, CaseIterable, Sendable { |
| 6 | case checking, savings, credit, investment, loan, crypto, property, other |
| 7 | |
| 8 | public var title: String { |
| 9 | switch self { |
| 10 | case .checking: "Checking" |
| 11 | case .savings: "Savings" |
| 12 | case .credit: "Credit card" |
| 13 | case .investment: "Investment" |
| 14 | case .loan: "Loan" |
| 15 | case .crypto: "Crypto" |
| 16 | case .property: "Property" |
| 17 | case .other: "Other" |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | public var group: AccountGroup { |
| 22 | switch self { |
| 23 | case .checking, .savings: .cash |
| 24 | case .credit: .credit |
| 25 | case .investment, .crypto: .investments |
| 26 | case .loan: .loans |
| 27 | case .property, .other: .other |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | public var isLiability: Bool { self == .credit || self == .loan } |
| 32 | |
| 33 | /// Best guess from a bank's own words ("Sapphire Card", "Roth IRA", "Adv Plus Banking"). |
| 34 | /// Matches whole words, so an account number like "5401" never reads as a 401(k). |
| 35 | public static func guess(from text: String) -> AccountKind { |
| 36 | let words = text.lowercased() |
| 37 | .replacingOccurrences(of: "(k)", with: "k").replacingOccurrences(of: "(b)", with: "b") |
| 38 | .split { !$0.isLetter && !$0.isNumber } |
| 39 | .filter { !$0.allSatisfy(\.isNumber) } |
| 40 | let padded = " " + words.joined(separator: " ") + " " |
| 41 | func has(_ phrases: String...) -> Bool { phrases.contains { padded.contains(" \($0) ") } } |
| 42 | if has("credit card", "card", "visa", "mastercard", "amex", "american express", "sapphire", "cash rewards", "rewards card", "signature") { return .credit } |
| 43 | if has("mortgage", "loan", "auto loan", "student loan", "heloc", "line of credit") { return .loan } |
| 44 | if has("crypto", "bitcoin", "coinbase", "btc", "eth", "ethereum") { return .crypto } |
| 45 | if has("brokerage", "ira", "rollover", "401k", "403b", "457b", "529", "invest", "investment", "investments", "investing", "roth", "hsa", |
| 46 | "retirement", "stock", "stocks", "cma", "self directed", "merrill", "edge", "fidelity", "vanguard", "schwab", "robinhood", "etrade", "sep") { return .investment } |
| 47 | if has("saving", "savings", "money market", "mma", "cd", "certificate") { return .savings } |
| 48 | if has("checking", "chequing", "debit", "spend", "spending", "banking", "everyday", "share draft") { return .checking } |
| 49 | return .other |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public enum AccountGroup: String, Codable, CaseIterable, Sendable { |
| 54 | case cash, credit, investments, loans, other |
| 55 | public var title: String { |
| 56 | switch self { |
| 57 | case .cash: "Cash" |
| 58 | case .credit: "Credit" |
| 59 | case .investments: "Investments" |
| 60 | case .loans: "Loans" |
| 61 | case .other: "Other" |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public enum SourceKind: String, Codable, CaseIterable, Sendable { |
| 67 | case simplefin, plaid, financekit, csv, manual, coinbase |
| 68 | /// Pulled live by the Mac's bank sync. |
| 69 | public var syncs: Bool { self == .simplefin || self == .plaid || self == .coinbase } |
| 70 | public var title: String { |
| 71 | switch self { |
| 72 | case .simplefin: "SimpleFIN Bridge" |
| 73 | case .plaid: "Plaid (your keys)" |
| 74 | case .coinbase: "Coinbase (your read-only key)" |
| 75 | case .financekit: "Apple Wallet" |
| 76 | case .csv: "CSV import" |
| 77 | case .manual: "Manual" |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// One bank link. Its secret (SimpleFIN access URL, Plaid access token) lives in the Keychain under |
| 83 | /// the connection's ID, never here. |
| 84 | public struct Connection: Codable, Identifiable, Hashable, Sendable { |
| 85 | public var id: String |
| 86 | public var kind: SourceKind |
| 87 | public var name: String |
| 88 | public var createdAt: Date |
| 89 | public var lastSyncAt: Date? |
| 90 | public var lastError: String? |
| 91 | /// Plaid only: "sandbox" or "production", and the /transactions/sync cursor (not a secret). |
| 92 | public var plaidEnvironment: String? |
| 93 | public var plaidCursor: String? |
| 94 | |
| 95 | public init(id: String = UUID().uuidString, kind: SourceKind, name: String, createdAt: Date = .now, |
| 96 | plaidEnvironment: String? = nil) { |
| 97 | self.id = id; self.kind = kind; self.name = name; self.createdAt = createdAt |
| 98 | self.plaidEnvironment = plaidEnvironment |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | public struct Account: Codable, Identifiable, Hashable, Sendable { |
| 103 | public var id: String |
| 104 | public var connectionID: String |
| 105 | public var name: String |
| 106 | public var institution: String |
| 107 | public var kind: AccountKind |
| 108 | /// Signed the way it counts toward net worth: assets positive, money owed negative. |
| 109 | public var balance: Decimal |
| 110 | public var available: Decimal? |
| 111 | public var currency: String |
| 112 | public var balanceDate: Date |
| 113 | public var hidden: Bool = false |
| 114 | public var nickname: String? |
| 115 | /// True once the user picked the type by hand; bank syncs then keep it. |
| 116 | public var kindChosen: Bool? |
| 117 | /// True once the account's first 90 days have been pulled. An account linked after the first sync |
| 118 | /// would otherwise only get the two weeks each later sync re-reads. |
| 119 | public var historyLoaded: Bool? |
| 120 | /// Positions in a brokerage account, when the connector sends them (SimpleFIN Bridge does). |
| 121 | public var holdings: [Holding]? |
| 122 | |
| 123 | public init(id: String, connectionID: String, name: String, institution: String, kind: AccountKind, |
| 124 | balance: Decimal, available: Decimal? = nil, currency: String = "USD", balanceDate: Date = .now) { |
| 125 | self.id = id; self.connectionID = connectionID; self.name = name; self.institution = institution |
| 126 | self.kind = kind; self.balance = balance; self.available = available; self.currency = currency |
| 127 | self.balanceDate = balanceDate |
| 128 | } |
| 129 | |
| 130 | public var displayName: String { nickname ?? name } |
| 131 | } |
| 132 | |
| 133 | /// One position in an investment account. |
| 134 | public struct Holding: Codable, Hashable, Identifiable, Sendable { |
| 135 | public var id: String |
| 136 | public var symbol: String? |
| 137 | public var name: String |
| 138 | public var shares: Decimal? |
| 139 | public var marketValue: Decimal |
| 140 | public var costBasis: Decimal? |
| 141 | public init(id: String, symbol: String?, name: String, shares: Decimal?, marketValue: Decimal, costBasis: Decimal?) { |
| 142 | self.id = id; self.symbol = symbol; self.name = name; self.shares = shares; self.marketValue = marketValue; self.costBasis = costBasis |
| 143 | } |
| 144 | /// Gain since purchase, when the cost basis is known. |
| 145 | public var gain: Decimal? { costBasis.map { marketValue - $0 } } |
| 146 | } |
| 147 | |
| 148 | /// A day's closing balance for one account, used for the net worth chart. |
| 149 | public struct BalancePoint: Codable, Hashable, Sendable { |
| 150 | public var accountID: String |
| 151 | public var day: String |
| 152 | public var balance: Decimal |
| 153 | public init(accountID: String, day: String, balance: Decimal) { self.accountID = accountID; self.day = day; self.balance = balance } |
| 154 | } |
| 155 | |
| 156 | // MARK: Transactions |
| 157 | |
| 158 | /// What the bank sent. Never edited by the user; edits live in `TransactionEdit` so a re-sync can't |
| 159 | /// overwrite them ("user edits win over bank data"). |
| 160 | public struct Transaction: Codable, Identifiable, Hashable, Sendable { |
| 161 | public var id: String |
| 162 | public var accountID: String |
| 163 | public var day: String |
| 164 | /// Negative is money out, positive is money in. |
| 165 | public var amount: Decimal |
| 166 | public var description: String |
| 167 | public var payee: String? |
| 168 | public var bankCategory: String? |
| 169 | public var pending: Bool |
| 170 | public var importedAt: Date |
| 171 | |
| 172 | public init(id: String, accountID: String, day: String, amount: Decimal, description: String, |
| 173 | payee: String? = nil, bankCategory: String? = nil, pending: Bool = false, importedAt: Date = .now) { |
| 174 | self.id = id; self.accountID = accountID; self.day = day; self.amount = amount; self.description = description |
| 175 | self.payee = payee; self.bankCategory = bankCategory; self.pending = pending; self.importedAt = importedAt |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | public struct Split: Codable, Hashable, Identifiable, Sendable { |
| 180 | public var id: String |
| 181 | public var amount: Decimal |
| 182 | public var categoryID: String |
| 183 | public var note: String? |
| 184 | public init(id: String = UUID().uuidString, amount: Decimal, categoryID: String, note: String? = nil) { |
| 185 | self.id = id; self.amount = amount; self.categoryID = categoryID; self.note = note |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// The user's changes to one transaction, from the Mac, the iPhone or an agent. Nil fields keep the |
| 190 | /// bank's (or a rule's) value. Two-way iCloud sync merges these per transaction: the newest wins. |
| 191 | public struct TransactionEdit: Codable, Hashable, Sendable { |
| 192 | public var transactionID: String |
| 193 | public var name: String? |
| 194 | public var categoryID: String? |
| 195 | public var note: String? |
| 196 | public var tags: [String]? |
| 197 | public var reviewed: Bool? |
| 198 | public var splits: [Split]? |
| 199 | public var excluded: Bool? |
| 200 | /// The purchase this credit refunds, once the user accepts the match. |
| 201 | public var refundOf: String? |
| 202 | public var updatedAt: Date |
| 203 | public var device: String |
| 204 | |
| 205 | public init(transactionID: String, updatedAt: Date = .now, device: String = DeviceName.current) { |
| 206 | self.transactionID = transactionID; self.updatedAt = updatedAt; self.device = device |
| 207 | } |
| 208 | |
| 209 | /// Field by field, so a phone that only marked a row reviewed doesn't erase the Mac's note. |
| 210 | public func merged(over older: TransactionEdit) -> TransactionEdit { |
| 211 | var out = older |
| 212 | if let name { out.name = name } |
| 213 | if let categoryID { out.categoryID = categoryID } |
| 214 | if let note { out.note = note } |
| 215 | if let tags { out.tags = tags } |
| 216 | if let reviewed { out.reviewed = reviewed } |
| 217 | if let splits { out.splits = splits } |
| 218 | if let excluded { out.excluded = excluded } |
| 219 | if let refundOf { out.refundOf = refundOf } |
| 220 | out.updatedAt = max(updatedAt, older.updatedAt) |
| 221 | out.device = updatedAt >= older.updatedAt ? device : older.device |
| 222 | return out |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /// A transaction as the app shows it: bank data, then rules, then the user's edits on top. |
| 227 | public struct LedgerEntry: Identifiable, Hashable, Sendable { |
| 228 | public let transaction: Transaction |
| 229 | public var name: String |
| 230 | public var categoryID: String |
| 231 | public var note: String? |
| 232 | public var tags: [String] |
| 233 | public var reviewed: Bool |
| 234 | public var splits: [Split] |
| 235 | public var excluded: Bool |
| 236 | public var ruleID: String? |
| 237 | public var edited: Bool |
| 238 | /// True when the user picked the category by hand (not a rule or Bucksley's guess). |
| 239 | public var categoryChosen: Bool = false |
| 240 | public var refundOf: String? |
| 241 | |
| 242 | public var id: String { transaction.id } |
| 243 | public var day: String { transaction.day } |
| 244 | public var amount: Decimal { transaction.amount } |
| 245 | public var accountID: String { transaction.accountID } |
| 246 | |
| 247 | /// Category amounts, honoring splits. Splits carry positive amounts of the outflow. |
| 248 | public var parts: [(categoryID: String, amount: Decimal)] { |
| 249 | guard !splits.isEmpty else { return [(categoryID, amount)] } |
| 250 | let sign: Decimal = amount < 0 ? -1 : 1 |
| 251 | return splits.map { ($0.categoryID, $0.amount * sign) } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // MARK: Categories, rules, budgets, recurring |
| 256 | |
| 257 | public enum CategoryKind: String, Codable, CaseIterable, Sendable { case expense, income, transfer } |
| 258 | |
| 259 | public struct CategoryGroup: Codable, Identifiable, Hashable, Sendable { |
| 260 | public var id: String |
| 261 | public var name: String |
| 262 | public init(id: String, name: String) { self.id = id; self.name = name } |
| 263 | } |
| 264 | |
| 265 | public struct Category: Codable, Identifiable, Hashable, Sendable { |
| 266 | public var id: String |
| 267 | public var name: String |
| 268 | public var symbol: String |
| 269 | public var groupID: String |
| 270 | public var colorIndex: Int |
| 271 | public var kind: CategoryKind |
| 272 | /// The user's own emoji; nil falls back to the starter emoji for built-in categories. |
| 273 | public var emoji: String? |
| 274 | /// Spending the person can't easily change, such as rent, insurance or utilities. Smart budgets set |
| 275 | /// these at what's actually spent and never cut them. Nil uses Bucksley's guess from the name. |
| 276 | public var fixed: Bool? |
| 277 | public init(id: String, name: String, symbol: String, groupID: String, colorIndex: Int, kind: CategoryKind = .expense, emoji: String? = nil, fixed: Bool? = nil) { |
| 278 | self.id = id; self.name = name; self.symbol = symbol; self.groupID = groupID; self.colorIndex = colorIndex; self.kind = kind; self.emoji = emoji; self.fixed = fixed |
| 279 | } |
| 280 | |
| 281 | /// Whether smart budgets treat this as fixed spending. |
| 282 | public var isFixed: Bool { |
| 283 | if let fixed { return fixed } |
| 284 | if Defaults.fixedIDs.contains(id) { return true } |
| 285 | let words = name.lowercased() |
| 286 | return Defaults.fixedWords.contains { words.contains($0) } |
| 287 | } |
| 288 | |
| 289 | /// What every pill, row and budget shows beside the name. |
| 290 | public var icon: String { emoji ?? Defaults.emoji[id] ?? "🏷️" } |
| 291 | } |
| 292 | |
| 293 | /// "When the name contains X (and the amount is in range, on this account), set these." |
| 294 | public struct Rule: Codable, Identifiable, Hashable, Sendable { |
| 295 | public var id: String |
| 296 | public var matchText: String |
| 297 | public var minAmount: Decimal? |
| 298 | public var maxAmount: Decimal? |
| 299 | public var accountID: String? |
| 300 | public var setCategoryID: String? |
| 301 | public var rename: String? |
| 302 | public var addTags: [String] |
| 303 | public var markReviewed: Bool |
| 304 | public var enabled: Bool |
| 305 | |
| 306 | public init(id: String = UUID().uuidString, matchText: String, minAmount: Decimal? = nil, maxAmount: Decimal? = nil, |
| 307 | accountID: String? = nil, setCategoryID: String? = nil, rename: String? = nil, addTags: [String] = [], |
| 308 | markReviewed: Bool = false, enabled: Bool = true) { |
| 309 | self.id = id; self.matchText = matchText; self.minAmount = minAmount; self.maxAmount = maxAmount |
| 310 | self.accountID = accountID; self.setCategoryID = setCategoryID; self.rename = rename |
| 311 | self.addTags = addTags; self.markReviewed = markReviewed; self.enabled = enabled |
| 312 | } |
| 313 | |
| 314 | public func matches(_ tx: Transaction) -> Bool { |
| 315 | guard enabled, !matchText.isEmpty else { return false } |
| 316 | let haystack = [tx.description, tx.payee ?? ""].joined(separator: " ").lowercased() |
| 317 | guard haystack.contains(matchText.lowercased()) else { return false } |
| 318 | let size = abs(tx.amount) |
| 319 | if let minAmount, size < minAmount { return false } |
| 320 | if let maxAmount, size > maxAmount { return false } |
| 321 | if let accountID, tx.accountID != accountID { return false } |
| 322 | return true |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /// A monthly budget on one category, or on a whole category group when `categoryID` is a group's ID. |
| 327 | /// A group budget covers its member categories as they are grouped today, in every month. |
| 328 | public struct Budget: Codable, Identifiable, Hashable, Sendable { |
| 329 | public var categoryID: String |
| 330 | public var amount: Decimal |
| 331 | public var rollover: Bool |
| 332 | /// First month the budget counts for rollover, "yyyy-MM". |
| 333 | public var startMonth: String |
| 334 | /// A different amount for particular months ("yyyy-MM" → amount), like a bigger December. |
| 335 | public var monthAmounts: [String: Decimal]? |
| 336 | public var id: String { categoryID } |
| 337 | public init(categoryID: String, amount: Decimal, rollover: Bool = false, startMonth: String = MonthKey.current) { |
| 338 | self.categoryID = categoryID; self.amount = amount; self.rollover = rollover; self.startMonth = startMonth |
| 339 | } |
| 340 | |
| 341 | /// What this budget allows in a month, honoring a one-month change. |
| 342 | public func amount(for month: String) -> Decimal { monthAmounts?[month] ?? amount } |
| 343 | } |
| 344 | |
| 345 | public enum Cadence: String, Codable, CaseIterable, Sendable { |
| 346 | case weekly, biweekly, monthly, quarterly, yearly |
| 347 | public var days: Int { |
| 348 | switch self { case .weekly: 7; case .biweekly: 14; case .monthly: 30; case .quarterly: 91; case .yearly: 365 } |
| 349 | } |
| 350 | public var title: String { rawValue.capitalized } |
| 351 | } |
| 352 | |
| 353 | public enum RecurringStatus: String, Codable, Sendable { case detected, confirmed, dismissed } |
| 354 | |
| 355 | public struct RecurringItem: Identifiable, Hashable, Sendable { |
| 356 | public var id: String |
| 357 | public var name: String |
| 358 | public var cadence: Cadence |
| 359 | public var amount: Decimal |
| 360 | public var lastDay: String |
| 361 | public var nextDay: String |
| 362 | public var categoryID: String |
| 363 | public var count: Int |
| 364 | public var status: RecurringStatus |
| 365 | } |
| 366 | |
| 367 | // MARK: Agents and settings |
| 368 | |
| 369 | public struct AgentAction: Codable, Identifiable, Hashable, Sendable { |
| 370 | public var id: String |
| 371 | public var at: Date |
| 372 | public var client: String |
| 373 | public var tool: String |
| 374 | public var summary: String |
| 375 | public init(client: String, tool: String, summary: String, at: Date = .now) { |
| 376 | id = UUID().uuidString; self.at = at; self.client = client; self.tool = tool; self.summary = summary |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | public enum AskProvider: String, Codable, CaseIterable, Sendable { |
| 381 | case apple, claude, openai |
| 382 | case claudeCode = "claude-code", codex |
| 383 | /// Gemini through the Antigravity CLI (`agy`). It answers from the summary only, with no tools. |
| 384 | case gemini |
| 385 | public var title: String { |
| 386 | switch self { |
| 387 | case .apple: "Apple Intelligence" |
| 388 | case .claude: "Claude API key" |
| 389 | case .openai: "OpenAI API key" |
| 390 | case .claudeCode: "Claude Code" |
| 391 | case .codex: "Codex" |
| 392 | case .gemini: "Gemini" |
| 393 | } |
| 394 | } |
| 395 | /// An agent installed on this Mac, signed in with the person's own account. |
| 396 | public var isAgent: Bool { self == .claudeCode || self == .codex || self == .gemini } |
| 397 | /// The agent reads more through Bucksley's read-only MCP tools. |
| 398 | public var usesTools: Bool { self == .claudeCode || self == .codex } |
| 399 | /// The company that gets the question. |
| 400 | public var company: String { |
| 401 | switch self { |
| 402 | case .apple: "Apple" |
| 403 | case .claude, .claudeCode: "Anthropic" |
| 404 | case .openai, .codex: "OpenAI" |
| 405 | case .gemini: "Google" |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | public struct Settings: Codable, Hashable, Sendable { |
| 411 | public var agentsCanWrite = false |
| 412 | public var agentsCanSetKeys = false |
| 413 | public var askProvider: AskProvider = .apple |
| 414 | public var claudeModel = "claude-opus-5-5" |
| 415 | public var openAIModel = "gpt-6.1-sol" |
| 416 | /// Model for each installed agent ("claude-code", "codex"); missing uses the agent's default. |
| 417 | public var agentModels: [String: String]? |
| 418 | public var shareWithIPhone = true |
| 419 | public var lastSyncAt: Date? |
| 420 | public var lastSharedAt: Date? |
| 421 | /// Bank sync runs this often while the Mac app is open. |
| 422 | public var syncEveryHours = 6 |
| 423 | public init() {} |
| 424 | |
| 425 | /// The model to ask for with this answer source. |
| 426 | public func model(for provider: AskProvider) -> String? { |
| 427 | switch provider { |
| 428 | case .apple: nil |
| 429 | case .claude: claudeModel |
| 430 | case .openai: openAIModel |
| 431 | case .claudeCode, .codex, .gemini: agentModels?[provider.rawValue] |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | public struct Workspace: Codable, Sendable { |
| 437 | public var connections: [Connection] = [] |
| 438 | public var accounts: [Account] = [] |
| 439 | public var groups: [CategoryGroup] = Defaults.groups |
| 440 | public var categories: [Category] = Defaults.categories |
| 441 | public var rules: [Rule] = [] |
| 442 | public var budgets: [Budget] = [] |
| 443 | public var recurring: [String: RecurringStatus] = [:] |
| 444 | public var settings = Settings() |
| 445 | public var agentLog: [AgentAction] = [] |
| 446 | public init() {} |
| 447 | |
| 448 | public func category(_ id: String?) -> Category? { categories.first { $0.id == id } } |
| 449 | public func account(_ id: String) -> Account? { accounts.first { $0.id == id } } |
| 450 | |
| 451 | public enum CodingKeys: String, CodingKey { case connections, accounts, groups, categories, rules, budgets, recurring, settings, agentLog } |
| 452 | public init(from decoder: Decoder) throws { |
| 453 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 454 | connections = try c.decodeIfPresent([Connection].self, forKey: .connections) ?? [] |
| 455 | accounts = try c.decodeIfPresent([Account].self, forKey: .accounts) ?? [] |
| 456 | groups = try c.decodeIfPresent([CategoryGroup].self, forKey: .groups) ?? Defaults.groups |
| 457 | categories = try c.decodeIfPresent([Category].self, forKey: .categories) ?? Defaults.categories |
| 458 | rules = try c.decodeIfPresent([Rule].self, forKey: .rules) ?? [] |
| 459 | budgets = try c.decodeIfPresent([Budget].self, forKey: .budgets) ?? [] |
| 460 | recurring = try c.decodeIfPresent([String: RecurringStatus].self, forKey: .recurring) ?? [:] |
| 461 | settings = try c.decodeIfPresent(Settings.self, forKey: .settings) ?? Settings() |
| 462 | agentLog = try c.decodeIfPresent([AgentAction].self, forKey: .agentLog) ?? [] |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | public enum BucksleyError: LocalizedError, Sendable { |
| 467 | case missing(String), notAllowed(String), network(String), invalid(String) |
| 468 | public var errorDescription: String? { |
| 469 | switch self { case .missing(let s), .notAllowed(let s), .network(let s), .invalid(let s): s } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | // MARK: Days, months and money |
| 474 | |
| 475 | public enum DayKey { |
| 476 | static let formatter: DateFormatter = { |
| 477 | let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.locale = Locale(identifier: "en_US_POSIX") |
| 478 | f.timeZone = .current; f.dateFormat = "yyyy-MM-dd"; return f |
| 479 | }() |
| 480 | public static func from(_ date: Date) -> String { formatter.string(from: date) } |
| 481 | public static func date(_ key: String) -> Date? { formatter.date(from: key) } |
| 482 | public static var today: String { from(.now) } |
| 483 | public static func adding(_ days: Int, to key: String) -> String { |
| 484 | guard let d = date(key), let out = Calendar.current.date(byAdding: .day, value: days, to: d) else { return key } |
| 485 | return from(out) |
| 486 | } |
| 487 | public static func between(_ a: String, _ b: String) -> Int { |
| 488 | guard let x = date(a), let y = date(b) else { return 0 } |
| 489 | return Calendar.current.dateComponents([.day], from: x, to: y).day ?? 0 |
| 490 | } |
| 491 | /// The last `n` days ending today, oldest first. |
| 492 | public static func lastDays(_ n: Int, endingOn end: String = today) -> [String] { |
| 493 | (0..<n).reversed().map { adding(-$0, to: end) } |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | public enum MonthKey { |
| 498 | public static var current: String { String(DayKey.today.prefix(7)) } |
| 499 | public static func of(_ day: String) -> String { String(day.prefix(7)) } |
| 500 | public static func adding(_ months: Int, to month: String) -> String { |
| 501 | guard let d = DayKey.date(month + "-01"), let out = Calendar.current.date(byAdding: .month, value: months, to: d) else { return month } |
| 502 | return String(DayKey.from(out).prefix(7)) |
| 503 | } |
| 504 | public static func days(in month: String) -> Int { |
| 505 | guard let d = DayKey.date(month + "-01") else { return 30 } |
| 506 | return Calendar.current.range(of: .day, in: .month, for: d)?.count ?? 30 |
| 507 | } |
| 508 | public static func title(_ month: String) -> String { |
| 509 | guard let d = DayKey.date(month + "-01") else { return month } |
| 510 | return d.formatted(.dateTime.month(.wide).year()) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | public enum DeviceName { |
| 515 | public static var current: String { |
| 516 | #if os(macOS) |
| 517 | Host.current().localizedName ?? "Mac" |
| 518 | #else |
| 519 | "iPhone" |
| 520 | #endif |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | public extension Decimal { |
| 525 | /// Parsed from the decimal text, which avoids the binary noise NSDecimalNumber.doubleValue adds. |
| 526 | var double: Double { Double(description) ?? NSDecimalNumber(decimal: self).doubleValue } |
| 527 | init(cents: Int) { self = Decimal(cents) / 100 } |
| 528 | /// Parses "1,234.56", "-12.30", "(45.00)" and "$9.99". |
| 529 | init?(money text: String) { |
| 530 | var t = text.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "$", with: "").replacingOccurrences(of: ",", with: "") |
| 531 | var negative = false |
| 532 | if t.hasPrefix("(") && t.hasSuffix(")") { negative = true; t = String(t.dropFirst().dropLast()) } |
| 533 | guard !t.isEmpty, let value = Decimal(string: t, locale: Locale(identifier: "en_US_POSIX")) else { return nil } |
| 534 | self = negative ? -value : value |
| 535 | } |
| 536 | func rounded(_ places: Int = 2) -> Decimal { |
| 537 | var input = self, out = Decimal() |
| 538 | NSDecimalRound(&out, &input, places, .bankers) |
| 539 | return out |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | public enum Money { |
| 544 | public static func format(_ value: Decimal, cents: Bool = true, signed: Bool = false, currency: String = "USD") -> String { |
| 545 | let style = Decimal.FormatStyle.Currency(code: currency).precision(.fractionLength(cents ? 2 : 0)) |
| 546 | let text = abs(value).formatted(style) |
| 547 | if value < 0 { return "−" + text } |
| 548 | return signed && value > 0 ? "+" + text : text |
| 549 | } |
| 550 | /// "$142.4k", "$1.2M" for chart axes and tight cards. |
| 551 | public static func short(_ value: Decimal) -> String { |
| 552 | let v = value.double, a = Swift.abs(v), sign = v < 0 ? "−" : "" |
| 553 | switch a { |
| 554 | case 1_000_000...: return sign + "$" + String(format: "%.1fM", a / 1_000_000) |
| 555 | case 10_000...: return sign + "$" + String(format: "%.0fk", a / 1_000) |
| 556 | case 1_000...: return sign + "$" + String(format: "%.1fk", a / 1_000) |
| 557 | default: return sign + "$" + String(format: "%.0f", a) |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | public func abs(_ value: Decimal) -> Decimal { value < 0 ? -value : value } |