Skip to content

Commit

Permalink
Add save button
Browse files Browse the repository at this point in the history
  • Loading branch information
amk-stripe committed Nov 26, 2024
1 parent 1b99e55 commit e16838f
Show file tree
Hide file tree
Showing 11 changed files with 268 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ internal class CustomerSheetViewModel(
selectedBrand = it
)
},
updateExecutor = ::updateExecutor,
),
isLiveMode = isLiveModeProvider(),
)
Expand Down Expand Up @@ -614,12 +615,7 @@ internal class CustomerSheetViewModel(
},
displayName = providePaymentMethodName(paymentMethod.paymentMethod.type?.code),
removeExecutor = ::removeExecutor,
updateExecutor = { method, brand ->
when (val result = modifyCardPaymentMethod(method, brand)) {
is CustomerSheetDataResult.Success -> Result.success(result.value)
is CustomerSheetDataResult.Failure -> Result.failure(result.cause)
}
},
updateExecutor = ::updateExecutor,
canRemove = customerState.canRemove,
isLiveMode = requireNotNull(customerState.metadata).stripeIntent.isLiveMode,
cardBrandFilter = PaymentSheetCardBrandFilter(customerState.configuration.cardBrandAcceptance)
Expand All @@ -637,6 +633,13 @@ internal class CustomerSheetViewModel(
}.failureOrNull()?.cause
}

private suspend fun updateExecutor(paymentMethod: PaymentMethod, brand: CardBrand): Result<PaymentMethod> {
return when (val result = modifyCardPaymentMethod(paymentMethod, brand)) {
is CustomerSheetDataResult.Success -> Result.success(result.value)
is CustomerSheetDataResult.Failure -> Result.failure(result.cause)
}
}

private fun removePaymentMethodFromState(paymentMethod: PaymentMethod) {
val currentCustomerState = customerState.value
val newSavedPaymentMethods = currentCustomerState.paymentMethods.filter { it.id != paymentMethod.id!! }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ internal class SavedPaymentMethodMutator(
displayableSavedPaymentMethod,
cardBrandFilter = cardBrandFilter,
removeExecutor = ::removePaymentMethodInEditScreen,
updateExecutor = ::modifyCardPaymentMethod,
onBrandChoiceOptionsShown = {
eventReporter.onShowPaymentOptionBrands(
source = EventReporter.CardBrandChoiceEventSource.Edit,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ internal interface UpdatePaymentMethodInteractor {
val screenTitle: ResolvableString?
val cardBrandFilter: CardBrandFilter
val isExpiredCard: Boolean
val isModifiablePaymentMethod: Boolean

val state: StateFlow<State>

data class State(
val error: ResolvableString?,
val status: Status,
val cardBrandChoice: CardBrandChoice,
val cardBrandHasBeenChanged: Boolean,
)

enum class Status {
Expand All @@ -46,6 +48,7 @@ internal interface UpdatePaymentMethodInteractor {
data object BrandChoiceOptionsShown : ViewAction()
data class BrandChoiceChanged(val cardBrandChoice: CardBrandChoice) : ViewAction()
data object BrandChoiceOptionsDismissed : ViewAction()
data object SaveButtonPressed : ViewAction()
}

companion object {
Expand All @@ -68,6 +71,7 @@ internal class DefaultUpdatePaymentMethodInteractor(
override val displayableSavedPaymentMethod: DisplayableSavedPaymentMethod,
override val cardBrandFilter: CardBrandFilter,
private val removeExecutor: PaymentMethodRemoveOperation,
private val updateExecutor: PaymentMethodUpdateOperation,
private val onBrandChoiceOptionsShown: (CardBrand) -> Unit,
private val onBrandChoiceOptionsDismissed: (CardBrand) -> Unit,
workContext: CoroutineContext = Dispatchers.Default,
Expand All @@ -76,21 +80,27 @@ internal class DefaultUpdatePaymentMethodInteractor(
private val error = MutableStateFlow(getInitialError())
private val status = MutableStateFlow(UpdatePaymentMethodInteractor.Status.Idle)
private val cardBrandChoice = MutableStateFlow(getInitialCardBrandChoice())
private val cardBrandHasBeenChanged = MutableStateFlow(false)
private val savedCardBrand = MutableStateFlow(getInitialCardBrandChoice())

override val isExpiredCard = paymentMethodIsExpiredCard()
override val screenTitle: ResolvableString? = UpdatePaymentMethodInteractor.screenTitle(
displayableSavedPaymentMethod
)
override val isModifiablePaymentMethod: Boolean
get() = !isExpiredCard && displayableSavedPaymentMethod.isModifiable()

private val _state = combineAsStateFlow(
error,
status,
cardBrandChoice,
) { error, status, cardBrandChoice ->
cardBrandHasBeenChanged,
) { error, status, cardBrandChoice, cardBrandHasBeenChanged, ->
UpdatePaymentMethodInteractor.State(
error = error,
status = status,
cardBrandChoice = cardBrandChoice
cardBrandChoice = cardBrandChoice,
cardBrandHasBeenChanged = cardBrandHasBeenChanged,
)
}
override val state = _state
Expand All @@ -104,6 +114,7 @@ internal class DefaultUpdatePaymentMethodInteractor(
UpdatePaymentMethodInteractor.ViewAction.BrandChoiceOptionsDismissed -> onBrandChoiceOptionsDismissed(
cardBrandChoice.value.brand
)
UpdatePaymentMethodInteractor.ViewAction.SaveButtonPressed -> savePaymentMethod()
is UpdatePaymentMethodInteractor.ViewAction.BrandChoiceChanged -> onBrandChoiceChanged(
viewAction.cardBrandChoice
)
Expand All @@ -122,8 +133,28 @@ internal class DefaultUpdatePaymentMethodInteractor(
}
}

private fun savePaymentMethod() {
coroutineScope.launch {
val newCardBrand = cardBrandChoice.value.brand

error.emit(getInitialError())
status.emit(UpdatePaymentMethodInteractor.Status.Updating)

val updateResult = updateExecutor(displayableSavedPaymentMethod.paymentMethod, newCardBrand)

updateResult.onSuccess {
savedCardBrand.emit(CardBrandChoice(brand = newCardBrand))
cardBrandHasBeenChanged.emit(false)
}.onFailure {
error.emit(it.stripeErrorMessage())
}
status.emit(UpdatePaymentMethodInteractor.Status.Idle)
}
}

private fun onBrandChoiceChanged(cardBrandChoice: CardBrandChoice) {
this.cardBrandChoice.value = cardBrandChoice
this.cardBrandHasBeenChanged.value = cardBrandChoice != savedCardBrand.value

onBrandChoiceOptionsDismissed(cardBrandChoice.brand)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import com.stripe.android.uicore.stripeColors
import com.stripe.android.uicore.stripeShapes
import com.stripe.android.uicore.utils.collectAsState
import com.stripe.android.uicore.utils.mapAsStateFlow
import com.stripe.android.common.ui.PrimaryButton as PrimaryButton
import com.stripe.android.paymentsheet.R as PaymentSheetR

@Composable
Expand Down Expand Up @@ -104,7 +105,19 @@ internal fun UpdatePaymentMethodUI(interactor: UpdatePaymentMethodInteractor, mo
)
}

if (interactor.isModifiablePaymentMethod) {
Spacer(modifier = Modifier.requiredHeight(32.dp))
UpdatePaymentMethodUi(interactor)
}

if (interactor.canRemove) {
val spacerHeight = if (interactor.isModifiablePaymentMethod) {
16.dp
} else {
32.dp
}

Spacer(modifier = Modifier.requiredHeight(spacerHeight))
DeletePaymentMethodUi(interactor)
}
}
Expand All @@ -128,7 +141,8 @@ private fun CardDetailsUI(
CardNumberField(
card = card,
selectedBrand = selectedBrand,
isModifiable = displayableSavedPaymentMethod.isModifiable(),
shouldShowCardBrandDropdown = interactor.isModifiablePaymentMethod
&& displayableSavedPaymentMethod.isModifiable(),
cardBrandFilter = interactor.cardBrandFilter,
savedPaymentMethodIcon = displayableSavedPaymentMethod
.paymentMethod
Expand Down Expand Up @@ -252,13 +266,24 @@ private fun BankAccountTextField(
}
}

@Composable
private fun UpdatePaymentMethodUi(interactor: UpdatePaymentMethodInteractor) {
val state by interactor.state.collectAsState()

PrimaryButton(
label = stringResource(id = PaymentSheetR.string.stripe_paymentsheet_save),
isLoading = state.status == UpdatePaymentMethodInteractor.Status.Updating,
isEnabled = state.cardBrandHasBeenChanged && state.status == UpdatePaymentMethodInteractor.Status.Idle,
onButtonClick = { interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.SaveButtonPressed) },
modifier = Modifier.testTag(UPDATE_PM_SAVE_BUTTON_TEST_TAG)
)
}

@Composable
private fun DeletePaymentMethodUi(interactor: UpdatePaymentMethodInteractor) {
val openDialogValue = rememberSaveable { mutableStateOf(false) }
val status by interactor.state.mapAsStateFlow { it.status }.collectAsState()

Spacer(modifier = Modifier.requiredHeight(32.dp))

RemoveButton(
title = R.string.stripe_remove.resolvableString,
borderColor = MaterialTheme.colors.error,
Expand All @@ -283,7 +308,7 @@ private fun CardNumberField(
card: PaymentMethod.Card,
selectedBrand: CardBrandChoice,
cardBrandFilter: CardBrandFilter,
isModifiable: Boolean,
shouldShowCardBrandDropdown: Boolean,
savedPaymentMethodIcon: Int,
onBrandOptionsShown: () -> Unit,
onBrandChoiceChanged: (CardBrandChoice) -> Unit,
Expand All @@ -293,7 +318,7 @@ private fun CardNumberField(
value = "•••• •••• •••• ${card.last4}",
label = stringResource(id = R.string.stripe_acc_label_card_number),
trailingIcon = {
if (isModifiable) {
if (shouldShowCardBrandDropdown) {
CardBrandDropdown(
selectedBrand = selectedBrand,
availableBrands = card.getAvailableNetworks(cardBrandFilter),
Expand Down Expand Up @@ -450,6 +475,7 @@ private fun PreviewUpdatePaymentMethodUI() {
canRemove = true,
displayableSavedPaymentMethod = exampleCard,
removeExecutor = { null },
updateExecutor = { paymentMethod, _ -> Result.success(paymentMethod) },
cardBrandFilter = DefaultCardBrandFilter,
onBrandChoiceOptionsShown = {},
onBrandChoiceOptionsDismissed = {},
Expand Down Expand Up @@ -481,6 +507,7 @@ private const val YEAR_2100 = 2100
internal const val UPDATE_PM_EXPIRY_FIELD_TEST_TAG = "update_payment_method_expiry_date"
internal const val UPDATE_PM_CVC_FIELD_TEST_TAG = "update_payment_method_cvc"
internal const val UPDATE_PM_REMOVE_BUTTON_TEST_TAG = "update_payment_method_remove_button"
internal const val UPDATE_PM_SAVE_BUTTON_TEST_TAG = "update_payment_method_save_button"
internal const val UPDATE_PM_ERROR_MESSAGE_TEST_TAG = "update_payment_method_error_message"
internal const val UPDATE_PM_US_BANK_ACCOUNT_TEST_TAG = "update_payment_method_bank_account_ui"
internal const val UPDATE_PM_SEPA_DEBIT_TEST_TAG = "update_payment_method_sepa_debit_ui"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ internal class CustomerSheetScreenshotTest {
updatePaymentMethodInteractor = DefaultUpdatePaymentMethodInteractor(
displayableSavedPaymentMethod = PaymentMethodFixtures.displayableCard(),
removeExecutor = { null },
updateExecutor = { paymentMethod, _ -> Result.success(paymentMethod) },
canRemove = true,
isLiveMode = true,
cardBrandFilter = DefaultCardBrandFilter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ internal object PaymentMethodFixtures {
type = PaymentMethod.Type.Card,
billingDetails = BILLING_DETAILS,
customerId = "cus_AQsHpvKfKwJDrF",
card = CARD.copy(
card = CARD_WITH_NETWORKS.copy(
expiryMonth = 4,
expiryYear = 2024,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ class DefaultUpdatePaymentMethodInteractorTest {
}
}

@Test
fun expiredCard_isNotModifiablePM() {
runScenario(
displayableSavedPaymentMethod = PaymentMethodFixtures
.EXPIRED_CARD_PAYMENT_METHOD
.toDisplayableSavedPaymentMethod()
) {
assertThat(interactor.isModifiablePaymentMethod).isFalse()
}
}

@Test
fun nonExpiredCard_hasNoInitialError() {
runScenario(
Expand Down Expand Up @@ -123,19 +134,113 @@ class DefaultUpdatePaymentMethodInteractorTest {
}
}

@Test
fun cbcEligibleCard_isModifiablePaymentMethod() {
runScenario(
displayableSavedPaymentMethod = PaymentMethodFixtures
.CARD_WITH_NETWORKS_PAYMENT_METHOD
.toDisplayableSavedPaymentMethod()
) {
assertThat(interactor.isModifiablePaymentMethod).isTrue()
}
}

@Test
fun updatingCardBrand_updatesStateAsExpected() {
var updatedPaymentMethod: PaymentMethod? = null
var newCardBrand: CardBrand? = null
val initialPaymentMethod = PaymentMethodFixtures.CARD_WITH_NETWORKS_PAYMENT_METHOD

fun updateExecutor(paymentMethod: PaymentMethod, brand: CardBrand): Result<PaymentMethod> {
updatedPaymentMethod = paymentMethod
newCardBrand = brand

return Result.success(paymentMethod)
}

runScenario(
displayableSavedPaymentMethod = initialPaymentMethod.toDisplayableSavedPaymentMethod(),
onSavePaymentMethod = ::updateExecutor,
) {
interactor.state.test {
assertThat(awaitItem().cardBrandChoice.brand).isEqualTo(CardBrand.CartesBancaires)
}

val expectedNewCardBrand = CardBrand.Visa
interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.BrandChoiceChanged(
cardBrandChoice = CardBrandChoice(brand = expectedNewCardBrand)
))
interactor.state.test {
assertThat(awaitItem().cardBrandHasBeenChanged).isTrue()
}

interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.SaveButtonPressed)

assertThat(updatedPaymentMethod).isEqualTo(initialPaymentMethod)
assertThat(newCardBrand).isEqualTo(expectedNewCardBrand)
// We reset the cardBrandHasBeenChanged value when saving a new card brand, so that a user could change
// their card brand back to the original value if they wanted to.
interactor.state.test {
assertThat(awaitItem().cardBrandHasBeenChanged).isFalse()
}

// Re-clicking on the already saved card brand doesn't update cardBrandHasBeenChanged incorectly.
interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.BrandChoiceChanged(
cardBrandChoice = CardBrandChoice(brand = expectedNewCardBrand)
))
interactor.state.test {
assertThat(awaitItem().cardBrandHasBeenChanged).isFalse()
}
}
}

@Test
fun saveButtonClick_failure_displaysError() {
val updateException = IllegalStateException("Not allowed.")
fun updateExecutor(paymentMethod: PaymentMethod, brand: CardBrand): Result<PaymentMethod> {
return Result.failure(updateException)
}

runScenario(
displayableSavedPaymentMethod = PaymentMethodFixtures
.CARD_WITH_NETWORKS_PAYMENT_METHOD
.toDisplayableSavedPaymentMethod(),
onSavePaymentMethod = ::updateExecutor,
) {
val originalCardBrand = CardBrand.CartesBancaires
interactor.state.test {
assertThat(awaitItem().cardBrandChoice.brand).isEqualTo(originalCardBrand)
}

interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.BrandChoiceChanged(
cardBrandChoice = CardBrandChoice(brand = CardBrand.Visa)
))
interactor.handleViewAction(UpdatePaymentMethodInteractor.ViewAction.SaveButtonPressed)

interactor.state.test {
val state = awaitItem()
// Card brand has been changed is still true -- the user could try again.
assertThat(state.cardBrandHasBeenChanged).isTrue()
assertThat(state.error).isEqualTo(updateException.stripeErrorMessage())
}
}
}

private val notImplemented: () -> Nothing = { throw AssertionError("Not implemented") }

private fun runScenario(
canRemove: Boolean = false,
displayableSavedPaymentMethod: DisplayableSavedPaymentMethod = PaymentMethodFixtures.displayableCard(),
onRemovePaymentMethod: (PaymentMethod) -> Throwable? = { notImplemented() },
onSavePaymentMethod: (PaymentMethod, CardBrand) -> Result<PaymentMethod> = { _, _ -> notImplemented() },
testBlock: suspend TestParams.() -> Unit
) {
val interactor = DefaultUpdatePaymentMethodInteractor(
isLiveMode = false,
canRemove = canRemove,
displayableSavedPaymentMethod = displayableSavedPaymentMethod,
removeExecutor = onRemovePaymentMethod,
updateExecutor = onSavePaymentMethod,
workContext = UnconfinedTestDispatcher(),
cardBrandFilter = DefaultCardBrandFilter,
onBrandChoiceOptionsShown = {},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ internal class FakeUpdatePaymentMethodInteractor(
override val displayableSavedPaymentMethod: DisplayableSavedPaymentMethod,
override val canRemove: Boolean,
override val isExpiredCard: Boolean,
override val isModifiablePaymentMethod: Boolean,
val viewActionRecorder: ViewActionRecorder<UpdatePaymentMethodInteractor.ViewAction>?,
initialState: UpdatePaymentMethodInteractor.State,
) : UpdatePaymentMethodInteractor {
Expand Down
Loading

0 comments on commit e16838f

Please sign in to comment.