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

WIP get billing preview when holiday stop api is called #2243

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
Copy link
Contributor

@graham228221 graham228221 May 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we remove Mario's invoicing-api experiment (testInProdPreviewPublications) as part of this? This is currently erroring due to a problem with invoicing-api credentials, but if it were working it would also be requesting a billing-preview.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed in #2504

Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ object Handler extends Logging {
idGenerator,
FulfilmentDatesFetcher(fetchString, Stage()),
PreviewPublications.preview,
getBillingPreviewFromZuora(config, backend),
LocalDate.now,
)(
request,
sfClient.setupRequest(withAlternateAccessTokenIfPresentInHeaderList(request.headers)),
Expand All @@ -118,6 +120,8 @@ object Handler extends Logging {
idGenerator: => String,
fulfilmentDatesFetcher: FulfilmentDatesFetcher,
previewPublications: (String, String, String) => Either[ApiFailure, PreviewPublicationsResponse] = null, // FIXME
getBillingPreview: GetBillingPreview,
today: LocalDate,
) = {
(for {
httpMethod <- validateMethod(request.httpMethod)
Expand All @@ -131,6 +135,8 @@ object Handler extends Logging {
idGenerator,
fulfilmentDatesFetcher,
previewPublications,
getBillingPreview,
today,
)).fold(
{ errorMessage: String =>
badrequest(errorMessage) _
Expand Down Expand Up @@ -162,6 +168,8 @@ object Handler extends Logging {
idGenerator: => String,
fulfilmentDatesFetcher: FulfilmentDatesFetcher,
previewPublications: (String, String, String) => Either[ApiFailure, PreviewPublicationsResponse] = null, // FIXME
getBillingPreview: GetBillingPreview,
today: LocalDate,
) = {
path match {
case "potential" :: _ :: Nil =>
Expand All @@ -171,12 +179,12 @@ object Handler extends Logging {
}
case "hsr" :: Nil =>
httpMethod match {
case "POST" => stepsToCreate(getAccessToken, getSubscription, getAccount) _
case "POST" => stepsToCreate(getAccessToken, getSubscription, getAccount, getBillingPreview, today) _
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

coincidentally @tjmw has got a bit of refactoring on this to get rid of the underscores and neaten up the types. So we might end up with a small conflict in this area.

case _ => unsupported _
}
case "bulk-hsr" :: Nil =>
httpMethod match {
case "POST" => stepsToBulkCreate(getAccessToken, getSubscription, getAccount) _
case "POST" => stepsToBulkCreate(getAccessToken, getSubscription, getAccount, getBillingPreview, today) _
case _ => unsupported _
}
case "hsr" :: _ :: Nil =>
Expand Down Expand Up @@ -371,31 +379,41 @@ object Handler extends Logging {
getAccessToken: () => Either[ApiFailure, AccessToken],
getSubscription: (AccessToken, SubscriptionName) => Either[ApiFailure, Subscription],
getAccount: (AccessToken, String) => Either[ApiFailure, ZuoraAccount],
getBillingPreview: GetBillingPreview,
today: LocalDate,
)(req: ApiGatewayRequest, sfClient: SfClient): ApiResponse =
stepsToCreate(
getAccessToken,
getSubscription,
getAccount,
req.bodyAsCaseClass[HolidayStopRequestPartial](),
getBillingPreview,
today,
)(req, sfClient)

def stepsToBulkCreate(
getAccessToken: () => Either[ApiFailure, AccessToken],
getSubscription: (AccessToken, SubscriptionName) => Either[ApiFailure, Subscription],
getAccount: (AccessToken, String) => Either[ApiFailure, ZuoraAccount],
getBillingPreview: GetBillingPreview,
today: LocalDate,
)(req: ApiGatewayRequest, sfClient: SfClient): ApiResponse =
stepsToCreate(
getAccessToken,
getSubscription,
getAccount,
req.bodyAsCaseClass[BulkHolidayStopRequestPartial](),
getBillingPreview,
today,
)(req, sfClient)

private def stepsToCreate(
getAccessToken: () => Either[ApiFailure, AccessToken],
getSubscription: (AccessToken, SubscriptionName) => Either[ApiFailure, Subscription],
getAccount: (AccessToken, String) => Either[ApiFailure, ZuoraAccount],
requestBodyOp: ApiGatewayOp[HolidayStopRequestPartialTrait],
getBillingPreview: GetBillingPreview,
today: LocalDate,
)(req: ApiGatewayRequest, sfClient: SfClient): ApiResponse = {

val verifyContactOwnsSubOp =
Expand All @@ -416,6 +434,10 @@ object Handler extends Logging {
.toApiGatewayOp(s"get subscription ${requestBody.subscriptionName}")
account <- getAccount(accessToken, subscription.accountNumber)
.toApiGatewayOp(s"get account ${subscription.accountNumber}")
billingPreview <- getBillingPreview
.getBillingPreview(accessToken, subscription.accountNumber, today.plusMonths(13))
.toApiGatewayOp(s"get billing preview for account ${subscription.accountNumber}")
_ = logger.info("billingPreview: " + billingPreview)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

at this stage it just logs the response rather than passing it in to the subscriptiondata. we could try to paralellise the getAccount and getBillingPreview if we want to improve performance.

issuesData <- SubscriptionData(subscription, account)
.map(_.issueDataForPeriod(requestBody.startDate, requestBody.endDate))
.toApiGatewayOp(s"calculating publication dates")
Expand Down Expand Up @@ -576,6 +598,12 @@ object Handler extends Logging {
accountKey: String,
): Either[ApiFailure, ZuoraAccount] = Zuora.accountGetResponse(config.zuoraConfig, accessToken, backend)(accountKey)

def getBillingPreviewFromZuora(
config: Config,
backend: SttpBackend[Identity, Any],
): GetBillingPreview =
GetBillingPreviewLive.billingPreviewGetResponse(config.zuoraConfig, backend)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could inline this, I'm not sure why the convention is to have one function that calls another


def getAccessTokenFromZuora(
config: Config,
backend: SttpBackend[Identity, Any],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.gu.holiday_stops

import cats.Id
import com.gu.holiday_stops.Handler.{getAccessTokenFromZuora, getBillingPreviewFromZuora}
import com.gu.test.EffectsTest
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import sttp.client3.HttpURLConnectionBackend
import sttp.client3.logging.{LogLevel, Logger, LoggingBackend}

import java.time.LocalDate

class GetBillingPreviewEffectsTest extends AnyFlatSpec with Matchers {

lazy val config = {
zio.Runtime.default.unsafeRun {
Configuration.config.provideLayer(ConfigurationLive.impl)
}
}

lazy val backend = LoggingBackend(
HttpURLConnectionBackend(),
new Logger[Id] {
override def apply(level: LogLevel, message: => String): Id[Unit] = info("LOG: " + message)

override def apply(level: LogLevel, message: => String, t: Throwable): Id[Unit] =
info("LOG: " + message + t.toString)
},
logResponseBody = true,
)

"get billing preview" should "fetch a test subscription's preview" taggedAs EffectsTest ignore {

val ACCOUNT_TO_USE = "A00211577"

val op = getBillingPreviewFromZuora(config, backend)
val accessToken = getAccessTokenFromZuora(config, backend).toOption.get

val preview = op.getBillingPreview(accessToken, ACCOUNT_TO_USE, LocalDate.now.plusMonths(13))
info("preview is: " + preview)
preview.toOption.get.length shouldBe 26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this line checking, out of interest?

we might want to be aware that this is a real account in the api sandbox, and its state may change (it currently has two active subscriptions, but one or both could be cancelled any time, or more could be acquired).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it's good to flag this - this is more like a manual test, as I couldn't think of a quick way to make it reliable. It should be left as "ignore" unless it's being used.
If we can make it reliable then that's even better and we should do that (although even then, it's an Effects test and we don't have them automated yet)

To answer your question it's just checking that 26 items were returned for the 13 months (rather than an error). so not really a completely useful assertion.

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.gu.zuora.subscription

import com.gu.zuora.{AccessToken, ZuoraConfig}
import io.circe.generic.semiauto._
import io.circe.{Decoder, Encoder, HCursor}
import sttp.client3._
import sttp.client3.circe._

import java.time.LocalDate

object GetBillingPreview {

case class InvoiceItem(
chargeDate: LocalDate,
chargeId: String,
)
implicit val decode: Decoder[InvoiceItem] = (c: HCursor) =>
for {
chargeDate <- c.downField("chargeDate").as[String].map(_.takeWhile(_ != ' ')).map(LocalDate.parse)
Copy link
Member Author

@johnduffell johnduffell May 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

zuora returns a simplified date-time kind of this format yyyy-mm-dd hh:mm:ss that doesn't parse as a LocalDate, I did this as we're only interested in the date part anyway.

chargeId <- c.downField("chargeId").as[String]
} yield InvoiceItem(chargeDate, chargeId)

case class BillingPreview(
invoiceItems: List[InvoiceItem],
)
implicit val decode2: Decoder[BillingPreview] = deriveDecoder
implicit val encode: Encoder[BillingPreviewRequest] = deriveEncoder
case class BillingPreviewRequest(
accountNumber: String,
targetDate: LocalDate,
assumeRenewal: String = "Autorenew",
)
}
trait GetBillingPreview {
import GetBillingPreview._
def getBillingPreview(
accessToken: AccessToken,
accountNumber: String,
targetDate: LocalDate,
): Either[ApiFailure, List[InvoiceItem]]
}

object GetBillingPreviewLive {

def billingPreviewGetResponse(
config: ZuoraConfig,
backend: SttpBackend[Identity, Any],
): GetBillingPreview =
(accessToken: AccessToken, accountNumber: String, targetDate: LocalDate) => {
val request = GetBillingPreview.BillingPreviewRequest(accountNumber, targetDate)
basicRequest
.post(uri"${config.baseUrl}/operations/billing-preview")
.body(request)
.header("Authorization", s"Bearer ${accessToken.access_token}")
.response(asJson[GetBillingPreview.BillingPreview])
.mapResponse(_.left.map(e => ZuoraApiFailure(e.getMessage)))
.send(backend)
.body
.map(_.invoiceItems)
}

}
Loading