SPB Git

Repository Public

PrivateMarketsView.swift 24.6 KB 387 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/DeFi/PrivateMarketsView.swift10// Description      : Private-company contracts — DISPLAY ONLY. Companies, their11//                    synthetic contracts venue by venue, each contract sheet12//                    with its review state and expiry, sources and dates. A13//                    valuation implied by a price is shown ONLY when the server14//                    derived it from a formula it marks as published AND the15//                    sheet is reviewed and not expired; an expired sheet reads16//                    « fiche expirée », never a number. Contracts of different17//                    venues are never merged. Nothing here can be traded.18// Module           : Features19// Repository       : https://git.spboucher.ai/sp-wallet-ios20// Created          : 2026-11-1821// Last Modified    : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import SPWalletCore9798/** One company row of the list, with what the table sorts on. */99struct PrivateCompanyRow: Identifiable, Hashable {100    let slug: String101    let name: String102    let contracts: Int103    let valuationUsd: Double?104    let valuationText: String?105    let valuationDate: String106    let valuationKind: String?107    var id: String { slug }108    var sortValuation: Double { valuationUsd ?? -1 }109110    static func rows(_ l: PrivateMarketList) -> [PrivateCompanyRow] {111        l.companies.map { c in112            let v = c.lastPrivateValuation113            return PrivateCompanyRow(slug: c.slug, name: c.name, contracts: l.markets.filter { $0.company?.slug == c.slug }.count, valuationUsd: v?.valueUsd.flatMap(Double.init),114                                     valuationText: v?.valueUsd, valuationDate: v?.date ?? "", valuationKind: v?.kind)115        }116    }117}118119enum PrivateWords {120    static func referenceKind(_ k: String) -> String {121        switch k {122        case "primary_round": String(localized: "tour primaire")123        case "tender": String(localized: "offre de rachat")124        case "secondary_estimate": String(localized: "estimation du marché secondaire")125        case "ipo_range": String(localized: "fourchette d’introduction en bourse")126        case "press_estimate": String(localized: "estimation de presse")127        default: k128        }129    }130    static func confidence(_ c: String) -> String { c == "high" ? String(localized: "confiance élevée") : c == "medium" ? String(localized: "confiance moyenne") : c == "low" ? String(localized: "confiance faible") : c }131    static func status(_ s: String) -> (String, Tone) {132        switch s { case "live": (String(localized: "coté"), .info); case "delisted": (String(localized: "retiré de la cote"), .neutral); case "halted": (String(localized: "suspendu"), .warn); case "reduce_only": (String(localized: "réduction seulement"), .warn); default: (s, .neutral) }133    }134}135136struct PrivateMarketsView: View {137    @Environment(AppModel.self) private var model138    @Environment(\.horizontalSizeClass) private var sizeClass139    @State private var list = Loaded<PrivateMarketList>()140    @State private var selection: String?141    @State private var sortOrder = [KeyPathComparator(\PrivateCompanyRow.sortValuation, order: .reverse)]142143    var body: some View {144        Group { if sizeClass == .regular { wide } else { compact } }145            .task { if list.value == nil { await load() } }146            .refreshable { await load() }147    }148    private func load() async { list = await SnapshotRead.read(PrivateMarketList.self, path: "/private-markets", key: "markets-private", app: model, current: list) }149150    @ViewBuilder private var head: some View {151        FreshnessBanner()152        if let l = list.value {153            Notice(tone: .warn, title: String(localized: "Affichage seulement — non négociable depuis ce portefeuille"), message: l.notice.text, icon: "eye")154                .accessibilityIdentifier("private.notice")155            if !list.live { Label(String(localized: "Instantané du \(list.savedAt?.formatted(date: .abbreviated, time: .shortened) ?? "—")"), systemImage: "clock.badge.exclamationmark").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn) }156            ForEach(l.venues.filter { $0.status != "ok" }, id: \.venue) { v in Notice(tone: .warn, title: String(localized: "\(v.name ?? v.venue) : \(v.status)"), message: v.error) }157        } else if let e = list.error { ErrorNotice(error: e) { Task { await load() } }.accessibilityIdentifier("private.error") }158        else if model.offlineBrowsing { EmptyState(icon: "building.2", title: String(localized: "Marchés privés indisponibles hors ligne")) }159        else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }160    }161162    private var compact: some View {163        ScrollView {164            LazyVStack(alignment: .leading, spacing: 10) {165                head166                if let l = list.value {167                    ForEach(PrivateCompanyRow.rows(l).sorted { $0.sortValuation > $1.sortValuation }) { c in168                        NavigationLink { PrivateCompanyView(slug: c.slug, name: c.name).wallet(model) } label: {169                            VStack(alignment: .leading, spacing: 5) {170                                HStack { Text(c.name).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink); Spacer(); Image(systemName: "chevron.right").foregroundStyle(Theme.mute) }171                                Text(String(localized: "\(c.contracts) contrat(s) synthétique(s)")).font(.spFootnote).foregroundStyle(Theme.mute)172                                if let v = c.valuationText {173                                    Text(String(localized: "Dernière valorisation privée connue : \(Fmt.usdCompact(v) ?? v) · \(c.valuationKind.map(PrivateWords.referenceKind) ?? "") · \(c.valuationDate)"))174                                        .font(.spFootnote).foregroundStyle(Theme.mute).multilineTextAlignment(.leading)175                                } else { Text(String(localized: "Aucune valorisation privée de référence")).font(.spFootnote).foregroundStyle(Theme.mute) }176                            }.spCard()177                        }.buttonStyle(.plain).accessibilityIdentifier("private.company.\(c.slug)")178                    }179                    excluded(l)180                }181            }182            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)183        }184    }185186    private var wide: some View {187        HStack(spacing: 0) {188            VStack(alignment: .leading, spacing: 10) {189                head190                if let l = list.value {191                    Table(PrivateCompanyRow.rows(l).sorted(using: sortOrder), selection: $selection, sortOrder: $sortOrder) {192                        TableColumn(String(localized: "Société"), value: \.name) { Text($0.name).font(.system(size: 14.5, weight: .semibold)) }193                        TableColumn(String(localized: "Contrats"), value: \.contracts) { Text(String($0.contracts)).monospacedDigit() }194                        TableColumn(String(localized: "Dernière valorisation privée"), value: \.sortValuation) { c in Text(c.valuationText.map { Fmt.usdCompact($0) ?? $0 } ?? "—").monospacedDigit() }195                        TableColumn(String(localized: "Nature · date"), value: \.valuationDate) { c in Text([c.valuationKind.map(PrivateWords.referenceKind), c.valuationDate.isEmpty ? nil : c.valuationDate].compactMap { $0 }.joined(separator: " · ")).font(.system(size: 12.5)).foregroundStyle(Theme.mute) }196                    }.accessibilityIdentifier("private.table")197                } else { Spacer() }198            }199            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 12).frame(minWidth: 420, maxWidth: .infinity)200            if let s = selection, let c = list.value?.companies.first(where: { $0.slug == s }) {201                Divider()202                PrivateCompanyView(slug: c.slug, name: c.name).wallet(model).id(c.slug).frame(minWidth: 380, maxWidth: 560)203            }204        }205    }206207    @ViewBuilder private func excluded(_ l: PrivateMarketList) -> some View {208        if let ex = l.excluded, !ex.isEmpty {209            DisclosureGroup(String(localized: "Contrats écartés de la liste (\(ex.count))")) {210                ForEach(ex, id: \.id) { e in FieldRow(label: e.id + (e.company.map { " · \($0)" } ?? ""), value: e.reason) }211            }.font(.spCallout.weight(.semibold)).spCard()212        }213        if let na = l.venuesWithoutAdapter, !na.isEmpty {214            DisclosureGroup(String(localized: "Plateformes non lues (\(na.count))")) { ForEach(na, id: \.venue) { v in FieldRow(label: v.venue, value: v.note) } }.font(.spCallout.weight(.semibold)).spCard()215        }216    }217}218219struct PrivateCompanyView: View {220    @Environment(AppModel.self) private var model221    let slug: String222    let name: String223    @State private var detail = Loaded<PrivateCompanyDetail>()224225    var body: some View {226        ScrollView {227            VStack(alignment: .leading, spacing: Theme.Space.section) {228                FreshnessBanner()229                if let d = detail.value {230                    Notice(tone: .warn, title: String(localized: "Affichage seulement — non négociable"), message: d.notice.text, icon: "eye")231                    if !detail.live { Label(String(localized: "Instantané du \(detail.savedAt?.formatted(date: .abbreviated, time: .shortened) ?? "—")"), systemImage: "clock.badge.exclamationmark").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn) }232                    if let n = d.company.note { Text(n).font(.spFootnote).foregroundStyle(Theme.mute) }233                    referencesCard(d)234                    if !d.divergence.isEmpty { divergenceCard(d) }235                    ForEach(d.contracts) { m in PrivateContractSheet(market: m) }236                    if !d.delisted.isEmpty {237                        Text(String(localized: "Contrats retirés de la cote")).spEyebrow()238                        ForEach(d.delisted) { m in PrivateContractSheet(market: m) }239                    }240                    Text(String(localized: "Lu \(Fmt.date(ms: d.ts) ?? "—")")).font(.system(size: 12)).foregroundStyle(Theme.mute)241                } else if let e = detail.error { ErrorNotice(error: e) { Task { await load() } } }242                else if model.offlineBrowsing { EmptyState(icon: "building.2", title: String(localized: "Fiche indisponible hors ligne")) }243                else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }244            }245            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)246            .frame(maxWidth: 900).frame(maxWidth: .infinity)247        }248        .spPage()249        .navigationTitle(name).navigationBarTitleDisplayMode(.inline)250        .task { await load() }251        .refreshable { await load() }252    }253    private func load() async {254        detail = await SnapshotRead.read(PrivateCompanyDetail.self, path: "/private-markets/companies/\(APIClient.segment(slug))", key: "markets-private-company-\(slug)", app: model, current: detail)255    }256257    private func referencesCard(_ d: PrivateCompanyDetail) -> some View {258        VStack(alignment: .leading, spacing: 0) {259            SectionHeader(title: String(localized: "Valorisations privées de référence")).padding(.bottom, 4)260            if d.references.isEmpty { Text(String(localized: "Aucune référence.")).font(.spCallout).foregroundStyle(Theme.mute) }261            ForEach(Array(d.references.enumerated()), id: \.offset) { _, r in262                VStack(alignment: .leading, spacing: 3) {263                    Text((r.valueUsd.map { Fmt.usdCompact($0) ?? $0 } ?? r.value ?? String(localized: "montant non publié")) + " · " + PrivateWords.referenceKind(r.kind)).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink)264                    Text(r.date + " · " + PrivateWords.confidence(r.confidence)).font(.spFootnote).foregroundStyle(Theme.mute)265                    Text(r.detail).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)266                    if let u = URL(string: r.sourceUrl), u.scheme == "https" { Link(destination: u) { Label(u.host ?? r.sourceUrl, systemImage: "arrow.up.right.square").font(.spFootnote.weight(.semibold)) } }267                    else { Text(r.sourceUrl).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute) }268                }.padding(.vertical, 7)269                Divider()270            }271            if let m = d.mergedReason { Text(m).font(.system(size: 12)).foregroundStyle(Theme.mute).padding(.top, 6).fixedSize(horizontal: false, vertical: true) }272        }.spCard()273    }274275    private func divergenceCard(_ d: PrivateCompanyDetail) -> some View {276        VStack(alignment: .leading, spacing: 4) {277            SectionHeader(title: String(localized: "Écart entre contrats de même unité"))278            ForEach(Array(d.divergence.enumerated()), id: \.offset) { _, x in279                FieldRow(label: x.unitLabel ?? x.unit ?? String(localized: "unité"), value: String(localized: "écart \(x.spreadBps) pb · ") + x.contracts.map { "\($0.id) : \($0.price)" }.joined(separator: " · ") + (x.note.map { "\n\($0)" } ?? ""))280            }281        }.spCard()282    }283}284285/** The sheet of ONE synthetic contract, as reviewed. */286struct PrivateContractSheet: View {287    let market: PrivateMarket288    var now = Date()289290    var body: some View {291        let validity = PrivateSheet.validity(market.review, now: now)292        let (status, tone) = PrivateWords.status(market.status)293        return VStack(alignment: .leading, spacing: 0) {294            HStack(alignment: .top) {295                VStack(alignment: .leading, spacing: 2) {296                    Text(market.platform ?? market.venue).font(.spHeadline).foregroundStyle(Theme.ink)297                    Text(market.id).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute)298                }299                Spacer()300                Pill(text: status, tone: tone)301            }.padding(.bottom, 6)302            validityNotice(validity).padding(.bottom, 6)303            if let e = market.error { Notice(tone: .warn, title: String(localized: "Contrat illisible pour le moment"), message: e).padding(.bottom, 6) }304305            // market data: each figure with its source and date; the unit is named only on a valid sheet306            let unit: String? = { if case .valid = validity { return market.contract.unit.label }; return nil }()307            datum(String(localized: "Prix synthétique") + (unit.map { " — \($0)" } ?? " — " + String(localized: "unité non confirmée")), market.market.price ?? market.valuation.syntheticPrice)308            if market.market.frozen == true { Label(String(localized: "Prix figé : la plateforme ne le met plus à jour"), systemImage: "snowflake").font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.warn).padding(.vertical, 4) }309            if let o = market.market.oracle { Divider(); datum(String(localized: "Oracle"), o) }310            if let f = market.market.funding { Divider(); datum(String(localized: "Financement"), f) }311            if let v = market.market.volume24h { Divider(); datum(String(localized: "Volume 24 h"), v) }312            if let v = market.market.openInterestUsd { Divider(); datum(String(localized: "Intérêt ouvert (USD)"), v) }313            Divider()314315            // implied valuation: a number only from a published formula on a valid sheet316            let implied = PrivateSheet.impliedValuation(market, now: now)317            VStack(alignment: .leading, spacing: 3) {318                Text(String(localized: "Valorisation implicite de la société")).font(.spFootnote).foregroundStyle(Theme.mute)319                if let v = implied.value {320                    Text((market.valuation.impliedValuation.label.map { "\($0) : " } ?? "") + (Fmt.usdCompact(v) ?? v)).font(.spBody.weight(.semibold)).foregroundStyle(Theme.ink).accessibilityIdentifier("private.implied.value")321                    Text(String(localized: "Formule publiée : \(implied.why)")).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)322                    if let s = market.valuation.impliedValuation.formulaSource {323                        Text("« \(s.quote) » — " + String(localized: "lu le \(s.readAt)")).font(.system(size: 12)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)324                        if let u = URL(string: s.url), u.scheme == "https" { Link(destination: u) { Label(u.host ?? s.url, systemImage: "arrow.up.right.square").font(.system(size: 12, weight: .semibold)) } }325                    }326                } else {327                    Text(String(localized: "Non affichée : \(implied.why)")).font(.spBody.weight(.medium)).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("private.implied.none")328                }329            }.padding(.vertical, 7)330            if case .valid = validity {331                let p = market.valuation.premiumDiscount332                if let bps = p.premiumBps { Divider(); FieldRow(label: String(localized: "Prime / décote sur la dernière valorisation privée"), value: "\(bps) pb" + (p.caveat.map { "\n\($0)" } ?? "")) }333                else if let r = p.reason { Divider(); FieldRow(label: String(localized: "Prime / décote"), value: String(localized: "non calculée : \(r)")) }334            }335            if let ref = market.valuation.lastPrivateValuation {336                Divider()337                FieldRow(label: String(localized: "Dernière valorisation privée (référence)"), value: (ref.valueUsd.map { Fmt.usdCompact($0) ?? $0 } ?? ref.value ?? "—") + " · " + PrivateWords.referenceKind(ref.kind) + " · " + ref.date + " · " + PrivateWords.confidence(ref.confidence))338            }339            DisclosureGroup(String(localized: "Fiche du contrat")) { contractRows }.font(.spCallout.weight(.semibold)).padding(.top, 6)340            if !market.valuation.caveats.isEmpty {341                DisclosureGroup(String(localized: "Mises en garde (\(market.valuation.caveats.count))")) {342                    ForEach(market.valuation.caveats, id: \.code) { c in Text(c.text).font(.spFootnote).foregroundStyle(Theme.mute).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 3) }343                }.font(.spCallout.weight(.semibold))344            }345            if let nt = market.notTradable {346                Text(String(localized: "Non négociable (\(nt.code)) : \(nt.reasons.joined(separator: " "))")).font(.system(size: 12)).foregroundStyle(Theme.mute).padding(.top, 6).fixedSize(horizontal: false, vertical: true)347            }348        }349        .spCard()350    }351352    @ViewBuilder private func validityNotice(_ v: PrivateSheet.Validity) -> some View {353        switch v {354        case .expired(let until):355            Notice(tone: .danger, title: String(localized: "Fiche expirée"), message: String(localized: "Valide jusqu’au \(until). Aucune unité ni valorisation dérivée n’est affichée tant que la fiche n’a pas été revue. \(market.review.reasons.joined(separator: " "))"), icon: "calendar.badge.exclamationmark")356                .accessibilityIdentifier("private.sheet.expired")357        case .notReviewed(let state):358            Notice(tone: .warn, title: PrivateSheet.reviewLabel(state).capitalized, message: market.review.reasons.joined(separator: " "))359        case .valid(let until):360            Label([PrivateSheet.reviewLabel(market.review.state), market.review.reviewedAt.map { String(localized: "revue le \($0)") }, until.map { String(localized: "valide jusqu’au \($0)") }].compactMap { $0 }.joined(separator: " · "), systemImage: "checkmark.seal.fill")361                .font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.emerald)362        }363    }364365    private func datum(_ label: String, _ d: SourcedDatum) -> some View {366        VStack(alignment: .leading, spacing: 3) {367            Text(label).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)368            Text(d.value.map { Money.brief($0, maxFraction: 6) } ?? String(localized: "indisponible")).font(.spBody.weight(.medium)).monospacedDigit().foregroundStyle(d.stale ? Theme.mute : Theme.ink)369            Label([d.stale ? String(localized: "périmé") : nil, String(localized: "source : \(d.source)"), Fmt.date(ms: d.ts), d.priceKind].compactMap { $0 }.joined(separator: " · "), systemImage: d.stale ? "clock.badge.exclamationmark" : "clock")370                .font(.system(size: 11.5)).foregroundStyle(d.stale ? Theme.warn : Theme.mute)371        }.padding(.vertical, 7)372    }373374    @ViewBuilder private var contractRows: some View {375        let c = market.contract376        let rows: [(String, String?)] = [377            (String(localized: "Nature"), c.nature), (String(localized: "Opérateur"), market.operator), (String(localized: "Sous-jacent"), c.underlying),378            (String(localized: "Devise de cotation · collatéral"), [c.quoteCurrency, c.collateral].compactMap { $0 }.joined(separator: " · ")),379            (String(localized: "Taille du contrat"), c.contractSize), (String(localized: "Règlement"), c.settlement), (String(localized: "Conversion à l’introduction en bourse"), c.ipoConversion),380            (String(localized: "Oracle"), c.oracle), (String(localized: "Liquidation"), c.liquidation), (String(localized: "Levier maximal · marge"), [c.maxLeverage, c.margin].compactMap { $0 }.joined(separator: " · ")),381            (String(localized: "Description sur la chaîne"), c.onChainDescription),382        ]383        ForEach(Array(rows.enumerated()), id: \.offset) { _, r in if let v = r.1, !v.isEmpty { FieldRow(label: r.0, value: v) } }384        if let s = c.sources, !s.isEmpty { FieldRow(label: String(localized: "Sources de la fiche"), value: s.joined(separator: "\n"), mono: true) }385    }386}387
Files main
Menu

Theme