SPB Git

Repository Public

ActivityView.swift 17.1 KB 274 lines swift

1// SP Wallet iOS2// File: Features/Activity/ActivityView.swift3// Description: Transaction history: every proposal with its real state (intermediate states kept) and every observed deposit.4//              Search, filters, detail with full identifiers, explorer link, CSV export (the server's own file) and PDF export5//              (rendered locally from what is displayed).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112struct ActivityFilter: Equatable {13    var kind: String?14    var network: String?15    var status: Status = .all16    enum Status: String, CaseIterable { case all, inProgress, settled, failed17        var label: String { switch self { case .all: String(localized: "Tous les états"); case .inProgress: String(localized: "En cours"); case .settled: String(localized: "Confirmées"); case .failed: String(localized: "Échouées ou refusées") } }18    }19    var isActive: Bool { kind != nil || network != nil || status != .all }2021    func matches(_ i: ActivityItem, query: String) -> Bool {22        if let kind, i.kind != kind { return false }23        if let network, i.network != network { return false }24        switch status {25        case .all: break26        case .settled: if !i.isSettled { return false }27        case .failed: if !(i.proposalState?.isFailure ?? false) { return false }28        case .inProgress: if i.isSettled || (i.proposalState?.isTerminal ?? false) { return false }29        }30        if query.isEmpty { return true }31        let q = query.lowercased()32        return [i.symbol, i.txid, i.to, i.from, i.note, i.networkName, i.amountDisplay, i.memo].compactMap { $0?.lowercased() }.contains { $0.contains(q) }33    }34}3536struct ActivityView: View {37    @Environment(AppModel.self) private var model38    @State private var query = ""39    @State private var filter = ActivityFilter()40    @State private var exportURL: URL?41    @State private var exportError: Error?42    @State private var exporting = false4344    private var items: [ActivityItem] { (model.activity.value ?? []).filter { filter.matches($0, query: query) } }4546    var body: some View {47        let grouped = Dictionary(grouping: items) { Calendar.current.startOfDay(for: $0.at) }.sorted { $0.key > $1.key }48        List {49            Section { FreshnessBanner().listRowInsets(.init()).listRowBackground(Color.clear) }50            if let e = exportError { Section { ErrorNotice(error: e) } }51            if model.activity.value == nil {52                if let e = model.activity.error { ErrorNotice(error: e) { Task { await model.refreshActivity() } } } else { ProgressView() }53            } else if items.isEmpty {54                EmptyState(icon: "clock", title: filter.isActive || !query.isEmpty ? String(localized: "Aucun résultat") : String(localized: "Aucune transaction"))55                    .listRowBackground(Color.clear)56            }57            ForEach(grouped, id: \.key) { day, rows in58                Section(day.formatted(date: .complete, time: .omitted)) {59                    ForEach(rows) { i in NavigationLink(value: i) { TransactionRow(item: i) }.accessibilityIdentifier("activity.row") }60                }61            }62        }63        .listStyle(.insetGrouped).scrollContentBackground(.hidden).spPage()64        .searchable(text: $query, prompt: String(localized: "Adresse, hash, actif, note"))65        .refreshable { await model.refreshActivity() }66        .navigationTitle(AppSection.activity.title)67        .navigationDestination(for: ActivityItem.self) { ActivityDetailView(item: $0).wallet(model) }68        .toolbar {69            ToolbarItem(placement: .topBarTrailing) { filterMenu }70            ToolbarItem(placement: .topBarTrailing) { exportMenu }71        }72        .sheet(item: $exportURL) { url in ShareSheet(items: [url]) }73    }7475    private var filterMenu: some View {76        Menu {77            Picker(String(localized: "Type"), selection: $filter.kind) {78                Text(String(localized: "Tous les types")).tag(String?.none)79                Text(String(localized: "Envois")).tag(String?("send")); Text(String(localized: "Réceptions")).tag(String?("receive"))80                Text(String(localized: "Échanges")).tag(String?("swap")); Text(String(localized: "Ponts")).tag(String?("bridge"))81            }82            Picker(String(localized: "État"), selection: $filter.status) { ForEach(ActivityFilter.Status.allCases, id: \.self) { Text($0.label).tag($0) } }83            Picker(String(localized: "Réseau"), selection: $filter.network) {84                Text(String(localized: "Tous les réseaux")).tag(String?.none)85                ForEach(Array(Set((model.activity.value ?? []).map(\.network))).sorted(), id: \.self) { n in Text(model.network(n)?.name ?? n).tag(String?(n)) }86            }87            if filter.isActive { Button(String(localized: "Effacer les filtres"), role: .destructive) { filter = ActivityFilter() } }88        } label: { Image(systemName: filter.isActive ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle") }89        .accessibilityLabel(String(localized: "Filtrer"))90    }9192    private var exportMenu: some View {93        Menu {94            Button { Task { await exportCSV() } } label: { Label(String(localized: "Exporter en CSV (tout l’historique)"), systemImage: "tablecells") }.disabled(model.offlineBrowsing || model.offline)95            Button { exportPDF() } label: { Label(String(localized: "Exporter en PDF (liste affichée)"), systemImage: "doc.richtext") }.disabled(items.isEmpty)96        } label: { if exporting { ProgressView() } else { Image(systemName: "square.and.arrow.up") } }97        .accessibilityLabel(String(localized: "Exporter"))98    }99100    private func exportCSV() async {101        exporting = true; defer { exporting = false }102        do {103            let data = try await model.env.wallet.activityCSV()104            exportURL = try ExportFiles.write(data, name: "sp-wallet-activity-\(ExportFiles.stamp()).csv"); exportError = nil105        } catch { exportError = error }106    }107108    private func exportPDF() {109        do {110            let data = ActivityPDF.render(items: items, title: String(localized: "SP Wallet — historique"), savedAt: model.activity.savedAt, live: model.activity.live,111                                          networkName: { model.network($0)?.name ?? $0 })112            exportURL = try ExportFiles.write(data, name: "sp-wallet-activity-\(ExportFiles.stamp()).pdf"); exportError = nil113        } catch { exportError = error }114    }115}116117extension URL: @retroactive Identifiable { public var id: String { absoluteString } }118119enum ExportFiles {120    static func stamp() -> String { Date().formatted(.iso8601.year().month().day().dateSeparator(.dash)) }121    /** Exports live in the temporary directory, protected while the device is locked, and are removed by the system. */122    static func write(_ data: Data, name: String) throws -> URL {123        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("exports", isDirectory: true)124        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)125        let url = dir.appendingPathComponent(name)126        try data.write(to: url, options: [.atomic, .completeFileProtection])127        return url128    }129}130131struct ShareSheet: UIViewControllerRepresentable {132    let items: [Any]133    func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: items, applicationActivities: nil) }134    func updateUIViewController(_ c: UIActivityViewController, context: Context) {}135}136137enum ActivityPDF {138    /** A plain, complete table: date, type, network, amount, state, counterparty, hash. Nothing is abbreviated. */139    static func render(items: [ActivityItem], title: String, savedAt: Date?, live: Bool, networkName: (String) -> String) -> Data {140        let page = CGRect(x: 0, y: 0, width: 612, height: 792), margin: CGFloat = 40141        let renderer = UIGraphicsPDFRenderer(bounds: page)142        let head = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: .semibold)]143        let small = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 8.5), .foregroundColor: UIColor.darkGray]144        let body = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 9.5, weight: .medium)]145        let mono = [NSAttributedString.Key.font: UIFont.monospacedSystemFont(ofSize: 7.5, weight: .regular), .foregroundColor: UIColor.darkGray]146        return renderer.pdfData { ctx in147            var y: CGFloat = 0148            func newPage() {149                ctx.beginPage(); y = margin150                (title as NSString).draw(at: CGPoint(x: margin, y: y), withAttributes: head); y += 22151                let note = (live ? String(localized: "Données du serveur") : String(localized: "Instantané hors ligne")) + (savedAt.map { " · " + $0.formatted(date: .abbreviated, time: .standard) } ?? "")152                    + " · " + String(localized: "\(items.count) lignes") + " · " + String(localized: "seul l’état « confirmé » atteste une transaction réglée")153                (note as NSString).draw(at: CGPoint(x: margin, y: y), withAttributes: small); y += 18154            }155            newPage()156            for i in items {157                if y > page.height - margin - 44 { newPage() }158                let (state, _, _) = activityStateLabel(i)159                let line1 = "\(i.at.formatted(date: .numeric, time: .shortened))   \(i.kind)   \(networkName(i.network))   \(i.isIncoming ? "+" : "−")\(i.amountDisplay ?? i.amount) \(i.symbol)   \(state)"160                (line1 as NSString).draw(in: CGRect(x: margin, y: y, width: page.width - 2 * margin, height: 14), withAttributes: body); y += 13161                let party = i.isIncoming ? (i.from.map { "de \($0)" } ?? "") : (i.to.map { "à \($0)" } ?? "")162                let line2 = [party, i.txid.map { "tx \($0)" } ?? ""].filter { !$0.isEmpty }.joined(separator: "   ")163                let rect = (line2 as NSString).boundingRect(with: CGSize(width: page.width - 2 * margin, height: 60), options: .usesLineFragmentOrigin, attributes: mono, context: nil)164                (line2 as NSString).draw(in: CGRect(x: margin, y: y, width: page.width - 2 * margin, height: rect.height + 2), withAttributes: mono); y += rect.height + 9165            }166        }167    }168}169170struct ActivityDetailView: View {171    @Environment(AppModel.self) private var model172    let item: ActivityItem173174    var body: some View {175        let (label, tone, symbol) = activityStateLabel(item)176        ScrollView {177            VStack(alignment: .leading, spacing: Theme.Space.section) {178                VStack(alignment: .leading, spacing: 6) {179                    Label(label, systemImage: symbol).font(.spCallout.weight(.semibold)).foregroundStyle(tone.color)180                    Text((item.isIncoming ? "+" : "−") + Money.exact(item.amountDisplay ?? item.amount) + " " + item.symbol)181                        .font(.system(size: 30, weight: .semibold)).tracking(-0.6).foregroundStyle(Theme.ink).textSelection(.enabled)182                }183                if !item.isIncoming, !(item.proposalState?.isTerminal ?? true) { ProposalTracker(proposalId: item.id) }184                VStack(alignment: .leading, spacing: 0) {185                    FieldRow(label: String(localized: "Date"), value: item.at.formatted(date: .complete, time: .standard)); Divider()186                    FieldRow(label: String(localized: "Réseau"), value: item.networkName ?? item.network); Divider()187                    FieldRow(label: String(localized: "Actif"), value: item.symbol + (item.asset.map { $0 == "native" ? "" : " · \($0)" } ?? ""), mono: item.asset != nil && item.asset != "native")188                    if let f = item.from { Divider(); FieldRow(label: String(localized: "De"), value: f, mono: true, copyable: true) }189                    if let t = item.to { Divider(); FieldRow(label: String(localized: "À"), value: t, mono: true, copyable: true) }190                    if let m = item.memo, !m.isEmpty { Divider(); FieldRow(label: String(localized: "Mémo / tag"), value: m, mono: true) }191                    if let n = item.note, !n.isEmpty { Divider(); FieldRow(label: String(localized: "Note"), value: n) }192                    if let f = item.feeDisplay { Divider(); FieldRow(label: String(localized: "Frais estimés"), value: Money.exact(f) + " " + (item.feeSymbol ?? "")) }193                    if let c = item.confirmations { Divider(); FieldRow(label: String(localized: "Confirmations"), value: String(c)) }194                    if let t = item.txid { Divider(); FieldRow(label: String(localized: "Hash de transaction"), value: t, mono: true, copyable: true) }195                    if let e = item.error { Divider(); FieldRow(label: String(localized: "Erreur"), value: e + (item.errorCode.map { " (\($0))" } ?? ""), tone: .danger) }196                }.spCard(padding: 16)197                ForEach(sections, id: \.0) { title, value in198                    VStack(alignment: .leading, spacing: 4) { SectionHeader(title: title); JSONFields(value: value) }.spCard(padding: 16)199                }200                if let e = item.explorer, let u = URL(string: e), u.scheme == "https" {201                    Link(destination: u) { Label(String(localized: "Ouvrir dans l’explorateur du réseau"), systemImage: "arrow.up.right.square") }.buttonStyle(.spSecondary)202                    Text(u.host ?? "").font(.spFootnote).foregroundStyle(Theme.mute)203                }204            }205            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)206            .frame(maxWidth: 760).frame(maxWidth: .infinity)207        }208        .spPage()209        .navigationTitle(String(localized: "Transaction")).navigationBarTitleDisplayMode(.inline)210    }211212    private var sections: [(String, JSONValue)] {213        var s: [(String, JSONValue)] = []214        if let v = item.swap, !v.isNull { s.append((String(localized: "Échange"), v)) }215        if let v = item.bridge, !v.isNull { s.append((String(localized: "Transfert entre réseaux"), v)) }216        if let v = item.xswap, !v.isNull { s.append((String(localized: "Échange natif entre réseaux"), v)) }217        if let v = item.nft, !v.isNull { s.append(("NFT", v)) }218        return s219    }220}221222/** A proposal opened by id (dashboard "in progress"): its live status, then its fields. */223struct ProposalDetailView: View {224    @Environment(AppModel.self) private var model225    let proposalId: String226    @State private var proposal: Proposal?227    @State private var error: Error?228    var body: some View {229        ScrollView {230            VStack(alignment: .leading, spacing: Theme.Space.section) {231                if let p = proposal {232                    Text("−" + Money.exact(p.amountDisplay) + " " + p.symbol).font(.system(size: 30, weight: .semibold)).tracking(-0.6).foregroundStyle(Theme.ink)233                    ProposalTracker(proposalId: p.id)234                    VStack(alignment: .leading, spacing: 0) {235                        FieldRow(label: String(localized: "Réseau"), value: p.networkName ?? p.network)236                        if let t = p.to { Divider(); FieldRow(label: String(localized: "À"), value: t, mono: true, copyable: true) }237                        if let f = p.maxFeeDisplay { Divider(); FieldRow(label: String(localized: "Frais, plafond"), value: Money.exact(f) + " " + (p.feeSymbol ?? "")) }238                        if let h = p.intentHash { Divider(); FieldRow(label: String(localized: "Empreinte de l’intention"), value: h, mono: true, copyable: true) }239                    }.spCard(padding: 16)240                } else if let error { ErrorNotice(error: error) } else { ProgressView().frame(maxWidth: .infinity).padding(.top, 60) }241            }242            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28).frame(maxWidth: 760).frame(maxWidth: .infinity)243        }244        .spPage()245        .navigationTitle(String(localized: "Opération")).navigationBarTitleDisplayMode(.inline)246        .task { do { proposal = try await model.env.transfers.proposal(proposalId) } catch let e { error = e } }247    }248}249250/** Server-provided detail rendered as labelled rows, verbatim: nested objects are indented; nothing is interpreted. */251struct JSONFields: View {252    let value: JSONValue253    var depth = 0254    var body: some View {255        if let o = value.objectValue {256            VStack(alignment: .leading, spacing: 0) {257                ForEach(o.keys.sorted(), id: \.self) { k in258                    if let v = o[k], !v.isNull {259                        if v.objectValue != nil || v.arrayValue != nil {260                            Text(k).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.mute).padding(.top, 8)261                            JSONFields(value: v, depth: depth + 1).padding(.leading, 12)262                        } else { FieldRow(label: k, value: Self.text(v), mono: Self.text(v).count > 24, copyable: true) }263                    }264                }265            }266        } else if let a = value.arrayValue {267            VStack(alignment: .leading, spacing: 0) { ForEach(Array(a.enumerated()), id: \.offset) { _, v in JSONFields(value: v, depth: depth + 1) } }268        } else { Text(Self.text(value)).font(.spMono).foregroundStyle(Theme.ink) }269    }270    static func text(_ v: JSONValue) -> String {271        switch v { case .string(let s): s; case .int(let i): String(i); case .double(let d): String(d); case .bool(let b): b ? String(localized: "oui") : String(localized: "non"); default: "" }272    }273}274
Files main
Menu

Theme