PaymentTransactionView.swift (14751B)
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 // MARK: - 13 struct MerchantHeader: View { 14 let terms: MerchantContractTerms? 15 16 @Environment(\.colorScheme) private var colorScheme 17 @Environment(\.colorSchemeContrast) private var colorSchemeContrast 18 19 func compactAddress(_ address: Location?) -> String? { 20 if let address { 21 var result: String = EMPTYSTRING 22 if let street = address.street { 23 result.append(street) 24 } 25 if let town = address.town { 26 if !result.isEmpty { 27 result.append(", ") 28 } 29 result.append(town) 30 } 31 if let country = address.country { 32 if !result.isEmpty { 33 result.append(", ") 34 } 35 result.append(country) 36 } 37 return result.isEmpty ? nil : result 38 } 39 return nil 40 } 41 42 var body: some View { 43 if let terms { 44 VStack(alignment: .leading) { 45 HStack { 46 if let imageBase64 = terms.merchant.logo { 47 if let image = Image(imageBase64: imageBase64) { 48 image 49 .resizable() 50 .aspectRatio(contentMode: .fit) 51 .frame(maxHeight: 50) 52 .padding(.trailing, 8) 53 } 54 } else { 55 #if TALER_NIGHTLY 56 let imageName = if #available(iOS 17.0, *) { MERCHANT17 } else { MERCHANT14 } 57 Image(systemName: imageName) 58 .resizable() 59 .frame(width: 44, height: 44) 60 #endif 61 } 62 VStack(alignment: .leading) { 63 let merchant = terms.merchant 64 Text(merchant.name) 65 .talerFont(.title3) 66 if let address = compactAddress(merchant.address) { 67 Text(address) 68 .talerFont(.body) 69 } 70 } 71 } .foregroundStyle(Color.primary) 72 .padding(.bottom) 73 // Text("Summary") 74 // .talerFont(.title3) 75 // .foregroundColor(WalletColors().secondary2(colorScheme, colorSchemeContrast)) 76 } 77 } 78 } 79 } 80 // MARK: - 81 struct PaymentTransactionView: View { 82 private let symLog = SymLogV(0) 83 let stack: CallStack 84 let common: TransactionCommon 85 let paymentTransaction: PaymentTransaction 86 @Binding var scope: ScopeInfo? 87 @Binding var possible: Bool? 88 #if GNU_TALER 89 @Binding var effective: Amount? 90 @Binding var payNow: Bool 91 @Binding var selectedChoice: Int? 92 #else 93 @Binding var isFinished: Bool? 94 #endif 95 @EnvironmentObject private var controller: Controller 96 @EnvironmentObject private var model: WalletModel 97 98 @State private var showProducts: Bool = false 99 #if !GNU_TALER 100 @State private var effective: Amount? = nil 101 @State private var payNow: Bool = false 102 @State private var selectedChoice: Int? = nil 103 @State private var currencyInfo: CurrencyInfo = CurrencyInfo.zero(UNKNOWN) 104 @State private var formatted: (String, String)? = nil 105 #endif 106 107 func selectIndex(_ index: Int?, of choices: [ChoiceTriple]) -> Int? { 108 let index1 = index ?? 0 109 let select = index1 < choices.count ? index1 : 0 110 let choice = choices[select] 111 let selectionDetail = choice.0 112 if selectionDetail.status == .paymentPossible { 113 selectedChoice = select 114 effective = selectionDetail.amountEffective 115 possible = true 116 return select 117 } else { 118 possible = false 119 } 120 return nil 121 } 122 123 func automaticOrDefault(_ automaticIndex: Int?,_ defaultChoiceIndex: Int?, of choices: [ChoiceTriple]) { 124 if let automaticIndex { 125 // Pay Automatically - usually with a subscription token 126 if let selectedAutomatic = selectIndex(automaticIndex, of: choices) { 127 if selectedAutomatic == automaticIndex { 128 // check if automatic choice does NOT have an amount 129 let choiceTriple = choices[selectedAutomatic] 130 let selectionDetail = choiceTriple.0 131 if selectionDetail.status == .paymentPossible { 132 // we currently don't want to pay MONEY automatically, only tokens 133 // TODO: make the maximum value a user default 134 if selectionDetail.amountRaw.isZero { 135 payNow = true 136 } 137 } 138 return 139 } else if let defaultChoiceIndex { 140 if selectedAutomatic == defaultChoiceIndex { return } 141 // else fall thru and select defaultChoiceIndex 142 } else { // there is no default - keep selectedAutomatic 143 return 144 } 145 } 146 } 147 _ = selectIndex(defaultChoiceIndex, of: choices) 148 } 149 150 var isNotClaiming: Bool { 151 !common.isClaiming 152 } 153 154 func selectedOrFirst(_ choices: [ChoiceTriple]) -> ChoiceTriple? { 155 if let selectedChoice { 156 if selectedChoice < choices.count { 157 return choices[selectedChoice] 158 } 159 } 160 if let choice = choices.first { 161 return choice 162 } 163 return nil 164 } 165 166 func buttonAction() { 167 withAnimation { 168 showProducts.toggle() 169 } 170 } 171 172 #if !GNU_TALER 173 private func payTransaction() async { 174 if let confirmPayResult = try? await model.confirmPay(common.transactionId, 175 choiceIndex: selectedChoice) { 176 // symLog.log(confirmPayResult as Any) 177 if confirmPayResult.type == "done" { 178 // if let url { 179 // controller.removeURL(url) 180 // } 181 } else { 182 // if let url { 183 // controller.removeURL(url) // TODO: pending might fail - in which case we might want to try again 184 // } 185 } 186 let txId = confirmPayResult.transactionId 187 if let matched = try? await model.waitTransactionState(txId, token: txId, major: .done), matched { 188 } else { 189 print("payTransaction: waitTransactionState bail") // TODO: ??? 190 } 191 } 192 } 193 #endif 194 195 @ViewBuilder 196 func choicesView(choices: [ChoiceTriple], 197 terms: MerchantContractTerms, 198 showHeader: Bool, 199 automaticIndex: Int? 200 ) -> some View { 201 #if GNU_TALER 202 ChoicesView(stack: stack.push(), 203 choiceTriples: choices, 204 terms: terms, 205 showHeader: showHeader, 206 automaticIndex: automaticIndex, 207 selectedChoice: $selectedChoice) 208 #else 209 ChoicesView(stack: stack.push(), 210 choiceTriples: choices, 211 terms: terms, 212 showHeader: showHeader, 213 automaticIndex: automaticIndex, 214 selectedChoice: $selectedChoice, 215 formatted: formatted, 216 payNow: $payNow, 217 isFinished: $isFinished 218 ) 219 #endif 220 } 221 222 var body: some View { 223 #if PRINT_CHANGES 224 let _ = Self._printChanges() 225 let _ = symLog.vlog() 226 #endif 227 let details = paymentTransaction.details 228 if common.isDialog { // show payment confirmation dialog 229 let state = common.txState 230 let terms1 = details.contractTerms 231 let choicesTuple = controller.choicesTuple 232 let txId = choicesTuple.0 233 let choicesForPayment = choicesTuple.1 234 235 Section { 236 let summary = Text(terms1?.locSummary ?? "Summary") 237 .talerFont(.title3) 238 239 if let choicesForPayment { 240 if txId == common.transactionId { 241 let terms2 = choicesForPayment.contractTerms 242 if let products = terms2.products { 243 let chevron = Image(systemName: CHEVRON_UP) // 244 Button(action: buttonAction) { 245 HStack(alignment: .firstTextBaseline) { 246 summary 247 Spacer() 248 chevron.rotationEffect(.degrees((showProducts ? 0 : -180))) 249 .accessibilityHidden(true) 250 } 251 } 252 if showProducts { 253 ProductsView(stack: stack.push(), 254 scope: scope, 255 products: products) 256 } 257 } else { 258 summary 259 } 260 } 261 } 262 } header: { 263 MerchantHeader(terms: details.contractTerms) 264 } 265 .task(id: state.hashValue) { 266 if txId != common.transactionId || choicesForPayment == nil { 267 symLog.log("❗️❗️ task: \(state)") 268 await controller.loadChoicesForPayment(stack.push(), 269 txId: common.transactionId) 270 } else { 271 symLog.log("❗️❗️ choicesForPayment exists, no need for task: \(state)") 272 } 273 } // loadChoicesForPayment 274 275 if let choicesForPayment { 276 if txId == common.transactionId { 277 let terms2 = choicesForPayment.contractTerms 278 if let (choices, showHeader) = choicesForPayment.choiceTriple() { 279 let hasAutomatic = choicesForPayment.automaticExecution ?? false 280 let automaticIndex = hasAutomatic ? choicesForPayment.automaticExecutableIndex : nil 281 choicesView(choices: choices, 282 terms: terms2, 283 showHeader: showHeader, 284 automaticIndex: automaticIndex) 285 .task { 286 automaticOrDefault(automaticIndex, choicesForPayment.defaultChoiceIndex, of: choices) 287 } 288 .onChange(of: selectedChoice) { newValue in 289 if let newValue, newValue < choices.count { 290 let newChoice = choices[newValue] 291 effective = newChoice.0.amountEffective 292 possible = newChoice.0.status == .paymentPossible 293 scope = newChoice.0.scopeInfo 294 #if !GNU_TALER 295 if let scope, let effective, !effective.isZero { 296 currencyInfo = controller.info(for: scope) ?? CurrencyInfo.zero(UNKNOWN) 297 formatted = effective.formatted(currencyInfo) 298 } else { 299 effective = nil 300 scope = nil 301 formatted = nil 302 } 303 #endif 304 } else { 305 effective = nil 306 possible = nil 307 scope = nil 308 } 309 } 310 .onChange(of: payNow) { payNow2 in 311 #if !GNU_TALER 312 if payNow2 { 313 Task { 314 await payTransaction() 315 payNow = false // re-enable "Pay now" if this attempt did not lead to a state transition 316 } 317 } 318 #endif 319 } 320 321 if let choice = selectedOrFirst(choices) { 322 // let summary = details.info?.locSummary ?? 323 // String(localized: "No summary", comment: "OrderShortInfo.summary") 324 let selectionDetail: ChoiceSelectionDetail = choice.0 325 // let contractChoice: ContractChoice = choice.1 326 PaymentView2(stack: stack.push(), // TODO: details.info.merchant.name 327 paid: false, 328 raw: selectionDetail.amountRaw, 329 effective: effective, // V0? 330 firstScope: scope, 331 baseURL: nil, 332 balanceDetails: selectionDetail.balanceDetails) 333 } 334 } else { // should never happen... 335 // TODO: show some error 336 } 337 } else { // cached data outdated 338 // TODO: purge and reload 339 } 340 } 341 } else if isNotClaiming { // show finished payment 342 PaidTransactionDetailV(stack: stack.push(), 343 paymentTx: paymentTransaction) // TODO: details.info.merchant.name 344 ThreeAmountsSheet(stack: stack.push(), 345 scope: scope, 346 common: common, 347 topAbbrev: String(localized: "Price:", comment: "mini"), 348 topTitle: String(localized: "Price (net):"), 349 baseURL: nil, // TODO: baseURL 350 noFees: nil, // TODO: noFees 351 feeIsNegative: false, 352 large: true, 353 header: details.info?.locSummary) 354 } // show finished payment 355 } // body 356 } // PaymentTransactionView