SPB Git

Repository Public

PortfoliosView.swift 17.9 KB 322 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/PortfoliosView.swift3// Description: The Portfolios section: the list of synced portfolios (`main`, the one the agent reasons about, first), the header of the open one (name, base currency, benchmark, sync state) and its two tabs, Holdings and Analysis.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910enum PortfolioTab: String, CaseIterable { case holdings, analysis }1112/// Launch arguments (DEBUG): `-VQPortfolio <id>`, `-VQTab holdings|analysis|rebalance|risk|import`,13/// `-VQXImportCSV "<csv text, lines separated by \n>"` (opens the import preview on that text).14struct PortfolioView: View {15    let app: AppEnvironment16    @Bindable var model: WindowModel17    @Environment(\.undoManager) private var undo18    @State private var tab: PortfolioTab = .holdings19    @State private var analysisTab: AnalysisTab = .portfolio20    @State private var renaming: String?21    @State private var renameText = ""22    @State private var deleting: String?23    @State private var importing: ImportDraft?24    @State private var pickingFile = false25    @State private var consumedLaunch = false2627    private var collection: VQSyncedCollection<VQPortfolio>? { app.sync.active?.portfolios }28    private var main: VQObject<VQPortfolio>? { collection?[VQObjectID.mainPortfolio] }29    private var others: [VQObject<VQPortfolio>] {30        (collection?.items ?? []).filter { $0.id != VQObjectID.mainPortfolio }.sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) }31    }32    /// `main` when it exists or when nothing else does; otherwise what the window was asked to show.33    private var selectedId: String {34        if let id = model.portfolioId, id == VQObjectID.mainPortfolio || collection?[id] != nil { return id }35        return main != nil ? VQObjectID.mainPortfolio : (others.first?.id ?? VQObjectID.mainPortfolio)36    }37    private var selected: VQObject<VQPortfolio>? { collection?[selectedId] }3839    var body: some View {40        HStack(spacing: 0) {41            list.frame(width: 232)42            VHairline()43            detail.frame(maxWidth: .infinity, maxHeight: .infinity)44        }45        .background(VQTokens.Palette.ink0)46        .onAppear { consumeLaunch() }47        .onChange(of: collection?.isLoaded) { _, _ in consumeLaunch() }48        .alert("Rename Portfolio", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {49            TextField("Name", text: $renameText)50            Button("Rename") { if let id = renaming { rename(id, renameText) } }51            Button("Cancel", role: .cancel) {}52        }53        .confirmationDialog("Delete “\(deleting.flatMap { collection?[$0]?.data.name } ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {54            Button("Delete Portfolio", role: .destructive) {55                if let id = deleting { if model.portfolioId == id { model.portfolioId = nil }; Task { await app.portfolios.delete(id) } }56            }57        } message: { Text("The portfolio and its saved versions are erased from your account on every device. It is a record of holdings: nothing is sold.") }58        .sheet(item: $importing) { draft in59            PortfolioImportSheet(app: app, draft: draft, existing: selected?.data.positions.map(\.symbol) ?? [], portfolioName: selected?.data.name ?? "") { rows, mode in60                apply(rows, mode)61            }62            .vqTheme(app.vqTheme)63        }64        .fileImporter(isPresented: $pickingFile, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in65            if case .success(let url) = result { openImport(url) }66        }67    }6869    // MARK: list7071    private var list: some View {72        VStack(alignment: .leading, spacing: 0) {73            HStack {74                Overline("Portfolios")75                Spacer()76                Button { create() } label: { Image(systemName: "plus").font(.system(size: 12, weight: .semibold)) }77                    .buttonStyle(.borderless).help("New portfolio").disabled(collection == nil)78                    .accessibilityIdentifier("portfolio.new")79            }80            .padding(.horizontal, VQTokens.Space.s4).padding(.top, VQTokens.Space.s4).padding(.bottom, VQTokens.Space.s2)81            ScrollView {82                VStack(alignment: .leading, spacing: 2) {83                    MasterRow(isSelected: selectedId == VQObjectID.mainPortfolio) { model.portfolioId = VQObjectID.mainPortfolio } content: {84                        PortfolioRowLabel(name: main?.data.name ?? "Main portfolio", detail: main.map { Self.summary($0.data) } ?? "Appears with the first position",85                                          isMain: true, pending: collection?.pendingIDs.contains(VQObjectID.mainPortfolio) == true)86                    }87                    .accessibilityIdentifier("portfolio.row.main")88                    .contextMenu { if main != nil { Button("Rename…") { beginRename(VQObjectID.mainPortfolio) }; Button("Duplicate") { duplicate(VQObjectID.mainPortfolio) } } }89                    if !others.isEmpty { Hairline().padding(.vertical, 6).padding(.horizontal, VQTokens.Space.s3) }90                    ForEach(others) { o in91                        MasterRow(isSelected: selectedId == o.id) { model.portfolioId = o.id } content: {92                            PortfolioRowLabel(name: o.data.name.isEmpty ? "Untitled" : o.data.name, detail: Self.summary(o.data), isMain: false, pending: collection?.pendingIDs.contains(o.id) == true)93                        }94                        .accessibilityIdentifier("portfolio.row.\(o.data.name)")95                        .contextMenu {96                            Button("Rename…") { beginRename(o.id) }97                            Button("Duplicate") { duplicate(o.id) }98                            Divider()99                            Button("Delete…", role: .destructive) { deleting = o.id }100                        }101                    }102                }103                .padding(.horizontal, VQTokens.Space.s2)104            }105            Hairline()106            Text("Records of holdings for analysis. VQuant is not connected to a broker and cannot place orders.")107                .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)108                .padding(VQTokens.Space.s3)109        }110        .background(VQTokens.Palette.ink1)111    }112113    static func summary(_ p: VQPortfolio) -> String {114        let n = p.positions.count115        return "\(n) position\(n == 1 ? "" : "s") · \(p.baseCurrency)"116    }117118    // MARK: detail119120    @ViewBuilder private var detail: some View {121        if app.sync.active == nil {122            CenteredEmpty { VQEmptyState(systemImage: "icloud.slash", title: "Sync is off", message: "Portfolios are kept in your account. Sign in to see them.") }123        } else if collection?.isLoaded != true {124            VStack(alignment: .leading, spacing: VQTokens.Space.s4) { VQSkeletonText(lines: 2); VQSkeletonRows(rows: 6, columns: 6) }.padding(VQTokens.Space.s6).frame(maxHeight: .infinity, alignment: .top)125        } else if let object = selected {126            VStack(alignment: .leading, spacing: 0) {127                header(object)128                Hairline()129                switch tab {130                case .holdings:131                    HoldingsPane(app: app, model: model, id: object.id, portfolio: object.data, importCSV: { pickingFile = true }, dropped: { openImport($0) })132                case .analysis:133                    PortfolioAnalysisPane(app: app, model: model, id: object.id, portfolio: object.data, tab: $analysisTab)134                }135            }136            .id(object.id)137        } else {138            MainPortfolioPlaceholder(app: app)139        }140    }141142    private func header(_ o: VQObject<VQPortfolio>) -> some View {143        let p = o.data144        let isMain = o.id == VQObjectID.mainPortfolio145        return VStack(alignment: .leading, spacing: VQTokens.Space.s2) {146            HStack(spacing: VQTokens.Space.s2) {147                Overline(isMain ? "Main portfolio · the one the agent reasons about" : "Portfolio", color: isMain ? VQTokens.Palette.accentText : VQTokens.Palette.text3)148                if collection?.pendingIDs.contains(o.id) == true { PendingSyncMark() }149                Spacer()150                Text("Updated \(VQFormat.relative(o.updatedAt, language: .en))").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)151            }152            InlineField(value: p.name, placeholder: "Portfolio name", role: VQTokens.Typography.displayMd, identifier: "portfolio.title") { text in153                let t = text.trimmingCharacters(in: .whitespaces)154                guard !t.isEmpty else { return false }155                var n = p; n.name = t; app.portfolios.write(n, id: o.id, action: "Rename Portfolio", undo: undo); return true156            }157            .padding(.leading, -6)158            HStack(spacing: VQTokens.Space.s4) {159                LabeledInline(label: "Base currency") {160                    InlineField(value: p.baseCurrency, placeholder: "USD", role: VQTokens.Typography.numSm, identifier: "portfolio.base") { text in161                        let c = text.trimmingCharacters(in: .whitespaces).uppercased()162                        guard c.count == 3, c.allSatisfy({ $0.isASCII && $0.isLetter }) else { app.toasts.show("A currency is a 3-letter code (USD, CAD, EUR…).", error: true); return false }163                        var n = p; n.baseCurrency = c; app.portfolios.write(n, id: o.id, action: "Change Base Currency", undo: undo); return true164                    }.frame(width: 52)165                }166                LabeledInline(label: "Benchmark") {167                    InlineField(value: p.benchmark ?? "", placeholder: "SPY", role: VQTokens.Typography.numSm, identifier: "portfolio.benchmark") { text in168                        let t = text.trimmingCharacters(in: .whitespaces)169                        var n = p170                        if t.isEmpty { n.benchmark = nil } else { guard let s = PortfolioImport.normalizeSymbol(t) else { app.toasts.show("“\(t)” is not a ticker symbol.", error: true); return false }; n.benchmark = s }171                        app.portfolios.write(n, id: o.id, action: "Change Benchmark", undo: undo); return true172                    }.frame(width: 76)173                }174                Spacer()175                VQSegmentedControl("View", selection: $tab, options: [.init(.holdings, "Holdings"), .init(.analysis, "Analysis")])176                    .accessibilityIdentifier("portfolio.tabs")177            }178        }179        .padding(.horizontal, VQTokens.Space.s6).padding(.top, VQTokens.Space.s4).padding(.bottom, VQTokens.Space.s3)180    }181182    // MARK: actions183184    private func create() {185        let n = others.count + 1186        Task { if let id = await app.portfolios.create(VQPortfolio(name: (app.options.isUITest ? "mac-test-ui " : "") + "Portfolio \(n)", baseCurrency: main?.data.baseCurrency ?? "USD", benchmark: "SPY")) { model.portfolioId = id; tab = .holdings } }187    }188189    private func duplicate(_ id: String) {190        guard var copy = collection?[id]?.data else { return }191        copy.name += " copy"192        Task { if let new = await app.portfolios.create(copy) { model.portfolioId = new } }193    }194195    private func beginRename(_ id: String) { renameText = collection?[id]?.data.name ?? ""; renaming = id }196    private func rename(_ id: String, _ name: String) {197        let t = name.trimmingCharacters(in: .whitespaces)198        guard !t.isEmpty, var p = collection?[id]?.data else { return }199        p.name = t200        app.portfolios.write(p, id: id, action: "Rename Portfolio", undo: undo)201    }202203    private func openImport(_ url: URL) {204        let scoped = url.startAccessingSecurityScopedResource()205        defer { if scoped { url.stopAccessingSecurityScopedResource() } }206        guard let data = try? Data(contentsOf: url), data.count <= 2_000_000, let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {207            app.toasts.show("“\(url.lastPathComponent)” could not be read as a text file of at most 2 MB.", error: true); return208        }209        importing = ImportDraft(name: url.lastPathComponent, data: PortfolioImport(csv: text))210    }211212    /// Writes the valid rows into the open portfolio. Fields a row does not state keep the value the position had213    /// (merge and replace alike), and keys this app does not know stay where they are.214    private func apply(_ rows: [PortfolioImport.Row], _ mode: PortfolioImport.Mode) {215        guard let o = selected, !rows.isEmpty else { return }216        var p = o.data217        if mode == .replace { let keep = Set(rows.map(\.symbol)); p.positions = p.positions.filter { keep.contains($0.symbol) } }218        for r in rows { if let q = r.quantity { p.upsert(VQPortfolio.Position(symbol: r.symbol, quantity: q, costBasis: r.costBasis, currency: r.currency, note: r.note, openedAt: r.openedAt)) } }219        app.portfolios.write(p, id: o.id, action: "Import Positions", undo: undo)220        app.toasts.show("\(rows.count) position\(rows.count == 1 ? "" : "s") imported into \(p.name).")221    }222223    private func consumeLaunch() {224        guard !consumedLaunch, collection?.isLoaded == true else { return }225        consumedLaunch = true226        switch model.launchTab {227        case "analysis": tab = .analysis228        case "rebalance": tab = .analysis; analysisTab = .rebalance229        case "risk": tab = .analysis; analysisTab = .risk230        default: break231        }232        if let csv = app.options.extra["ImportCSV"], model.launchTab == "import" {233            importing = ImportDraft(name: "holdings.csv", data: PortfolioImport(csv: csv.replacingOccurrences(of: "\\n", with: "\n")))234        }235        if [PortfolioTab.holdings.rawValue, "analysis", "rebalance", "risk", "import"].contains(model.launchTab ?? "") { model.launchTab = nil }236    }237}238239struct ImportDraft: Identifiable {240    let id = UUID()241    var name: String242    var data: PortfolioImport243}244245private struct LabeledInline<Content: View>: View {246    let label: String247    @ViewBuilder var content: Content248    var body: some View {249        HStack(spacing: 2) {250            Text(label).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)251            content252        }253    }254}255256private struct PortfolioRowLabel: View {257    let name: String258    let detail: String259    let isMain: Bool260    let pending: Bool261    var body: some View {262        VStack(alignment: .leading, spacing: 2) {263            HStack(spacing: 6) {264                Text(name).font(VQTokens.Typography.bodySm.font.weight(.medium)).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)265                if pending { PendingSyncMark() }266                Spacer(minLength: 0)267                if isMain { Text("AGENT").font(VQTokens.Typography.overline.font).tracking(0.8).foregroundStyle(VQTokens.Palette.accentText).help("The agent reasons about this portfolio") }268            }269            Text(detail).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)270        }271    }272}273274/// `main` does not exist until the person's first position (CONTRACT §1.4). It is never created empty from here:275/// the first position is recorded through the route the agent and the 1.x clients use, and the server starts `main`.276private struct MainPortfolioPlaceholder: View {277    let app: AppEnvironment278    @State private var symbol: String?279    @State private var quantity = ""280    @State private var cost = ""281    @State private var saving = false282    @State private var error: String?283284    var body: some View {285        CenteredEmpty { placeholder }286    }287288    private var placeholder: some View {289        VQEmptyState(systemImage: "briefcase", title: "No main portfolio yet",290                     message: "The main portfolio is the one the agent reasons about. It appears with its first position — record one here, or ask the agent to. Other portfolios can be created at any time with +.") {291            VStack(spacing: VQTokens.Space.s2) {292                HStack(spacing: VQTokens.Space.s2) {293                    if let symbol {294                        Text(symbol).font(VQTokens.Typography.numMd.font).padding(.horizontal, 8).padding(.vertical, 3).background(RoundedRectangle(cornerRadius: 5).fill(VQTokens.Palette.ink3))295                        Button { self.symbol = nil } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.borderless)296                    } else {297                        SymbolSearchField(app: app, placeholder: "Symbol or company") { symbol = $0 }.frame(width: 220)298                    }299                    TextField("Quantity", text: $quantity).textFieldStyle(.roundedBorder).frame(width: 90)300                    TextField("Cost per unit (optional)", text: $cost).textFieldStyle(.roundedBorder).frame(width: 160)301                    Button("Record") { save() }.buttonStyle(EmberButtonStyle()).disabled(symbol == nil || saving || !app.workspace.canEdit)302                }303                if let error { Text(error).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.critical) }304                Text("This records a holding on the VQuant server. It does not buy anything.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)305            }306        }307    }308309    private func save() {310        guard let symbol else { return }311        guard let q = PortfolioImport.number(quantity), q != 0 else { error = "Enter a quantity (a number other than zero)."; return }312        var cb: Double?313        if !cost.trimmingCharacters(in: .whitespaces).isEmpty { guard let c = PortfolioImport.number(cost), c >= 0 else { error = "The cost must be a positive number."; return }; cb = c }314        saving = true; error = nil315        Task {316            defer { saving = false }317            do { try await app.workspace.perform { _ = try await $0.savePosition(symbol: symbol, quantity: q, costBasis: cb, note: nil) }; await app.sync.syncNow() }318            catch { self.error = error.localizedDescription }319        }320    }321}322
Files main
Menu

Theme