summaryrefslogtreecommitdiff
path: root/TalerWallet1/Views/Banking/ManualWithdraw.swift
blob: ad95943c910074856c5fa5048707f3bedc9f9394 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/*
 * This file is part of GNU Taler, ©2022-24 Taler Systems S.A.
 * See LICENSE.md
 */
/**
 * @author Marc Stibane
 */
import SwiftUI
import taler_swift
import SymLog

// Will be called by either the user tapping "Withdraw Coins" in the exchanges list
// or from WithdrawExchangeV after a withdraw-exchange QR was scanned
struct ManualWithdraw: View {
    private let symLog = SymLogV(0)
    let stack: CallStack
    let isSheet: Bool
//    let exchangeBaseUrl: String
    let scopeInfo: ScopeInfo?
    @Binding var exchange: Exchange?
    @Binding var amountToTransfer: Amount

    @EnvironmentObject private var controller: Controller
    @EnvironmentObject private var model: WalletModel
    @AppStorage("minimalistic") var minimalistic: Bool = false

    @State private var withdrawalAmountDetails: WithdrawalAmountDetails? = nil
//    @State var ageMenuList: [Int] = []
//    @State var selectedAge = 0

    var body: some View {
#if PRINT_CHANGES
        let _ = Self._printChanges()
        let _ = symLog.vlog()       // just to get the # to compare it with .onAppear & onDisappear
#endif
        let baseURL = exchange?.exchangeBaseUrl
                   ?? scopeInfo?.url
                   ?? String(localized: "Unknown Payment Service")

      Group {
        if let exchange {
            let currency = exchange.scopeInfo.currency
            let currencyInfo = controller.info(for: currency, controller.currencyTicker)
            let currencySymbol = currencyInfo.specs.altUnitNames?[0] ?? currency
            let navTitle = String(localized: "NavTitle_Withdraw (currency)",
                               defaultValue: "Withdraw \(currencySymbol)",
                                    comment: "NavTitle: Withdraw 'currencySymbol'")
            let navA11y = String(localized: "NavTitle_Withdraw (currency) A11y",
                                 defaultValue: "Withdraw \(currency)",
                                 comment: "NavTitle: Withdraw 'currency'")
//          let agePicker = AgePicker(ageMenuList: $ageMenuList, selectedAge: $selectedAge)

            let someCoins = SomeCoins(details: withdrawalAmountDetails)
//          let restrictAge: Int? = (selectedAge == 0) ? nil
//                                                     : selectedAge
//  let _ = print(selectedAge, restrictAge)
            let destination = LazyView {
                ManualWithdrawDone(stack: stack.push(),
                                exchange: exchange,
                        amountToTransfer: amountToTransfer)
//                           restrictAge: restrictAge)
            }
            let disabled = amountToTransfer.isZero || someCoins.invalid || someCoins.tooMany
            let tosAccepted = exchange.tosStatus == .accepted
            ScrollView { VStack(alignment: .trailing) {
                Text("via \(exchange.exchangeBaseUrl.trimURL())")
                    .multilineTextAlignment(.center)
                    .talerFont(.body)
                if tosAccepted {
                    CurrencyInputView(amount: $amountToTransfer,
                                   available: nil,
                                       title: minimalistic ? String(localized: "Amount:")
                                                           : String(localized: "Amount to withdraw:"),
                              shortcutAction: nil)
                        .padding(.top)
                    QuiteSomeCoins(someCoins: someCoins,
                               shouldShowFee: true,           // TODO: set to false if we never charge withdrawal fees
                                    currency: currency,
                                currencyInfo: currencyInfo,
                             amountEffective: withdrawalAmountDetails?.amountEffective)
//                  agePicker
                    NavigationLink(destination: destination) {
                        Text("Confirm Withdrawal")      // VIEW_WITHDRAW_ACCEPT
                    }
                    .buttonStyle(TalerButtonStyle(type: .prominent, disabled: disabled))
                    .disabled(disabled)
                    .padding(.top)
                } else {
                    ToSButtonView(stack: stack.push(),
                        exchangeBaseUrl: exchange.exchangeBaseUrl,
                                 viewID: VIEW_WITHDRAW_TOS,         // TODO: YIKES might be withdraw-exchange
                                    p2p: false)
                    .padding(.top)
                }
            }.padding(.horizontal) } // ScrollVStack
            .frame(maxWidth: .infinity, alignment: .leading)
//            .scrollBounceBehavior(.basedOnSize)  needs iOS 16.4
            .background(WalletColors().backgroundColor.edgesIgnoringSafeArea(.all))
            .navigationTitle(navTitle)
            .onAppear {
                if isSheet {
                    DebugViewC.shared.setSheetID(SHEET_WITHDRAW_EXCHANGE)
                } else {
                    DebugViewC.shared.setViewID(VIEW_WITHDRAWAL, stack: stack.push())
                }
                symLog.log("❗️ \(navTitle) onAppear")
            }
            .onDisappear {
                symLog.log("❗️ \(navTitle) onDisappear")
            }
        } else {
            let contacting = String(localized: "Contacting...")
            LoadingView(scopeInfo: scopeInfo, message: contacting)
        }
      }
        .task(id: amountToTransfer.value) { // re-run this whenever amountToTransfer changes
            if let exchangeBaseUrl = scopeInfo?.url {
                symLog.log("getExchangeByUrl(\(exchangeBaseUrl))")
                if exchange == nil || exchange?.tosStatus != .accepted {
                    exchange = try? await model.getExchangeByUrl(url: exchangeBaseUrl)
                }
                if !amountToTransfer.isZero {
                    do {
                        let details = try await model.getWithdrawalDetailsForAmountM(exchangeBaseUrl,
                                                                              amount: amountToTransfer,
                                                                      cancellationId: "cancel",
                                                                         viewHandles: true)
                        withdrawalAmountDetails = details
//                      agePicker.setAges(ages: withdrawalAmountDetails?.ageRestrictionOptions)
                    } catch WalletBackendError.walletCoreError(let walletBackendResponseError) {
                        symLog.log(walletBackendResponseError?.hint)
                        // TODO: ignore WALLET_CORE_REQUEST_CANCELLED but handle all others
                        // Passing non-nil to clientCancellationId will throw WALLET_CORE_REQUEST_CANCELLED
                        // when calling getWithdrawalDetailsForAmount again before the last call returned.
                        // Since amountToTransfer changed and we don't need the old fee anymore, we just
                        // ignore it and do nothing.
                    } catch {
                        symLog.log(error.localizedDescription)
                        withdrawalAmountDetails = nil
                    }
                }
            }
        }
    }
}
// MARK: -
#if DEBUG
//struct ManualWithdraw_Previews: PreviewProvider {
//    struct StateContainer : View {
//        @State private var amountToPreview = Amount(currency: LONGCURRENCY, cent: 510)
//        @State private var exchange: Exchange? = Exchange(exchangeBaseUrl: DEMOEXCHANGE,
//                                                                scopeInfo: ScopeInfo(type: .exchange, currency: LONGCURRENCY),
//                                                                paytoUris: [],
//                                                                tosStatus: .accepted,
//                                                      exchangeEntryStatus: .ephemeral,
//                                                     exchangeUpdateStatus: .ready,
//                                                    ageRestrictionOptions: [])
//
//        var body: some View {
//            ManualWithdraw(stack: CallStack("Preview"), isSheet: false,
//                       scopeInfo: <#ScopeInfo?#>,
//                 exchangeBaseUrl: DEMOEXCHANGE,
//                        exchange: $exchange,
//                amountToTransfer: $amountToPreview)
//        }
//    }
//
//    static var previews: some View {
//        StateContainer()
//    }
//}
#endif