summaryrefslogtreecommitdiff
path: root/wallee-c2ec/app/src/main/java/ch/bfh/habej2/wallee_c2ec/withdrawal/WithdrawalActivity.kt
blob: 94238e70785b5cccc7ae7445bba3aa493134f6f5 (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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package ch.bfh.habej2.wallee_c2ec.withdrawal

import android.app.Activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import ch.bfh.habej2.wallee_c2ec.client.taler.config.TalerBankIntegrationConfig
import ch.bfh.habej2.wallee_c2ec.client.wallee.WalleeResponseHandler
import com.wallee.android.till.sdk.ApiClient
import com.wallee.android.till.sdk.data.LineItem
import com.wallee.android.till.sdk.data.Transaction
import com.wallee.android.till.sdk.data.TransactionProcessingBehavior
import java.math.BigDecimal
import java.util.Currency
import java.util.Optional

class WithdrawalActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {

            val model = WithdrawalViewModel()
            val navController = rememberNavController()

            NavHost(navController = navController, startDestination = "chooseExchangeScreen") {
                composable("chooseExchangeScreen") {
                    ExchangeSelectionScreen(model) {
                        navController.navigate("registerWithdrawalScreen")
                    }
                }
                composable("registerWithdrawalScreen") {
                    RegisterWithdrawalScreen(model) {
                        navController.navigate("paymentScreen")
                    }
                }
                composable("paymentScreen") { PaymentScreen(model) }
            }
        }
    }
}

@Composable
fun RegisterWithdrawalScreen(
    model: WithdrawalViewModel,
    navigateToWhenRegistered: () -> Unit
) {

    val uiState by model.uiState.collectAsState()
    val activity = (LocalContext.current as Activity)

    model.startAuthorizationWhenReadyOrAbort(navigateToWhenRegistered) {
        activity.finish()
    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(text = "QR-Code content: ${formatTalerUri(uiState.encodedWopid)}")

        QRCode(formatTalerUri(uiState.encodedWopid))

        Button(onClick = {
            model.withdrawalOperationFailed()
            activity.finish()
        }) {
            Text(text = "abort")
        }
    }
}

@Composable
fun PaymentScreen(model: WithdrawalViewModel) {

    val activity = LocalContext.current as Activity

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(text = "present card, trigger payment")

        TextField(
            value = "",
            onValueChange = {
                val optAmount = parseAmount(it)
                if (optAmount.isPresent) {
                    model.updateAmount(optAmount.get())
                }
            },
            label = { Text(text = "Enter amount") },
            placeholder = { Text(text = "amount") }
        )

        AuthorizePaymentButton(model = model)

        Button(onClick = {
            model.withdrawalOperationFailed()
            activity.finish()
        }) {
            Text(text = "abort")
        }
    }
}

@Composable
fun AuthorizePaymentButton(model: WithdrawalViewModel) {

    val uiState by model.uiState.collectAsState()
    val activity = LocalContext.current as Activity
    val client = ApiClient(WalleeResponseHandler())

    client.bind(activity)

    Button(enabled = false, onClick = {
        val withdrawalAmount = LineItem
            .ListBuilder(
                uiState.encodedWopid,
                BigDecimal("${uiState.amount.value}.${uiState.amount.frac}")
            )
            .build()

        val transaction = Transaction.Builder(withdrawalAmount)
            .setCurrency(Currency.getInstance(uiState.currency))
            .setInvoiceReference(uiState.encodedWopid)
            .setMerchantReference(uiState.encodedWopid)
            .setTransactionProcessingBehavior(TransactionProcessingBehavior.COMPLETE_IMMEDIATELY)
            .build()

        try {
            client.authorizeTransaction(transaction)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }) {
        Text(text = "")
    }
}

@Composable
fun ExchangeSelectionScreen(
    model: WithdrawalViewModel,
    onNavigateToWithdrawal: () -> Unit
) {

    val activity = LocalContext.current as Activity

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(text = "Choose the exchange to withdraw from")

        // TODO let user select exchanges from config here
        //  config must contain display name, credentials (generated by cli)
        //  and the base url of the c2ec bank-integration api

        val ctx = LocalContext.current
        Button(onClick = {
            // TODO trigger model.exchangeUpdated(...)
            model.exchangeUpdated(TalerBankIntegrationConfig("","","",""))
            onNavigateToWithdrawal()
        }) {
            Text(text = "withdraw")
        }

        Button(onClick = { activity.finish() }) {
            Text(text = "abort")
        }
    }
}

@Composable
fun SummaryScreen(model: WithdrawalViewModel) {

    val activity = LocalContext.current as Activity

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(text = "Transaction Executed")

        Button(onClick = { activity.finish() }) {
            Text(text = "finish")
        }
    }
}

/**
 * Format expected X[.X], X an integer
 */
private fun parseAmount(inp: String): Optional<Amount> {

    val points = inp.count { it == '.' }
    if (points > 1) {
        return Optional.empty()
    }

    if (points == 1) {
        val valueStr = inp.split(".")[0]
        val fracStr = inp.split(".")[1]
        return try {
            val value = valueStr.toInt()
            val frac = fracStr.toInt()
            Optional.of(Amount(value, frac))
        } catch (ex: NumberFormatException) {
            Optional.empty()
        }
    }

    return try {
        val value = inp.toInt()
        Optional.of(Amount(value, 0))
    } catch (ex: NumberFormatException) {
        Optional.empty()
    }
}

private fun formatTalerUri(encodedWopid: String) = "taler://withdraw/$encodedWopid"