taler-ios

iOS apps for GNU Taler (wallet)
Log | Files | Refs | README | LICENSE

PayTemplateScan.swift (12117B)


      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 // Will be called either by the user scanning a <pay-template> QR code or tapping the provided link,
     13 // both from the shop's website - or even from a printed QR code.
     14 // We check whether amount and/or summary is editable, and finally go to PaymentView
     15 struct PayTemplateScan: View {
     16     private let symLog = SymLogV(0)
     17     let stack: CallStack
     18 
     19     // the scanned URL
     20     let url: URL
     21 
     22     @EnvironmentObject private var controller: Controller
     23     @EnvironmentObject private var model: WalletModel
     24     @AppStorage("minimalistic") var minimalistic: Bool = false
     25     @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic
     26 
     27     let navTitle = String(localized: "Custom Amount", comment:"pay merchant")
     28 
     29 //    @State private var insufficient = false
     30 //    @State private var preparePayResult: PreparePayResult? = nil
     31     @State private var templateContract: TemplateContractDetails? = nil
     32     @State private var amountIsEditable = false
     33     @State private var amountToTransfer = Amount.zero(currency: EMPTYSTRING)    // Update currency when used
     34     @State private var amountShortcut = Amount.zero(currency: EMPTYSTRING)      // Update currency when used
     35     @State private var amountLastUsed = Amount.zero(currency: EMPTYSTRING)      // Update currency when used
     36     @State private var amountAvailable = Amount.zero(currency: EMPTYSTRING)     // TODO: set correct available amount (like in SendAmountV)
     37     @State private var shortcutSelected = false
     38     @State private var buttonSelected1 = false
     39     @State private var buttonSelected2 = false
     40     @State private var summaryIsEditable = false
     41     @State private var isPaivana = false
     42     @State private var summary: String = EMPTYSTRING       // templateParam
     43     @State private var scope: ScopeInfo? = nil
     44     /// survives PaymentScan being popped and pushed again, so that we don't
     45     ///  instantiate the template (= create another order) a second time
     46     @State private var prepared: PreparedTemplate? = nil
     47 
     48 //    @State private var feeAmount: Amount? = nil
     49 //    @State private var feeStr: String = EMPTYSTRING
     50 
     51     private func shortcutAction(_ shortcut: Amount) {
     52         amountShortcut = shortcut
     53         shortcutSelected = true
     54     }
     55     private func buttonAction1() {
     56         buttonSelected1 = true
     57     }
     58     private func buttonAction2() {
     59         buttonSelected2 = true
     60     }
     61 
     62     private func computeFeePayTemplate(_ amount: Amount) async -> ComputeFeeResult? {
     63         return nil
     64     }
     65 
     66     @MainActor
     67     private func viewDidLoad() async {
     68         if let response = try? await model.checkPayForTemplate(url.trimmedString) {
     69             let details = response.templateDetails
     70             let defaults = details.editableDefaults     // might be nil, or its fields might be nil
     71                 // TODO: let the user choose a currency from supportedCurrencies[]
     72             let supportedCurrencies = response.supportedCurrencies
     73                 // TODO: show 'availableBalances.amountAvailable' for the chosen currency
     74             let availableBalances = response.availableBalances
     75 
     76             /// checkPayForTemplate does not provide fees (yet)
     77             let contract = details.templateContract     // specifies fixed amount/summary
     78             if let amount = contract.amount {
     79                 controller.updateAmount(amount, forSaved: url)
     80             }
     81             if contract.templateType == .paivana {
     82                 // TODO: ???
     83                 isPaivana = true
     84             } else {
     85                 amountIsEditable = contract.amount == nil
     86                 summaryIsEditable = contract.summary == nil
     87             }
     88 
     89             let prepAmount = contract.amount ?? defaults?.amount        // might be nil
     90             var prepCurrency: String
     91             if let scope = contract.scopeInfo {
     92                 if let balance = controller.balance(for: scope) {
     93                     amountAvailable = balance.available
     94                 }
     95                 prepCurrency = scope.currency
     96             } else {
     97                 prepCurrency = contract.currency ?? defaults?.currency ?? supportedCurrencies.first ?? UNKNOWN
     98             }
     99             let zeroAmount = Amount(currency: prepCurrency, cent: 0)
    100             let prepSummary = contract.summary ?? defaults?.summary     // might be nil
    101 //          symLog.log("LoadingView.task preparePayForTemplate")
    102             /// preparePayForTemplate will make a network call to the merchant and create a TX
    103             ///  -> we only want to do this after the user entered amount and subject - but before confirmation of course
    104 //          if let result = await preparePayForTemplate(model: model,
    105 //                                                        url: url,
    106 //                                                     amount: amountIsEditable ? prepAmount ?? zeroAmount
    107 //                                                                              : nil,
    108 //                                                    summary: summaryIsEditable ? prepSummary ?? SPACE
    109 //                                                                               : nil,
    110 //                                                   announce: announce)
    111 //          {   symLog.log("preparePayForTemplate finished")
    112                 amountToTransfer = prepAmount ?? zeroAmount
    113                 summary = prepSummary ?? EMPTYSTRING
    114                 templateContract = contract
    115 //              insufficient = result.insufficient
    116 //              feeAmount = result.feeAmount
    117 //              feeStr = result.feeStr
    118 //              preparePayResult = result.ppCheck
    119 //          } else {
    120 //              symLog.log("preparePayForTemplateM failed")
    121 //          }
    122         }
    123     }
    124     var body: some View {
    125         if let templateContract {       // preparePayResult
    126 //            let currency = templateContract.currency ?? templateContract.amount?.currencyStr ?? UNKNOWN
    127             let a11yLabel = String(localized: "Amount to pay:", comment: "a11y, no abbreviations")
    128             let amountLabel = minimalistic ? String(localized: "Amount:")
    129                                            : a11yLabel
    130             // final destination with amountToTransfer, after user input of amount
    131             let finalDestinationI = PaymentScan(stack: stack.push(),
    132                                                   url: url,
    133                                              template: true,
    134                                      amountToTransfer: $amountToTransfer,
    135                                               summary: $summary,
    136                                      amountIsEditable: amountIsEditable,
    137                                     summaryIsEditable: summaryIsEditable,
    138                                              prepared: $prepared)
    139 
    140             // final destination with amountShortcut, when user tapped a shortcut
    141             let finalDestinationS = PaymentScan(stack: stack.push(),
    142                                                   url: url,
    143                                              template: true,
    144                                      amountToTransfer: $amountShortcut,
    145                                               summary: $summary,
    146                                      amountIsEditable: amountIsEditable,
    147                                     summaryIsEditable: summaryIsEditable,
    148                                              prepared: $prepared)
    149 
    150             // destination to subject input
    151             let inputDestination = SubjectInputV(stack: stack.push(),
    152                                                    url: url,
    153                                        amountAvailable: nil,
    154                                       amountToTransfer: $amountToTransfer,
    155                                            amountLabel: amountLabel,
    156                                                summary: $summary,
    157 //                                        insufficient: $insufficient,
    158 //                                           feeAmount: $feeAmount,
    159                                           feeIsNotZero: true, // TODO: feeIsNotZero()
    160                                             targetView: finalDestinationI)
    161 
    162             // destination to subject input, when user tapped an amount shortcut
    163             let shortcutDestination = SubjectInputV(stack: stack.push(),
    164                                                       url: url,
    165                                           amountAvailable: nil,
    166                                          amountToTransfer: $amountShortcut,
    167                                               amountLabel: amountLabel,
    168                                                   summary: $summary,
    169 //                                           insufficient: $insufficient,
    170 //                                              feeAmount: $feeAmount,
    171                                              feeIsNotZero: true, // TODO: feeIsNotZero()
    172                                                targetView: finalDestinationS)
    173           Group {
    174             if amountIsEditable {           // template contract amount is not fixed => let the user input an amount first
    175                 let amountInput = AmountInputV(stack: stack.push(),
    176                                                scope: scope,
    177                                      amountAvailable: $amountAvailable,
    178                                          amountLabel: amountLabel,
    179                                            a11yLabel: a11yLabel,
    180                                     amountToTransfer: $amountToTransfer,
    181                                       amountLastUsed: amountLastUsed,
    182                                              wireFee: nil,
    183                                              summary: $summary,
    184                                       shortcutAction: shortcutAction,
    185                                         buttonAction: buttonAction1,
    186                                           isIncoming: false,
    187                                           computeFee: computeFeePayTemplate)
    188                 ScrollView {
    189                     if summaryIsEditable {  // after amount input,
    190                         amountInput
    191                             .background( NavLink($shortcutSelected) { shortcutDestination } )
    192                             .background( NavLink($buttonSelected1) { inputDestination} )
    193 
    194                     } else {
    195                         amountInput
    196                             .background( NavLink($shortcutSelected) { finalDestinationS } )
    197                             .background( NavLink($buttonSelected1) { finalDestinationI } )
    198                     }
    199                 } // amountInput
    200             } else if summaryIsEditable {   // template contract summary is not fixed => let the user input a summary
    201                 ScrollView {
    202                     inputDestination
    203                         .background( NavLink($buttonSelected2) { finalDestinationI } )
    204                 } // inputDestination
    205             } else {    // both template contract amount and summary are fixed => directly show the payment
    206                 // Attention: contains a List, thus mustn't be included in a ScrollView
    207                 PaymentScan(stack: stack.push(),
    208                               url: url,
    209                          template: true,
    210                  amountToTransfer: $amountToTransfer,
    211                           summary: $summary,
    212                  amountIsEditable: amountIsEditable,
    213                 summaryIsEditable: summaryIsEditable,
    214                          prepared: $prepared)
    215             }
    216           } .navigationTitle(navTitle)
    217 //            .ignoresSafeArea(.keyboard, edges: .bottom)
    218             .frame(maxWidth: .infinity, alignment: .leading)
    219             .background(FullBackground())
    220             .onAppear() {
    221                 symLog.log("onAppear")
    222                 DebugViewC.shared.setSheetID(SHEET_PAY_TEMPLATE, stack: stack.push())
    223             }
    224         } else {
    225             LoadingView(stack: stack.push(), scopeInfo: nil, message: url.host)
    226                 .task { await viewDidLoad() }
    227         }
    228     }
    229 }