summaryrefslogtreecommitdiff
path: root/TalerWallet1/Views/Transactions/TransactionDetailView.swift
blob: bae70f27944f51e7979a0de725e13957d8b90afd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
 * This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
 * See LICENSE.md
 */
import SwiftUI
import taler_swift
import SymLog

extension Transaction {             // for Dummys
    init(dummyCurrency: String) {
        let amount = try! Amount(fromString: "\(dummyCurrency):0")
        let now = Timestamp.now()
        let common = TransactionCommon(type: .dummy,
                                       txState: TransactionState(major: .pending),
                                       amountEffective: amount,
                                       amountRaw: amount,
                                       transactionId: "",
                                       timestamp: now,
                                       txActions: [])
        self = .dummy(DummyTransaction(common: common))
    }
}
// MARK: -
struct TransactionDetailView: View {
    private let symLog = SymLogV(0)
    let stack: CallStack
    @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic
#if DEBUG
    @AppStorage("developerMode") var developerMode: Bool = true
#else
    @AppStorage("developerMode") var developerMode: Bool = false
#endif

    let transactionId: String
    let reloadAction: ((_ transactionId: String) async throws -> Transaction)

    let navTitle: String?
    let doneAction: (() -> Void)?
    let abortAction: ((_ transactionId: String) async throws -> Void)?
    let deleteAction: ((_ transactionId: String) async throws -> Void)?
    let failAction: ((_ transactionId: String) async throws -> Void)?
    let suspendAction: ((_ transactionId: String) async throws -> Void)?
    let resumeAction: ((_ transactionId: String) async throws -> Void)?

    @State var transaction: Transaction = Transaction(dummyCurrency: DEMOCURRENCY)
    @State var viewId = UUID()

    func accessibilityDate(_ date: Date?) -> String? {
        if let date {
            let formatted = date.formatted(date: .long, time: .shortened)
//            print(formatted)
            return formatted
        }
        return nil
    }

    var body: some View {
#if DEBUG
        let _ = Self._printChanges()
        let _ = symLog.vlog()       // just to get the # to compare it with .onAppear & onDisappear
#endif
        let common = transaction.common
        let pending = transaction.isPending
        let locale = TalerDater.shared.locale
        let (dateString, date) = TalerDater.dateString(from: common.timestamp)
        let accessibilityDate = accessibilityDate(date) ?? dateString
        let navTitle2 = transaction.localizedType
        Group {
            List {
                if developerMode {
                    if transaction.isSuspendable { if let suspendAction {
                        TransactionButton(transactionId: common.transactionId,
                                          command: .suspend, action: suspendAction)
                    } }
                    if transaction.isResumable { if let resumeAction {
                        TransactionButton(transactionId: common.transactionId,
                                          command: .resume, action: resumeAction)
                    } }
                } // Suspend + Resume buttons
                Text(dateString)
                    .accessibilityFont(.body)
                    .accessibilityLabel(accessibilityDate)
                    .foregroundColor(.secondary)
                    .listRowSeparator(.hidden)
                HStack {
                    Text(verbatim: "|")   // only reason for this leading-aligned text is to get a nice full length listRowSeparator
                        .accessibilityHidden(true)
                        .foregroundColor(Color.clear)
                    Spacer()
                    Text("Status: \(common.txState.major.localizedState)")
                }    .listRowSeparator(.automatic)
                    .accessibilityFont(.title)
                SwitchCase(transaction: $transaction, hasDone: doneAction != nil)

                if transaction.isAbortable { if let abortAction {
                    TransactionButton(transactionId: common.transactionId,
                                      command: .abort, action: abortAction)
                } } // Abort button
                if transaction.isFailable { if let failAction {
                    TransactionButton(transactionId: common.transactionId,
                                      command: .fail, action: failAction)
                } } // Fail button
                if transaction.isDeleteable { if let deleteAction {
                    TransactionButton(transactionId: common.transactionId,
                                      command: .delete, action: deleteAction)
                } } // Delete button
            }.id(viewId)    // change viewId to enforce a draw update
            .listStyle(myListStyle.style).anyView
                .safeAreaInset(edge: .bottom) {
                    if let doneAction {
                        Button(transaction.shouldConfirm ? "Confirm later" : "Done", action: doneAction)
                            .buttonStyle(TalerButtonStyle(type: transaction.shouldConfirm ? .bordered : .prominent))
                            .padding(.horizontal)
                    }
                }
        }.onNotification(.TransactionStateTransition) { notification in
            if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition {
                if transition.transactionId == common.transactionId {       // is the transition for THIS transaction?
                    let newMajor = transition.newTxState.major
                    let newMinor = transition.newTxState.minor
                    if let doneAction {
                        if newMajor == .done {
                            symLog.log("newTxState.major == done  => dismiss sheet")
// TODO:                           logger.info("newTxState.major == done  => dismiss sheet")
                            doneAction()        // if this view is in a sheet this action will dissmiss it
                        } else if newMajor == .expired {
                            symLog.log("newTxState.major == expired  => dismiss sheet")
// TODO:                           logger.info("newTxState.major == expired  => dismiss sheet")
                            doneAction()        // if this view is in a sheet this action will dissmiss it
                        } else if newMajor == .pending {
                            if let newMinor {
                                if newMinor == .exchangeWaitReserve { // user did confirm on bank website
                                    symLog.log("newTxState.minor == exchangeWaitReserve => dismiss sheet")
                                    doneAction()        // if this view is in a sheet this action will dissmiss it
                                } else if newMinor == .withdrawCoins { // coin-withdrawal has started
                                    symLog.log("newTxState.minor == withdrawCoins => dismiss sheet")
                                    doneAction()        // if this view is in a sheet this action will dissmiss it
                                } else {
                                    symLog.log("ignoring newTxState: \(newMajor):\(newMinor)")
                                }
                            }
                        } else {
                            symLog.log("ignoring newTxState.major: \(newMajor)")
                        }
                    } else { Task { // runs on MainActor
                        do {
                            symLog.log("newState: \(newMajor), reloading transaction")
                            withAnimation() { transaction = Transaction(dummyCurrency: DEMOCURRENCY); viewId = UUID() }
                            let reloadedTransaction = try await reloadAction(common.transactionId)
                            symLog.log("reloaded transaction: \(reloadedTransaction.common.txState.major)")
                            withAnimation() { transaction = reloadedTransaction; viewId = UUID() }      // redraw
                      } catch {
                          symLog.log(error.localizedDescription)
                    }}}
                }
            } else { // Yikes - should never happen
// TODO:                logger.warning("Can't get notification.userInfo as TransactionTransition")
                symLog.log(notification.userInfo as Any)
            }
        }
        .navigationTitle(navTitle ?? navTitle2)
        .task {
            do {
                symLog.log("task - load transaction")
                let reloadedTransaction = try await reloadAction(transactionId)
                withAnimation() { transaction = reloadedTransaction; viewId = UUID() }      // redraw
            } catch {
                symLog.log(error)
                withAnimation() { transaction = Transaction(dummyCurrency: DEMOCURRENCY); viewId = UUID() }
            }
        }
        .onAppear {
            symLog.log("onAppear")
            DebugViewC.shared.setViewID(VIEW_TRANSACTIONDETAIL, stack: stack.push())
        }
        .onDisappear {
            symLog.log("onDisappear")
        }
    }
//}
//
//extension TransactionDetail {
    struct SwitchCase: View {
        @Binding var transaction: Transaction
        let hasDone: Bool
        @AppStorage("iconOnly") var iconOnly: Bool = false

        var body: some View {
            let common = transaction.common
            let pending = transaction.isPending
            Group {
                switch transaction {
                    case .dummy(_):
                        let title = ""
                        Text(title)
                            .accessibilityFont(.body)
                    case .withdrawal(let withdrawalTransaction):
                        let details = withdrawalTransaction.details
                        if pending {
                            let withdrawalDetails = details.withdrawalDetails
                            switch withdrawalDetails.type {
                                case .manual:               // "Make a wire transfer of \(amount) to"
                                    ManualDetailsV(common: common, details: withdrawalDetails)
                                    
                                case .bankIntegrated:       // "Confirm with bank"
                                    let confirmed = withdrawalDetails.confirmed ?? false
                                    if !confirmed {
                                        if let confirmationUrl = withdrawalDetails.bankConfirmationUrl {
                                            if let destination = URL(string: confirmationUrl) {
                                                VStack(alignment: .leading) {  // Show Hint that User should Confirm on bank website
                                                    if !iconOnly {
                                                        Text("Waiting for bank confirmation")
                                                            .fixedSize(horizontal: false, vertical: true)       // wrap in scrollview
                                                            .multilineTextAlignment(.leading)                   // otherwise
                                                            .listRowSeparator(.hidden)
                                                    }
                                                    Link("Confirm with bank", destination: destination)
                                                        .buttonStyle(TalerButtonStyle(type: .prominent, narrow: false, aligned: .center))
                                                        .padding(.horizontal)                                                    
                                                }
                                            }
                                        }
                                    }
                            }
                        } // ManualDetails or Confirm with bank
                        ThreeAmountsSheet(common: common, topAbbrev: String(localized: "Chosen:"),
                                        topTitle: String(localized: "Chosen amount to withdraw:"),
                                         baseURL: details.exchangeBaseUrl, large: false)
                    case .payment(let paymentTransaction):
                        let details = paymentTransaction.details
                        Text(details.info.summary)
                            .accessibilityFont(.title2)
                            .lineLimit(4)
                            .padding(.bottom)
                        ThreeAmountsSheet(common: common, topAbbrev: String(localized: "Pay:"),
                                        topTitle: String(localized: "Sum to be paid:"),
                                         baseURL: nil, large: true)     // TODO: baseURL
                    case .refund(let refundTransaction):
                        let details = refundTransaction.details                 // TODO: more details
                        ThreeAmountsSheet(common: common, topAbbrev: String(localized: "Refunded:"),
                                        topTitle: String(localized: "Refunded amount:"),
                                         baseURL: nil, large: true)     // TODO: baseURL
                    case .reward(let rewardTransaction):
                        let details = rewardTransaction.details                 // TODO: more details
                        ThreeAmountsSheet(common: common, topAbbrev: String(localized: "Reward:"),
                                        topTitle: String(localized: "Received Reward:"),
                                         baseURL: details.exchangeBaseUrl, large: true)
                    case .refresh(let refreshTransaction):
                        let details = refreshTransaction.details                // TODO: details
                        ThreeAmountsSheet(common: common, topAbbrev: String(localized: "Refreshed:"),
                                        topTitle: String(localized: "Refreshed amount:"),
                                         baseURL: nil, large: true)     // TODO: baseURL
                    case .peer2peer(let p2pTransaction):
                        let details = p2pTransaction.details                    // TODO: details
                        Text(details.info.summary)
                            .accessibilityFont(.title2)
                            .lineLimit(4)
                            .padding(.bottom)
                        // TODO: isSendCoins should show QR only while not yet expired  - either set timer or wallet-core should do so and send a state-changed notification
                        if pending {
                            QRCodeDetails(transaction: transaction)
                            if hasDone {
                                Text("QR code and link can also be scanned or copied / shared from Transactions later.")
                                    .multilineTextAlignment(.leading)
                                    .accessibilityFont(.subheadline)
                                    .padding(.top)
                            }
                        }
                        let colon = ":"
                        ThreeAmountsSheet(common: common, topAbbrev: transaction.localizedType + colon,
                                        topTitle: transaction.localizedType + colon,
                                         baseURL: details.exchangeBaseUrl, large: false)
                } // switch
            } // Group
        }
    }

    struct QRCodeDetails: View {
        var transaction : Transaction
        var body: some View {
            let details = transaction.detailsToShow()
            let keys = details.keys
            if keys.contains(TALERURI) {
                if let talerURI = details[TALERURI] {
                    if talerURI.count > 10 {
                        QRCodeDetailView(talerURI: talerURI,
                                         incoming: transaction.isP2pIncoming,
                                           amount: transaction.common.amountRaw)
                    }
                }
            } else if keys.contains(EXCHANGEBASEURL) {
                if let baseURL = details[EXCHANGEBASEURL] {
                    Text("from \(baseURL.trimURL())") 
                        .accessibilityFont(.title2)
                        .padding(.bottom)
                }
            }
        }
    }
    struct DoneButton: View {
        var doneAction: () -> Void

        var body: some View {
            Button("Done") {
                doneAction()
            }
            .buttonStyle(TalerButtonStyle(type: .prominent))
            .padding(.horizontal)
        }
    }
}
// MARK: -
#if DEBUG
//struct TransactionDetail_Previews: PreviewProvider {
//    static func deleteTransactionDummy(transactionId: String) async throws {}
//    static func doneActionDummy() {}
//    static var withdrawal = Transaction(incoming: true,
//                                         pending: true,
//                                              id: "some withdrawal ID",
//                                            time: Timestamp(from: 1_666_000_000_000))
//    static var payment = Transaction(incoming: false,
//                                      pending: false,
//                                           id: "some payment ID",
//                                         time: Timestamp(from: 1_666_666_000_000))
//    static func reloadActionDummy(transactionId: String) async -> Transaction { return withdrawal }
//    static var previews: some View {
//        Group {
//            TransactionDetailView(transaction: withdrawal, reloadAction: reloadActionDummy, doneAction: doneActionDummy)
//            TransactionDetailView(transaction: payment, reloadAction: reloadActionDummy, deleteAction: deleteTransactionDummy)
//        }
//    }
//}
#endif