Bucksley / app · bucksley.ai / Sources / BucksleyKit / Connectors.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// The network, injectable so connector tests run against recorded responses. |
| 4 | public protocol HTTPClient: Sendable { |
| 5 | func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) |
| 6 | } |
| 7 | |
| 8 | public struct URLSessionHTTP: HTTPClient { |
| 9 | public init() {} |
| 10 | public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { |
| 11 | let (data, response) = try await URLSession.shared.data(for: request) |
| 12 | guard let http = response as? HTTPURLResponse else { throw BucksleyError.network("No HTTP response.") } |
| 13 | return (data, http) |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /// What one sync of one connection brought back. |
| 18 | public struct BankPull: Sendable { |
| 19 | public var accounts: [Account] = [] |
| 20 | public var transactions: [Transaction] = [] |
| 21 | public var removedTransactionIDs: [String] = [] |
| 22 | public var plaidCursor: String? |
| 23 | public var warnings: [String] = [] |
| 24 | public init() {} |
| 25 | } |
| 26 | |
| 27 | // MARK: SimpleFIN Bridge |
| 28 | |
| 29 | /// SimpleFIN Bridge (https://beta-bridge.simplefin.org): the user pastes a setup token, which is |
| 30 | /// exchanged once for an access URL. That URL (with its credentials) is the secret kept in the |
| 31 | /// Keychain; the Mac reads accounts and transactions from it directly. No server in between. |
| 32 | public struct SimpleFIN: Sendable { |
| 33 | let http: HTTPClient |
| 34 | public init(http: HTTPClient = URLSessionHTTP()) { self.http = http } |
| 35 | |
| 36 | /// The public demo bridge, handy for trying Bucksley without a bank. |
| 37 | public static let demoAccessURL = "https://demo:demo@beta-bridge.simplefin.org/simplefin" |
| 38 | |
| 39 | /// Setup token (base64 of a claim URL) → access URL. A token can be claimed only once. |
| 40 | public func claim(setupToken: String) async throws -> String { |
| 41 | let trimmed = setupToken.trimmingCharacters(in: .whitespacesAndNewlines) |
| 42 | guard let data = Data(base64Encoded: trimmed) ?? Data(base64Encoded: trimmed + String(repeating: "=", count: (4 - trimmed.count % 4) % 4)), |
| 43 | let claim = String(data: data, encoding: .utf8), let url = URL(string: claim), url.scheme == "https" else { |
| 44 | throw BucksleyError.invalid("That doesn't look like a SimpleFIN setup token. Copy it again from SimpleFIN Bridge → Connect an app.") |
| 45 | } |
| 46 | var request = URLRequest(url: url); request.httpMethod = "POST"; request.setValue("0", forHTTPHeaderField: "Content-Length") |
| 47 | let (body, response) = try await http.send(request) |
| 48 | guard response.statusCode == 200, let access = String(data: body, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 49 | access.hasPrefix("https://") else { |
| 50 | throw BucksleyError.network(response.statusCode == 403 |
| 51 | ? "This setup token was already used or has expired. Make a new one in SimpleFIN Bridge." |
| 52 | : "SimpleFIN couldn't claim the token (HTTP \(response.statusCode)).") |
| 53 | } |
| 54 | return access |
| 55 | } |
| 56 | |
| 57 | /// Accounts and transactions since `since`, asked for in 45-day windows (SimpleFIN's limit). |
| 58 | public func pull(accessURL: String, connectionID: String, since: Date, now: Date = .now) async throws -> BankPull { |
| 59 | guard var parts = URLComponents(string: accessURL), let user = parts.user, let password = parts.password else { |
| 60 | throw BucksleyError.invalid("The saved SimpleFIN access URL is incomplete. Connect SimpleFIN again.") |
| 61 | } |
| 62 | parts.user = nil; parts.password = nil |
| 63 | let auth = "Basic " + Data("\(user):\(password)".utf8).base64EncodedString() |
| 64 | var pull = BankPull() |
| 65 | var seenAccounts: [String: Account] = [:] |
| 66 | var windowStart = since |
| 67 | while windowStart < now { |
| 68 | let windowEnd = min(now, windowStart.addingTimeInterval(45 * 86_400)) |
| 69 | var c = parts |
| 70 | c.path += "/accounts" |
| 71 | c.queryItems = [.init(name: "start-date", value: String(Int(windowStart.timeIntervalSince1970))), |
| 72 | .init(name: "end-date", value: String(Int(windowEnd.timeIntervalSince1970) + 1)), |
| 73 | .init(name: "pending", value: "1"), |
| 74 | .init(name: "version", value: "2")] |
| 75 | guard let url = c.url else { throw BucksleyError.invalid("Bad SimpleFIN URL.") } |
| 76 | var request = URLRequest(url: url); request.setValue(auth, forHTTPHeaderField: "Authorization") |
| 77 | let (data, response) = try await http.send(request) |
| 78 | if response.statusCode == 402 { throw BucksleyError.network("Your SimpleFIN Bridge subscription needs attention (payment required).") } |
| 79 | if response.statusCode == 403 { throw BucksleyError.network("SimpleFIN refused the access URL. It may have been revoked; connect again.") } |
| 80 | guard response.statusCode == 200 else { throw BucksleyError.network("SimpleFIN returned HTTP \(response.statusCode).") } |
| 81 | let set = try JSONDecoder().decode(AccountSet.self, from: data) |
| 82 | let banks = Dictionary((set.connections ?? []).map { ($0.connID, $0) }, uniquingKeysWith: { first, _ in first }) |
| 83 | pull.warnings += (set.errors ?? []).filter { !$0.contains("recommended range") } |
| 84 | pull.warnings += (set.errlist ?? []).compactMap { $0.warning(bank: $0.connID.flatMap { banks[$0]?.displayName }) } |
| 85 | for bank in banks.values where !set.accounts.contains(where: { $0.connID == bank.connID }) { |
| 86 | pull.warnings.append("\(bank.displayName) is connected in SimpleFIN Bridge but sent no accounts. Open beta-bridge.simplefin.org, check that connection (it may need you to sign in again) and that its accounts are shared with this app.") |
| 87 | } |
| 88 | for a in set.accounts { |
| 89 | let id = "\(connectionID):\(a.id)" |
| 90 | let institution = a.org?.name ?? a.org?.domain ?? a.connID.flatMap { banks[$0]?.displayName } ?? "Bank" |
| 91 | var kind = AccountKind.guess(from: a.name) |
| 92 | if kind == .other, AccountKind.guess(from: institution) == .investment { kind = .investment } |
| 93 | let balance = Decimal(money: a.balance) ?? 0 |
| 94 | if kind == .other && balance < 0 { kind = .credit } |
| 95 | var account = Account(id: id, connectionID: connectionID, name: a.name, institution: institution, kind: kind, |
| 96 | balance: balance, available: a.availableBalance.flatMap { Decimal(money: $0) }, currency: a.currency.count == 3 ? a.currency : "USD", |
| 97 | balanceDate: Date(timeIntervalSince1970: TimeInterval(a.balanceDate))) |
| 98 | let holdings = (a.holdings ?? []).compactMap(\.holding) |
| 99 | if !holdings.isEmpty { |
| 100 | account.holdings = holdings |
| 101 | if account.kind == .other || account.kind == .checking { account.kind = .investment } |
| 102 | } |
| 103 | seenAccounts[id] = account |
| 104 | for t in a.transactions ?? [] { |
| 105 | let when = Date(timeIntervalSince1970: TimeInterval(t.transactedAt ?? t.posted)) |
| 106 | pull.transactions.append(Transaction(id: "\(id):\(t.id)", accountID: id, day: DayKey.from(when), |
| 107 | amount: Decimal(money: t.amount) ?? 0, description: t.description, |
| 108 | payee: t.payee, bankCategory: t.mcc.map { "mcc:\($0)" } ?? t.memo, |
| 109 | pending: t.pending ?? (t.posted == 0))) |
| 110 | } |
| 111 | } |
| 112 | windowStart = windowEnd |
| 113 | } |
| 114 | pull.accounts = Array(seenAccounts.values).sorted { $0.name < $1.name } |
| 115 | return pull |
| 116 | } |
| 117 | |
| 118 | /// Protocol v2 (errlist, connections, conn_id) with the v1 fields (errors, org) still read, |
| 119 | /// so either server version decodes. |
| 120 | struct AccountSet: Decodable { |
| 121 | let errors: [String]? |
| 122 | let errlist: [SFError]? |
| 123 | let connections: [SFConnection]? |
| 124 | let accounts: [SFAccount] |
| 125 | } |
| 126 | struct SFError: Decodable { |
| 127 | let code: String?, msg: String?, connID: String?, accountID: String? |
| 128 | enum CodingKeys: String, CodingKey { case code, msg, connID = "conn_id", accountID = "account_id" } |
| 129 | func warning(bank: String?) -> String? { |
| 130 | guard let msg, !msg.contains("recommended range") else { return nil } |
| 131 | if code?.hasPrefix("con.auth") == true { return "\(bank ?? "A bank") needs you to sign in again in SimpleFIN Bridge (beta-bridge.simplefin.org). \(msg)" } |
| 132 | return bank.map { "\($0): \(msg)" } ?? msg |
| 133 | } |
| 134 | } |
| 135 | struct SFConnection: Decodable { |
| 136 | let connID: String, name: String?, orgName: String?, orgURL: String? |
| 137 | enum CodingKeys: String, CodingKey { case connID = "conn_id", name, orgName = "org_name", orgURL = "org_url" } |
| 138 | var displayName: String { orgName ?? name ?? orgURL ?? "A bank" } |
| 139 | } |
| 140 | struct SFAccount: Decodable { |
| 141 | struct Org: Decodable { let name: String?; let domain: String? } |
| 142 | let id: String, name: String, currency: String, balance: String |
| 143 | let availableBalance: String? |
| 144 | let balanceDate: Int |
| 145 | let org: Org? |
| 146 | let connID: String? |
| 147 | let transactions: [SFTransaction]? |
| 148 | let holdings: [SFHolding]? |
| 149 | enum CodingKeys: String, CodingKey { |
| 150 | case id, name, currency, balance, org, transactions, holdings |
| 151 | case availableBalance = "available-balance", balanceDate = "balance-date", connID = "conn_id" |
| 152 | } |
| 153 | /// Lenient: brokerages sometimes send numbers where the spec says strings, or skip the date. |
| 154 | init(from decoder: Decoder) throws { |
| 155 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 156 | func text(_ key: CodingKeys) -> String? { |
| 157 | (try? c.decodeIfPresent(String.self, forKey: key)) ?? (try? c.decodeIfPresent(Double.self, forKey: key)).flatMap { $0.map { String($0) } } |
| 158 | } |
| 159 | id = try c.decode(String.self, forKey: .id) |
| 160 | name = (try? c.decodeIfPresent(String.self, forKey: .name)) ?? nil ?? "Account" |
| 161 | currency = (try? c.decodeIfPresent(String.self, forKey: .currency)) ?? nil ?? "USD" |
| 162 | balance = text(.balance) ?? "0" |
| 163 | availableBalance = text(.availableBalance) |
| 164 | balanceDate = (try? c.decodeIfPresent(Int.self, forKey: .balanceDate)) ?? nil ?? Int(Date().timeIntervalSince1970) |
| 165 | org = try? c.decodeIfPresent(Org.self, forKey: .org) |
| 166 | connID = try? c.decodeIfPresent(String.self, forKey: .connID) |
| 167 | transactions = (try? c.decodeIfPresent([Lenient<SFTransaction>].self, forKey: .transactions))??.compactMap(\.value) |
| 168 | holdings = (try? c.decodeIfPresent([Lenient<SFHolding>].self, forKey: .holdings))??.compactMap(\.value) |
| 169 | } |
| 170 | } |
| 171 | /// SimpleFIN Bridge's holdings extension (strings or numbers, per bank). |
| 172 | struct SFHolding: Decodable { |
| 173 | let id: String, symbol: String?, description: String? |
| 174 | let shares: Decimal?, marketValue: Decimal?, costBasis: Decimal? |
| 175 | enum CodingKeys: String, CodingKey { case id, symbol, description, shares, marketValue = "market_value", costBasis = "cost_basis" } |
| 176 | init(from decoder: Decoder) throws { |
| 177 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 178 | func number(_ key: CodingKeys) -> Decimal? { |
| 179 | if let s = try? c.decodeIfPresent(String.self, forKey: key) { return Decimal(money: s) } |
| 180 | return (try? c.decodeIfPresent(Double.self, forKey: key)).flatMap { $0.map { Decimal($0) } } |
| 181 | } |
| 182 | id = (try? c.decodeIfPresent(String.self, forKey: .id)) ?? nil ?? UUID().uuidString |
| 183 | symbol = (try? c.decodeIfPresent(String.self, forKey: .symbol)) ?? nil |
| 184 | description = (try? c.decodeIfPresent(String.self, forKey: .description)) ?? nil |
| 185 | shares = number(.shares); marketValue = number(.marketValue); costBasis = number(.costBasis) |
| 186 | } |
| 187 | var holding: Holding? { |
| 188 | guard let marketValue else { return nil } |
| 189 | let name = description ?? symbol ?? "Holding" |
| 190 | return Holding(id: id, symbol: symbol?.isEmpty == true ? nil : symbol, name: name, shares: shares, marketValue: marketValue, costBasis: costBasis) |
| 191 | } |
| 192 | } |
| 193 | /// Skips one malformed transaction instead of failing the whole pull. |
| 194 | struct Lenient<T: Decodable>: Decodable { |
| 195 | let value: T? |
| 196 | init(from decoder: Decoder) throws { value = try? T(from: decoder) } |
| 197 | } |
| 198 | struct SFTransaction: Decodable { |
| 199 | let id: String |
| 200 | let posted: Int |
| 201 | let amount: String |
| 202 | let description: String |
| 203 | let payee: String? |
| 204 | let memo: String? |
| 205 | let transactedAt: Int? |
| 206 | let pending: Bool? |
| 207 | let mcc: String? |
| 208 | enum CodingKeys: String, CodingKey { case id, posted, amount, description, payee, memo, pending, mcc, transactedAt = "transacted_at" } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | // MARK: Plaid with the user's own keys |
| 213 | |
| 214 | /// Plaid, called straight from the Mac with the user's own client ID and secret (from |
| 215 | /// dashboard.plaid.com). Bucksley never sees them; they live in the user's Keychain. |
| 216 | public struct Plaid: Sendable { |
| 217 | public enum Environment: String, CaseIterable, Sendable { |
| 218 | case sandbox, production |
| 219 | var host: String { "https://\(rawValue).plaid.com" } |
| 220 | } |
| 221 | |
| 222 | let http: HTTPClient |
| 223 | let environment: Environment |
| 224 | let clientID: String |
| 225 | let secret: String |
| 226 | |
| 227 | public init(environment: Environment, clientID: String, secret: String, http: HTTPClient = URLSessionHTTP()) { |
| 228 | self.environment = environment; self.clientID = clientID; self.secret = secret; self.http = http |
| 229 | } |
| 230 | |
| 231 | /// From the Keychain, or nil until the user adds their keys in Settings → Connections. |
| 232 | public static func fromKeychain(environment: Environment) -> Plaid? { |
| 233 | guard let id = Keychain.get(.plaidClientID), let secret = Keychain.get(.plaidSecret) else { return nil } |
| 234 | return Plaid(environment: environment, clientID: id, secret: secret) |
| 235 | } |
| 236 | |
| 237 | func call(_ path: String, _ body: [String: Any]) async throws -> [String: Any] { |
| 238 | var request = URLRequest(url: URL(string: environment.host + path)!) |
| 239 | request.httpMethod = "POST" |
| 240 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 241 | var payload = body; payload["client_id"] = clientID; payload["secret"] = secret |
| 242 | request.httpBody = try JSONSerialization.data(withJSONObject: payload) |
| 243 | let (data, response) = try await http.send(request) |
| 244 | let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] |
| 245 | guard response.statusCode == 200 else { |
| 246 | let message = json["error_message"] as? String ?? "HTTP \(response.statusCode)" |
| 247 | let code = json["error_code"] as? String |
| 248 | throw BucksleyError.network(code == "ITEM_LOGIN_REQUIRED" ? "Your bank needs you to sign in again. Reconnect it in Settings → Connections." : "Plaid: \(message)") |
| 249 | } |
| 250 | return json |
| 251 | } |
| 252 | |
| 253 | /// Starts Plaid Link (shown in a web view on the Mac). |
| 254 | public func linkToken(userID: String) async throws -> String { |
| 255 | let json = try await call("/link/token/create", [ |
| 256 | "client_name": "Bucksley", "language": "en", "country_codes": ["US"], "products": ["transactions"], |
| 257 | "user": ["client_user_id": userID], "transactions": ["days_requested": 730] |
| 258 | ]) |
| 259 | guard let token = json["link_token"] as? String else { throw BucksleyError.network("Plaid didn't return a link token.") } |
| 260 | return token |
| 261 | } |
| 262 | |
| 263 | /// Link's public token → the item's access token (kept in the Keychain). |
| 264 | public func exchange(publicToken: String) async throws -> String { |
| 265 | let json = try await call("/item/public_token/exchange", ["public_token": publicToken]) |
| 266 | guard let token = json["access_token"] as? String else { throw BucksleyError.network("Plaid didn't return an access token.") } |
| 267 | return token |
| 268 | } |
| 269 | |
| 270 | /// Sandbox only: skips Link with Plaid's test bank ("First Platypus Bank"). |
| 271 | public func sandboxPublicToken(institution: String = "ins_109508") async throws -> String { |
| 272 | let json = try await call("/sandbox/public_token/create", ["institution_id": institution, "initial_products": ["transactions"]]) |
| 273 | guard let token = json["public_token"] as? String else { throw BucksleyError.network("Plaid didn't return a sandbox token.") } |
| 274 | return token |
| 275 | } |
| 276 | |
| 277 | public func pull(accessToken: String, connectionID: String, institution: String, cursor: String?) async throws -> BankPull { |
| 278 | var pull = BankPull() |
| 279 | let balances = try await call("/accounts/balance/get", ["access_token": accessToken]) |
| 280 | let item = balances["item"] as? [String: Any] |
| 281 | let bank = item?["institution_name"] as? String ?? institution |
| 282 | for a in balances["accounts"] as? [[String: Any]] ?? [] { |
| 283 | guard let accountID = a["account_id"] as? String else { continue } |
| 284 | let b = a["balances"] as? [String: Any] ?? [:] |
| 285 | let type = a["type"] as? String ?? "other", subtype = a["subtype"] as? String ?? "" |
| 286 | let kind = Self.kind(type: type, subtype: subtype) |
| 287 | var current = Self.decimal(b["current"]) ?? 0 |
| 288 | if kind.isLiability { current = -current } |
| 289 | let name = (a["name"] as? String) ?? (a["official_name"] as? String) ?? "Account" |
| 290 | let mask = (a["mask"] as? String).map { " ••\($0)" } ?? "" |
| 291 | pull.accounts.append(Account(id: "\(connectionID):\(accountID)", connectionID: connectionID, name: name + mask, institution: bank, |
| 292 | kind: kind, balance: current, available: Self.decimal(b["available"]), |
| 293 | currency: b["iso_currency_code"] as? String ?? "USD")) |
| 294 | } |
| 295 | var next = cursor |
| 296 | var more = true |
| 297 | while more { |
| 298 | var body: [String: Any] = ["access_token": accessToken, "count": 500] |
| 299 | if let next { body["cursor"] = next } |
| 300 | let page = try await call("/transactions/sync", body) |
| 301 | for t in (page["added"] as? [[String: Any]] ?? []) + (page["modified"] as? [[String: Any]] ?? []) { |
| 302 | guard let id = t["transaction_id"] as? String, let account = t["account_id"] as? String, let day = t["date"] as? String else { continue } |
| 303 | let category = (t["personal_finance_category"] as? [String: Any])?["detailed"] as? String |
| 304 | pull.transactions.append(Transaction(id: "\(connectionID):\(account):\(id)", accountID: "\(connectionID):\(account)", day: day, |
| 305 | amount: -(Self.decimal(t["amount"]) ?? 0), // Plaid: positive is money out |
| 306 | description: t["name"] as? String ?? "", payee: t["merchant_name"] as? String, |
| 307 | bankCategory: category?.lowercased(), pending: t["pending"] as? Bool ?? false)) |
| 308 | } |
| 309 | for r in page["removed"] as? [[String: Any]] ?? [] { |
| 310 | if let id = r["transaction_id"] as? String, let account = r["account_id"] as? String { pull.removedTransactionIDs.append("\(connectionID):\(account):\(id)") } |
| 311 | } |
| 312 | next = page["next_cursor"] as? String ?? next |
| 313 | more = page["has_more"] as? Bool ?? false |
| 314 | } |
| 315 | pull.plaidCursor = next |
| 316 | return pull |
| 317 | } |
| 318 | |
| 319 | static func kind(type: String, subtype: String) -> AccountKind { |
| 320 | switch type { |
| 321 | case "depository": subtype == "checking" ? .checking : (subtype.contains("saving") || subtype == "money market" || subtype == "cd" ? .savings : .checking) |
| 322 | case "credit": .credit |
| 323 | case "loan": .loan |
| 324 | case "investment", "brokerage": subtype.contains("crypto") ? .crypto : .investment |
| 325 | default: .other |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | static func decimal(_ any: Any?) -> Decimal? { |
| 330 | switch any { |
| 331 | case let n as NSNumber: Decimal(string: n.stringValue) |
| 332 | case let s as String: Decimal(string: s) |
| 333 | default: nil |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // MARK: CSV import (Copilot Money export and similar) |
| 339 | |
| 340 | /// Reads a transactions CSV: Copilot Money's export (date, name, amount, status, category, parent |
| 341 | /// category, excluded, tags, type, account, account mask, note, recurring) and most bank exports |
| 342 | /// with a date, a description and an amount column. Copilot's amounts are positive for spending. |
| 343 | public enum CSVImport { |
| 344 | public struct Result: Sendable { |
| 345 | public var accounts: [Account] = [] |
| 346 | public var transactions: [Transaction] = [] |
| 347 | public var edits: [TransactionEdit] = [] |
| 348 | public var newCategories: [Category] = [] |
| 349 | } |
| 350 | |
| 351 | public static func parse(_ text: String, connectionID: String, categories: [Category]) throws -> Result { |
| 352 | let rows = rowsOf(text) |
| 353 | guard let header = rows.first?.map({ $0.lowercased().trimmingCharacters(in: .whitespaces) }) else { throw BucksleyError.invalid("The file is empty.") } |
| 354 | func col(_ names: String...) -> Int? { names.lazy.compactMap { header.firstIndex(of: $0) }.first } |
| 355 | guard let dateCol = col("date", "transaction date", "posted date"), let amountCol = col("amount"), |
| 356 | let nameCol = col("name", "description", "payee", "merchant") else { |
| 357 | throw BucksleyError.invalid("Bucksley needs date, name (or description) and amount columns.") |
| 358 | } |
| 359 | let isCopilot = header.contains("parent category") || header.contains("excluded") |
| 360 | let categoryCol = col("category"), accountCol = col("account"), maskCol = col("account mask"), noteCol = col("note", "notes"), |
| 361 | tagsCol = col("tags"), statusCol = col("status"), excludedCol = col("excluded"), typeCol = col("type") |
| 362 | var result = Result() |
| 363 | var known = Dictionary(uniqueKeysWithValues: categories.map { ($0.name.lowercased(), $0.id) }) |
| 364 | var accounts: [String: Account] = [:] |
| 365 | for (n, row) in rows.dropFirst().enumerated() where row.count >= header.count / 2 { |
| 366 | func v(_ i: Int?) -> String { guard let i, i < row.count else { return "" }; return row[i].trimmingCharacters(in: .whitespaces) } |
| 367 | guard let day = normalizeDay(v(dateCol)), var amount = Decimal(money: v(amountCol)) else { continue } |
| 368 | let type = v(typeCol).lowercased() |
| 369 | if isCopilot { amount = -amount } // Copilot: positive = spent |
| 370 | let accountName = v(accountCol).isEmpty ? "Imported" : v(accountCol) + (v(maskCol).isEmpty ? "" : " ••" + v(maskCol)) |
| 371 | let accountID = "\(connectionID):\(accountName.lowercased().filter { $0.isLetter || $0.isNumber })" |
| 372 | if accounts[accountID] == nil { |
| 373 | accounts[accountID] = Account(id: accountID, connectionID: connectionID, name: accountName, institution: "CSV import", |
| 374 | kind: .guess(from: accountName), balance: 0) |
| 375 | } |
| 376 | let name = v(nameCol) |
| 377 | let txID = "\(accountID):\(day):\(n)" |
| 378 | let tx = Transaction(id: txID, accountID: accountID, day: day, amount: amount, description: name, |
| 379 | bankCategory: v(categoryCol).isEmpty ? nil : v(categoryCol), pending: v(statusCol).lowercased() == "pending") |
| 380 | result.transactions.append(tx) |
| 381 | var edit = TransactionEdit(transactionID: txID, device: "CSV import") |
| 382 | var touched = false |
| 383 | let categoryName = v(categoryCol) |
| 384 | if !categoryName.isEmpty { |
| 385 | let key = categoryName.lowercased() |
| 386 | if known[key] == nil { |
| 387 | let id = key.filter { $0.isLetter || $0.isNumber } |
| 388 | let kind: CategoryKind = type.contains("income") ? .income : (type.contains("transfer") || key.contains("transfer")) ? .transfer : .expense |
| 389 | let created = Category(id: id.isEmpty ? UUID().uuidString : id, name: categoryName, symbol: "tag", groupID: kind == .income ? "income" : kind == .transfer ? "transfers" : "lifestyle", |
| 390 | colorIndex: (categories.count + result.newCategories.count) % 6, kind: kind) |
| 391 | result.newCategories.append(created); known[key] = created.id |
| 392 | } |
| 393 | edit.categoryID = known[key]; touched = true |
| 394 | } |
| 395 | if !v(noteCol).isEmpty { edit.note = v(noteCol); touched = true } |
| 396 | let tags = v(tagsCol).split(whereSeparator: { $0 == "," || $0 == ";" }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } |
| 397 | if !tags.isEmpty { edit.tags = tags; touched = true } |
| 398 | if v(excludedCol).lowercased() == "true" { edit.excluded = true; touched = true } |
| 399 | if isCopilot { edit.reviewed = true; touched = true } // already reviewed in the old app |
| 400 | if touched { result.edits.append(edit) } |
| 401 | } |
| 402 | result.accounts = Array(accounts.values) |
| 403 | return result |
| 404 | } |
| 405 | |
| 406 | static func normalizeDay(_ text: String) -> String? { |
| 407 | let t = text.trimmingCharacters(in: .whitespaces) |
| 408 | if t.count >= 10, DayKey.date(String(t.prefix(10))) != nil { return String(t.prefix(10)) } |
| 409 | let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX") |
| 410 | for format in ["M/d/yyyy", "MM/dd/yyyy", "M/d/yy", "MMM d, yyyy"] { |
| 411 | f.dateFormat = format |
| 412 | if let d = f.date(from: t) { return DayKey.from(d) } |
| 413 | } |
| 414 | return nil |
| 415 | } |
| 416 | |
| 417 | /// RFC 4180 rows: quoted fields, doubled quotes, commas and newlines inside quotes. |
| 418 | static func rowsOf(_ text: String) -> [[String]] { |
| 419 | var rows: [[String]] = [], row: [String] = [], field = "", quoted = false |
| 420 | var chars = Array(text.replacingOccurrences(of: "\r\n", with: "\n")).makeIterator() |
| 421 | var pending: Character? = nil |
| 422 | while let c = pending ?? chars.next() { |
| 423 | pending = nil |
| 424 | if quoted { |
| 425 | if c == "\"" { |
| 426 | if let n = chars.next() { if n == "\"" { field.append("\"") } else { quoted = false; pending = n } } else { quoted = false } |
| 427 | } else { field.append(c) } |
| 428 | } else if c == "\"" { quoted = true } |
| 429 | else if c == "," { row.append(field); field = "" } |
| 430 | else if c == "\n" { row.append(field); field = ""; if !(row.count == 1 && row[0].isEmpty) { rows.append(row) }; row = [] } |
| 431 | else { field.append(c) } |
| 432 | } |
| 433 | if !field.isEmpty || !row.isEmpty { row.append(field); rows.append(row) } |
| 434 | return rows |
| 435 | } |
| 436 | } |