summaryrefslogtreecommitdiff
path: root/TalerWallet1/Views/Transactions/TransactionSummaryV.swift
blob: 4f089c45ca5ad36ffccd8d0260653a3e19784076 (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
 * This file is part of GNU Taler, ©2022-24 Taler Systems S.A.
 * See LICENSE.md
 */
/**
 * @author Marc Stibane
 */
import SwiftUI
import taler_swift
import SymLog

extension Transaction {             // for Dummys
    init(dummyCurrency: String) {
        let amount = Amount.zero(currency: dummyCurrency)
        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 TransactionSummaryV: View {
    private let symLog = SymLogV(0)
    let stack: CallStack
    let transactionId: String
    let reloadAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Transaction)
    let navTitle: String?
    let doneAction: ((_ stack: CallStack) -> Void)?
    let abortAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Void)?
    let deleteAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Void)?
    let failAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Void)?
    let suspendAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Void)?
    let resumeAction: ((_ transactionId: String, _ viewHandles: Bool) async throws -> Void)?

    @Environment(\.colorScheme) private var colorScheme
    @Environment(\.colorSchemeContrast) private var colorSchemeContrast
    @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic
#if DEBUG
    @AppStorage("developerMode") var developerMode: Bool = true
#else
    @AppStorage("developerMode") var developerMode: Bool = false
#endif

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

    func loadTransaction() async {
        if let reloadedTransaction = try? await reloadAction(transactionId, false) {
            symLog.log("reloaded transaction: \(reloadedTransaction.common.txState.major)")
            withAnimation() { transaction = reloadedTransaction; viewId = UUID() }      // redraw
        } else {
            withAnimation() { transaction = Transaction(dummyCurrency: DEMOCURRENCY); viewId = UUID() }
        }
    }

    @discardableResult
    func checkDismiss(_ notification: Notification, _ logStr: String = "") -> Bool {
        if let doneAction {
            if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition {
                if transition.transactionId == transaction.common.transactionId {       // is the transition for THIS transaction?
                    symLog.log(logStr)
                    doneAction(stack.push())        // if this view is in a sheet then dissmiss the sheet
                    return true
                }
            }
        } else { // no sheet but the details view -> reload
            checkReload(notification, logStr)
        }
        return false
    }

    func checkReload(_ notification: Notification, _ logStr: String = "") {
        if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition {
            if transition.transactionId == transactionId {       // is the transition for THIS transaction?
                let newMajor = transition.newTxState.major
                Task { // runs on MainActor
                       // flush the screen first, then reload
                    withAnimation() { transaction = Transaction(dummyCurrency: DEMOCURRENCY); viewId = UUID() }
                    symLog.log("newState: \(newMajor), reloading transaction")
                    await loadTransaction()
                }
            }
        } else { // Yikes - should never happen
// TODO:      logger.warning("Can't get notification.userInfo as TransactionTransition")
            symLog.log(notification.userInfo as Any)
        }
    }

    var body: some View {
#if PRINT_CHANGES
        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 = TalerDater.accessibilityDate(date) ?? dateString
        let navTitle2 = transaction.isDone ? transaction.localizedTypePast
                                           : transaction.localizedType
        VStack {
            List {
                if developerMode {
                    if transaction.isSuspendable { if let suspendAction {
                        TransactionButton(transactionId: common.transactionId,
                                          command: .suspend, warning: nil, action: suspendAction)
                    } }
                    if transaction.isResumable { if let resumeAction {
                        TransactionButton(transactionId: common.transactionId,
                                          command: .resume, warning: nil, action: resumeAction)
                    } }
                } // Suspend + Resume buttons
                Text(dateString)
                    .talerFont(.body)
                    .accessibilityLabel(accessibilityDate)
                    .foregroundColor(WalletColors().secondary(colorScheme, colorSchemeContrast))
                    .listRowSeparator(.hidden)
                VStack(alignment: .trailing) {
                    let majorState = common.txState.major.localizedState
                    let minorState = common.txState.minor?.localizedState ?? nil
                    let state = developerMode ? transaction.isPending ? minorState ?? majorState
                                                                      : majorState
                                              : majorState
                    HStack {
                        Text(verbatim: "|")   // only reason for this leading-aligned text is to get a nice full length listRowSeparator
                            .accessibilityHidden(true)
                            .foregroundColor(Color.clear)
                        Text("Status: \(state)")
                            .frame(maxWidth: .infinity, alignment: .trailing)
                            .multilineTextAlignment(.trailing)
                    }
                }    .listRowSeparator(.automatic)
                    .talerFont(.title)
                TypeDetail(stack: stack.push(),
                           transaction: $transaction, hasDone: doneAction != nil)

                // TODO: Retry Countdown, Retry Now button
//                if transaction.isRetryable { if let retryAction {
//                    TransactionButton(transactionId: common.transactionId, command: .retry,
//                                      warning: nil, action: abortAction)
//                } } // Retry button
                if transaction.isAbortable { if let abortAction {
                    TransactionButton(transactionId: common.transactionId, command: .abort,
                                      warning: String(localized: "Are you sure you want to abort this transaction?"),
                                      action: abortAction)
                } } // Abort button
                if transaction.isFailable { if let failAction {
                    TransactionButton(transactionId: common.transactionId, command: .fail,
                                      warning: String(localized: "Are you sure you want to fail this transaction?"),
                                      action: failAction)
                } } // Fail button
                if transaction.isDeleteable { if let deleteAction {
                    TransactionButton(transactionId: common.transactionId, command: .delete,
                                      warning: String(localized: "Are you sure you want to delete this transaction?"),
                                      action: deleteAction)
                } } // Delete button
                if let doneAction {
                    Button(transaction.shouldConfirm ? "Confirm later" : "Done", action: { doneAction(stack.push()) } )
                        .buttonStyle(TalerButtonStyle(type: transaction.shouldConfirm ? .bordered : .prominent))
                } // Done button
            }.id(viewId)    // change viewId to enforce a draw update
            .listStyle(myListStyle.style).anyView
        } // Group
        .onNotification(.TransactionExpired) { notification in
            // TODO: Alert user that this tx just expired
            if checkDismiss(notification, "newTxState.major == expired  => dismiss sheet") {
    // TODO:                  logger.info("newTxState.major == expired  => dismiss sheet")
            }
        }
        .onNotification(.TransactionDone) { notification in
            checkDismiss(notification, "newTxState.major == done  => dismiss sheet")
        }
        .onNotification(.DismissSheet) { notification in
            checkDismiss(notification, "exchangeWaitReserve or withdrawCoins  => dismiss sheet")
        }
        .onNotification(.PendingReady) { notification in
            checkReload(notification, "pending ready ==> reload for talerURI")
        }
        .onNotification(.TransactionStateTransition) { notification in
            checkReload(notification, "some transition ==> reload")
        }
        .navigationTitle(navTitle ?? navTitle2)
        .task {
            symLog.log("task - load transaction")
            await loadTransaction()
        }
        .onAppear {
            symLog.log("onAppear")
            DebugViewC.shared.setViewID(VIEW_TRANSACTIONSUMMARY, stack: stack.push())
        }
        .onDisappear {
            symLog.log("onDisappear")
        }
    }
//}
//
//extension TransactionSummaryV {
    struct KycButton: View {
        let destination: URL
        @AppStorage("minimalistic") var minimalistic: Bool = false

        var body: some View {
            VStack(alignment: .leading) {  // Show Hint that User must pass KYC on website
                if !minimalistic {
                    Text("You need to pass a KYC procedure")
                        .fixedSize(horizontal: false, vertical: true)       // wrap in scrollview
                        .multilineTextAlignment(.leading)                   // otherwise
                        .listRowSeparator(.hidden)
                }
                Link("Open KYC website", destination: destination)
                    .buttonStyle(TalerButtonStyle(type: .prominent, badge: NEEDS_KYC))
                    .accessibilityHint("Will go to KYC website to confirm this withdrawal.")
            }
        }
    }

    struct ConfirmationButton: View {
        let destination: URL
        @AppStorage("minimalistic") var minimalistic: Bool = false

        var body: some View {
            VStack(alignment: .leading) {  // Show Hint that User should Confirm on bank website
                if !minimalistic {
                    Text("The bank is waiting for your confirmation.")
//                        .fixedSize(horizontal: false, vertical: true)       // wrap in scrollview
                        .multilineTextAlignment(.leading)                   // otherwise
                        .listRowSeparator(.hidden)
                }
                Link("Confirm now", destination: destination)
                    .buttonStyle(TalerButtonStyle(type: .prominent, badge: CONFIRM_BANK))
                    .accessibilityHint("Will go to bank website to confirm this withdrawal.")
            }
        }
    }

    struct PendingWithdrawalDetails: View {
        @Binding var transaction: Transaction
        let details: WithdrawalTransactionDetails

        var body: some View {
            let common = transaction.common
            if transaction.isPendingKYC {
                if let kycUrl = common.kycUrl {
                    if let destination = URL(string: kycUrl) {
                        KycButton(destination: destination)
                    }
                }
            }
            let withdrawalDetails = details.withdrawalDetails
            switch withdrawalDetails.type {
                case .manual:               // "Make a wire transfer of \(amount) to"
                    ManualDetailsV(common: common, details: withdrawalDetails)

                case .bankIntegrated:       // "Confirm now" (with bank)
                    if !transaction.isPendingKYC {              // cannot confirm if KYC is needed first
                        let confirmed = withdrawalDetails.confirmed ?? false
                        if !confirmed {
                            if let confirmationUrl = withdrawalDetails.bankConfirmationUrl {
                                if let destination = URL(string: confirmationUrl) {
                                    ConfirmationButton(destination: destination)
                                }   }   }   }
            } // switch
        }
    }

    struct TypeDetail: View {
        let stack: CallStack
        @Binding var transaction: Transaction
        let hasDone: Bool
        @Environment(\.colorScheme) private var colorScheme
        @Environment(\.colorSchemeContrast) private var colorSchemeContrast
        @AppStorage("minimalistic") var minimalistic: Bool = false
        @State private var rotationEnabled = true

        func refreshFee(input: Amount, output: Amount) -> Amount? {
            do {
                let fee = try input - output
                return fee
            } catch {
                
            }
            return nil
        }

        var body: some View {
            let common = transaction.common
            let pending = transaction.isPending
            Group {
                switch transaction {
                    case .dummy(_):
                        let title = EMPTYSTRING
                        Text(title)
                            .talerFont(.body)
                        RotatingTaler(size: 100, progress: true,
                                      rotationEnabled: $rotationEnabled)
                            .frame(maxWidth: .infinity, alignment: .center)
//                            .accessibilityLabel("Progress indicator")
                    case .withdrawal(let withdrawalTransaction): Group {
                        let details = withdrawalTransaction.details
                        if pending {
                            PendingWithdrawalDetails(transaction: $transaction, details: details)
                        } // ManualDetails or Confirm now (with bank)
                        ThreeAmountsSheet(stack: stack.push(),
                                          common: common, topAbbrev: String(localized: "Chosen:", comment: "mini"),
                                        topTitle: String(localized: "Chosen amount to withdraw:"),
                                         baseURL: details.exchangeBaseUrl, noFees: nil, large: false,
                                         summary: nil, merchant: nil)
                    }
                    case .deposit(let depositTransaction): Group {
                        let details = depositTransaction.details
                        ThreeAmountsSheet(stack: stack.push(),
                                          common: common, topAbbrev: String(localized: "Deposit:", comment: "mini"),
                                          topTitle: String(localized: "Amount to deposit:"),
                                          baseURL: nil, noFees: nil, large: true,            // TODO: baseURL, noFees
                                          summary: nil, merchant: nil)
                    }
                    case .payment(let paymentTransaction): Group {
                        let details = paymentTransaction.details
                        TransactionDetailV(paymentTx: paymentTransaction)
                        ThreeAmountsSheet(stack: stack.push(),
                                          common: common, topAbbrev: String(localized: "Price:", comment: "mini"),
                                        topTitle: String(localized: "Price (net):"),
                                         baseURL: nil, noFees: nil, large: true,             // TODO: baseURL, noFees
                                         summary: details.info.summary,
                                        merchant: details.info.merchant.name)
                    }
                    case .refund(let refundTransaction): Group {
                        let details = refundTransaction.details                 // TODO: more details
                        ThreeAmountsSheet(stack: stack.push(),
                                          common: common, topAbbrev: String(localized: "Refunded:", comment: "mini"),
                                        topTitle: String(localized: "Refunded amount:"),
                                         baseURL: nil, noFees: nil, large: true,             // TODO: baseURL, noFees
                                         summary: details.info?.summary,
                                        merchant: details.info?.merchant.name)
                    }
                    case .refresh(let refreshTransaction): Group {
                        let labelColor = WalletColors().labelColor
                        let errorColor = WalletColors().errorColor
                        let details = refreshTransaction.details
                        Section {
                            Text(details.refreshReason.localizedRefreshReason)
                                .talerFont(.title)
                            let input = details.refreshInputAmount
                            AmountRowV(title: minimalistic ? "Refreshed:" : "Refreshed amount:",
                                      amount: input,
                                       color: labelColor,
                                       large: true)
                            if let fee = refreshFee(input: input, output: details.refreshOutputAmount) {
                                AmountRowV(title: minimalistic ? "Fee:" : "Refreshed fee:",
                                          amount: fee,
                                           color: labelColor,
                                           large: true)
                            }
                            if let error = details.error {
                                HStack {
                                    VStack(alignment: .leading) {
                                        Text(error.hint)
                                            .talerFont(.headline)
                                            .foregroundColor(errorColor)
                                            .listRowSeparator(.hidden)
                                        if let stack = error.stack {
                                            Text(stack)
                                                .talerFont(.body)
                                                .foregroundColor(errorColor)
                                                .listRowSeparator(.hidden)
                                        }
                                    }
                                    let stackStr = error.stack ?? EMPTYSTRING
                                    let errorStr = error.hint + "\n" + stackStr
                                    CopyButton(textToCopy: errorStr, vertical: true)
                                        .accessibilityLabel("Copy the error")
                                        .disabled(false)
                                }
                            }
                        }
                    }
                    case .peer2peer(let p2pTransaction): Group {
                        let details = p2pTransaction.details
                        if !transaction.isDone {
                            let expiration = details.info.expiration
                            let (dateString, date) = TalerDater.dateString(from: expiration)
                            let accessibilityDate = TalerDater.accessibilityDate(date) ?? dateString
                            let accessibilityLabel = String(localized: "Expires: \(accessibilityDate)")
                            Text("Expires: \(dateString)")
                                .talerFont(.body)
                                .accessibilityLabel(accessibilityLabel)
                                .foregroundColor(WalletColors().secondary(colorScheme, colorSchemeContrast))
                        }
                        // 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 {
                            if transaction.isPendingReady {
                                QRCodeDetails(transaction: transaction)
                                if hasDone {
                                    Text("QR code and link can also be scanned or copied / shared from Transactions later.")
                                        .multilineTextAlignment(.leading)
                                        .talerFont(.subheadline)
                                        .padding(.top)
                                }
                            } else {
                                Text("This transaction is not yet ready...")
                                    .multilineTextAlignment(.leading)
                                    .talerFont(.subheadline)
                            }
                        }
                        let colon = ":"
                        let localizedType = transaction.isDone ? transaction.localizedTypePast
                                                               : transaction.localizedType
                        ThreeAmountsSheet(stack: stack.push(),
                                          common: common,
                                       topAbbrev: localizedType + colon,
                                        topTitle: localizedType + colon,
                                         baseURL: details.exchangeBaseUrl, noFees: nil,         // TODO: noFees
                                           large: false,
                                         summary: details.info.summary,
                                        merchant: nil)
                    } // p2p
                    case .recoup(let recoupTransaction): Group {
                        let details = recoupTransaction.details                 // TODO: more details
                        ThreeAmountsSheet(stack: stack.push(),
                                         common: common, topAbbrev: String(localized: "Recoup:", comment: "mini"),
                                       topTitle: String(localized: "Recoup:"),
                                        baseURL: nil, noFees: nil, large: true,             // TODO: baseURL, noFees
                                        summary: nil,
                                       merchant: nil)

                    }
                    case .denomLoss(let denomLossTransaction): Group {
                        let details = denomLossTransaction.details              // TODO: more details
                        ThreeAmountsSheet(stack: stack.push(),
                                         common: common, topAbbrev: String(localized: "Lost:", comment: "mini"),
                                       topTitle: String(localized: "Money lost:"),
                                        baseURL: details.exchangeBaseUrl, noFees: nil, large: true,             // TODO: baseURL, noFees
                                        summary: details.lossEventType.rawValue,
                                       merchant: nil)
                    }
                } // 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())") 
                        .talerFont(.title2)
                        .padding(.bottom)
                }
            }
        }
    }
}
// MARK: -
#if DEBUG
//struct TransactionSummary_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 {
//            TransactionSummaryV(transaction: withdrawal, reloadAction: reloadActionDummy, doneAction: doneActionDummy)
//            TransactionSummaryV(transaction: payment, reloadAction: reloadActionDummy, deleteAction: deleteTransactionDummy)
//        }
//    }
//}
#endif