Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Activity/ActivityView.swift3// Description: Transaction history: date, network, asset, amount, fee, address, type, hash, status and confirmations, with search, filters, CSV and PDF export and links to the network's block explorer. Intermediate states are kept as they are; a broadcast transaction is never shown as a success.4import SwiftUI5import UniformTypeIdentifiers6import SPWalletCore78struct ActivityView: View {9 let model: AppModel10 @State private var search = ""11 @State private var kind = "all"12 @State private var network = "all"13 @State private var status = "all"14 @State private var selection: ActivityItem.ID?15 @State private var exportMessage: String?16 @State private var sort = [KeyPathComparator(\ActivityItem.at, order: .reverse)]1718 private var items: [ActivityItem] {19 let q = search.trimmingCharacters(in: .whitespaces).lowercased()20 return (model.activity?.value ?? []).filter { i in21 (kind == "all" || i.kind == kind) && (network == "all" || i.network == network) &&22 (status == "all" || (status == "final" ? i.isSettled : status == "pending" ? (!i.isSettled && i.proposalState?.isFailure != true && i.state != "not_broadcast") : (i.proposalState?.isFailure == true || i.state == "not_broadcast"))) &&23 (q.isEmpty || [i.symbol, i.networkName ?? "", i.to ?? "", i.from ?? "", i.txid ?? "", i.note ?? "", i.memo ?? ""].contains { $0.lowercased().contains(q) })24 }.sorted(using: sort)25 }2627 var body: some View {28 let rows = items29 VStack(spacing: 0) {30 HStack {31 Text("Activité").font(.largeTitle.weight(.semibold))32 Spacer()33 if let src = model.activity { ProvenanceTag(p: src.fromCache ? .stale : .verified, text: src.fromCache ? "Synchronisée le \(Fmt.date(src.fetchedAt))" : "À jour \(Fmt.relative(src.fetchedAt))") }34 }.padding([.horizontal, .top], 24)35 HStack {36 TextField("Rechercher (adresse, hash, actif, note)", text: $search).textFieldStyle(.roundedBorder).frame(maxWidth: 320)37 Picker("Type", selection: $kind) { Text("Tous types").tag("all"); ForEach(["send", "receive", "swap", "bridge", "gmx"], id: \.self) { Text(TransactionRow.kindTitle($0)).tag($0) } }.frame(width: 170)38 Picker("Réseau", selection: $network) { Text("Tous réseaux").tag("all"); ForEach(Array(Set((model.activity?.value ?? []).map(\.network))).sorted(), id: \.self) { Text(model.network($0)?.name ?? $0).tag($0) } }.frame(width: 200)39 Picker("État", selection: $status) { Text("Tous états").tag("all"); Text("Finalisées").tag("final"); Text("En cours").tag("pending"); Text("Échecs").tag("failed") }.frame(width: 160)40 Spacer()41 Menu("Exporter") {42 Button("CSV — sélection affichée (\(rows.count))…") { exportCSV(rows) }43 Button("CSV complet du serveur…") { Task { await exportServerCSV() } }.disabled(!model.canOperate)44 Button("PDF — sélection affichée (\(rows.count))…") { exportPDF(rows) }45 }.frame(width: 110)46 }.labelsHidden().padding(.horizontal, 24).padding(.vertical, 10)47 if let m = exportMessage { Text(m).font(.callout).foregroundStyle(.secondary).padding(.horizontal, 24).frame(maxWidth: .infinity, alignment: .leading) }48 Table(rows, selection: $selection, sortOrder: $sort) {49 TableColumn("Date", value: \.at) { Text(Fmt.date($0.at)).monospacedDigit() }.width(min: 130, ideal: 150)50 TableColumn("Type") { Text(TransactionRow.kindTitle($0.kind)) }.width(80)51 TableColumn("Réseau") { Text($0.networkName ?? $0.network) }.width(min: 90, ideal: 110)52 TableColumn("Montant") { i in Text("\(i.isIncoming ? "+" : "−")\(Fmt.amount(i.amountDisplay, maxFraction: 8)) \(i.symbol)").monospacedDigit() }.width(min: 130, ideal: 170)53 TableColumn("Frais") { i in Text(i.feeDisplay.map { "\(Fmt.amount($0, maxFraction: 8)) \(i.feeSymbol ?? "")" } ?? "—").monospacedDigit().foregroundStyle(.secondary) }.width(min: 90, ideal: 120)54 TableColumn("Contrepartie") { i in Text(Fmt.short(i.isIncoming ? i.from : i.to)).font(Theme.monoSmall) }.width(min: 120, ideal: 150)55 TableColumn("État") { StatusPill(raw: $0.state) }.width(min: 130, ideal: 180)56 TableColumn("Conf.") { Text($0.confirmations.map(String.init) ?? "—").monospacedDigit() }.width(46)57 }58 .overlay { if rows.isEmpty { EmptyState(symbol: "list.bullet.rectangle", title: model.activity == nil ? "Historique non synchronisé" : "Aucune transaction ne correspond") } }59 if let id = selection, let item = rows.first(where: { $0.id == id }) { Divider(); ActivityDetail(item: item).padding(16).frame(maxHeight: 250) }60 }61 .background(Color(nsColor: .windowBackgroundColor))62 }6364 // MARK: export6566 private func save(_ type: UTType, name: String, data: @escaping () -> Data?) {67 let panel = NSSavePanel(); panel.allowedContentTypes = [type]; panel.nameFieldStringValue = name; panel.canCreateDirectories = true68 guard panel.runModal() == .OK, let url = panel.url else { return }69 guard let d = data() else { exportMessage = "Export impossible."; return }70 do { try d.write(to: url, options: .atomic); exportMessage = "Exporté : \(url.lastPathComponent)" } catch { exportMessage = "Écriture impossible : \(error.localizedDescription)" }71 }72 private func exportCSV(_ rows: [ActivityItem]) { save(.commaSeparatedText, name: "sp-wallet-activite.csv") { ActivityExport.csv(rows).data(using: .utf8) } }73 private func exportPDF(_ rows: [ActivityItem]) { save(.pdf, name: "sp-wallet-activite.pdf") { ActivityExport.pdf(rows, title: "SP Wallet — activité", subtitle: "\(rows.count) opérations · exporté le \(Fmt.date(Date()))\(model.activity?.fromCache == true ? " · données locales du \(Fmt.date(model.activity?.fetchedAt))" : "")") } }74 private func exportServerCSV() async {75 do { let d = try await model.wallet.activityCSV(); save(.commaSeparatedText, name: "sp-wallet-activity.csv") { d } } catch { exportMessage = model.describe(error) }76 }77}7879struct ActivityDetail: View {80 let item: ActivityItem81 var body: some View {82 ScrollView {83 VStack(alignment: .leading, spacing: 6) {84 HStack { Text("\(TransactionRow.kindTitle(item.kind)) · \(Fmt.dateSeconds(item.at))").font(.headline); Spacer(); StatusPill(raw: item.state) }85 Field(label: "Réseau", value: item.networkName ?? item.network)86 Field(label: "Actif", value: item.asset.map { $0 == "native" ? "\(item.symbol) (natif)" : "\(item.symbol) — \($0)" } ?? item.symbol)87 Field(label: "Montant", value: "\(Fmt.amount(item.amountDisplay)) \(item.symbol) (\(item.amount) unités de base)")88 if let f = item.from { Field(label: "De", value: f, mono: true) }89 if let t = item.to { Field(label: "Vers", value: t, mono: true) }90 if let f = item.feeDisplay { Field(label: "Frais", value: "\(f) \(item.feeSymbol ?? "") (estimation au moment de la préparation)") }91 if let m = item.memo { Field(label: "Mémo", value: m) }92 if let n = item.note, !n.isEmpty { Field(label: "Note", value: n) }93 if let tx = item.txid { Field(label: "Hash", value: tx, mono: true) }94 if let c = item.confirmations { Field(label: "Confirmations", value: String(c)) }95 if let e = item.error { Banner(.warning, e) }96 if !item.isSettled, item.txid != nil, item.proposalState?.isFailure != true { Text("Un hash de transaction n’est pas une confirmation : seul l’état « Finalisée » atteste du succès.").font(.caption).foregroundStyle(.secondary) }97 if let ex = item.explorer, let u = URL(string: ex), u.scheme == "https" { Link("Ouvrir dans l’explorateur (\(u.host ?? ""))", destination: u) }98 }99 }100 }101}102103enum ActivityExport {104 /// Spreadsheet-safe CSV: quotes doubled, and a leading = + - @ neutralized (formula injection).105 static func cell(_ v: String) -> String {106 var s = v.replacingOccurrences(of: "\"", with: "\"\"")107 if let f = s.first, "=+-@\t\r".contains(f) { s = "'" + s }108 return "\"\(s)\""109 }110 static func csv(_ rows: [ActivityItem]) -> String {111 var lines = ["date_utc,type,reseau,actif,contrat,montant,montant_unites_de_base,frais,de,vers,memo,etat,confirmations,hash,explorateur"]112 for i in rows {113 lines.append([ISO8601.string(i.at), i.kind, i.network, i.symbol, i.asset ?? "", i.amountDisplay ?? "", i.amount, i.feeDisplay.map { "\($0) \(i.feeSymbol ?? "")" } ?? "", i.from ?? "", i.to ?? "", i.memo ?? "", i.state, i.confirmations.map(String.init) ?? "", i.txid ?? "", i.explorer ?? ""].map(cell).joined(separator: ","))114 }115 return lines.joined(separator: "\r\n") + "\r\n"116 }117118 /// A paginated A4-landscape PDF drawn with Core Text (no web engine involved).119 static func pdf(_ rows: [ActivityItem], title: String, subtitle: String) -> Data? {120 let page = CGRect(x: 0, y: 0, width: 842, height: 595), margin: CGFloat = 36121 let data = NSMutableData()122 guard let consumer = CGDataConsumer(data: data), let ctx = CGContext(consumer: consumer, mediaBox: nil, nil) else { return nil }123 let cols: [(String, CGFloat)] = [("Date", 105), ("Type", 60), ("Réseau", 80), ("Montant", 130), ("Contrepartie", 150), ("État", 110), ("Hash", 135)]124 let font = NSFont.systemFont(ofSize: 8), bold = NSFont.boldSystemFont(ofSize: 8), mono = NSFont.monospacedSystemFont(ofSize: 7, weight: .regular)125 func draw(_ s: String, _ f: NSFont, x: CGFloat, y: CGFloat, w: CGFloat, color: NSColor = .black) {126 let p = NSMutableParagraphStyle(); p.lineBreakMode = .byTruncatingMiddle127 let line = CTLineCreateWithAttributedString(NSAttributedString(string: s, attributes: [.font: f, .foregroundColor: color, .paragraphStyle: p]))128 let fit = CTLineCreateTruncatedLine(line, Double(w - 4), .middle, nil) ?? line129 ctx.textPosition = CGPoint(x: x, y: y); CTLineDraw(fit, ctx)130 }131 var index = 0, pageNo = 0132 let perPage = Int((page.height - 2 * margin - 60) / 13)133 repeat {134 pageNo += 1135 var box = page; ctx.beginPage(mediaBox: &box)136 draw(title, NSFont.boldSystemFont(ofSize: 14), x: margin, y: page.height - margin - 8, w: 500)137 draw(subtitle, font, x: margin, y: page.height - margin - 24, w: 700, color: .darkGray)138 var x = margin; let top = page.height - margin - 46139 for (name, w) in cols { draw(name, bold, x: x, y: top, w: w); x += w }140 ctx.setStrokeColor(NSColor.gray.cgColor); ctx.setLineWidth(0.5); ctx.move(to: CGPoint(x: margin, y: top - 4)); ctx.addLine(to: CGPoint(x: page.width - margin, y: top - 4)); ctx.strokePath()141 var y = top - 16142 for i in rows[index..<min(index + perPage, rows.count)] {143 x = margin144 let cells: [(String, NSFont)] = [(Fmt.date(i.at), font), (TransactionRow.kindTitle(i.kind), font), (i.networkName ?? i.network, font),145 ("\(i.isIncoming ? "+" : "−")\(i.amountDisplay ?? i.amount) \(i.symbol)", font), ((i.isIncoming ? i.from : i.to) ?? "—", mono), (ErrorText.activityState(i.state), font), (i.txid ?? "—", mono)]146 for (k, c) in cells.enumerated() { draw(c.0, c.1, x: x, y: y, w: cols[k].1); x += cols[k].1 }147 y -= 13148 }149 index += perPage150 draw("Page \(pageNo) · Seul l’état « Finalisée » atteste d’un succès confirmé par la chaîne.", font, x: margin, y: margin - 14, w: 600, color: .gray)151 ctx.endPage()152 } while index < rows.count153 ctx.closePDF()154 return data as Data155 }156}157