taler-ios

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

ChoicesView.swift (11481B)


      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 struct SelectedBackground: View, Sendable {
     13     let useColor: Bool?
     14 
     15     var body: some View {
     16         let rect = RoundedRectangle(cornerRadius: Bool.iOS26 ? 26 : 10)
     17         let line = useColor == nil ? 0.5 : 2.4
     18         let color = useColor == true ? WalletColors().primaryAccent
     19                   : useColor == false ? .secondary : WalletColors().gray4
     20         if #available(iOS 17.0, *) {
     21             rect
     22                 .fill(.background)
     23                 .strokeBorder(color, lineWidth: line)
     24         } else {
     25             rect
     26                 .strokeBorder(color, lineWidth: line)
     27                 .background(.background)
     28                 .clipped()
     29                 .clipShape(rect)
     30         }
     31     }
     32 }
     33 // MARK: -
     34 struct TokenView: View, Sendable {
     35     let count: Int?
     36     let slug: String
     37     let tokenFamilies: [String: ContractTokenFamily]   // token_family_slug: String
     38 
     39     var body: some View {
     40         if let family = tokenFamilies[slug] {
     41             let accent = WalletColors().primaryAccent
     42             let onPrimary = WalletColors().onPrimary
     43             let isPass = family.details.clazz == "subscription" // else "discount"
     44             HStack {
     45                 TokenLabel(title: family.name, isActive: true, isPass: isPass)
     46                 Spacer()
     47                 if let count {
     48                     Text("x\(count)")
     49                         .foregroundColor(onPrimary)
     50                         .padding(.horizontal, 8)
     51                         .padding(.vertical, 4)
     52                         .background(Capsule().fill(accent.opacity(0.3)))
     53                 }
     54             }
     55             .talerFont(.headline)
     56             .padding(4)
     57             .background(RoundedRectangle(cornerRadius: 8).fill(accent.opacity(0.1)))
     58         }
     59 
     60     }
     61 }
     62 struct OutputTokenView: View, Sendable {
     63     let outputs: [ContractOutputAny]
     64     let tokenFamilies: [String: ContractTokenFamily]   // token_family_slug: String
     65 
     66     var body: some View {
     67         ForEach(outputs, id: \.self) { output in
     68             switch output {
     69                 case .token(let token):
     70                     if let slug = token.tokenFamilySlug {
     71                         let count = token.count ?? 1
     72                         TokenView(count: count > 1 ? count : nil,
     73                                    slug: slug,
     74                           tokenFamilies: tokenFamilies)
     75                     }
     76                 case .taxReceipt(let taxReceipt):
     77                     let amount = taxReceipt.amount
     78                     // TODO: taxReceipt
     79                 case .unknown(let string):
     80                     let _ = print("❗️❗️ChoicesView: Unknown output type: \(string)")
     81             }
     82         }
     83     }
     84 }
     85 struct InputTokenView: View, Sendable {
     86     let inputs: [ContractInput]
     87     let tokenFamilies: [String: ContractTokenFamily]   // token_family_slug: String
     88 
     89     var body: some View {
     90         ForEach(inputs, id: \.self) { input in
     91             if let slug = input.tokenFamilySlug {
     92                 let count = input.count ?? 1
     93                 TokenView(count: count, slug: slug, tokenFamilies: tokenFamilies)
     94             }
     95         }
     96     }
     97 }
     98 // MARK: -
     99 struct ChoicesView: View, Sendable {
    100     private let symLog = SymLogV(0)
    101     let stack: CallStack
    102     let choiceTriples: [ChoiceTriple]
    103     let terms: MerchantContractTerms
    104     let showHeader: Bool
    105     let automaticIndex: Int?
    106     @Binding var selectedChoice: Int?
    107 #if !GNU_TALER
    108     let formatted: (String, String)?
    109     @Binding var payNow: Bool
    110     @Binding var isFinished: Bool?
    111     @Namespace private var namespace
    112 #endif
    113     @Environment(\.colorScheme) private var colorScheme
    114     @Environment(\.colorSchemeContrast) private var colorSchemeContrast
    115 
    116     @ViewBuilder
    117     func headerV(_ contractChoice: ContractChoice) -> some View {
    118         if showHeader {     // V1
    119             if let description = contractChoice.locDescription {
    120                 Text(description)
    121                     .talerFont(.body)
    122         }   }
    123     }
    124     @ViewBuilder
    125     func amountV(_ amount: Amount, scope: ScopeInfo?, possible: Bool) -> some View {
    126         if !amount.isZero {
    127             HStack {
    128                 Spacer()
    129                 AmountV(stack: stack.push(),
    130                         scope: scope,
    131                        amount: amount)
    132                 .foregroundColor(possible ? .primary : .secondary)
    133             }
    134         }
    135     }
    136     var body: some View {
    137         Section {
    138             ForEach(choiceTriples, id: \.2) { triple in
    139                 let selectionDetail: ChoiceSelectionDetail = triple.0
    140                 let contractChoice: ContractChoice = triple.1
    141                 let index: Int = triple.2
    142                 let isPaymentPossible = selectionDetail.status == .paymentPossible
    143                 let payAutomatic = automaticIndex == index
    144                 let scopeInfo = selectionDetail.scopeInfo
    145                 let amount = selectionDetail.amountRaw
    146                 /// Disable but don’t hide it if insufficient - that serves as advertisement what you could buy if you had more money / tokens.
    147                 /// If it only contains tokens, and insufficient, then hide it. Most probably there is a money payment option to acquire those tokens, which is advertisement enough.
    148                 /// Tokens only, paymentPossible. If automaticIndex, then also hide it (and auto-pay it). Otherwise show it, so the user can select it.
    149 //                if (!amount.isZero || isPaymentPossible) && !payAutomatic {
    150                     VStack(alignment: .leading) {
    151                         let header = headerV(contractChoice)
    152                         let amount = amountV(contractChoice.amount, scope: scopeInfo, possible: isPaymentPossible)
    153                         if #available(iOS 16.0, *) {
    154                             ViewThatFits(in: .horizontal) {
    155                                 HStack(alignment: .firstTextBaseline) {
    156                                     header
    157                                     amount
    158                                 }
    159                                 Group {
    160                                     header
    161                                     amount
    162                                 }
    163                             }
    164                         } else { // Fallback on earlier versions
    165                             header
    166                             amount
    167                         }
    168 #if GNU_TALER
    169                         let isSelected = false
    170 #else
    171                         let isSelected = selectedChoice == index
    172 #endif
    173                         if let tokenFamilies = terms.tokenFamilies {
    174                             // Spend Input tokens
    175                             let inputs = contractChoice.inputs
    176                             if !inputs.isEmpty {
    177                                 Text("Spend now:")
    178                                     .talerFont(.body)
    179                                     .padding(.bottom, -4)
    180                                     .padding(.top, 0.1)
    181                                 InputTokenView(inputs: inputs, tokenFamilies: tokenFamilies)
    182                             }
    183                         }
    184 #if !GNU_TALER
    185                         if isSelected {
    186                             PaymentButton(symLog: symLog,
    187                                            stack: stack.push(),
    188                                            terms: terms,
    189                                        formatted: formatted,
    190                                       isFinished: $isFinished,
    191                                           payNow: $payNow)
    192                             .matchedGeometryEffect(id: "PaymentButton", in: namespace)
    193                         }
    194 #endif
    195                         if let tokenFamilies = terms.tokenFamilies {
    196                             // Receive output tokens
    197                             let outputs = contractChoice.outputs
    198                             if !outputs.isEmpty {
    199                                 Text("Get with your purchase:")
    200                                     .talerFont(.body)
    201                                     .padding(.bottom, -4)
    202                                     .padding(.top, isSelected ? 6 : 0.1)
    203                                 OutputTokenView(outputs: outputs, tokenFamilies: tokenFamilies)
    204                             }
    205                         }
    206                     }
    207                             .contentShape(.rect)
    208                             .onTapGesture {
    209                                 if isPaymentPossible {
    210                                   withAnimation {
    211                                     selectedChoice = index
    212                                   }
    213                                 }
    214                             }
    215 
    216                     .listRowBackground(
    217                         SelectedBackground(useColor: index == selectedChoice ? isPaymentPossible : nil)
    218                     )
    219 //                }
    220             }.listRowSeparator(.hidden)
    221         } header: {
    222             Text("Payment Options")
    223                 .talerFont(.title3)
    224                 .foregroundColor(WalletColors().secondary2(colorScheme, colorSchemeContrast))
    225         }
    226     }
    227 }
    228 // MARK: -
    229 struct ProductsView: View, Sendable {
    230     let stack: CallStack
    231     let scope: ScopeInfo?
    232     let products: [ProductSold]
    233 
    234     @Environment(\.colorScheme) private var colorScheme
    235     @Environment(\.colorSchemeContrast) private var colorSchemeContrast
    236 
    237     var body: some View {
    238         if !products.isEmpty {
    239             Section {
    240                 ForEachWithIndex(array: products) { index, product in
    241                     HStack {
    242                         VStack(alignment: .leading) {
    243                             HStack {
    244                                 if let imageBase64 = product.image {
    245                                     if let image = Image(imageBase64: imageBase64) {
    246                                         image
    247                                             .resizable()
    248                                             .aspectRatio(contentMode: .fit)
    249                                             .frame(maxHeight: 50)
    250                                             .padding(.trailing, 8)
    251                                     }
    252                                 }
    253                                 if let name = product.productName {
    254                                     Text(name)
    255                                         .bold()
    256                                         .talerFont(.body)
    257                                 }
    258                             }
    259                             Text(product.locDescription)
    260                                 .talerFont(.subheadline)
    261 
    262                             HStack {
    263                                 if let quantity = product.unitQuantity {
    264                                     Text(quantity)
    265                                 }
    266                                 if let unit = product.unit {
    267                                     // TODO: MerchantUnit
    268                                     Text(unit)
    269                                 }
    270                             }.talerFont(.subheadline)
    271                         }
    272                         Spacer()
    273                         if let price = product.prices?.first ?? product.price {
    274                             AmountV(scope, price, isNegative: nil)
    275                         }
    276                     }.id(index)
    277                     .listRowSeparator(.hidden)
    278                 }
    279             }
    280         }
    281     }
    282 }