TransactionSummaryList.swift (29935B)
1 /* 2 * This file is part of GNU Taler, ©2022-26 Taler Systems S.A. 3 * See LICENSE.md 4 */ 5 /** 6 * @author Marc Stibane 7 */ 8 import SwiftUI 9 import taler_swift 10 import SymLog 11 12 extension TalerTransaction { // for Dummys 13 init(dummyCurrency: String) { 14 let amount = Amount.zero(currency: dummyCurrency) 15 let now = Timestamp.now() 16 let common = TransactionCommon(type: .dummy, 17 transactionId: EMPTYSTRING, 18 timestamp: now, 19 scopes: [], 20 txState: TransactionState(major: .pending), 21 txActions: [], 22 amountRaw: amount, 23 amountEffective: amount) 24 self = .dummy(DummyTransaction(common: common)) 25 } 26 } 27 // MARK: - 28 struct TransactionSummaryList: View { 29 private let symLog = SymLogV(0) 30 let stack: CallStack 31 let transactionId: String 32 @Binding var talerTX: TalerTransaction 33 let navTitle: String? 34 let hasDone: Bool // false: just old tx, true: the conclusion of an transaction 35 let showDone: TalerButtonStyleType? 36 let url: URL? // the scanned talerURL from PaymentView 37 let withActions: Bool // true if called from pending or history, or refund 38 39 @EnvironmentObject private var controller: Controller 40 @EnvironmentObject private var model: WalletModel 41 @Environment(\.colorScheme) private var colorScheme 42 @Environment(\.colorSchemeContrast) private var colorSchemeContrast 43 @Environment(\.dismiss) var dismiss // call dismiss() to pop back 44 @AppStorage("minimalistic") var minimalistic: Bool = false 45 @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic 46 @AppStorage("preferredColorScheme") var preferredColorScheme: Int = 0 47 #if DEBUG 48 @AppStorage("developerMode") var developerMode: Bool = true 49 #else 50 @AppStorage("developerMode") var developerMode: Bool = false 51 #endif 52 53 @State private var currencyInfo: CurrencyInfo = CurrencyInfo.zero(UNKNOWN) 54 @State private var ignoreThis: Bool = false 55 @State private var didDelete: Bool = false 56 @State private var jsonTransaction: String = EMPTYSTRING 57 @State private var viewId = UUID() 58 @State private var paymentPossible: Bool? = nil 59 @State private var scope: ScopeInfo? = nil 60 @State private var isFinished: Bool? = false 61 #if GNU_TALER 62 @State private var effective: Amount? = nil 63 @State private var payNow: Bool = false 64 @State private var selectedChoice: Int? = nil 65 #endif 66 @State private var isWorking: Bool = false 67 @State private var tosAccepted: Bool? = nil 68 @State private var tosBaseUrl: String = EMPTYSTRING 69 @Namespace var topID 70 71 func loadTransaction() async { 72 if let reloadedTransaction = try? await model.getTransactionById(transactionId, 73 includeContractTerms: true, viewHandles: false) { 74 symLog.log("reloaded \(reloadedTransaction.localizedType): \(reloadedTransaction.common.txState.major)") 75 withAnimation { 76 talerTX = reloadedTransaction; 77 isWorking = reloadedTransaction.common.isWorking 78 #if DEBUG 79 // controller.playSound(1104, useSystem: true) 80 #endif 81 scope = reloadedTransaction.common.scopes.first 82 } 83 if developerMode { 84 if let json = try? await model.jsonTransactionById(transactionId, 85 includeContractTerms: true, viewHandles: false) { 86 jsonTransaction = json 87 } else { 88 jsonTransaction = EMPTYSTRING 89 } 90 } 91 } else { 92 withAnimation{ 93 talerTX = TalerTransaction(dummyCurrency: DEMOCURRENCY); 94 isWorking = false 95 viewId = UUID() 96 } 97 jsonTransaction = EMPTYSTRING 98 } 99 } 100 101 #if GNU_TALER 102 private func payTransaction() async { 103 if let confirmPayResult = try? await model.confirmPay(transactionId, 104 choiceIndex: selectedChoice) { 105 // symLog.log(confirmPayResult as Any) 106 if confirmPayResult.type == "done" { 107 if let url { 108 controller.removeURL(url) 109 } 110 } else { 111 if let url { 112 controller.removeURL(url) // TODO: pending might fail - in which case we might want to try again 113 } 114 } 115 let txId = confirmPayResult.transactionId 116 if let matched = try? await model.waitTransactionState(txId, token: txId, major: .done), matched { 117 symLog.log("waitTransactionState matched") 118 } else { 119 symLog.log("payTransaction: waitTransactionState bail") // TODO: ??? 120 } 121 } 122 } 123 #endif 124 @MainActor 125 @discardableResult 126 func checkDismiss(_ notification: Notification, _ logStr: String = EMPTYSTRING) -> Bool { 127 if let transition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition { 128 if transition.transactionId == talerTX.common.transactionId { // is the transition for THIS transaction? 129 if transition.newTxState.major == .deleted { 130 dismissTop(stack.push()) // dissmiss the sheet / the navigation stack 131 return true 132 } 133 if hasDone { 134 symLog.log(logStr) 135 if talerTX.common.type.isPayment { 136 checkReload(stack.push("checkDismiss1"), notification, logStr) 137 } else { 138 dismissTop(stack.push()) // if this view is in a sheet then dissmiss the sheet 139 return true 140 } 141 } else { // no sheet but the details view -> reload 142 checkReload(stack.push("checkDismiss2"), notification, logStr) 143 } 144 } else if let paymentTransaction = talerTX.paymentTransaction, // is it a payment? 145 transition.transactionId == paymentTransaction.details.repurchaseTransactionId { 146 // repurchase detected: reload 147 doReload(stack.push("checkDismiss3"), transition: transition) 148 } 149 } 150 return false 151 } 152 153 @MainActor 154 private func dismiss(_ stack: CallStack) { 155 if hasDone { // if this view is in a sheet then dissmiss the whole sheet 156 dismissTop(stack.push()) 157 } else { // on a NavigationStack just pop 158 dismiss() 159 } 160 } 161 162 func doReload(_ stack: CallStack, transition: TransactionTransition) { 163 Task { // runs on MainActor 164 let newMajor = transition.newTxState.major 165 // flush the screen first, then reload 166 withAnimation { talerTX = TalerTransaction(dummyCurrency: DEMOCURRENCY); viewId = UUID() } 167 if newMajor != .none { // don't reload after delete 168 let message = stack.peek()?.message ?? "?" 169 symLog.log("newState: \(newMajor), reloading transaction, for: \(message)") 170 await loadTransaction() 171 } 172 } 173 } 174 175 func checkReload(_ stack: CallStack, _ notification: Notification, _ logStr: String = EMPTYSTRING) { 176 if let transition: TransactionTransition = notification.userInfo?[TRANSACTIONTRANSITION] as? TransactionTransition { 177 if transition.transactionId == transactionId { // is the transition for THIS transaction? 178 let newMajor = transition.newTxState.major 179 let message = stack.peek()?.message ?? "?" 180 if newMajor == .deleted { 181 symLog.log("newState: \(newMajor), show 'deleted', for: \(message)") 182 let error = transition.errorInfo ?? 183 TalerErrorDetail(code: 7049, // WALLET_MERCHANT_ORDER_NOT_FOUND 184 when: .now(), 185 hint: "Transaction has been deleted") 186 model.setError(WalletBackendError.walletCoreError(error)) 187 } else { 188 doReload(stack, transition: transition) 189 } 190 } 191 } else { // Yikes - should never happen 192 // TODO: logger.warning("Can't get notification.userInfo as TransactionTransition") 193 symLog.log(notification.userInfo as Any) 194 } 195 } 196 197 func localizedState(_ txState: TransactionState) -> String { 198 let major = txState.major 199 if let minor = txState.minor { 200 if developerMode { return minor.localizedDbgState } 201 // if talerTX.isPayment { 202 // return String(localized: "Payment", comment: "TxMajorState heading") 203 // } 204 return minor.localizedState ?? major.localizedState 205 } 206 return major.localizedState 207 } 208 209 @ViewBuilder 210 func dateAndStatus(_ common: TransactionCommon) -> some View { 211 let (dateString, date) = TalerDater.dateString(common.timestamp, minimalistic) 212 let a11yDate = TalerDater.accessibilityDate(date) ?? dateString 213 Text(dateString) 214 .talerFont(.body) 215 .accessibilityLabel(a11yDate) 216 .foregroundColor(WalletColors().secondary2(colorScheme, colorSchemeContrast)) 217 .id(topID) 218 let state = localizedState(common.txState) 219 let statusT = Text(state) 220 .multilineTextAlignment(.trailing) 221 let imageT = Text(common.type.icon()) 222 .accessibilityHidden(true) 223 HStack(alignment: .center, spacing: HSPACING) { 224 imageT 225 Spacer(minLength: 0) 226 statusT 227 } // TODO: a11y for tx icon 228 if developerMode { 229 if !jsonTransaction.isEmpty { 230 CopyButton(jsonTransaction, title: "Copy JSON") 231 } 232 } 233 } 234 235 @ViewBuilder 236 func dateSection(_ common: TransactionCommon) -> some View { 237 #if DEBUG 238 let background = developerMode ? Color.red : nil 239 #else 240 let background: Color? = nil 241 #endif 242 Section { 243 HStack { 244 VStack(alignment: .leading) { 245 dateAndStatus(common) 246 .listRowSeparator(.hidden) 247 .talerFont(.title) 248 } 249 if isWorking { 250 RotatingTaler(size: 80, progress: true, once: false, 251 background: background, 252 rotationEnabled: Binding.constant(true)) 253 .transition(.opacity.combined(with: .scale)) 254 } 255 } 256 } 257 } 258 259 @ViewBuilder 260 func suspendResume(_ common: TransactionCommon) -> some View { 261 if talerTX.isSuspendable { 262 TransactionButton(transactionId: common.transactionId, 263 command: .suspend, 264 warning: nil, 265 didExecute: $ignoreThis, 266 action: model.suspendTransaction) 267 .listRowSeparator(.hidden) 268 } 269 if talerTX.isResumable { 270 TransactionButton(transactionId: common.transactionId, 271 command: .resume, 272 warning: nil, 273 didExecute: $ignoreThis, 274 action: model.resumeTransaction) 275 .listRowSeparator(.hidden) 276 } 277 } 278 279 @ViewBuilder 280 func abortFailDelete(_ common: TransactionCommon) -> some View { 281 if talerTX.isAbortable { 282 let warning = String(localized: "Are you sure you want to abort this transaction?") 283 TransactionButton(transactionId: common.transactionId, 284 command: .abort, 285 warning: warning, 286 didExecute: $ignoreThis, 287 action: model.abortTransaction) 288 } // Abort button 289 if talerTX.isFailable { 290 let warning = String(localized: "Are you sure you want to abandon this transaction?") 291 TransactionButton(transactionId: common.transactionId, 292 command: .fail, 293 warning: warning, 294 didExecute: $ignoreThis, 295 action: model.failTransaction) 296 } // Fail button 297 if talerTX.isDeleteable { 298 let warning = String(localized: "Are you sure you want to delete this transaction?") 299 TransactionButton(transactionId: common.transactionId, 300 command: .delete, 301 warning: warning, 302 didExecute: $didDelete, 303 action: model.deleteTransaction) 304 .onChange(of: didDelete) { wasDeleted in 305 if wasDeleted { 306 symLog.log("wasDeleted -> dismiss view") 307 dismiss(stack) 308 } 309 } 310 } // Delete button 311 } 312 313 @ViewBuilder 314 func cancelButton() -> some View { 315 Button("Cancel") { dismissTop(stack.push()) } 316 .buttonStyle(TalerButtonStyle(type: .bordered)) 317 .padding(Bool.iOS26 ? .horizontal : .all) 318 } 319 320 var possibleStr: String { 321 if let possible = paymentPossible { 322 return possible ? String(localized: "Confirm Payment", comment:"pay merchant navTitle") 323 : String(localized: "Payment not possible", comment:"pay merchant navTitle") 324 } 325 return String(localized: "Payment", comment:"pay merchant navTitle") 326 } 327 var navTitleStr: String { 328 let isPaying = talerTX.isPayment && talerTX.isDialog 329 let isRepurchase = talerTX.common.isRepurchase 330 return talerTX.isDone ? talerTX.localizedTypePast 331 : isPaying ? possibleStr 332 : isRepurchase ? String(localized: "Already paid", comment:"repurchase merchant navTitle") 333 : talerTX.localizedType 334 } 335 336 func checkToS(for newBaseUrl: String) { 337 print(" onChange of tosBaseUrl: \(newBaseUrl)") 338 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { 339 Task { 340 tosAccepted = await controller.checkToS(for: newBaseUrl) 341 } 342 } 343 } 344 345 var body: some View { 346 #if PRINT_CHANGES 347 let _ = Self._printChanges() 348 let _ = symLog.vlog() // just to get the # to compare it with .onAppear & onDisappear 349 #endif 350 let common = talerTX.common 351 // let scope = common.scopes.first // might be nil if scopes == [] 352 let locale = TalerDater.shared.locale 353 let isPayment = talerTX.isPayment 354 let isPayDialog = isPayment && talerTX.isDialog 355 Group { 356 if common.type != .dummy && transactionId == common.transactionId { 357 let list = List { 358 if developerMode && withActions { suspendResume(common) } 359 if !isPayDialog { 360 dateSection(common) 361 } 362 if !controller.stalledConnection { 363 #if GNU_TALER 364 TransactionTypeDetail(stack: stack.push(), 365 transaction: $talerTX, 366 tosAccepted: tosAccepted, // only for ToSButtonView above List 367 tosBaseUrl: $tosBaseUrl, 368 payNow: $payNow, 369 selectedChoice: $selectedChoice, 370 effective: $effective, // return amount for "Pay <amount> now" 371 scope: $scope, 372 possible: $paymentPossible, 373 hasDone: hasDone) 374 .onChange(of: tosBaseUrl) { newBaseUrl in 375 checkToS(for: newBaseUrl) 376 } 377 #else 378 TransactionTypeDetail(stack: stack.push(), 379 transaction: $talerTX, 380 tosAccepted: tosAccepted, // only for ToSButtonView above List 381 tosBaseUrl: $tosBaseUrl, 382 isFinished: $isFinished, 383 scope: $scope, 384 possible: $paymentPossible, 385 hasDone: hasDone) 386 .onChange(of: tosBaseUrl) { newBaseUrl in 387 checkToS(for: newBaseUrl) 388 } 389 #endif 390 if withActions { abortFailDelete(common) } 391 } 392 }.id(viewId) // change viewId to enforce a draw update 393 .listStyle(myListStyle.style).anyView 394 395 VStack { 396 if tosAccepted == false { 397 ToSButtonView(stack: stack.push(), 398 exchangeBaseUrl: tosBaseUrl, 399 viewID: SHEET_RCV_P2P_TOS, // TODO 400 shouldDismiss: false, // pop back to here 401 p2p: true) // TODO 402 } 403 if #available(iOS 17.0, *) { 404 list 405 .scrollContentBackground(preferredColorScheme == 3 ? .hidden : .visible) 406 .toolbarTitleDisplayMode(.inlineLarge) 407 } else { 408 list 409 } 410 } 411 .background(FullBackground()) 412 .navigationBarBackButtonHidden(hasDone) 413 .interactiveDismissDisabled(hasDone && !isPayDialog) // can only use "Done" button to dismiss 414 .safeAreaInset(edge: .bottom) { 415 let cancelButton = cancelButton() 416 if controller.stalledConnection { 417 VStack { 418 StalledView() 419 cancelButton 420 .padding(.bottom) 421 } 422 .background { 423 SelectedBackground(useColor: false) 424 } 425 .padding(Bool.iOS26 ? .horizontal : .all) 426 .transition(.move(edge: .bottom)) 427 } else { 428 ZStack { // we only ever have one item - but need to apply padding 429 let major = common.txState.major.rawValue 430 let minor = common.txState.minor 431 if isPayDialog { 432 if case .payment(let paymentTransaction) = talerTX { 433 let details = paymentTransaction.details 434 if let terms = details.contractTerms, isFinished == false { 435 #if GNU_TALER // else pay button is shown inside each payment option 436 if let effective { 437 let formatted = effective.formatted(currencyInfo) 438 // let _ = print("💰 PaymentButton") 439 PaymentButton(symLog: symLog, 440 stack: stack.push(), 441 terms: terms, 442 amountString: formatted.0, 443 amountA11y: formatted.1, 444 isFinished: $isFinished, 445 payNow: $payNow) 446 } else { 447 // let _ = print("💰 no Cancel") 448 } // wait for $effective - don't show Cancel 449 #endif 450 } else { 451 // let eff = effective != nil ? "effective" : "-" 452 // let ter = details.contractTerms != nil ? "terms" : "-" 453 // let fin = isFinished == false ? "not finished" : "-" 454 // let _ = print("💰 Cancel \(eff), \(ter), \(fin)") 455 cancelButton 456 } // Cancel 457 } else { 458 #if DEBUG 459 let _ = print("😂 should never happen") 460 #endif 461 } // don't show any bottom button 462 } else if let showDone { 463 if !isPayment || (minor != .claimProposal && minor != .submitPayment) { 464 // let _ = print("\(isPayment ? "💰" : "😂") Done \(major).\(minor?.rawValue ?? "")") 465 Button("Done") { dismissTop(stack.push()) } 466 .buttonStyle(TalerButtonStyle(type: showDone)) 467 .padding(Bool.iOS26 ? .horizontal : .all) 468 } 469 } 470 } 471 .padding(Bool.iOS26 ? .horizontal : .all) 472 // .transition(.scale.combined(with: .opacity)) 473 } 474 } 475 .navigationTitle(navTitle ?? navTitleStr) 476 .onDisappear { 477 // the cached choices (payable or not, effective amount) depend on the balance - 478 // drop them, so that opening this payment again asks wallet-core afresh 479 if controller.choicesTuple.0 == transactionId { 480 controller.choicesTuple = (nil, nil) 481 } 482 } 483 .onChange(of: controller.exchanges) { _ in 484 if !tosBaseUrl.isEmpty { 485 Task { 486 tosAccepted = await controller.checkToS(for: tosBaseUrl) 487 } 488 } 489 } 490 #if GNU_TALER 491 .onChange(of: payNow) { payNow2 in 492 if payNow2 { 493 Task { 494 await payTransaction() 495 payNow = false // re-enable "Pay now" if this attempt did not lead to a state transition 496 } 497 } 498 } 499 #endif 500 .onNotification(.TransactionExpired) { notification in 501 // TODO: Alert user that this tx just expired 502 if checkDismiss(notification, "newTxState.major == expired => dismiss sheet") { 503 // TODO: logger.info("newTxState.major == expired => dismiss sheet") 504 } 505 } 506 .onNotification(.TransactionDone) { notification in 507 checkDismiss(notification, "newTxState.major == done => dismiss sheet") 508 } 509 .onNotification(.DismissSheet) { notification in 510 checkDismiss(notification, "exchangeWaitReserve or withdrawCoins => dismiss sheet") 511 } 512 } else { 513 Color.clear 514 .frame(maxWidth: .infinity, maxHeight: .infinity) 515 .task { 516 symLog.log("task - load transaction") 517 await loadTransaction() 518 } 519 } // else 520 } // Group 521 .onNotification(.PendingReady) { notification in 522 checkReload(stack.push("pendingReady"), notification, "pending ready ==> reload for talerURI") 523 } 524 .onNotification(.TransactionStateTransition) { notification in 525 if !didDelete { 526 checkReload(stack.push("TransactionStateTransition"), notification, "some transition ==> reload") 527 } 528 } 529 .onChange(of: scope) { newVal in 530 if let newVal { 531 currencyInfo = controller.info(for: newVal) ?? CurrencyInfo.zero(UNKNOWN) 532 } 533 } 534 .onAppear { 535 symLog.log("onAppear") 536 DebugViewC.shared.setViewID(VIEW_TRANSACTIONSUMMARY, stack: stack.push()) 537 } // setViewID 538 .onDisappear { 539 symLog.log("onDisappear") 540 } 541 } 542 } // TransactionSummaryList 543 // MARK: - 544 struct KYCbutton: View { 545 let kycUrl: String? 546 547 var body: some View { 548 if let kycUrl { 549 if let destination = URL(string: kycUrl) { 550 LinkButton(destination: destination, 551 hintTitle: String(localized: "You need to pass a legitimization procedure.", comment: "KYC"), 552 buttonTitle: String(localized: "Open legitimization website", comment: "KYC"), 553 a11yHint: String(localized: "Will go to legitimization website to permit this withdrawal.", comment: "a11y"), 554 badge: NEEDS_KYC) 555 } 556 } 557 } 558 } 559 // MARK: - 560 struct PendingWithdrawalDetails: View { 561 let stack: CallStack 562 @Binding var transaction: TalerTransaction 563 let details: WithdrawalTransactionDetails 564 565 var body: some View { 566 let common = transaction.common 567 if transaction.isPendingKYC { 568 if let kycUrl = common.kycUrl { 569 KYCbutton(kycUrl: common.kycUrl) 570 } else { 571 Text("Legitimization procedure required", comment: "KYC") 572 } 573 } else { 574 let withdrawalDetails = details.withdrawalDetails 575 switch withdrawalDetails.type { 576 case .manual: // "Make a wire transfer of \(amount) to" 577 ManualDetailsV(stack: stack.push(), common: common, details: withdrawalDetails) 578 579 case .bankIntegrated: // "Authorize now" (with bank) 580 if !transaction.isPendingKYC { // cannot authorize if KYC is needed first 581 let confirmed = withdrawalDetails.confirmed ?? false 582 if !confirmed { 583 if let confirmationUrl = withdrawalDetails.bankConfirmationUrl { 584 if let destination = URL(string: confirmationUrl) { 585 LinkButton(destination: destination, 586 hintTitle: String(localized: "The bank is waiting for your authorization."), 587 buttonTitle: String(localized: "Authorize now"), 588 a11yHint: String(localized: "Will go to bank website to authorize this withdrawal.", comment: "a11y"), 589 badge: CONFIRM_BANK) 590 } } } } 591 @unknown default: 592 ErrorView(stack.push(), 593 title: "Unknown withdrawal type", // should not happen, so no L10N 594 message: withdrawalDetails.toJSON(), 595 copyable: true) 596 } // switch 597 } 598 } 599 } 600 // MARK: - 601 struct QRCodeDetails: View { 602 let stack: CallStack 603 var transaction : TalerTransaction 604 var body: some View { 605 let details = transaction.detailsToShow() 606 let keys = details.keys 607 if keys.contains(TALERURI) { 608 if let talerURI = details[TALERURI] { 609 let summary = details["summary"] 610 if talerURI.count > 10 { 611 QRCodeDetailView(stack: stack.push(), 612 talerURI: talerURI, 613 incoming: transaction.isP2pIncoming, 614 amount: transaction.common.amountRaw, 615 scope: transaction.common.scopes.first, 616 subject: summary) 617 // scopes shouldn't (- but might) be nil! 618 } 619 } 620 } else if keys.contains(EXCHANGEBASEURL) { 621 if let baseURL = details[EXCHANGEBASEURL] { 622 Text("from \(baseURL.trimURL)", comment: "baseURL") 623 .talerFont(.title2) 624 .padding(.bottom) 625 } 626 } 627 } 628 } 629 // MARK: - 630 #if DEBUG 631 //struct TransactionSummary_Previews: PreviewProvider { 632 // static func deleteTransactionDummy(transactionId: String) async throws {} 633 // static func doneActionDummy() {} 634 // static var withdrawal = TalerTransaction(incoming: true, 635 // pending: true, 636 // id: "some withdrawal ID", 637 // time: Timestamp(from: 1_666_000_000_000)) 638 // static var payment = TalerTransaction(incoming: false, 639 // pending: false, 640 // id: "some payment ID", 641 // time: Timestamp(from: 1_666_666_000_000)) 642 // static func reloadActionDummy(transactionId: String) async -> TalerTransaction { return withdrawal } 643 // static var previews: some View { 644 // Group { 645 // TransactionSummaryV(transaction: withdrawal, reloadAction: reloadActionDummy, doneAction: doneActionDummy) 646 // TransactionSummaryV(transaction: payment, reloadAction: reloadActionDummy) 647 // } 648 // } 649 //} 650 #endif