Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Samer/create fake data sources #9296

Draft
wants to merge 2 commits into
base: samer/use-data-source-in-cs-view-model
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,16 @@ import com.stripe.android.core.strings.ResolvableString
import com.stripe.android.core.strings.orEmpty
import com.stripe.android.core.strings.resolvableString
import com.stripe.android.core.utils.requireApplication
import com.stripe.android.customersheet.CustomerAdapter.PaymentOption.Companion.toPaymentOption
import com.stripe.android.customersheet.analytics.CustomerSheetEventReporter
import com.stripe.android.customersheet.data.CustomerSheetDataResult
import com.stripe.android.customersheet.data.CustomerSheetIntentDataSource
import com.stripe.android.customersheet.data.CustomerSheetPaymentMethodDataSource
import com.stripe.android.customersheet.data.CustomerSheetSavedSelectionDataSource
import com.stripe.android.customersheet.data.failureOrNull
import com.stripe.android.customersheet.data.fold
import com.stripe.android.customersheet.data.mapCatching
import com.stripe.android.customersheet.data.onFailure
import com.stripe.android.customersheet.data.onSuccess
import com.stripe.android.customersheet.injection.CustomerSheetViewModelScope
import com.stripe.android.customersheet.injection.DaggerCustomerSheetViewModelComponent
import com.stripe.android.customersheet.util.CustomerSheetHacks
Expand Down Expand Up @@ -48,6 +56,8 @@ import com.stripe.android.paymentsheet.R
import com.stripe.android.paymentsheet.forms.FormArgumentsFactory
import com.stripe.android.paymentsheet.forms.FormFieldValues
import com.stripe.android.paymentsheet.model.PaymentSelection
import com.stripe.android.paymentsheet.model.SavedSelection
import com.stripe.android.paymentsheet.model.toSavedSelection
import com.stripe.android.paymentsheet.parseAppearance
import com.stripe.android.paymentsheet.paymentdatacollection.ach.USBankAccountFormArguments
import com.stripe.android.paymentsheet.ui.EditPaymentMethodViewInteractor
Expand Down Expand Up @@ -81,7 +91,9 @@ internal class CustomerSheetViewModel(
application: Application, // TODO (jameswoo) remove application
private var originalPaymentSelection: PaymentSelection?,
private val paymentConfigurationProvider: Provider<PaymentConfiguration>,
private val customerAdapterProvider: Deferred<CustomerAdapter>,
private val paymentMethodDataSourceProvider: Deferred<CustomerSheetPaymentMethodDataSource>,
private val intentDataSourceProvider: Deferred<CustomerSheetIntentDataSource>,
private val savedSelectionDataSourceProvider: Deferred<CustomerSheetSavedSelectionDataSource>,
private val configuration: CustomerSheet.Configuration,
private val logger: Logger,
private val stripeRepository: StripeRepository,
Expand Down Expand Up @@ -114,7 +126,9 @@ internal class CustomerSheetViewModel(
application = application,
originalPaymentSelection = originalPaymentSelection,
paymentConfigurationProvider = paymentConfigurationProvider,
customerAdapterProvider = CustomerSheetHacks.adapter,
paymentMethodDataSourceProvider = CustomerSheetHacks.paymentMethodDataSource,
intentDataSourceProvider = CustomerSheetHacks.intentDataSource,
savedSelectionDataSourceProvider = CustomerSheetHacks.savedSelectionDataSource,
configuration = configuration,
logger = logger,
stripeRepository = stripeRepository,
Expand Down Expand Up @@ -493,8 +507,8 @@ internal class CustomerSheetViewModel(
}
}

private suspend fun removePaymentMethod(paymentMethod: PaymentMethod): CustomerAdapter.Result<PaymentMethod> {
return awaitCustomerAdapter().detachPaymentMethod(
private suspend fun removePaymentMethod(paymentMethod: PaymentMethod): CustomerSheetDataResult<PaymentMethod> {
return awaitPaymentMethodDataSource().detachPaymentMethod(
paymentMethodId = paymentMethod.id!!,
).onSuccess {
eventReporter.onRemovePaymentMethodSucceeded()
Expand All @@ -510,8 +524,8 @@ internal class CustomerSheetViewModel(
private suspend fun modifyCardPaymentMethod(
paymentMethod: PaymentMethod,
brand: CardBrand
): CustomerAdapter.Result<PaymentMethod> {
return awaitCustomerAdapter().updatePaymentMethod(
): CustomerSheetDataResult<PaymentMethod> {
return awaitPaymentMethodDataSource().updatePaymentMethod(
paymentMethodId = paymentMethod.id!!,
params = PaymentMethodUpdateParams.createCard(
networks = PaymentMethodUpdateParams.Card.Networks(
Expand Down Expand Up @@ -584,8 +598,8 @@ internal class CustomerSheetViewModel(
},
updateExecutor = { method, brand ->
when (val result = modifyCardPaymentMethod(method, brand)) {
is CustomerAdapter.Result.Success -> Result.success(result.value)
is CustomerAdapter.Result.Failure -> Result.failure(result.cause)
is CustomerSheetDataResult.Success -> Result.success(result.value)
is CustomerSheetDataResult.Failure -> Result.failure(result.cause)
}
},
canRemove = customerState.canRemove,
Expand Down Expand Up @@ -935,16 +949,32 @@ internal class CustomerSheetViewModel(

private fun attachPaymentMethodToCustomer(paymentMethod: PaymentMethod) {
viewModelScope.launch(workContext) {
if (awaitCustomerAdapter().canCreateSetupIntents) {
attachWithSetupIntent(paymentMethod = paymentMethod)
} else {
attachPaymentMethod(id = paymentMethod.id!!)
awaitIntentDataSource().canCreateSetupIntents().onSuccess { canCreateSetupIntents ->
if (canCreateSetupIntents) {
attachWithSetupIntent(paymentMethod = paymentMethod)
} else {
attachPaymentMethod(id = paymentMethod.id!!)
}
}.onFailure { cause, displayMessage ->
logger.error(
msg = "Could not determine if setup intents could be created: $paymentMethod",
t = cause,
)

updateViewState<CustomerSheetViewState.AddPaymentMethod> {
it.copy(
errorMessage = displayMessage?.resolvableString ?: cause.stripeErrorMessage(),
enabled = true,
primaryButtonEnabled = it.formFieldValues != null && !it.isProcessing,
isProcessing = false,
)
}
}
}
}

private suspend fun attachWithSetupIntent(paymentMethod: PaymentMethod) {
awaitCustomerAdapter().setupIntentClientSecretForCustomerAttach()
awaitIntentDataSource().retrieveSetupIntentClientSecret()
.mapCatching { clientSecret ->
val intent = stripeRepository.retrieveSetupIntent(
clientSecret = clientSecret,
Expand Down Expand Up @@ -1035,7 +1065,7 @@ internal class CustomerSheetViewModel(
}

private suspend fun attachPaymentMethod(id: String) {
awaitCustomerAdapter().attachPaymentMethod(id)
awaitPaymentMethodDataSource().attachPaymentMethod(id)
.onSuccess { attachedPaymentMethod ->
eventReporter.onAttachPaymentMethodSucceeded(
style = CustomerSheetEventReporter.AddPaymentMethodStyle.CreateAttach
Expand All @@ -1062,7 +1092,7 @@ internal class CustomerSheetViewModel(
private suspend fun refreshAndUpdatePaymentMethods(
newPaymentMethod: PaymentMethod
) {
awaitCustomerAdapter().retrievePaymentMethods().onSuccess { paymentMethods ->
awaitPaymentMethodDataSource().retrievePaymentMethods().onSuccess { paymentMethods ->
errorReporter.report(
ErrorReporter.SuccessEvent.CUSTOMER_SHEET_PAYMENT_METHODS_REFRESH_SUCCESS,
)
Expand Down Expand Up @@ -1092,8 +1122,8 @@ internal class CustomerSheetViewModel(

private fun selectSavedPaymentMethod(savedPaymentSelection: PaymentSelection.Saved?) {
viewModelScope.launch(workContext) {
awaitCustomerAdapter().setSelectedPaymentOption(
savedPaymentSelection?.toPaymentOption()
awaitSavedSelectionDataSource().setSavedSelection(
savedPaymentSelection?.toSavedSelection()
).onSuccess {
confirmPaymentSelection(
paymentSelection = savedPaymentSelection,
Expand All @@ -1112,7 +1142,7 @@ internal class CustomerSheetViewModel(

private fun selectGooglePay() {
viewModelScope.launch(workContext) {
awaitCustomerAdapter().setSelectedPaymentOption(CustomerAdapter.PaymentOption.GooglePay)
awaitSavedSelectionDataSource().setSavedSelection(SavedSelection.GooglePay)
.onSuccess {
confirmPaymentSelection(
paymentSelection = PaymentSelection.GooglePay,
Expand Down Expand Up @@ -1189,8 +1219,16 @@ internal class CustomerSheetViewModel(
}
}

private suspend fun awaitCustomerAdapter(): CustomerAdapter {
return customerAdapterProvider.await()
private suspend fun awaitPaymentMethodDataSource(): CustomerSheetPaymentMethodDataSource {
return paymentMethodDataSourceProvider.await()
}

private suspend fun awaitIntentDataSource(): CustomerSheetIntentDataSource {
return intentDataSourceProvider.await()
}

private suspend fun awaitSavedSelectionDataSource(): CustomerSheetSavedSelectionDataSource {
return savedSelectionDataSourceProvider.await()
}

private val CustomerSheetViewState.eventReporterScreen: CustomerSheetEventReporter.Screen?
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,54 @@
package com.stripe.android.customersheet.data

import com.stripe.android.customersheet.CustomerAdapter
import com.stripe.android.customersheet.CustomerAdapter.PaymentOption.Companion.toPaymentOption
import com.stripe.android.customersheet.ExperimentalCustomerSheetApi
import com.stripe.android.customersheet.map
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodUpdateParams
import com.stripe.android.paymentsheet.model.SavedSelection
import javax.inject.Inject

@OptIn(ExperimentalCustomerSheetApi::class)
internal class CustomerAdapterDataSource @Inject constructor(
private val customerAdapter: CustomerAdapter,
) : CustomerSheetSavedSelectionDataSource, CustomerSheetPaymentMethodDataSource {
) : CustomerSheetSavedSelectionDataSource,
CustomerSheetPaymentMethodDataSource,
CustomerSheetIntentDataSource {
override suspend fun canCreateSetupIntents(): CustomerSheetDataResult<Boolean> {
return CustomerSheetDataResult.success(customerAdapter.canCreateSetupIntents)
}

override suspend fun retrievePaymentMethods(): CustomerSheetDataResult<List<PaymentMethod>> {
return customerAdapter.retrievePaymentMethods().toCustomerSheetDataResult()
}

override suspend fun updatePaymentMethod(
paymentMethodId: String,
params: PaymentMethodUpdateParams,
): CustomerSheetDataResult<PaymentMethod> {
return customerAdapter.updatePaymentMethod(paymentMethodId, params).toCustomerSheetDataResult()
}

override suspend fun attachPaymentMethod(paymentMethodId: String): CustomerSheetDataResult<PaymentMethod> {
return customerAdapter.attachPaymentMethod(paymentMethodId).toCustomerSheetDataResult()
}

override suspend fun detachPaymentMethod(paymentMethodId: String): CustomerSheetDataResult<PaymentMethod> {
return customerAdapter.detachPaymentMethod(paymentMethodId).toCustomerSheetDataResult()
}

override suspend fun retrieveSavedSelection(): CustomerSheetDataResult<SavedSelection?> {
return customerAdapter.retrieveSelectedPaymentOption().map { result ->
result?.toSavedSelection()
}.toCustomerSheetDataResult()
}

override suspend fun setSavedSelection(selection: SavedSelection?): CustomerSheetDataResult<Unit> {
return customerAdapter.setSelectedPaymentOption(selection?.toPaymentOption()).toCustomerSheetDataResult()
}

override suspend fun retrieveSetupIntentClientSecret(): CustomerSheetDataResult<String> {
return customerAdapter.setupIntentClientSecretForCustomerAttach().toCustomerSheetDataResult()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.stripe.android.customersheet.data

import com.stripe.android.core.exception.StripeException
import com.stripe.android.customersheet.CustomerAdapter
import com.stripe.android.customersheet.ExperimentalCustomerSheetApi

Expand All @@ -13,3 +14,76 @@ internal fun <T> CustomerAdapter.Result<T>.toCustomerSheetDataResult(): Customer
)
}
}

internal inline fun <R, T> CustomerSheetDataResult<T>.map(
transform: (value: T) -> R
): CustomerSheetDataResult<R> {
return when (this) {
is CustomerSheetDataResult.Success -> CustomerSheetDataResult.success(transform(this.value))
is CustomerSheetDataResult.Failure -> CustomerSheetDataResult.failure(
cause = this.cause,
displayMessage = this.displayMessage
)
}
}

internal inline fun <R, T> CustomerSheetDataResult<T>.mapCatching(
transform: (value: T) -> R
): CustomerSheetDataResult<R> {
return when (this) {
is CustomerSheetDataResult.Success -> runCatching { transform(this.value) }
is CustomerSheetDataResult.Failure -> CustomerSheetDataResult.failure(
cause = this.cause,
displayMessage = this.displayMessage
)
}
}

internal inline fun <R, T> CustomerSheetDataResult<T>.onSuccess(
action: (value: T) -> R
): CustomerSheetDataResult<T> {
if (this is CustomerSheetDataResult.Success) {
action(this.value)
}
return this
}

internal inline fun <R, T> CustomerSheetDataResult<T>.onFailure(
action: (cause: Throwable, displayMessage: String?) -> R
): CustomerSheetDataResult<T> {
failureOrNull()?.let {
val displayMessage = it.displayMessage
?: (it.cause as? StripeException)?.stripeError?.message
action(it.cause, displayMessage)
}
return this
}

internal inline fun <R, T> CustomerSheetDataResult<T>.fold(
onSuccess: (value: T) -> R,
onFailure: (cause: Throwable, displayMessage: String?) -> R
): R {
return when (this) {
is CustomerSheetDataResult.Failure -> {
onFailure(this.cause, this.displayMessage)
}
is CustomerSheetDataResult.Success -> {
onSuccess(this.value)
}
}
}

internal fun<T> CustomerSheetDataResult<T>.failureOrNull(): CustomerSheetDataResult.Failure<T>? =
when (this) {
is CustomerSheetDataResult.Failure -> this
else -> null
}

private inline fun <R, T> T.runCatching(block: T.() -> R): CustomerSheetDataResult<R> {
return kotlin.runCatching {
CustomerSheetDataResult.success(block())
}.fold(
onSuccess = { it },
onFailure = { CustomerSheetDataResult.failure(it, null) }
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.stripe.android.customersheet.data

internal interface CustomerSheetIntentDataSource {
suspend fun canCreateSetupIntents(): CustomerSheetDataResult<Boolean>

suspend fun retrieveSetupIntentClientSecret(): CustomerSheetDataResult<String>
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.stripe.android.customersheet.data

import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodUpdateParams

/**
* [CustomerSheetPaymentMethodDataSource] defines a set of operations for managing saved payment methods within a
Expand All @@ -13,4 +14,13 @@ internal interface CustomerSheetPaymentMethodDataSource {
* @return a result containing the list of payment methods if operation was successful
*/
suspend fun retrievePaymentMethods(): CustomerSheetDataResult<List<PaymentMethod>>

suspend fun updatePaymentMethod(
paymentMethodId: String,
params: PaymentMethodUpdateParams,
): CustomerSheetDataResult<PaymentMethod>

suspend fun attachPaymentMethod(paymentMethodId: String): CustomerSheetDataResult<PaymentMethod>

suspend fun detachPaymentMethod(paymentMethodId: String): CustomerSheetDataResult<PaymentMethod>
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ internal interface CustomerSheetSavedSelectionDataSource {
* @return a result containing the saved selection if operation was successful
*/
suspend fun retrieveSavedSelection(): CustomerSheetDataResult<SavedSelection?>

suspend fun setSavedSelection(selection: SavedSelection?): CustomerSheetDataResult<Unit>
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import androidx.lifecycle.LifecycleOwner
import com.stripe.android.customersheet.CustomerAdapter
import com.stripe.android.customersheet.ExperimentalCustomerSheetApi
import com.stripe.android.customersheet.data.CustomerAdapterDataSource
import com.stripe.android.customersheet.data.CustomerSheetIntentDataSource
import com.stripe.android.customersheet.data.CustomerSheetPaymentMethodDataSource
import com.stripe.android.customersheet.data.CustomerSheetSavedSelectionDataSource
import kotlinx.coroutines.CompletableDeferred
Expand Down Expand Up @@ -35,6 +36,9 @@ internal object CustomerSheetHacks {
val savedSelectionDataSource: Deferred<CustomerSheetSavedSelectionDataSource>
get() = _dataSource.asDeferred()

val intentDataSource: Deferred<CustomerSheetIntentDataSource>
get() = _dataSource.asDeferred()

fun initialize(
lifecycleOwner: LifecycleOwner,
adapter: CustomerAdapter,
Expand Down Expand Up @@ -63,9 +67,11 @@ internal object CustomerSheetHacks {

private class CombinedDataSource<T>(dataSource: T) :
CustomerSheetSavedSelectionDataSource by dataSource,
CustomerSheetPaymentMethodDataSource by dataSource
CustomerSheetPaymentMethodDataSource by dataSource,
CustomerSheetIntentDataSource by dataSource
where T : CustomerSheetSavedSelectionDataSource,
T : CustomerSheetPaymentMethodDataSource
T : CustomerSheetPaymentMethodDataSource,
T : CustomerSheetIntentDataSource

fun clear() {
_adapter.value = null
Expand Down
Loading