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

Create a new term for subscriptions during product switch #2097

Merged
merged 32 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
677860d
Add a TermRenewal service
rupertbates Oct 16, 2023
c3aac26
Working TermRenewal service
rupertbates Oct 31, 2023
5ff63ea
Use TermRenewal service during switch
rupertbates Oct 31, 2023
5c8de5e
Naming change
rupertbates Oct 31, 2023
7b0c6f4
Fix test
rupertbates Oct 31, 2023
304c438
Change the point at which we start the new term
rupertbates Nov 1, 2023
75a5e0c
Set collect to true when renewing term
rupertbates Nov 1, 2023
f82c83e
Collect requires runBilling
rupertbates Nov 1, 2023
637af96
Use applyCreditBalance to handle balance from renewal
rupertbates Nov 1, 2023
85e06f4
Update comment
rupertbates Nov 1, 2023
25dc20f
Standardise the method of fetching today's date
rupertbates Nov 6, 2023
5b594a8
Check the result of the amend term length request
rupertbates Nov 6, 2023
0e8ffd1
Get rid of default values for RenewalRequest body
rupertbates Nov 6, 2023
008f52c
TermRenewal.startNewTermFromToday can return Unit
rupertbates Nov 6, 2023
72a0a22
Do term length change in the subscription update
rupertbates Nov 8, 2023
08ae068
Ignore IT test again
rupertbates Nov 9, 2023
8c7917e
>= 0.5
rupertbates Nov 9, 2023
f522603
Tidy some stuff up
rupertbates Nov 9, 2023
d9c9a0d
Remove extra GetSubscription
rupertbates Nov 9, 2023
fa74951
New call structure for RecurringContributionToSupporterPlus
rupertbates Nov 10, 2023
9e66460
Remove unused layers
rupertbates Nov 10, 2023
a8c43ec
Ignore IT test
rupertbates Nov 10, 2023
b5b86fb
Add email and tracking back in
rupertbates Nov 13, 2023
1dd355c
Remove `checkChargeAmountBeforeUpdate` parameter
rupertbates Nov 13, 2023
ae4562a
Reorder functions in RecurringContributionToSupporterPlus
rupertbates Nov 13, 2023
8384541
A couple of new comments
rupertbates Nov 13, 2023
ae09df5
Correct comments
rupertbates Nov 13, 2023
d328111
Update handlers/product-move-api/src/main/scala/com/gu/productmove/sw…
rupertbates Nov 13, 2023
fe34754
Update handlers/product-move-api/src/main/scala/com/gu/productmove/sw…
rupertbates Nov 13, 2023
06a0c62
PR feedback
rupertbates Nov 13, 2023
0703163
Update handlers/product-move-api/src/main/scala/com/gu/productmove/sw…
rupertbates Nov 13, 2023
28dcea5
PR feedback
rupertbates Nov 14, 2023
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
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def lambdaProject(
Project(projectName, file(s"handlers/$projectName"))
.enablePlugins(RiffRaffArtifact)
.configs(EffectsTest, HealthCheckTest)
.settings(scalaSettings, testSettings)
.settings(scalaSettings, testSettings, scalafmtSettings)
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
.settings(
name := projectName,
description := projectDescription,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ package com.gu.productmove.endpoint.move

import com.gu.newproduct.api.productcatalog.{Annual, BillingPeriod, Monthly}
import com.gu.supporterdata.model.SupporterRatePlanItem

import com.gu.productmove.SecretsLive
import com.gu.productmove.endpoint.move.ProductMoveEndpointTypes._
import com.gu.productmove.endpoint.move.ProductMoveEndpointTypes.*
import com.gu.productmove.GuStageLive.Stage
import com.gu.productmove.framework.ZIOApiGatewayRequestHandler.TIO
import com.gu.productmove.framework.{LambdaEndpoint, ZIOApiGatewayRequestHandler}
Expand All @@ -15,16 +14,18 @@ import com.gu.productmove.zuora.rest.{ZuoraClientLive, ZuoraGet, ZuoraGetLive}
import com.gu.productmove.zuora.{
GetAccount,
GetAccountLive,
GetInvoiceItems,
GetInvoiceItemsLive,
GetSubscription,
GetSubscriptionLive,
InvoiceItemAdjustment,
InvoiceItemAdjustmentLive,
Subscribe,
SubscribeLive,
SubscriptionUpdate,
SubscriptionUpdateLive,
GetInvoiceItems,
GetInvoiceItemsLive,
InvoiceItemAdjustment,
InvoiceItemAdjustmentLive,
TermRenewal,
TermRenewalLive,
ZuoraCancel,
ZuoraCancelLive,
}
Expand All @@ -41,12 +42,12 @@ import com.gu.productmove.{
SQSLive,
SttpClientLive,
}
import sttp.tapir._
import sttp.tapir.*
import sttp.tapir.EndpointIO.Example
import sttp.tapir.Schema
import sttp.tapir.json.zio.jsonBody
import zio._
import zio.json._
import zio.*
import zio.json.*
import com.gu.newproduct.api.productcatalog.ZuoraIds.ZuoraIds

import java.time.format.DateTimeFormatter
Expand Down Expand Up @@ -186,6 +187,7 @@ object ProductMoveEndpoint {
ZuoraClientLive.layer,
ZuoraGetLive.layer,
SubscriptionUpdateLive.layer,
TermRenewalLive.layer,
SQSLive.layer,
GetAccountLive.layer,
InvoiceItemAdjustmentLive.layer,
Expand Down
Copy link
Member Author

Choose a reason for hiding this comment

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

I reordered a lot of functions in this class which is why the diff is so big

Copy link
Member

Choose a reason for hiding this comment

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

ok thanks for the warning, I'll do my best, I will try to comment on new code rather than reordered stuff!

Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import com.gu.productmove.zuora.{
GetSubscriptionLive,
InvoiceItemAdjustment,
RemoveRatePlan,
RenewalResponse,
Subscribe,
SubscribeLive,
SubscriptionUpdate,
Expand All @@ -46,9 +47,12 @@ import com.gu.productmove.zuora.{
SubscriptionUpdateRequest,
SubscriptionUpdateResponse,
SwitchProductUpdateRequest,
TermRenewal,
UpdateSubscriptionAmount,
ZuoraCancel,
ZuoraCancelLive,
given_JsonDecoder_SubscriptionUpdatePreviewResponse,
given_JsonDecoder_SubscriptionUpdateResponse,
}
import com.gu.productmove.{
AwsCredentialsLive,
Expand All @@ -67,8 +71,6 @@ import com.gu.productmove.{
import com.gu.supporterdata.model.SupporterRatePlanItem
import com.gu.util.config
import com.gu.util.config.ZuoraEnvironment
import com.gu.productmove.zuora.given_JsonDecoder_SubscriptionUpdateResponse
import com.gu.productmove.zuora.given_JsonDecoder_SubscriptionUpdatePreviewResponse
import zio.*
import zio.json.*

Expand Down Expand Up @@ -103,6 +105,8 @@ object RecurringContributionToSupporterPlus {
): ZIO[
GetSubscription
with SubscriptionUpdate
with TermRenewal
with GetSubscription
with GetInvoiceItems
with InvoiceItemAdjustment
with GetAccount
Expand Down Expand Up @@ -331,7 +335,15 @@ object RecurringContributionToSupporterPlus {
csrUserId: Option[String],
caseId: Option[String],
): ZIO[
GetAccount with SubscriptionUpdate with GetInvoiceItems with InvoiceItemAdjustment with SQS with Stage with Dynamo,
GetAccount
with SubscriptionUpdate
with TermRenewal
with GetSubscription
with GetInvoiceItems
with InvoiceItemAdjustment
with SQS
with Stage
with Dynamo,
ErrorResponse,
OutputBody,
] = {
Expand Down Expand Up @@ -391,6 +403,9 @@ object RecurringContributionToSupporterPlus {
amountPayableToday,
)

// Start a new term when we do the switch to avoid issues with billing dates
_ <- TermRenewal.startNewTermFromToday[RenewalResponse](subscriptionName)
rupertbates marked this conversation as resolved.
Show resolved Hide resolved

account <- accountFuture.join

identityId <- ZIO
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ object GetSubscription {
id: String,
accountId: String,
accountNumber: AccountNumber,
termStartDate: LocalDate,
ratePlans: List[RatePlan],
)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package com.gu.productmove.zuora

import com.gu.i18n.Currency
import com.gu.newproduct.api.productcatalog.PlanId.{AnnualSupporterPlus, MonthlySupporterPlus}
import com.gu.newproduct.api.productcatalog.ZuoraIds.{
ProductRatePlanId,
SupporterPlusZuoraIds,
ZuoraIds,
zuoraIdsForStage,
}
import com.gu.newproduct.api.productcatalog.*
import com.gu.productmove.AwsS3
import com.gu.productmove.GuStageLive.Stage
import com.gu.productmove.endpoint.move.ProductMoveEndpointTypes.{ErrorResponse, InternalServerError, PreviewResult}
import com.gu.productmove.zuora.GetSubscription.GetSubscriptionResponse
import com.gu.productmove.zuora.model.{SubscriptionId, SubscriptionName}
import com.gu.productmove.zuora.rest.ZuoraGet
import com.gu.productmove.zuora.rest.ZuoraRestBody.ZuoraSuccessCheck
import com.gu.util.config
import sttp.capabilities.zio.ZioStreams
import sttp.capabilities.{Effect, WebSockets}
import sttp.client3.*
import sttp.client3.httpclient.zio.HttpClientZioBackend
import sttp.client3.ziojson.*
import sttp.model.Uri
import zio.json.*
import zio.json.ast.Json
import zio.json.internal.Write
import zio.{Clock, IO, RIO, Task, UIO, URLayer, ZIO, ZLayer}

import java.time.LocalDate
import java.time.temporal.ChronoUnit

trait TermRenewal:
def startNewTermFromToday[R: JsonDecoder](
subscriptionName: SubscriptionName,
): ZIO[Stage with GetSubscription, ErrorResponse, R]

object TermRenewalLive:
val layer: URLayer[ZuoraGet, TermRenewal] = ZLayer.fromFunction(TermRenewalLive(_))

private class TermRenewalLive(zuoraGet: ZuoraGet) extends TermRenewal:
/*
Start a new term for this subscription from today.
This is to avoid problems with charges not aligning correctly with the term and resulting in unpredictable
billing dates and amounts.

To do this we need to adjust the current term length so that it ends today using an amend call:
https://www.zuora.com/developer/api-references/older-api/operation/Action_POSTamend/

Then renew the subscription using https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription/

During this process two invoices will be generated - a negative one for the full amount which represents the fact
that we have reduced the current term to zero days from today's payment and then a positive one for the full amount
which covers the new 12 month term.

In order to balance these out, we can use the `applyCreditBalance` parameter in the renewal request.
*/

override def startNewTermFromToday[R: JsonDecoder](
subscriptionName: SubscriptionName,
): ZIO[Stage with GetSubscription, ErrorResponse, R] = for {
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
subscription <- GetSubscription.get(subscriptionName)
_ <- amendTermEndDateToToday(SubscriptionId(subscription.id), subscription.termStartDate)
response <- renewSubscription(subscriptionName)
} yield response

private def amendTermEndDateToToday[R: JsonDecoder](
subscriptionId: SubscriptionId,
termStartDate: LocalDate,
): ZIO[Stage, ErrorResponse, R] = {
val today = LocalDate.now
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
val newLength =
ChronoUnit.DAYS.between(termStartDate, today).toInt
val requestBody = AmendTermLengthRequest(
List(
AmendmentRequest(
List(
Amendment(
ContractEffectiveDate = today,
CustomerAcceptanceDate = today,
SubscriptionId = subscriptionId.value,
CurrentTerm = newLength,
),
),
),
),
)
zuoraGet.put[AmendTermLengthRequest, R](
relativeUrl = uri"action/amend",
input = requestBody,
zuoraSuccessCheck = ZuoraSuccessCheck.None,
)
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
}

private def renewSubscription[R: JsonDecoder](
subscriptionName: SubscriptionName,
): ZIO[Stage, ErrorResponse, R] = {
val today = LocalDate.now
val requestBody = RenewalRequest(today)
zuoraGet.put[RenewalRequest, R](
relativeUrl = uri"subscriptions/${subscriptionName.value}/renew",
input = requestBody,
zuoraSuccessCheck = ZuoraSuccessCheck.SuccessCheckLowercase,
)
}

object TermRenewal {
def startNewTermFromToday[R: JsonDecoder](
subscriptionName: SubscriptionName,
): ZIO[TermRenewal with Stage with GetSubscription, ErrorResponse, R] =
ZIO.serviceWithZIO[TermRenewal](_.startNewTermFromToday[R](subscriptionName))
}
case class AmendmentRequest(Amendments: List[Amendment])
case class Amendment(
ContractEffectiveDate: LocalDate,
CustomerAcceptanceDate: LocalDate,
SubscriptionId: String,
CurrentTerm: Int,
CurrentTermPeriodType: String = "Day",
Status: String = "Completed",
Name: String = "Amend current term to end today by product-move-api during switch to Supporter Plus",
Type: String = "TermsAndConditions",
)
case class AmendTermLengthRequest(
requests: List[AmendmentRequest],
)
case class AmendmentResponse(results: List[AmendmentResult])
case class AmendmentResult(AmendmentIds: List[String], Success: Boolean)
case class RenewalRequest(
contractEffectiveDate: LocalDate,
applyCreditBalance: Boolean = true, // When we shorten
runBilling: Boolean = true,
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
)
case class RenewalResponse(success: Option[Boolean])
given JsonEncoder[AmendTermLengthRequest] = DeriveJsonEncoder.gen[AmendTermLengthRequest]
given JsonEncoder[Amendment] = DeriveJsonEncoder.gen[Amendment]
given JsonEncoder[AmendmentRequest] = DeriveJsonEncoder.gen[AmendmentRequest]
given JsonDecoder[AmendmentResult] = DeriveJsonDecoder.gen[AmendmentResult]
object RenewalResponse {
given JsonDecoder[RenewalResponse] = DeriveJsonDecoder.gen[RenewalResponse]
}
given JsonEncoder[RenewalRequest] = DeriveJsonEncoder.gen[RenewalRequest]
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.gu.productmove.zuora.model

import zio.json.{JsonDecoder, JsonEncoder}

case class SubscriptionId(value: String)

object SubscriptionId {
given JsonDecoder[SubscriptionId] = JsonDecoder.string.map(SubscriptionId(_))
given JsonEncoder[SubscriptionId] = JsonEncoder.string.contramap(_.value)
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,12 @@ private class ZuoraGetLive(zuoraClient: ZuoraClient) extends ZuoraGet:
override def put[Request: JsonEncoder, Response: JsonDecoder](
relativeUrl: Uri,
input: Request,
zuoraSuccessCheck: ZuoraSuccessCheck = ZuoraSuccessCheck.SuccessCheckLowercase,
): IO[ErrorResponse, Response] =
for {
response <- zuoraClient.send(basicRequest.contentType("application/json").body(input.toJson).put(relativeUrl))
parsedBody <- ZIO.fromEither(
ZuoraRestBody.parseIfSuccessful[Response](response, ZuoraSuccessCheck.SuccessCheckLowercase),
ZuoraRestBody.parseIfSuccessful[Response](response, zuoraSuccessCheck),
)
} yield parsedBody

Expand All @@ -52,7 +53,11 @@ trait ZuoraGet:
input: Request,
zuoraSuccessCheck: ZuoraSuccessCheck = ZuoraSuccessCheck.SuccessCheckLowercase,
): IO[ErrorResponse, Response]
def put[Request: JsonEncoder, Response: JsonDecoder](relativeUrl: Uri, input: Request): IO[ErrorResponse, Response]
def put[Request: JsonEncoder, Response: JsonDecoder](
rupertbates marked this conversation as resolved.
Show resolved Hide resolved
relativeUrl: Uri,
input: Request,
zuoraSuccessCheck: ZuoraSuccessCheck = ZuoraSuccessCheck.SuccessCheckLowercase,
): IO[ErrorResponse, Response]

object ZuoraGet {
def get[T: JsonDecoder](
Expand All @@ -71,6 +76,7 @@ object ZuoraGet {
def put[Request: JsonEncoder, Response: JsonDecoder](
relativeUrl: Uri,
input: Request,
zuoraSuccessCheck: ZuoraSuccessCheck = ZuoraSuccessCheck.SuccessCheckLowercase,
): ZIO[ZuoraGet, ErrorResponse, Response] =
ZIO.serviceWithZIO[ZuoraGet](_.put(relativeUrl, input))
ZIO.serviceWithZIO[ZuoraGet](_.put(relativeUrl, input, zuoraSuccessCheck))
}
Loading
Loading