Repository Public
1import Foundation2import SwiftUI3import SheetCore4import SheetUI5import FinanceModels6import AnalysisKit78/// The 18 statement lines used by the ratio analysis, their labels and the keywords used to find them.9enum RatioMapping {10 struct Item: Sendable, Identifiable {11 var id: String12 var label: String13 /// Folded (lower-case, no accents) fragments looked for in the row labels, most specific first.14 var keywords: [String]15 var exclude: [String] = []16 }1718 /// Matching order: specific lines before the general ones they contain.19 static var items: [Item] {20 [21 Item(id: "costOfGoodsSold", label: L("Cost of goods sold"), keywords: ["cost of goods", "cost of sales", "cogs", "cout des marchandises", "cout des ventes", "cout des produits vendus"]),22 Item(id: "revenue", label: L("Revenue"), keywords: ["revenue", "net sales", "sales", "chiffre d'affaires", "produits d'exploitation", "ventes", "revenus"], exclude: ["cost", "cout"]),23 Item(id: "operatingIncome", label: L("Operating income (EBIT)"), keywords: ["operating income", "operating profit", "ebit", "resultat d'exploitation", "benefice d'exploitation", "baii"], exclude: ["ebitda", "baiia"]),24 Item(id: "interestExpense", label: L("Interest expense"), keywords: ["interest expense", "charges d'interets", "frais financiers", "interets", "interest"], exclude: ["minority", "minoritaire"]),25 Item(id: "pretaxIncome", label: L("Pre-tax income"), keywords: ["pre-tax", "pretax", "before tax", "avant impot", "ebt"]),26 Item(id: "netIncome", label: L("Net income"), keywords: ["net income", "net profit", "net earnings", "benefice net", "resultat net"]),27 Item(id: "depreciationAmortization", label: L("Depreciation & amortization"), keywords: ["depreciation", "amortization", "amortissement", "d&a"]),28 Item(id: "marketableSecurities", label: L("Marketable securities"), keywords: ["marketable", "short-term investments", "titres negociables", "placements a court terme", "placements"]),29 Item(id: "cash", label: L("Cash"), keywords: ["cash and cash equivalents", "cash", "tresorerie", "encaisse"], exclude: ["flow", "flux"]),30 Item(id: "receivables", label: L("Accounts receivable"), keywords: ["receivable", "debiteurs", "comptes clients", "creances", "clients"]),31 Item(id: "inventory", label: L("Inventory"), keywords: ["inventor", "stocks", "stock"]),32 Item(id: "currentAssets", label: L("Total current assets"), keywords: ["current assets", "actif a court terme", "actifs a court terme", "actifs courants", "actif courant"]),33 Item(id: "totalAssets", label: L("Total assets"), keywords: ["total assets", "total de l'actif", "actif total", "total actif", "total des actifs"]),34 Item(id: "payables", label: L("Accounts payable"), keywords: ["payable", "crediteurs", "fournisseurs"]),35 Item(id: "currentLiabilities", label: L("Total current liabilities"), keywords: ["current liabilities", "passif a court terme", "passifs a court terme", "passifs courants", "passif courant"]),36 Item(id: "totalLiabilities", label: L("Total liabilities"), keywords: ["total liabilities", "total du passif", "passif total", "total passif", "total des passifs"]),37 Item(id: "totalDebt", label: L("Total debt"), keywords: ["total debt", "dette totale", "total de la dette", "debt", "dette", "emprunts"]),38 Item(id: "equity", label: L("Shareholders' equity"), keywords: ["equity", "capitaux propres", "avoir des actionnaires"]),39 ]40 }4142 static func fold(_ s: String) -> String {43 s.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: Locale(identifier: "en_US")).lowercased()44 .replacingOccurrences(of: "’", with: "'")45 }4647 /// Row of each item found from the labels (each row is used at most once).48 static func autoMatch(labels: [String]) -> [String: Int] {49 let folded = labels.map(fold)50 var used = Set<Int>(), out = [String: Int]()51 for item in items {52 search: for k in item.keywords {53 for (i, l) in folded.enumerated() where !used.contains(i) && !l.isEmpty && l.contains(k) && !item.exclude.contains(where: { l.contains($0) }) {54 out[item.id] = i; used.insert(i)55 break search56 }57 }58 }59 return out60 }6162 /// Explicit choices stored in the form: "revenue=3;cash=-1" (−1 = none).63 static func decode(_ text: String) -> [String: Int] {64 var out = [String: Int]()65 for part in text.split(separator: ";") {66 let kv = part.split(separator: "=")67 if kv.count == 2, let i = Int(kv[1]) { out[String(kv[0])] = i }68 }69 return out70 }71 static func encode(_ map: [String: Int]) -> String { map.keys.sorted().map { "\($0)=\(map[$0]!)" }.joined(separator: ";") }7273 /// Final row of each item: the explicit choice when valid, else the automatic match.74 static func resolve(labels: [String], explicit: [String: Int]) -> [String: Int] {75 var out = autoMatch(labels: labels)76 for (k, i) in explicit {77 if i < 0 { out[k] = nil } else if i < labels.count { out[k] = i }78 }79 return out80 }8182 static func statement(_ rows: [String: Int], values: [Double]) -> StatementItems {83 func v(_ id: String) -> Double {84 guard let i = rows[id], i < values.count, values[i].isFinite else { return 0 }85 return values[i]86 }87 return StatementItems(revenue: v("revenue"), costOfGoodsSold: v("costOfGoodsSold"), operatingIncome: v("operatingIncome"), interestExpense: v("interestExpense"),88 pretaxIncome: v("pretaxIncome"), netIncome: v("netIncome"), depreciationAmortization: v("depreciationAmortization"), cash: v("cash"),89 marketableSecurities: v("marketableSecurities"), receivables: v("receivables"), inventory: v("inventory"), currentAssets: v("currentAssets"),90 totalAssets: v("totalAssets"), payables: v("payables"), currentLiabilities: v("currentLiabilities"), totalDebt: v("totalDebt"),91 totalLiabilities: v("totalLiabilities"), equity: v("equity"))92 }93}9495/// Form section where the user checks and corrects the line mapping.96struct RatioMappingView: View {97 let context: ToolFormContext9899 private var labels: [String] {100 _ = context.session.contentRevision101 let v = context.values.wrappedValue102 guard let frame = ToolInputResolver.frame(v.range("data"), session: context.session), let i = v.columnIndex("labels"), i < frame.columns.count else { return [] }103 return frame.columns[i].labels104 }105106 var body: some View {107 let labels = self.labels108 let auto = RatioMapping.autoMatch(labels: labels)109 let explicit = RatioMapping.decode(context.values.wrappedValue.text("mapping"))110 VStack(alignment: .leading, spacing: 6) {111 Text(L("Statement lines").uppercased()).font(.system(size: 10.5, weight: .semibold)).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)112 .accessibilityAddTraits(.isHeader)113 Text(L("Lines are matched from their labels (English or French). Correct any line below; unmatched lines count as 0."))114 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)115 LazyVGrid(columns: [GridItem(.flexible(minimum: 300), spacing: 12), GridItem(.flexible(minimum: 300))], alignment: .leading, spacing: 5) {116 ForEach(RatioMapping.items.sorted { $0.label < $1.label }) { item in117 HStack(spacing: 8) {118 Text(item.label).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 178, alignment: .trailing).lineLimit(1)119 .accessibilityHidden(true)120 Picker(item.label, selection: Binding(get: { explicit[item.id] ?? -2 }, set: { new in121 var map = RatioMapping.decode(context.values.wrappedValue.text("mapping"))122 if new == -2 { map[item.id] = nil } else { map[item.id] = new }123 context.values.wrappedValue.set("mapping", text: RatioMapping.encode(map))124 })) {125 Text(auto[item.id].map { L("Automatic: %@", labels[$0]) } ?? L("Automatic: no match")).tag(-2)126 Text(L("None (0)")).tag(-1)127 Divider()128 ForEach(Array(labels.enumerated()), id: \.offset) { i, l in if !l.isEmpty { Text(l).tag(i) } }129 }130 .labelsHidden().frame(maxWidth: 230)131 .accessibilityLabel(item.label)132 .accessibilityIdentifier("finance.ratios.map.\(item.id)")133 if auto[item.id] == nil && explicit[item.id] == nil {134 Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 10)).foregroundStyle(ORIX.Palette.warning)135 .help(L("No line matched")).accessibilityLabel(L("No line matched"))136 }137 }138 }139 }140 }141 .padding(.top, 4)142 }143}144