BankEditView.swift (17252B)
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 /// This view shows the currency name in an exchange section 13 /// currency 14 struct BankEditView: View { 15 private let symLog = SymLogV(0) 16 let stack: CallStack 17 let accountID: String? 18 19 @Environment(\.dismiss) var dismiss // pop back once 20 @EnvironmentObject private var model: WalletModel 21 @EnvironmentObject private var controller: Controller 22 @AppStorage("minimalistic") var minimalistic: Bool = false 23 @AppStorage("demoHints") var demoHints: Bool = true 24 // @AppStorage("fakeNoFees") var fakeNoFees: Bool = true TODO: use this flag! 25 @AppStorage("ownerName") var ownerName: String = EMPTYSTRING 26 27 @State private var shouldReloadBalances: Int = 0 28 @State private var currencyInfo: CurrencyInfo = CurrencyInfo.zero(UNKNOWN) 29 @State private var didDelete: Bool = false 30 @State private var disabled: Bool = false 31 @State private var showAlert: Bool = false 32 33 @State private var myAccount: String? = nil 34 @State private var accountHolder: String = EMPTYSTRING 35 @State private var iban: String = EMPTYSTRING 36 @State private var ibanValid = false 37 @State private var xTaler: String = EMPTYSTRING 38 @State private var xTalerHost: String = EMPTYSTRING 39 @State private var xTalerAccount: String = EMPTYSTRING 40 @State private var methods: [PaytoType] = [.iban, .xTalerBank] 41 @State private var talerBankHosts: [String] = [] 42 @State private var accountLabel: String = EMPTYSTRING 43 @State private var paytoType: PaytoType = .iban 44 @State private var selected = 0 45 @State private var kycCompleted = false 46 @State private var finished = false 47 @State private var unchanged = true 48 @State private var userTyped = false 49 50 @FocusState private var focus:FocusedField? 51 52 enum FocusedField: Hashable { 53 case accountLabel, accountHolder, iban, xTaler 54 } 55 56 // @MainActor 57 // private func validateIban() async { 58 // if (try? await model.validateIban(iban)) == true { 59 // let payto = "payto://iban/\(iban)?receiver-name=\(accountHolder)" 60 // paytoUri = payto.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! 61 // } else { 62 // paytoUri = nil 63 // } 64 // } 65 66 /// An x-taler-bank target is BANK-HOST/ACCOUNT (RFC 8905) with two components 67 private var xTalerValid: Bool { 68 let parts = xTaler.split(separator: "/", omittingEmptySubsequences: false) 69 return parts.count >= 2 70 && parts.allSatisfy { !$0.isEmpty && !$0.contains(where: { $0.isWhitespace }) } 71 } 72 73 @ViewBuilder func barButton() -> some View { 74 let isNew = accountID == nil 75 let titleStr = isNew ? String(localized: "Add", comment: "button title: Add bank account") 76 : String(localized: "Update", comment: "button title: Update bank account") 77 let a11yStr = isNew ? String(localized: "Add bank account", comment: "a11y") 78 : String(localized: "Update bank account", comment: "a11y") 79 let notValid: Bool = paytoType == .iban ? (iban.isEmpty || !ibanValid) 80 : !xTalerValid 81 DoneButton(titleStr: titleStr, accessibilityLabelStr: titleStr) { 82 Task { 83 if await updateAccount() { 84 dismiss() 85 } 86 } 87 } 88 .disabled(disabled || notValid || unchanged) 89 } 90 91 @MainActor 92 private func viewDidLoad() async { 93 if let accountID { 94 if let account = try? await model.getBankAccountById(accountID) { 95 accountLabel = account.label ?? EMPTYSTRING 96 kycCompleted = account.kycCompleted 97 let payTo = PayTo(account.paytoUri) 98 accountHolder = payTo.receiver ?? ownerName 99 xTaler = payTo.xTaler ?? EMPTYSTRING 100 iban = payTo.iban ?? EMPTYSTRING 101 if iban.isEmpty { 102 if xTaler.count > 1 { 103 paytoType = .xTalerBank 104 } 105 } else if let result = try? await model.validateIban(iban) { 106 ibanValid = result 107 } 108 } 109 } else { 110 // offer only the account types the user's payment services can deposit to 111 if let details = try? await model.depositWireTypes(nil) { 112 var supported: [PaytoType] = [] 113 for detail in details where [PaytoType.iban, .xTalerBank].contains(detail.paymentTargetType) { 114 if !supported.contains(detail.paymentTargetType) { 115 supported.append(detail.paymentTargetType) 116 } 117 for host in detail.talerBankHostnames ?? [] where !talerBankHosts.contains(host) { 118 talerBankHosts.append(host) 119 } 120 } 121 if !supported.isEmpty { 122 methods = supported 123 selected = 0 124 paytoType = supported[0] 125 } 126 if let host = talerBankHosts.first { 127 xTalerHost = host 128 } 129 } 130 } 131 } 132 133 private func composeXTaler() { 134 xTaler = xTalerAccount.isEmpty ? EMPTYSTRING : xTalerHost + "/" + xTalerAccount 135 if userTyped { 136 unchanged = false 137 } 138 } 139 140 @MainActor 141 private func updateAccount() async -> Bool { 142 let isIBAN = paytoType == .iban 143 if !accountHolder.isEmpty && !accountLabel.isEmpty { 144 if isIBAN ? !iban.isEmpty 145 : xTalerValid { 146 // Build the payto URI with URLComponents so each component is escaped as a 147 // component. The previous code percent-encoded the ALREADY-ASSEMBLED string 148 // with .urlQueryAllowed, which leaves "?", "&" and "=" untouched — an 149 // account holder called "a&foo=bar" injected extra query parameters. 150 151 // TODO: for x-taler-bank the target must be BANK-HOST/ACCOUNT. Accounts read 152 // from an existing payto now round-trip with their host, but there is still 153 // no separate input field for it, so a hand-typed account without a host 154 // produces an incomplete target. See bugs.txt [14.2]. 155 var components = URLComponents() 156 components.scheme = "payto" 157 components.host = isIBAN ? "iban" : "x-taler-bank" 158 let target = isIBAN ? iban.filter { !$0.isWhitespace }.uppercased() : xTaler 159 components.path = "/" + target 160 components.queryItems = [URLQueryItem(name: "receiver-name", value: accountHolder)] 161 guard let paytoUri = components.string else { 162 symLog.log("could not build a payto URI from the entered account") 163 showAlert = true 164 return false 165 } 166 symLog.log(paytoUri) 167 if let account = try? await model.addBankAccount(paytoUri, 168 label: accountLabel, 169 replace: myAccount ?? accountID 170 ) { 171 symLog.log(account) 172 myAccount = account 173 return true 174 } else { 175 symLog.log("error addBankAccount") 176 } 177 } 178 } 179 return false 180 } 181 182 @MainActor 183 private func deleteAccount() { 184 disabled = true // don't try this more than once 185 Task { // runs on MainActor 186 if let id = myAccount ?? accountID { 187 if let _ = try? await model.forgetBankAccount(id) { 188 symLog.log("forgot \(id)") 189 didDelete = true // change button text 190 // NotificationCenter.default.post(name: .ExchangeDeleted, object: nil, userInfo: nil) 191 // NotificationCenter.default.post(name: .BalanceChange, object: nil, userInfo: nil) 192 dismissTop(stack.push()) 193 } else { 194 showAlert = true 195 disabled = false 196 } 197 } 198 } 199 } 200 201 var body: some View { 202 #if PRINT_CHANGES 203 let _ = Self._printChanges() 204 // let _ = symLog.vlog() // just to get the # to compare it with .onAppear & onDisappear 205 #endif 206 List { 207 if kycCompleted // || true 208 { Section { 209 Text("If you change the account holder name or the IBAN, you may have to perform the legitimization procedure again.") // TODO: BBAN 210 .talerFont(.body) 211 } 212 } 213 Section { 214 let labelTitle = String(localized: "Label") 215 let labelColon = String("\(labelTitle):") 216 if !minimalistic { 217 Text(labelColon) 218 .talerFont(.picker) 219 .accessibilityHidden(true) 220 .padding(.bottom, -12) 221 } 222 TextField(minimalistic ? labelTitle : EMPTYSTRING, text: $accountLabel) 223 .accessibilityLabel(labelColon) 224 .focused($focus, equals: .accountLabel) 225 .talerFont(.title3) 226 .foregroundColor(WalletColors().fieldForeground) // text color 227 .background(WalletColors().fieldBackground) 228 .textFieldStyle(.roundedBorder) 229 .padding(.bottom) 230 .onChange(of: accountLabel) { newValue in 231 if userTyped { 232 unchanged = false 233 } 234 } 235 236 let holderTitle = String(localized: "Account holder") 237 let holderColon = String("\(holderTitle):") 238 if !minimalistic { 239 Text(holderColon) 240 .talerFont(.picker) 241 .accessibilityHidden(true) 242 .padding(.bottom, -12) 243 } 244 TextField(minimalistic ? holderTitle : EMPTYSTRING, text: $accountHolder) 245 .accessibilityLabel(holderColon) 246 .focused($focus, equals: .accountHolder) 247 .talerFont(.title3) 248 .foregroundColor(WalletColors().fieldForeground) // text color 249 .background(WalletColors().fieldBackground) 250 .textFieldStyle(.roundedBorder) 251 .padding(.bottom) 252 .onChange(of: accountHolder) { newValue in 253 if userTyped { 254 unchanged = false 255 } 256 } 257 258 let paytoStr = paytoType.rawValue.uppercased() 259 let paytoColon = String("\(paytoStr):") 260 if let accountID { 261 // we are editing an existing bank account 262 Text(paytoColon) 263 .talerFont(.picker) 264 .accessibilityHidden(true) 265 .padding(.bottom, -12) 266 } else if methods.count > 1 { 267 // this is a NEW bank account - choose a payment method 268 Picker(EMPTYSTRING, selection: $selected) { 269 ForEach(0..<methods.count, id: \.self) { index in 270 let method = methods[index] 271 Text(method.rawValue.uppercased()) 272 .tag(index) 273 } 274 } 275 .pickerStyle(.segmented) 276 .onChange(of: selected) { newValue in 277 paytoType = methods[newValue] 278 } 279 } 280 if paytoType == .iban { 281 TextField(paytoStr, text: $iban) // TODO: BBAN 282 .accessibilityLabel(paytoColon) 283 .focused($focus, equals: .iban) 284 .talerFont(.title3) 285 .foregroundColor(WalletColors().fieldForeground) // text color 286 .background(WalletColors().fieldBackground) 287 .textFieldStyle(.roundedBorder) 288 .padding(.bottom) 289 .onChange(of: iban) { newValue in 290 Task { 291 if let result = try? await model.validateIban(newValue) { 292 ibanValid = result 293 } 294 } 295 } 296 } else if paytoType == .xTalerBank && accountID == nil && !talerBankHosts.isEmpty { 297 // NEW x-taler-bank account: the bank comes from the payment service, 298 // the user only types the account name 299 let bankTitle = String(localized: "Bank") 300 Picker(bankTitle, selection: $xTalerHost) { 301 ForEach(talerBankHosts, id: \.self) { host in 302 Text(host).tag(host) 303 } 304 } 305 .talerFont(.title3) 306 .onChange(of: xTalerHost) { _ in composeXTaler() } 307 let accountColon = String(localized: "Account:") 308 if !minimalistic { 309 Text(accountColon) 310 .talerFont(.picker) 311 .accessibilityHidden(true) 312 .padding(.bottom, -12) 313 } 314 TextField(minimalistic ? accountColon : EMPTYSTRING, text: $xTalerAccount) 315 .accessibilityLabel(accountColon) 316 .focused($focus, equals: .xTaler) 317 .talerFont(.title3) 318 .foregroundColor(WalletColors().fieldForeground) // text color 319 .background(WalletColors().fieldBackground) 320 .textFieldStyle(.roundedBorder) 321 .padding(.bottom) 322 .onChange(of: xTalerAccount) { _ in composeXTaler() } 323 } else if paytoType == .xTalerBank { 324 TextField("BANK-HOST/ACCOUNT", text: $xTaler) 325 .accessibilityLabel(paytoColon) 326 .focused($focus, equals: .xTaler) 327 .talerFont(.title3) 328 .foregroundColor(WalletColors().fieldForeground) // text color 329 .background(WalletColors().fieldBackground) 330 .textFieldStyle(.roundedBorder) 331 .autocapitalization(.none) 332 .disableAutocorrection(true) 333 .padding(.bottom, xTaler.isEmpty || xTalerValid ? nil : 0) 334 .onChange(of: xTaler) { newValue in 335 if userTyped { 336 unchanged = false 337 } 338 } 339 if !xTaler.isEmpty && !xTalerValid { 340 Text("Enter the account as BANK-HOST/ACCOUNT", 341 comment: "hint below the x-taler-bank field") 342 .talerFont(.body) 343 .padding(.bottom) 344 } 345 } else { 346 Text("unknown payment method") 347 .talerFont(.title3) 348 .padding(.bottom) 349 } 350 351 if let accountID { 352 let buttonTitle = String(localized: "Account.Delete", defaultValue: "Forget bank account", comment: "Action button") 353 let warningText1 = String(localized: "Are you sure you want to forget this bank account?") 354 WarningButton(warningText: warningText1, 355 buttonTitle: buttonTitle, 356 buttonIcon: "trash", 357 role: .destructive, // TODO: WalletColors().errorColor 358 disabled: $disabled, 359 action: deleteAccount) 360 .padding(.top) 361 } 362 }.listRowSeparator(.hidden) 363 } // List 364 .navigationBarItems(trailing: barButton()) 365 // .ignoresSafeArea(.keyboard, edges: .bottom) 366 .onChange(of: focus) { [focus] newState in 367 switch newState { 368 case .none: 369 break 370 case .some(_): 371 userTyped = true 372 } 373 } 374 .task { await viewDidLoad() } 375 .onDisappear() { 376 disabled = false 377 } 378 } 379 }