def consolidatePaymentMethod()

in membership-attribute-service/app/controllers/ExistingPaymentOptionsController.scala [52:72]


  def consolidatePaymentMethod(existingPaymentOptions: List[ExistingPaymentOption]): Iterable[ExistingPaymentOption] = {

    def extractConsolidationPart(existingPaymentOption: ExistingPaymentOption): Option[String] = existingPaymentOption.paymentMethodOption match {
      case Some(card: PaymentCard) => card.paymentCardDetails.map(_.lastFourDigits)
      case Some(dd: GoCardless) => Some(dd.accountNumber)
      case Some(payPal: PayPalMethod) => Some(payPal.email)
      case _ => None
    }

    def mapConsolidatedBackToSingle(consolidated: List[ExistingPaymentOption]): ExistingPaymentOption = {
      val theChosenOne = consolidated.head // TODO in future perhaps use custom fields on PaymentMethod to see which is safe to clone
      ExistingPaymentOption(
        freshlySignedIn = theChosenOne.freshlySignedIn,
        objectAccount = theChosenOne.objectAccount,
        paymentMethodOption = theChosenOne.paymentMethodOption,
        subscriptions = consolidated.flatMap(_.subscriptions),
      )
    }

    existingPaymentOptions.groupBy(extractConsolidationPart).view.filterKeys(_.isDefined).values.map(mapConsolidatedBackToSingle)
  }