ManualWithdraw.swift (14092B)
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 // Called when tapping [Withdraw] 13 // or from WithdrawExchangeScan after a withdraw-exchange QR was scanned 14 struct ManualWithdraw: View { 15 private let symLog = SymLogV(0) 16 let stack: CallStack 17 let url: URL? 18 // when Action is tapped while in currency TransactionList… 19 let selectedBalance: Balance? // …then use THIS balance, otherwise show picker 20 @Binding var amountLastUsed: Amount 21 @Binding var amountToTransfer: Amount // Update currency when used 22 let exchange: Exchange? // only for withdraw-exchange 23 let maySwitchCurrencies: Bool // not for withdraw-exchange 24 let isSheet: Bool // true: WithdrawExchangeScan 25 26 @EnvironmentObject private var controller: Controller 27 @EnvironmentObject private var model: WalletModel 28 29 @State private var balanceIndex = 0 30 @State private var balance: Balance? = nil // nil only when balances == [] 31 @State private var currencyInfo: CurrencyInfo = CurrencyInfo.zero(UNKNOWN) 32 33 private func viewDidLoad() async { 34 if let exchange { 35 currencyInfo = controller.info(for: exchange.scopeInfo, controller.currencyTicker) 36 return 37 } else if let selectedBalance { 38 balance = selectedBalance 39 balanceIndex = controller.balances.firstIndex(of: selectedBalance) ?? 0 40 } else { 41 balanceIndex = 0 42 balance = controller.balances.isEmpty ? nil : controller.balances[0] 43 } 44 if let balance { 45 currencyInfo = controller.info(for: balance.scopeInfo, controller.currencyTicker) 46 } 47 } 48 49 func navTitle(_ currency: String, _ condition: Bool = true) -> String { 50 condition ? String(localized: "NavTitle_Withdraw_Currency)", 51 defaultValue: "Withdraw \(currency)", 52 comment: "NavTitle: Withdraw 'currency'") 53 : String(localized: "NavTitle_Withdraw", 54 defaultValue: "Withdraw", 55 comment: "NavTitle: Withdraw") 56 } 57 58 func updateCurrInfo(_ scope: ScopeInfo) { 59 symLog.log("balance = \(scope.url)") 60 amountToTransfer.setCurrency(scope.currency) 61 currencyInfo = controller.info(for: scope, controller.currencyTicker) 62 } 63 64 var body: some View { 65 #if PRINT_CHANGES 66 let _ = Self._printChanges() 67 #endif 68 let currencySymbol = currencyInfo.symbol 69 let navA11y = navTitle(currencyInfo.name) // always include currency for a11y 70 let navTitle = navTitle(currencySymbol, currencyInfo.hasSymbol) 71 let count = controller.balances.count 72 let scrollView = ScrollView { 73 if maySwitchCurrencies && count > 1 { 74 ScopePicker(stack: stack.push(), 75 value: $balanceIndex, 76 onlyNonZero: false) 77 { index in 78 balanceIndex = index 79 balance = controller.balances[index] 80 if let balance { 81 updateCurrInfo(balance.scopeInfo) 82 } 83 } 84 .padding(.horizontal) 85 .padding(.bottom, 4) 86 } // TODO: else show static text? 87 if let scope = balance?.scopeInfo ?? exchange?.scopeInfo { 88 let _ = symLog.log("exchange = \(exchange?.exchangeBaseUrl), scope = \(scope.url), amountToTransfer = \(amountToTransfer.currencyStr)") 89 ManualWithdrawContent(stack: stack.push(), 90 url: url, 91 scope: scope, 92 amountLastUsed: $amountLastUsed, 93 amountToTransfer: $amountToTransfer, 94 exchange: exchange) 95 } else { // should never happen, we either have an exchange or a balance 96 ErrorView(stack.push(), title: navTitle, titleA11y: navA11y, 97 message: String(localized: "No scope"), copyable: true) 98 } 99 } // ScrollView 100 .navigationTitle(navTitle) 101 // .accessibilityLabel(Text(navA11y)) can't add A11y to navTitle in SwiftUI 102 .frame(maxWidth: .infinity, alignment: .leading) 103 .background(FullBackground()) 104 .onAppear { 105 if isSheet { 106 DebugViewC.shared.setSheetID(SHEET_WITHDRAW_EXCHANGE, // 135 WithdrawExchangeScan 107 stack: stack.push()) 108 } else { 109 DebugViewC.shared.setViewID(VIEW_WITHDRAWAL, // 30 WithdrawAmount 110 stack: stack.push()) 111 } 112 symLog.log("❗️ \(navTitle) onAppear") 113 } 114 .onDisappear { 115 symLog.log("❗️ \(navTitle) onDisappear") 116 } 117 .task { await viewDidLoad() } 118 .task(id: controller.currencyTicker) { 119 // runs whenever a new currencyInfo is available 120 symLog.log("❗️ task \(controller.currencyTicker)") 121 let scopeInfo = maySwitchCurrencies ? balance?.scopeInfo 122 : exchange?.scopeInfo 123 if let scopeInfo { 124 updateCurrInfo(scopeInfo) 125 } 126 } 127 128 if #available(iOS 16.4, *) { 129 scrollView.toolbar(.hidden, for: .tabBar) 130 .scrollBounceBehavior(.basedOnSize) 131 } else { 132 scrollView 133 } 134 } 135 } 136 // MARK: - 137 struct ManualWithdrawContent: View { 138 private let symLog = SymLogV(0) 139 let stack: CallStack 140 let url: URL? 141 let scope: ScopeInfo 142 @Binding var amountLastUsed: Amount 143 @Binding var amountToTransfer: Amount 144 let exchange: Exchange? 145 146 @EnvironmentObject private var controller: Controller 147 @EnvironmentObject private var model: WalletModel 148 @AppStorage("minimalistic") var minimalistic: Bool = false 149 #if DEBUG 150 @AppStorage("developerMode") var developerMode: Bool = true 151 #else 152 @AppStorage("developerMode") var developerMode: Bool = false 153 #endif 154 155 @State private var detailsForAmount: WithdrawalDetailsForAmount? = nil 156 @State private var loadError: Error? = nil 157 // @State private var ageMenuList: [Int] = [] 158 // @State private var selectedAge = 0 159 @State private var tosAccepted: Bool? = nil 160 161 @MainActor 162 private func getWithdrawalDetailsForAmount(_ amount: Amount, _ reload: Bool = false) async { 163 do { 164 let details = try await model.getWithdrawalDetailsForAmount(amount, 165 baseUrl: nil, 166 scope: scope, 167 viewHandles: true) 168 if reload { 169 tosAccepted = await controller.checkToS(for: details.exchangeBaseUrl) 170 } 171 detailsForAmount = details 172 loadError = nil 173 // agePicker.setAges(ages: detailsForAmount?.ageRestrictionOptions) 174 } catch WalletBackendError.walletCoreError(let walletBackendResponseError) { 175 symLog.log(walletBackendResponseError?.hint) 176 // TODO: ignore WALLET_CORE_REQUEST_CANCELLED but handle all others 177 // Passing non-nil to progressToken will throw WALLET_CORE_REQUEST_CANCELLED 178 // when calling getWithdrawalDetailsForAmount again before the last call returned. 179 // Since amountToTransfer changed and we don't need the old fee anymore, we just 180 // ignore it and do nothing. 181 // especially DON'T set detailsForAmount to nil 182 if detailsForAmount == nil, 183 walletBackendResponseError?.code != 7036 { // WALLET_CORE_REQUEST_CANCELLED 184 // nothing to show yet, so we would spin forever - show the error instead 185 loadError = WalletBackendError.walletCoreError(walletBackendResponseError) 186 } 187 } catch { 188 symLog.log(error.localizedDescription) 189 detailsForAmount = nil 190 loadError = error 191 } 192 } 193 194 @MainActor 195 private func computeFee(_ amount: Amount) async -> ComputeFeeResult? { 196 if amount.isZero { 197 return ComputeFeeResult.zero() 198 } 199 await getWithdrawalDetailsForAmount(amount) 200 // TODO: actually compute the fee 201 return nil 202 } // computeFee 203 204 @MainActor 205 private func viewDidLoad2() async { 206 // neues scope wenn balance geändert wird? 207 await getWithdrawalDetailsForAmount(amountToTransfer, true) 208 } 209 210 private func withdrawButtonTitle(_ currency: String) -> String { 211 switch currency { 212 case CHF_4217: 213 String(localized: "WITHDRAW_CONFIRM_BUTTONTITLE_CHF", defaultValue: "Confirm Withdrawal") 214 case EUR_4217: 215 String(localized: "WITHDRAW_CONFIRM_BUTTONTITLE_EUR", defaultValue: "Confirm Withdrawal") 216 default: 217 String(localized: "WITHDRAW_CONFIRM_BUTTONTITLE", defaultValue: "Confirm Withdrawal") 218 } 219 } 220 221 var body: some View { 222 #if PRINT_CHANGES 223 let _ = Self._printChanges() 224 let _ = symLog.vlog() // just to get the # to compare it with .onAppear & onDisappear 225 #endif 226 227 if let detailsForAmount { 228 ScrollView { 229 let coinData = CoinData(details: detailsForAmount) 230 let currency = detailsForAmount.scopeInfo.currency 231 let baseURL = detailsForAmount.exchangeBaseUrl 232 // let agePicker = AgePicker(ageMenuList: $ageMenuList, selectedAge: $selectedAge) 233 // let restrictAge: Int? = (selectedAge == 0) ? nil 234 // : selectedAge 235 // let _ = print(selectedAge, restrictAge) 236 let destination = ManualWithdrawDone(stack: stack.push(), 237 // scope: detailsForAmount.scopeInfo, 238 url: url, 239 baseURL: baseURL, 240 amountToTransfer: amountToTransfer) 241 // restrictAge: restrictAge) 242 let disabled = amountToTransfer.isZero || coinData.invalid || coinData.tooMany 243 244 if tosAccepted == true { // Von der Bank abzuhebender Betrag 245 let a11yLabel = String(localized: "Amount to withdraw from bank", comment: "a11y, no abbreviations") 246 let title = String(localized: "Amount to withdraw from bank:") 247 let amountLabel = minimalistic ? String(localized: "Amount:") 248 : title 249 CurrencyInputView(scope: scope, 250 amount: $amountToTransfer, 251 amountLastUsed: amountLastUsed, 252 available: nil, // enable shortcuts always 253 insufficient: false, // TODO: insufficient 254 title: amountLabel, 255 a11yTitle: a11yLabel, 256 shortcutAction: nil) 257 .padding(.top) 258 .task(id: amountToTransfer.value) { // re-run this whenever amountToTransfer changes 259 await computeFee(amountToTransfer) 260 } 261 QuiteSomeCoins(scope: scope, 262 coinData: coinData, 263 shouldShowFee: true, // TODO: set to false if we never charge withdrawal fees 264 feeIsNegative: true) 265 // agePicker 266 NavigationLink(destination: destination) { // VIEW_WITHDRAW_ACCEPT 267 Text(withdrawButtonTitle(currency)) 268 } 269 .buttonStyle(TalerButtonStyle(type: .prominent, disabled: disabled)) 270 .accessibilityIdentifier(A11yID.withdrawConfirmButton) 271 .disabled(disabled) 272 .padding(.top) 273 } else { 274 ToSButtonView(stack: stack.push(), 275 exchangeBaseUrl: scope.url ?? baseURL, 276 viewID: VIEW_WITHDRAW_TOS, // 31 WithdrawTOSView TODO: might be withdraw-exchange 277 shouldDismiss: true, // pop back to here 278 p2p: false) 279 .padding(.top) 280 } 281 } // ScrollView 282 .padding(.horizontal) 283 // .ignoresSafeArea(.keyboard, edges: .bottom) 284 .task(id: amountToTransfer.currencyStr) { 285 await getWithdrawalDetailsForAmount(amountToTransfer, true) 286 } 287 .onChange(of: controller.exchanges) { _ in 288 Task { 289 tosAccepted = await controller.checkToS(for: detailsForAmount.exchangeBaseUrl) 290 } 291 } 292 } else if let loadError { 293 // "OK" clears the error, which brings back the LoadingView and thus retries 294 ErrorView(stack.push(), error: loadError, devMode: developerMode) { 295 self.loadError = nil 296 } 297 } else { 298 LoadingView(stack: stack.push(), scopeInfo: scope, message: nil) 299 .task { await viewDidLoad2() } 300 } 301 } 302 }