taler-ios

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

PaymentScan.swift (17219B)


      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 typealias Announce = (_ this: String) -> ()
     13 
     14 fileprivate func feeLabel(_ feeString: String) -> String {
     15     feeString.isEmpty ? EMPTYSTRING : String(localized: "+ \(feeString) fee")
     16 }
     17 
     18 /// The pay-template instantiation which already created an order at the merchant
     19 struct PreparedTemplate: Equatable {
     20     let key: String                 // the parameters that order was created for
     21     let transactionId: String
     22 }
     23 
     24 // MARK: -
     25 // Will be called either by the user scanning a <pay> QR code or tapping the provided link,
     26 // both from the shop's website - or even from a printed QR code.
     27 // We show the payment details in a sheet, and a "Confirm payment" / "Pay now" button.
     28 // This is also the final view after the user entered data of a <pay-template>.
     29 struct PaymentScan: View, Sendable {
     30     private let symLog = SymLogV(0)
     31     let stack: CallStack
     32 
     33     // the scanned URL
     34     let url: URL
     35     let template: Bool
     36     @Binding var amountToTransfer: Amount
     37     @Binding var summary: String
     38     let amountIsEditable: Bool                      //
     39     let summaryIsEditable: Bool                      //
     40     var prepared: Binding<PreparedTemplate?>? = nil // template only, lives in PayTemplateScan
     41 
     42     @EnvironmentObject private var model: WalletModel
     43     @EnvironmentObject private var controller: Controller
     44     @AppStorage("myListStyle") var myListStyle: MyListStyle = .automatic
     45 
     46     @State private var currencyInfo: CurrencyInfo = CurrencyInfo.zero(UNKNOWN)
     47     @State private var txId: String? = nil
     48 
     49     @State private var elapsed: Int = 0
     50     @State private var talerTX = TalerTransaction(dummyCurrency: DEMOCURRENCY)
     51 
     52     /// the parameters an already instantiated template order belongs to
     53     private var templateKey: String {
     54         url.trimmedString + LINEFEED
     55           + (amountIsEditable ? amountToTransfer.description : EMPTYSTRING) + LINEFEED
     56           + (summaryIsEditable ? summary : EMPTYSTRING)
     57     }
     58 
     59     @MainActor
     60     private func viewDidLoad() async {
     61 //        symLog.log(".task")
     62         if template {
     63             /// Instantiating a template creates a fresh order at the merchant, and this view is
     64             ///  pushed anew (with new @State) whenever the user navigates back and forward again
     65             ///  - so only instantiate once per amount/subject the user entered.
     66             let key = templateKey
     67             if let already = prepared?.wrappedValue, already.key == key {
     68                 txId = already.transactionId
     69                 return
     70             }
     71             if let templateResponse = try? await model.preparePayForTemplate(url.trimmedString,
     72                                                    amount: amountIsEditable ? amountToTransfer : nil,
     73                                                  summary: summaryIsEditable ? summary : nil) {
     74                 txId = templateResponse.transactionId
     75                 prepared?.wrappedValue = PreparedTemplate(key: key, transactionId: templateResponse.transactionId)
     76 //                preparePayResult = templateResponse
     77 //                let raw = templateResponse.amountRaw
     78 //                controller.updateAmount(raw, forSaved: url)
     79             }
     80         } else {
     81             if let payResponse = try? await model.preparePayForUri(url.trimmedString) {
     82                 txId = payResponse.transactionId
     83 //                let raw = payResponse.amountRaw
     84 //                controller.updateAmount(raw, forSaved: url)       // TODO: update scanned URL
     85             }
     86         }
     87         if let txId {
     88             if let matched = try? await model.waitTransactionState(txId, token: txId, major: .dialog), matched {
     89                 symLog.log("waitTransactionState matched")
     90             } else {
     91                 symLog.log("PaymentScan: waitTransactionState bail")      // TODO: ???
     92             }
     93         } else {
     94             // TODO: didn't get a txId
     95         }
     96     }
     97 
     98     var body: some View {
     99         ZStack {
    100             if let txId {
    101                 TransactionSummaryList(stack: stack.push(),
    102                                transactionId: txId,
    103                                      talerTX: $talerTX,
    104                                     navTitle: nil,
    105                                      hasDone: true,                 // conclude payment
    106                                     showDone: .prominent,
    107                                          url: url,
    108                                  withActions: false)
    109 #if TALER_NIGHTLY2
    110 //            if let preparePayResult {
    111                 let status = preparePayResult.status
    112                 let paid = status == .alreadyConfirmed
    113                 let navTitle = paid ? String(localized: "Already paid", comment:"pay merchant navTitle")
    114                                     : String(localized: "Confirm Payment", comment:"pay merchant navTitle")
    115                 let list = List {
    116                     TransactionSummaryList.MerchantHeader(terms: terms)
    117 
    118                     if paid {
    119                         Text("You already paid for this article.")
    120                             .talerFont(.headline)
    121                         if let fulfillmentUrl = terms.fulfillmentURL {
    122                             if let destination = URL(string: fulfillmentUrl) {
    123                                 let buttonTitle = terms.fulfillmentMessage ?? String(localized: "Open merchant website")
    124                                 Link(buttonTitle, destination: destination)
    125                                     .buttonStyle(TalerButtonStyle(type: .bordered))
    126                                     .accessibilityHint(String(localized: "Will go to the merchant website.", comment: "a11y"))
    127                             }
    128                         }
    129                     } // You already paid
    130 
    131                 }
    132                 .listStyle(myListStyle.style).anyView
    133 #if OIM
    134                 .overlay { if #available(iOS 16.4, *) {
    135                     if controller.oimSheetActive {
    136                         OIMpayView(stack: stack.push(),
    137                                    amount: effective)
    138                     }
    139                 } }
    140 #endif
    141 
    142                 if #available(iOS 17.0, *) {
    143                     list.toolbarTitleDisplayMode(.inlineLarge)
    144                 } else {
    145                     list
    146                 }
    147 #endif
    148             } else {
    149                 LoadingView(stack: stack.push(), scopeInfo: nil, message: url.host)
    150                     .task { await viewDidLoad() }
    151             }
    152         }.onAppear() {
    153             symLog.log("onAppear")
    154             DebugViewC.shared.setSheetID(SHEET_PAYMENT, stack: stack.push())
    155         }
    156     }
    157 }
    158 // MARK: -
    159 struct PaymentView2: View, Sendable {
    160     let stack: CallStack
    161     let paid: Bool
    162     let raw: Amount
    163     let effective: Amount?
    164     let firstScope: ScopeInfo?
    165     let baseURL: String?
    166 //    let terms: MerchantContractTerms
    167     let balanceDetails: PaymentInsufficientBalanceDetails?
    168 
    169     func computeFee(raw: Amount?, eff: Amount?) -> Amount? {
    170         if let raw, let eff {
    171             // fee can only be computed if raw and eff are the same currency
    172             return try? Amount.diff(raw, eff)
    173         }
    174         return nil
    175     }
    176 
    177     var body: some View {
    178                 // TODO: show balanceDetails.balanceAvailable
    179                 let topTitle = paid ? String(localized: "Paid amount:")
    180                                     : String(localized: "Amount to pay:")
    181                 let topAbbrev =  paid ? String(localized: "Paid:", comment: "mini")
    182                                       : String(localized: "Pay:", comment: "mini")
    183                 let bottomTitle = paid ? String(localized: "Spent amount:")
    184                                        : String(localized: "Amount to spend:")
    185                 if let effective {  // payment possible
    186                     let fee = computeFee(raw: raw, eff: effective)
    187                     ThreeAmountsSection(stack: stack.push("PaymentView2"),
    188                                         scope: firstScope,
    189                                      topTitle: topTitle,
    190                                     topAbbrev: topAbbrev,
    191                                     topAmount: raw,
    192                                        noFees: nil,        // TODO: check baseURL for fees
    193                                           fee: fee,
    194                                 feeIsNegative: nil,
    195                                   bottomTitle: bottomTitle,
    196                                  bottomAbbrev: String(localized: "Effective:", comment: "mini"),
    197                                  bottomAmount: effective,
    198                                         large: false,
    199                                 pendingDialog: !paid,
    200                                        isDone: paid,
    201                                      incoming: false,
    202                                       baseURL: baseURL,
    203                                    txStateLcl: nil,
    204                                        header: nil,
    205                     )
    206                     // TODO: payment: popup with all possible exchanges, check fees
    207                 } else if let balanceDetails {    // Insufficient
    208                     if let localizedCause = balanceDetails.causeHint?.localizedCause(raw.currencyStr) {
    209                         Text(localizedCause)
    210                             .talerFont(.headline)
    211                     }
    212                     ThreeAmountsSection(stack: stack.push(),
    213                                         scope: firstScope,
    214                                      topTitle: topTitle,
    215                                     topAbbrev: topAbbrev,
    216                                     topAmount: raw,
    217                                        noFees: nil,        // TODO: check baseURL for fees
    218                                           fee: nil,
    219                                 feeIsNegative: nil,
    220                                   bottomTitle: String(localized: "Amount available:"),
    221                                  bottomAbbrev: String(localized: "Available:", comment: "mini"),
    222                                  bottomAmount: balanceDetails.balanceAvailable,
    223                                         large: false,
    224                                 pendingDialog: false,       // TODO: true to always show currency the payment will be made in?
    225                                        isDone: false,
    226                                      incoming: false,
    227                                       baseURL: baseURL,
    228                                    txStateLcl: nil,
    229                                         header: nil,
    230                     )
    231                 } else {
    232 //                    let _ = print("No ThreeAmounts")
    233                     // TODO: Error - neither effective nor balanceDetails
    234                     // actually this is shown when effective is not yet loaded for a brief moment
    235                     // - so don't show an error here
    236 //                    Text("Error")
    237 //                        .talerFont(.body)
    238                 }
    239     }
    240 }
    241 // MARK: -
    242 struct PaymentButton: View, Sendable {
    243     let symLog: SymLogV?
    244     let stack: CallStack
    245     let terms: MerchantContractTerms
    246     let formatted: (String, String)?
    247     @Binding var isFinished: Bool?
    248     @Binding var payNow: Bool
    249 
    250     @EnvironmentObject private var controller: Controller
    251 
    252     @State private var wasTapped: Bool = false
    253     @State private var timeToPay: Int?
    254 
    255     func buttonAction() {
    256         if !wasTapped {
    257             wasTapped = true
    258             controller.hapticNotification(.success)
    259             symLog?.log("paying now")
    260 #if DEBUG       // 1 second delay
    261             DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    262                 payNow = true
    263             }
    264 #else
    265             payNow = true
    266 #endif
    267         }
    268     }
    269 
    270     var body: some View {
    271         let fiveMinutes = 5 * 60
    272         let disabled = wasTapped || isFinished != false
    273         let button = Button(action: buttonAction) {
    274             if let formatted {
    275                 let amountString = formatted.0
    276                 let amountA11y = formatted.1
    277                 Text("Pay \(amountString) now")
    278             } else {
    279                 Text("Spend discounts now")
    280             }
    281         }.id("payNow")
    282 //            .accessibilityLabel(Text("Pay \(amountA11y) now", comment: "a11y"))
    283             .buttonStyle(TalerButtonStyle(type: .prominent, disabled: disabled))
    284             .disabled(disabled)
    285             .onChange(of: payNow) { newValue in
    286                 if !newValue { wasTapped = false }  // this attempt finished (success or failure) - allow retry
    287             }
    288 //            .padding(.horizontal)
    289             .task {
    290                 timeToPay = terms.timeToPay(true)
    291                 if let timeToPay {
    292                     if timeToPay >= fiveMinutes {
    293                         let nextCheck = timeToPay - fiveMinutes + 1
    294                         DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(nextCheck)) {
    295                             self.timeToPay = terms.timeToPay(true)
    296                         }
    297                     } else if timeToPay < 2 {
    298                         isFinished = true
    299                     }
    300                 }
    301             }
    302 
    303         if let timeToPay {
    304             if timeToPay < fiveMinutes {
    305                 let timeView = TimeView(String(localized: "Time to pay:"),
    306                                 seconds: timeToPay,
    307                              isFinished: $isFinished)
    308                     .id("timeView")
    309 #if GNU_TALER
    310                 let view = VStack {
    311                     timeView
    312                         .padding(.top)
    313                     button
    314                 }
    315                 if #available(iOS 26.0, *) {
    316                     view
    317                         .glassEffect(in: .rect(cornerRadius: 16.0))
    318                 } else {
    319                     view
    320                 }
    321 #else
    322                 VStack {
    323                     button
    324                     timeView
    325                 }
    326 #endif
    327             } else {
    328                 let _ = symLog?.log("timeToPay \(timeToPay) seconds not shown")
    329                 button
    330             }
    331         } else {
    332             let _ = symLog?.log("no timeToPay")
    333             button
    334         }
    335     }
    336 }
    337 // MARK: -
    338 #if false
    339 struct PaymentURIView_Previews: PreviewProvider {
    340     static var previews: some View {
    341         let merchant = Merchant(name: "Merchant")
    342         let extra = Extra(articleName: "articleName")
    343         let product = Product(description: "description")
    344         let terms = MerchantContractTerms(hWire: "hWire",
    345                                      wireMethod: "wireMethod",
    346                                         summary: "summary",
    347                                     summaryI18n: nil,
    348                                           nonce: "nonce",
    349                                          amount: Amount(currency: LONGCURRENCY, cent: 220),
    350                                     payDeadline: Timestamp.tomorrow(),
    351                                          maxFee: Amount(currency: LONGCURRENCY, cent: 20),
    352                                        merchant: merchant,
    353                                     merchantPub: "merchantPub",
    354                                    deliveryDate: nil,
    355                                deliveryLocation: nil,
    356                                       exchanges: [],
    357                                        products: [product],
    358                                  refundDeadline: Timestamp.tomorrow(),
    359                            wireTransferDeadline: Timestamp.tomorrow(),
    360                                       timestamp: Timestamp.now(),
    361                                         orderID: "orderID",
    362                                 merchantBaseURL: "merchantBaseURL",
    363                                  fulfillmentURL: "fulfillmentURL",
    364                                publicReorderURL: "publicReorderURL",
    365                              fulfillmentMessage: nil,
    366                          fulfillmentMessageI18n: nil,
    367                                      minimumAge: nil
    368 //                                        extra: extra,
    369 //                                     auditors: []
    370                                   )
    371         let details = PreparePayResult(status: PreparePayResultType.paymentPossible,
    372                                 transactionId: "txn:payment:012345",
    373                                 contractTerms: terms,
    374                             contractTermsHash: "termsHash",
    375                                     amountRaw: Amount(currency: LONGCURRENCY, cent: 220),
    376                               amountEffective: Amount(currency: LONGCURRENCY, cent: 240),
    377                                balanceDetails: nil,
    378                                          paid: nil
    379 //                               ,   talerUri: "talerURI"
    380         )
    381         let url = URL(string: "taler://pay/some_amount")!
    382         
    383 //        @State private var amount: Amount? = nil        // templateParam
    384 //        @State private var summary: String? = nil       // templateParam
    385 
    386         PaymentView(stack: CallStack("Preview"), url: url,
    387                  template: false, amountToTransfer: nil, summary: nil,
    388          amountIsEditable: false, summaryIsEditable: false,
    389          preparePayResult: details)
    390     }
    391 }
    392 #endif