Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/PortfolioImportSheet.swift3// Description: CSV import of positions with a preview: the guessed column mapping (corrected by hand), every row as it will be read with the reason an invalid one is refused, and the choice between merging into the portfolio and replacing its positions.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89struct PortfolioImportSheet: View {10 let app: AppEnvironment11 @State var draft: ImportDraft12 let existing: [String]13 let portfolioName: String14 let apply: ([PortfolioImport.Row], PortfolioImport.Mode) -> Void1516 @State private var mode: PortfolioImport.Mode = .merge17 @Environment(\.dismiss) private var dismiss1819 var body: some View {20 let rows = draft.data.rows21 let valid = rows.filter(\.isValid)22 let effect = draft.data.effect(on: existing, mode: mode)23 VStack(alignment: .leading, spacing: 0) {24 VStack(alignment: .leading, spacing: 4) {25 Overline("Import positions")26 Text(draft.name).font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)27 Text("\(rows.count) row\(rows.count == 1 ? "" : "s") read\(draft.data.hasHeader ? " under a header line" : ", no header line") · \(valid.count) valid · \(rows.count - valid.count) flagged")28 .font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)29 .accessibilityIdentifier("import.summary")30 }31 .padding(.horizontal, VQTokens.Space.s5).padding(.top, VQTokens.Space.s5).padding(.bottom, VQTokens.Space.s3)32 Hairline()33 mapping.padding(.horizontal, VQTokens.Space.s5).padding(.vertical, VQTokens.Space.s3)34 Hairline()35 preview(rows)36 Hairline()37 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {38 HStack(spacing: VQTokens.Space.s3) {39 VQSegmentedControl("Mode", selection: $mode, options: [.init(.merge, "Merge"), .init(.replace, "Replace")])40 Text(mode == .merge41 ? "Merge into \(portfolioName): \(effect.added) added, \(effect.updated) updated, \(effect.kept) left as they are."42 : "Replace the positions of \(portfolioName): \(effect.added) added, \(effect.updated) updated, \(effect.removed) removed.")43 .font(VQTokens.Typography.bodySm.font).foregroundStyle(mode == .replace && effect.removed > 0 ? VQTokens.Palette.warn : VQTokens.Palette.text2)44 .fixedSize(horizontal: false, vertical: true)45 Spacer()46 }47 HStack {48 Text("Flagged rows are not imported. A field a row leaves empty keeps the value the position already has. The import can be undone (⌘Z).")49 .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)50 Spacer()51 Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)52 Button("Import \(valid.count) Position\(valid.count == 1 ? "" : "s")") { apply(valid, mode); dismiss() }53 .buttonStyle(EmberButtonStyle()).keyboardShortcut(.defaultAction).disabled(valid.isEmpty)54 .accessibilityIdentifier("import.apply")55 }56 }57 .padding(VQTokens.Space.s5)58 }59 .frame(width: 860, height: 600)60 .background(VQTokens.Palette.ink1)61 }6263 private var mapping: some View {64 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {65 Text("Columns").font(VQTokens.Typography.heading.font).foregroundStyle(VQTokens.Palette.text1)66 HStack(spacing: VQTokens.Space.s3) {67 ForEach(PortfolioImport.Field.allCases) { f in68 VStack(alignment: .leading, spacing: 2) {69 HStack(spacing: 3) {70 Overline(f.title)71 if f.isRequired { Text("required").font(.system(size: 9)).foregroundStyle(draft.data.mapping[f] == nil ? VQTokens.Palette.critical : VQTokens.Palette.text3) }72 }73 Picker(f.title, selection: Binding(get: { draft.data.mapping[f] ?? -1 }, set: { v in74 // a column feeds one field: taking it frees it from the field that had it75 if v >= 0 { for (k, i) in draft.data.mapping where i == v && k != f { draft.data.mapping[k] = nil } }76 draft.data.mapping[f] = v < 0 ? nil : v77 })) {78 Text("— not in the file").tag(-1)79 ForEach(0..<draft.data.columnCount, id: \.self) { i in Text(draft.data.columnTitle(i)).tag(i) }80 }81 .labelsHidden().controlSize(.small).frame(maxWidth: .infinity)82 .accessibilityIdentifier("import.map.\(f.rawValue)")83 }84 }85 }86 }87 }8889 private func preview(_ rows: [PortfolioImport.Row]) -> some View {90 let locale = app.numberLocale91 return VStack(spacing: 0) {92 HStack(spacing: 0) {93 cell("Line", 44, head: true); cell("", 22, head: true); cell("Symbol", 96, .leading, head: true); cell("Quantity", 90, head: true); cell("Cost", 90, head: true)94 cell("Ccy", 50, .center, head: true); cell("Opened", 96, .center, head: true); cell("Note", 130, .leading, head: true)95 Overline("Reading").padding(.leading, 8).frame(maxWidth: .infinity, alignment: .leading)96 }97 .padding(.horizontal, VQTokens.Space.s5).padding(.vertical, 5)98 Hairline(strong: true)99 ScrollView {100 LazyVStack(spacing: 0) {101 ForEach(rows) { r in102 HStack(spacing: 0) {103 cell(String(r.line), 44, color: VQTokens.Palette.text3)104 Image(systemName: r.isValid ? (r.warnings.isEmpty ? "checkmark.circle.fill" : "exclamationmark.circle.fill") : "xmark.octagon.fill")105 .font(.system(size: 11)).foregroundStyle(r.isValid ? (r.warnings.isEmpty ? VQTokens.Palette.info : VQTokens.Palette.warn) : VQTokens.Palette.critical).frame(width: 22)106 .accessibilityLabel(r.isValid ? "valid" : "invalid")107 cell(r.symbol.isEmpty ? VQFormat.nullText : r.symbol, 96, .leading, weight: .medium)108 cell(r.quantity.map { VQFormat.number($0, decimals: $0.rounded() == $0 ? 0 : 4, locale: locale) } ?? VQFormat.nullText, 90)109 cell(r.costBasis.map { VQFormat.number($0, decimals: 2, locale: locale) } ?? VQFormat.nullText, 90)110 cell(r.currency ?? VQFormat.nullText, 50, .center, color: VQTokens.Palette.text2)111 cell(r.openedAt.map { PlainNumber.day($0) } ?? VQFormat.nullText, 96, .center, color: VQTokens.Palette.text2)112 Text(r.note ?? "").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2).lineLimit(1).frame(width: 130, alignment: .leading)113 Text(r.isValid ? (r.warnings.isEmpty ? (existing.contains(r.symbol) ? "updates the position" : "new position") : r.warnings.joined(separator: "; ")) : r.issues.joined(separator: "; "))114 .font(VQTokens.Typography.caption.font).foregroundStyle(r.isValid ? (r.warnings.isEmpty ? VQTokens.Palette.text3 : VQTokens.Palette.warn) : VQTokens.Palette.critical)115 .lineLimit(2).padding(.leading, 8).frame(maxWidth: .infinity, alignment: .leading)116 }117 .padding(.horizontal, VQTokens.Space.s5).frame(minHeight: 28)118 .background(r.isValid ? Color.clear : VQTokens.Palette.critical.opacity(0.07))119 .accessibilityElement(children: .combine)120 .accessibilityIdentifier("import.row.\(r.line)")121 Hairline()122 }123 if rows.isEmpty { Text("The file has no data row.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3).padding(VQTokens.Space.s5) }124 }125 }126 }127 .background(VQTokens.Palette.ink0)128 }129130 private func cell(_ t: String, _ width: CGFloat, _ a: Alignment = .trailing, head: Bool = false, color: Color = VQTokens.Palette.text1, weight: Font.Weight = .regular) -> some View {131 Group {132 if head { Overline(t) } else { Text(t).font(VQTokens.Typography.numSm.font.weight(weight)).foregroundStyle(color).lineLimit(1) }133 }134 .frame(width: width, alignment: a)135 }136}137