diff --git a/.scalafix.conf b/.scalafix.conf new file mode 100644 index 0000000000..247446da7f --- /dev/null +++ b/.scalafix.conf @@ -0,0 +1,4 @@ +rules = [ + ExplicitResultTypes, +] +ExplicitResultTypes.skipSimpleDefinitions = false diff --git a/project/plugins.sbt b/project/plugins.sbt index 310e1fc0ae..eca78d6bd5 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -20,6 +20,8 @@ libraryDependencies += "org.vafer" % "jdeb" % "1.10" artifacts (Artifact("jdeb", addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2") +addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.13.0") + addSbtPlugin("com.gu" % "sbt-riffraff-artifact" % "1.1.18") addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.16") diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/conf/PatronsIdentityConfig.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/conf/PatronsIdentityConfig.scala index f3065639ed..ae4f408522 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/conf/PatronsIdentityConfig.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/conf/PatronsIdentityConfig.scala @@ -7,7 +7,7 @@ import com.gu.supporterdata.model.Stage case class PatronsIdentityConfig(apiUrl: String, apiClientToken: String) object PatronsIdentityConfig extends ConfigService { - def fromParameterStoreSync(stage: Stage) = { + def fromParameterStoreSync(stage: Stage): PatronsIdentityConfig = { logger.info(s"Loading Identity config") val params = ParameterStoreService(stage).getParametersByPathSync("identity-config") PatronsIdentityConfig( diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronCancelledEventLambda.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronCancelledEventLambda.scala index 50746ed478..7b8ababf8e 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronCancelledEventLambda.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronCancelledEventLambda.scala @@ -39,9 +39,10 @@ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.{Duration, DurationInt, MINUTES} import scala.jdk.CollectionConverters.MapHasAsScala import scala.util.{Failure, Success, Try} +import okhttp3.{Request, Response} class PatronCancelledEventLambda extends StrictLogging { - val runner = configurableFutureRunner(60.seconds) + val runner: Request => Future[Response] = configurableFutureRunner(60.seconds) implicit val stage: Stage = StageConstructors.fromEnvironment private val stripeConfig = PatronsStripeConfig.fromParameterStoreSync(stage) @@ -76,7 +77,7 @@ class PatronCancelledEventLambda extends StrictLogging { def cancelSubscriptionForEmail(email: String, subscriptionId: String, identityConfig: PatronsIdentityConfig)(implicit stage: Stage, - ) = for { + ): EitherT[Future, CancelError, Unit] = for { identityId <- getIdentityId(identityConfig, email) _ <- cancelSubscription(stage, identityId, subscriptionId) } yield () @@ -96,7 +97,7 @@ class PatronCancelledEventLambda extends StrictLogging { EitherT.pure(()) } - def getAPIGatewayResult(result: Either[CancelError, Unit]) = { + def getAPIGatewayResult(result: Either[CancelError, Unit]): APIGatewayProxyResponseEvent = { val response = new APIGatewayProxyResponseEvent() result match { case Left(error @ (ConfigLoadingError(_) | DynamoDbError(_))) => @@ -211,8 +212,8 @@ class PatronCancelledEventLambda extends StrictLogging { } case class PatronCancelledEvent(data: PatronCancelledData, `type`: String) { - def customerId = data.`object`.customer - def subscriptionId = data.`object`.id + def customerId: String = data.`object`.customer + def subscriptionId: String = data.`object`.id } object PatronCancelledEvent { implicit val decoder: Decoder[PatronCancelledEvent] = deriveDecoder diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronSignUpEventLambda.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronSignUpEventLambda.scala index 18f914ba11..42a52baa45 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronSignUpEventLambda.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/PatronSignUpEventLambda.scala @@ -39,9 +39,10 @@ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.{Duration, DurationInt, MINUTES} import scala.jdk.CollectionConverters.MapHasAsScala import scala.util.{Failure, Success, Try} +import okhttp3.{Request, Response} class PatronSignUpEventLambda extends StrictLogging { - val runner = configurableFutureRunner(60.seconds) + val runner: Request => Future[Response] = configurableFutureRunner(60.seconds) implicit val stage: Stage = StageConstructors.fromEnvironment private val stripeConfig = PatronsStripeConfig.fromParameterStoreSync(stage) @@ -77,7 +78,7 @@ class PatronSignUpEventLambda extends StrictLogging { } yield unit).value.map(getAPIGatewayResult(_)) } - def getAPIGatewayResult(result: Either[SignUpError, Unit]) = { + def getAPIGatewayResult(result: Either[SignUpError, Unit]): APIGatewayProxyResponseEvent = { val response = new APIGatewayProxyResponseEvent() result match { case Left(error @ (ConfigLoadingError(_) | SubscriptionProcessingError(_) | StripeGetCustomerFailedError(_))) => diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/ProcessStripeSubscriptionsLambda.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/ProcessStripeSubscriptionsLambda.scala index 9ab28992a0..a1ae6b4c74 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/ProcessStripeSubscriptionsLambda.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/lambdas/ProcessStripeSubscriptionsLambda.scala @@ -19,6 +19,7 @@ import com.gu.supporterdata.services.SupporterDataDynamoService import scala.concurrent.Await import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.{Duration, DurationInt, MILLISECONDS} +import scala.concurrent.Future class ProcessStripeSubscriptionsLambda extends RequestHandler[Unit, Unit] { @@ -26,7 +27,7 @@ class ProcessStripeSubscriptionsLambda extends RequestHandler[Unit, Unit] { private val stripeConfig = PatronsStripeConfig.fromParameterStoreSync(stage) private val identityConfig = PatronsIdentityConfig.fromParameterStoreSync(stage) - override def handleRequest(input: Unit, context: Context) = { + override def handleRequest(input: Unit, context: Context): Unit = { val account = GnmPatronScheme // TODO: allow this to be set by the caller Await.result( processSubscriptions(account, stage, stripeConfig, identityConfig), @@ -42,7 +43,7 @@ object ProcessStripeSubscriptionsLambda { stage: Stage, stripeConfig: PatronsStripeConfig, identityConfig: PatronsIdentityConfig, - ) = { + ): Future[Unit] = { val runner = configurableFutureRunner(60.seconds) val stripeService = new PatronsStripeService(stripeConfig, runner) val identityService = new PatronsIdentityService(identityConfig, runner) diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/model/StripeSubscriptionsResponse.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/model/StripeSubscriptionsResponse.scala index 23e7e8d191..937ee0bd5c 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/model/StripeSubscriptionsResponse.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/model/StripeSubscriptionsResponse.scala @@ -27,8 +27,8 @@ sealed trait StripeCustomer @ConfiguredJsonCodec case class ExpandedStripeCustomer(id: String, name: Option[String], email: String, metadata: Metadata) extends StripeCustomer { - val jointPatronEmail = metadata.jointPatronEmail - val jointPatronName = metadata.jointPatronName + val jointPatronEmail: Option[String] = metadata.jointPatronEmail + val jointPatronName: Option[String] = metadata.jointPatronName } case class UnexpandedStripeCustomer(id: String) extends StripeCustomer diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/model/identity/IdentityErrorResponse.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/model/identity/IdentityErrorResponse.scala index a9c7679782..db8ae7818a 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/model/identity/IdentityErrorResponse.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/model/identity/IdentityErrorResponse.scala @@ -34,9 +34,9 @@ object IdentityErrorResponse { object IdentityError { object InvalidEmailAddress { - val message = "Registration Error" - val description = "Please sign up using an email address from a different provider" - val errorReasonCode = "invalid_email_address" + val message: String = "Registration Error" + val description: String = "Please sign up using an email address from a different provider" + val errorReasonCode: String = "invalid_email_address" } def isDisallowedEmailError(identityError: IdentityError): Boolean = diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ConfigService.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ConfigService.scala index 68472c8934..b86cd72e30 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ConfigService.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ConfigService.scala @@ -6,14 +6,14 @@ import com.typesafe.scalalogging.StrictLogging trait ConfigService extends StrictLogging { - protected def findParameterOrThrow(name: String, params: List[Parameter]) = + protected def findParameterOrThrow(name: String, params: List[Parameter]): String = findParameterValue(name, params).getOrElse { val error = s"Missing config value for parameter $name" logger.error(error) throw new RuntimeException(error) } - protected def findParameterValue(name: String, params: List[Parameter]) = + protected def findParameterValue(name: String, params: List[Parameter]): Option[String] = params .find(_.getName.split('/').last == name) .map(_.getValue) diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ParameterStoreService.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ParameterStoreService.scala index b3db6ea7a5..a7ad5d8dc4 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ParameterStoreService.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/ParameterStoreService.scala @@ -24,11 +24,13 @@ import com.gu.supporterdata.model.Stage import scala.concurrent.ExecutionContext import scala.jdk.CollectionConverters._ +import com.amazonaws.services.simplesystemsmanagement.model.{Parameter, PutParameterResult} +import scala.concurrent.Future class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stage) { - val configRoot = s"/$stage/support/stripe-patrons-data" + val configRoot: String = s"/$stage/support/stripe-patrons-data" - def getParametersByPath(path: String)(implicit executionContext: ExecutionContext) = { + def getParametersByPath(path: String)(implicit executionContext: ExecutionContext): Future[List[Parameter]] = { val request: GetParametersByPathRequest = new GetParametersByPathRequest() .withPath(s"$configRoot/$path/") .withRecursive(false) @@ -37,7 +39,7 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag AwsAsync(client.getParametersByPathAsync, request).map(_.getParameters.asScala.toList) } - def getParametersByPathSync(path: String) = { + def getParametersByPathSync(path: String): List[Parameter] = { val request: GetParametersByPathRequest = new GetParametersByPathRequest() .withPath(s"$configRoot/$path/") .withRecursive(false) @@ -46,7 +48,7 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag client.getParametersByPath(request).getParameters.asScala.toList } - def getParameter(name: String)(implicit executionContext: ExecutionContext) = { + def getParameter(name: String)(implicit executionContext: ExecutionContext): Future[String] = { val request = new GetParameterRequest() .withName(s"$configRoot/$name") .withWithDecryption(true) @@ -54,7 +56,11 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag AwsAsync(client.getParameterAsync, request).map(_.getParameter.getValue) } - def putParameter(name: String, value: String, parameterType: ParameterType = ParameterType.String) = { + def putParameter( + name: String, + value: String, + parameterType: ParameterType = ParameterType.String, + ): Future[PutParameterResult] = { val putParameterRequest = new PutParameterRequest() .withName(s"$configRoot/$name") @@ -70,18 +76,18 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag object ParameterStoreService { // please update to AWS SDK 2 and use com.gu.aws.CredentialsProvider - lazy val CredentialsProviderDEPRECATEDV1 = new AWSCredentialsProviderChain( + lazy val CredentialsProviderDEPRECATEDV1: AWSCredentialsProviderChain = new AWSCredentialsProviderChain( new ProfileCredentialsProvider(ProfileName), new InstanceProfileCredentialsProvider(false), new EnvironmentVariableCredentialsProvider(), new EC2ContainerCredentialsProviderWrapper(), // for use with lambda snapstart ) - lazy val client = AWSSimpleSystemsManagementAsyncClientBuilder + lazy val client: AWSSimpleSystemsManagementAsync = AWSSimpleSystemsManagementAsyncClientBuilder .standard() .withRegion(Regions.EU_WEST_1) .withCredentials(CredentialsProviderDEPRECATEDV1) .build() - def apply(stage: Stage) = new ParameterStoreService(client, stage) + def apply(stage: Stage): ParameterStoreService = new ParameterStoreService(client, stage) } diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsIdentityService.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsIdentityService.scala index b7dfe86a8f..6412b2240f 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsIdentityService.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsIdentityService.scala @@ -11,9 +11,9 @@ import scala.concurrent.{ExecutionContext, Future} class PatronsIdentityService(val config: PatronsIdentityConfig, client: FutureHttpClient) extends WebServiceHelper[IdentityErrorResponse] { - override val wsUrl = config.apiUrl - override val httpClient = client - val authHeader = Map( + override val wsUrl: String = config.apiUrl + override val httpClient: FutureHttpClient = client + val authHeader: Map[String, String] = Map( "Authorization" -> s"Bearer ${config.apiClientToken}", ) @@ -45,7 +45,7 @@ class PatronsIdentityService(val config: PatronsIdentityConfig, client: FutureHt def createUserIdFromEmailUser( email: String, firstName: Option[String], - )(implicit ec: ExecutionContext) = { + )(implicit ec: ExecutionContext): Future[String] = { logger.info(s"Attempting to create guest identity account for user $email") val body = CreateGuestAccountRequestBody( email, diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsStripeService.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsStripeService.scala index 51484ae79c..71037cd39e 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsStripeService.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/PatronsStripeService.scala @@ -10,8 +10,8 @@ import scala.concurrent.{ExecutionContext, Future} class PatronsStripeService(val config: PatronsStripeConfig, client: FutureHttpClient)(implicit ec: ExecutionContext, ) extends WebServiceHelper[StripeError] { - override val wsUrl = "https://api.stripe.com/v1" - override val httpClient = client + override val wsUrl: String = "https://api.stripe.com/v1" + override val httpClient: FutureHttpClient = client def authHeader(account: PatronsStripeAccount): Map[String, String] = Map( "Authorization" -> s"Bearer ${account match { @@ -38,7 +38,7 @@ class PatronsStripeService(val config: PatronsStripeConfig, client: FutureHttpCl ) } - def getCustomer(account: PatronsStripeAccount, customerId: String) = + def getCustomer(account: PatronsStripeAccount, customerId: String): Future[ExpandedStripeCustomer] = get[ExpandedStripeCustomer]( s"customers/$customerId", authHeader(account), diff --git a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/StripeSubscriptionsProcessor.scala b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/StripeSubscriptionsProcessor.scala index 727768dfe4..d62fdd47cf 100644 --- a/stripe-patrons-data/src/main/scala/com/gu/patrons/services/StripeSubscriptionsProcessor.scala +++ b/stripe-patrons-data/src/main/scala/com/gu/patrons/services/StripeSubscriptionsProcessor.scala @@ -15,7 +15,7 @@ class StripeSubscriptionsProcessor( executionContext: ExecutionContext, ) extends SafeLogging { - def processSubscriptions(account: PatronsStripeAccount, pageSize: Int) = + def processSubscriptions(account: PatronsStripeAccount, pageSize: Int): Future[Unit] = processFutureResponse(account, pageSize, None) final def processFutureResponse( @@ -33,7 +33,7 @@ class StripeSubscriptionsProcessor( Future.successful(()) } yield result - def processSubs(list: List[StripeSubscription[ExpandedStripeCustomer]]) = { + def processSubs(list: List[StripeSubscription[ExpandedStripeCustomer]]): Future[List[Unit]] = { val unknownEmailViaCSR = "patrons@theguardian.com" Future.sequence( list @@ -56,7 +56,7 @@ abstract class DynamoProcessor( with SafeLogging { import scala.concurrent.ExecutionContext.Implicits.global - def writeToDynamo(identityId: String, sub: StripeSubscription[ExpandedStripeCustomer]) = { + def writeToDynamo(identityId: String, sub: StripeSubscription[ExpandedStripeCustomer]): Future[UpdateItemResponse] = { logger.info( s"Attempting to write subscription (${sub.customer.email}, $identityId) to Dynamo", ) @@ -75,7 +75,7 @@ abstract class DynamoProcessor( ) } - def logDynamoResult(email: String, addSubscriptionsToQueueState: UpdateItemResponse) = + def logDynamoResult(email: String, addSubscriptionsToQueueState: UpdateItemResponse): Unit = if (addSubscriptionsToQueueState.sdkHttpResponse().statusCode() == 200) logger.info(s"Dynamo record successfully written for $email") else @@ -90,7 +90,7 @@ class CreateMissingIdentityProcessor( ) extends DynamoProcessor(supporterDataDynamoService) { import scala.concurrent.ExecutionContext.Implicits.global - override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]) = + override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]): Future[Unit] = for { _ <- processCustomerEmail(subscription.customer.email, subscription.customer.name, subscription) _ <- maybeAddJointPatron(subscription) @@ -110,7 +110,7 @@ class CreateMissingIdentityProcessor( () } - def maybeAddJointPatron(subscription: StripeSubscription[ExpandedStripeCustomer]) = + def maybeAddJointPatron(subscription: StripeSubscription[ExpandedStripeCustomer]): Future[Unit] = subscription.customer.jointPatronEmail match { case Some(email) => logger.info(s"Customer ${subscription.customer.email} has an associated joint patron - $email") @@ -127,7 +127,7 @@ class SkipMissingIdentityProcessor( ) extends DynamoProcessor(supporterDataDynamoService) { import scala.concurrent.ExecutionContext.Implicits.global - override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]) = + override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]): Future[Unit] = identityService.getUserIdFromEmail(subscription.customer.email).map { case Some(identityId) => writeToDynamo(identityId, subscription).map(response => logDynamoResult(subscription.customer.email, response)) diff --git a/stripe-patrons-data/src/test/scala/com/gu/patrons/services/Fixtures.scala b/stripe-patrons-data/src/test/scala/com/gu/patrons/services/Fixtures.scala index e1db24e57d..c530731f1c 100644 --- a/stripe-patrons-data/src/test/scala/com/gu/patrons/services/Fixtures.scala +++ b/stripe-patrons-data/src/test/scala/com/gu/patrons/services/Fixtures.scala @@ -1,7 +1,7 @@ package com.gu.patrons.services object Fixtures { - val subscriptionJson = """ + val subscriptionJson: String = """ { "id": "sub_HHdivtqWAZRZLT", "object": "subscription", @@ -363,7 +363,7 @@ object Fixtures { } """ - val patronCancelledEventJson = + val patronCancelledEventJson: String = """ { "id": "evt_1LudpBJETvkRwpwqmTN4BiHf", @@ -492,7 +492,7 @@ object Fixtures { } """ - val patronSignUpEventJson = """ + val patronSignUpEventJson: String = """ { "id": "evt_1MX3M1JETvkRwpwqAQ6JAXKW", "object": "event", diff --git a/stripe-patrons-data/src/test/scala/com/gu/patrons/services/StripeSubscriptionsProcessorSpec.scala b/stripe-patrons-data/src/test/scala/com/gu/patrons/services/StripeSubscriptionsProcessorSpec.scala index 71fb534fcf..bc3e22a30a 100644 --- a/stripe-patrons-data/src/test/scala/com/gu/patrons/services/StripeSubscriptionsProcessorSpec.scala +++ b/stripe-patrons-data/src/test/scala/com/gu/patrons/services/StripeSubscriptionsProcessorSpec.scala @@ -9,6 +9,7 @@ import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.duration.DurationInt +import scala.concurrent.Future @IntegrationTest class StripeSubscriptionsProcessorSpec extends AsyncFlatSpec with Matchers { @@ -28,7 +29,7 @@ class StripeSubscriptionsProcessorSpec extends AsyncFlatSpec with Matchers { } class LoggingSubscriptionProcessor(identityService: PatronsIdentityService) extends SubscriptionProcessor { - override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]) = + override def processSubscription(subscription: StripeSubscription[ExpandedStripeCustomer]): Future[Unit] = identityService .getUserIdFromEmail(subscription.customer.email) .map(maybeIdentityId => diff --git a/support-config/src/main/scala/com/gu/monitoring/SafeLogger.scala b/support-config/src/main/scala/com/gu/monitoring/SafeLogger.scala index 85f92c46b0..0bba68de26 100644 --- a/support-config/src/main/scala/com/gu/monitoring/SafeLogger.scala +++ b/support-config/src/main/scala/com/gu/monitoring/SafeLogger.scala @@ -22,7 +22,7 @@ object SafeLogger { val sanitizedLogMessage: Marker = MarkerFactory.getMarker("SENTRY") case class LogMessage(withPersonalData: String, withoutPersonalData: String) { - override val toString = withoutPersonalData + override val toString: String = withoutPersonalData } } diff --git a/support-config/src/main/scala/com/gu/support/config/PriceSummaryConfig.scala b/support-config/src/main/scala/com/gu/support/config/PriceSummaryConfig.scala index 1ebf762fb4..8711d41234 100644 --- a/support-config/src/main/scala/com/gu/support/config/PriceSummaryConfig.scala +++ b/support-config/src/main/scala/com/gu/support/config/PriceSummaryConfig.scala @@ -5,7 +5,7 @@ import com.typesafe.config.Config case class PriceSummaryConfig(catalogConfig: CatalogConfig, promotionsConfig: PromotionsConfig) class PriceSummaryConfigProvider(config: Config, defaultStage: Stage) extends TouchpointConfigProvider[PriceSummaryConfig](config, defaultStage) { - override protected def fromConfig(config: Config) = { + override protected def fromConfig(config: Config): PriceSummaryConfig = { PriceSummaryConfig( CatalogConfig.fromConfig(config), PromotionsConfig.fromConfig(config), diff --git a/support-frontend/app/actions/CacheControl.scala b/support-frontend/app/actions/CacheControl.scala index 5a163b8f46..c54fc6998e 100644 --- a/support-frontend/app/actions/CacheControl.scala +++ b/support-frontend/app/actions/CacheControl.scala @@ -7,7 +7,7 @@ import HttpHeaders._ object CacheControl { - val defaultStaleIfErrors = 10.days + val defaultStaleIfErrors: FiniteDuration = 10.days def browser(maxAge: FiniteDuration): (String, String) = { "Cache-Control" -> standardDirectives(maxAge, 1.second max (maxAge / 10), defaultStaleIfErrors) diff --git a/support-frontend/app/actions/CachedActionBuilder.scala b/support-frontend/app/actions/CachedActionBuilder.scala index eba053ed97..222900414c 100644 --- a/support-frontend/app/actions/CachedActionBuilder.scala +++ b/support-frontend/app/actions/CachedActionBuilder.scala @@ -13,10 +13,10 @@ class CachedActionBuilder( val headers: List[(String, String)], ) extends ActionBuilder[Request, AnyContent] { - implicit private val ec = executionContext + implicit private val ec: ExecutionContext = executionContext private val maximumBrowserAge = 1.minute - override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = + override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = block(request).map(_.withHeaders(mergeHeader("Vary", cacheHeaders() ++ headers): _*)) private def cacheHeaders(now: DateTime = DateTime.now): List[(String, String)] = { diff --git a/support-frontend/app/actions/CustomActionBuilders.scala b/support-frontend/app/actions/CustomActionBuilders.scala index cfed4b0604..f6281a72ef 100644 --- a/support-frontend/app/actions/CustomActionBuilders.scala +++ b/support-frontend/app/actions/CustomActionBuilders.scala @@ -29,7 +29,7 @@ class CustomActionBuilders( featureSwitches: => FeatureSwitches, )(implicit private val ec: ExecutionContext) { - val PrivateAction = + val PrivateAction: PrivateActionBuilder = new PrivateActionBuilder(addToken, checkToken, csrfConfig, cc.parsers.defaultBodyParser, cc.executionContext) /** This is the action builder that should be used for all actions requiring authentication that are triggered by a @@ -109,11 +109,11 @@ class CustomActionBuilders( } - val CachedAction = new CachedAction(cc.parsers.defaultBodyParser, cc.executionContext) + val CachedAction: CachedAction = new CachedAction(cc.parsers.defaultBodyParser, cc.executionContext) - val NoCacheAction = new NoCacheAction(cc.parsers.defaultBodyParser, cc.executionContext) + val NoCacheAction: NoCacheAction = new NoCacheAction(cc.parsers.defaultBodyParser, cc.executionContext) - val GeoTargetedCachedAction = new CachedAction( + val GeoTargetedCachedAction: CachedAction = new CachedAction( cc.parsers.defaultBodyParser, cc.executionContext, List("Vary" -> FastlyGEOIP.fastlyCountryHeader), diff --git a/support-frontend/app/actions/NoCacheActionBuilder.scala b/support-frontend/app/actions/NoCacheActionBuilder.scala index 583863e5f5..da887d7eca 100644 --- a/support-frontend/app/actions/NoCacheActionBuilder.scala +++ b/support-frontend/app/actions/NoCacheActionBuilder.scala @@ -9,9 +9,9 @@ class NoCacheActionBuilder( val executionContext: ExecutionContext, val headers: List[(String, String)], ) extends ActionBuilder[Request, AnyContent] { - implicit private val ec = executionContext + implicit private val ec: ExecutionContext = executionContext - override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = + override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = block(request).map(_.withHeaders(mergeHeader("Vary", List(CacheControl.noCache) ++ headers): _*)) } diff --git a/support-frontend/app/actions/PrivateActionBuilder.scala b/support-frontend/app/actions/PrivateActionBuilder.scala index f59cae59c7..3897639949 100644 --- a/support-frontend/app/actions/PrivateActionBuilder.scala +++ b/support-frontend/app/actions/PrivateActionBuilder.scala @@ -13,11 +13,11 @@ class PrivateActionBuilder( val executionContext: ExecutionContext, ) extends ActionBuilder[Request, AnyContent] { - private implicit val ec = executionContext + private implicit val ec: ExecutionContext = executionContext override def composeAction[A](action: Action[A]): Action[A] = new CSRFAction(action, csrfConfig, addToken, checkToken) - override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = + override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = block(request).map(_.withHeaders(CacheControl.noCache)) } diff --git a/support-frontend/app/admin/ServersideAbTest.scala b/support-frontend/app/admin/ServersideAbTest.scala index e5d4e17155..f2b948abbc 100644 --- a/support-frontend/app/admin/ServersideAbTest.scala +++ b/support-frontend/app/admin/ServersideAbTest.scala @@ -18,7 +18,7 @@ object ServersideAbTest { case object Variant extends Participation object Participation { - implicit val encoder = Encoder.encodeString.contramap[Participation] { + implicit val encoder: Encoder[Participation] = Encoder.encodeString.contramap[Participation] { case Control => "Control" case Variant => "Variant" } diff --git a/support-frontend/app/admin/settings/ContributionTypes.scala b/support-frontend/app/admin/settings/ContributionTypes.scala index 1065a60cff..6fd62cc6b4 100644 --- a/support-frontend/app/admin/settings/ContributionTypes.scala +++ b/support-frontend/app/admin/settings/ContributionTypes.scala @@ -33,7 +33,6 @@ case class ContributionTypes( object ContributionTypes { import io.circe.generic.auto._ - import ContributionType._ implicit val contributionTypesDecoder = Decoder[ContributionTypes] implicit val contributionTypesEncoder = Encoder[ContributionTypes] diff --git a/support-frontend/app/admin/settings/Switches.scala b/support-frontend/app/admin/settings/Switches.scala index 54e0a9f852..d98d39c28a 100644 --- a/support-frontend/app/admin/settings/Switches.scala +++ b/support-frontend/app/admin/settings/Switches.scala @@ -1,8 +1,9 @@ package admin.settings import com.gu.support.encoding.Codec -import io.circe.generic.extras.Configuration -import io.circe.generic.extras.auto._ +import com.gu.support.encoding.Codec.deriveCodec +import io.circe.generic.extras.semiauto.{deriveEnumerationDecoder, deriveEnumerationEncoder} +import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import io.circe.{Decoder, Encoder, Json} import io.circe.optics.JsonPath._ @@ -11,7 +12,6 @@ case object On extends SwitchState(true) case object Off extends SwitchState(false) object SwitchState { - import io.circe.generic.extras.semiauto.{deriveEnumerationDecoder, deriveEnumerationEncoder} implicit val stateDecoder: Decoder[SwitchState] = deriveEnumerationDecoder[SwitchState] implicit val stateEncoder: Encoder[SwitchState] = deriveEnumerationEncoder[SwitchState] } @@ -21,23 +21,35 @@ case class FeatureSwitches( usStripeAccountForSingle: Option[SwitchState], authenticateWithOkta: Option[SwitchState], ) +object FeatureSwitches { + implicit val featureSwitchesCodec: Codec[FeatureSwitches] = deriveCodec +} case class CampaignSwitches( enableContributionsCampaign: Option[SwitchState], forceContributionsCampaign: Option[SwitchState], usEoy2024: Option[SwitchState] = None, ) +object CampaignSwitches { + implicit val campaignSwitchesCodec: Codec[CampaignSwitches] = deriveCodec +} case class SubscriptionsSwitches( enableDigitalSubGifting: Option[SwitchState], useDotcomContactPage: Option[SwitchState], checkoutPostcodeLookup: Option[SwitchState], ) +object SubscriptionsSwitches { + implicit val subscriptionsSwitchesCodec: Codec[SubscriptionsSwitches] = deriveCodec +} case class RecaptchaSwitches( enableRecaptchaBackend: Option[SwitchState], enableRecaptchaFrontend: Option[SwitchState], ) +object RecaptchaSwitches { + implicit val recaptchaSwitchesCodec: Codec[RecaptchaSwitches] = deriveCodec +} case class OneOffPaymentMethodSwitches( stripe: Option[SwitchState], @@ -48,6 +60,9 @@ case class OneOffPaymentMethodSwitches( payPal: Option[SwitchState], amazonPay: Option[SwitchState], ) +object OneOffPaymentMethodSwitches { + implicit val oneOffPaymentMethodSwitchesCodec: Codec[OneOffPaymentMethodSwitches] = deriveCodec +} case class RecurringPaymentMethodSwitches( stripe: Option[SwitchState], @@ -60,12 +75,18 @@ case class RecurringPaymentMethodSwitches( amazonPay: Option[SwitchState], sepa: Option[SwitchState], ) +object RecurringPaymentMethodSwitches { + implicit val recurringPaymentMethodSwitchesCodec: Codec[RecurringPaymentMethodSwitches] = deriveCodec +} case class SubscriptionsPaymentMethodSwitches( directDebit: Option[SwitchState], creditCard: Option[SwitchState], paypal: Option[SwitchState], ) +object SubscriptionsPaymentMethodSwitches { + implicit val subscriptionsPaymentMethodSwitchesCodec: Codec[SubscriptionsPaymentMethodSwitches] = deriveCodec +} case class Switches( oneOffPaymentMethods: OneOffPaymentMethodSwitches, @@ -97,10 +118,8 @@ object Switches { .getOrElse(switchGroup) } - implicit private val customConfig: Configuration = Configuration.default.withDefaults - - private val switchesEncoder = Encoder[Switches] - private val switchesDecoder = Decoder[Switches].prepare(_.withFocus(flattenAllSwitches)) + implicit val switchesEncoder: Encoder[Switches] = deriveEncoder + implicit val switchesDecoder: Decoder[Switches] = deriveDecoder[Switches].prepare(_.withFocus(flattenAllSwitches)) - implicit val switchesCodec = new Codec(switchesEncoder, switchesDecoder) + implicit val switchesCodec: Codec[Switches] = new Codec(switchesEncoder, switchesDecoder) } diff --git a/support-frontend/app/config/Configuration.scala b/support-frontend/app/config/Configuration.scala index 148462f45f..8b76bdff4e 100644 --- a/support-frontend/app/config/Configuration.scala +++ b/support-frontend/app/config/Configuration.scala @@ -10,53 +10,54 @@ import com.typesafe.config.{Config => TypesafeConfig} class Configuration(config: TypesafeConfig) { - lazy val stage = Stage.fromString(config.getString("stage")).get + lazy val stage: Stage = Stage.fromString(config.getString("stage")).get - lazy val sentryDsn = config.getOptionalString("sentry.dsn") + lazy val sentryDsn: Option[String] = config.getOptionalString("sentry.dsn") - lazy val identity = new Identity(config.getConfig("identity")) + lazy val identity: Identity = new Identity(config.getConfig("identity")) - lazy val googleAuth = new GoogleAuth(config.getConfig("googleAuth")) + lazy val googleAuth: GoogleAuth = new GoogleAuth(config.getConfig("googleAuth")) - lazy val getAddressIOConfig = GetAddressIOConfig.fromConfig(config) + lazy val getAddressIOConfig: GetAddressIOConfig = GetAddressIOConfig.fromConfig(config) - lazy val paperRoundConfigProvider = new PaperRoundConfigProvider(config, stage) + lazy val paperRoundConfigProvider: PaperRoundConfigProvider = new PaperRoundConfigProvider(config, stage) - lazy val guardianDomain = GuardianDomain(config.getString("guardianDomain")) + lazy val guardianDomain: GuardianDomain = GuardianDomain(config.getString("guardianDomain")) - lazy val supportUrl = config.getString("support.url") + lazy val supportUrl: String = config.getString("support.url") - lazy val paymentApiUrl = config.getString("paymentApi.url") + lazy val paymentApiUrl: String = config.getString("paymentApi.url") - lazy val membersDataServiceApiUrl = config.getString("membersDataService.api.url") + lazy val membersDataServiceApiUrl: String = config.getString("membersDataService.api.url") - lazy val metricUrl = MetricUrl(config.getString("metric.url")) + lazy val metricUrl: MetricUrl = MetricUrl(config.getString("metric.url")) - lazy val goCardlessConfigProvider = new GoCardlessConfigProvider(config, stage) + lazy val goCardlessConfigProvider: GoCardlessConfigProvider = new GoCardlessConfigProvider(config, stage) - lazy val regularPayPalConfigProvider = new PayPalConfigProvider(config, stage) + lazy val regularPayPalConfigProvider: PayPalConfigProvider = new PayPalConfigProvider(config, stage) - lazy val regularStripeConfigProvider = new StripePublicConfigProvider(config, stage) + lazy val regularStripeConfigProvider: StripePublicConfigProvider = new StripePublicConfigProvider(config, stage) - lazy val oneOffStripeConfigProvider = new StripePublicConfigProvider(config, stage, "oneOffStripe") + lazy val oneOffStripeConfigProvider: StripePublicConfigProvider = + new StripePublicConfigProvider(config, stage, "oneOffStripe") - lazy val amazonPayConfigProvider = new AmazonPayConfigProvider(config, stage) + lazy val amazonPayConfigProvider: AmazonPayConfigProvider = new AmazonPayConfigProvider(config, stage) - lazy val stepFunctionArn = StateMachineArn.fromString(config.getString("supportWorkers.arn")).get + lazy val stepFunctionArn: StateMachineArn = StateMachineArn.fromString(config.getString("supportWorkers.arn")).get lazy val settingsSources: SettingsSources = SettingsSources.fromConfig(config, stage).valueOr(throw _) lazy val fastlyConfig: Option[FastlyConfig] = FastlyConfig.fromConfig(config).valueOr(throw _) - lazy val priceSummaryConfigProvider = new PriceSummaryConfigProvider(config, stage) + lazy val priceSummaryConfigProvider: PriceSummaryConfigProvider = new PriceSummaryConfigProvider(config, stage) - lazy val promotionsConfigProvider = new PromotionsConfigProvider(config, stage) + lazy val promotionsConfigProvider: PromotionsConfigProvider = new PromotionsConfigProvider(config, stage) - lazy val recaptchaConfigProvider = new RecaptchaConfigProvider(config, stage) + lazy val recaptchaConfigProvider: RecaptchaConfigProvider = new RecaptchaConfigProvider(config, stage) - lazy val capiKey = config.getString("capi-key") + lazy val capiKey: String = config.getString("capi-key") - lazy val zuoraConfigProvider = new ZuoraConfigProvider(config, stage) + lazy val zuoraConfigProvider: ZuoraConfigProvider = new ZuoraConfigProvider(config, stage) } object Configuration { diff --git a/support-frontend/app/config/GoogleAuth.scala b/support-frontend/app/config/GoogleAuth.scala index 60cd548d94..8be5b3b879 100644 --- a/support-frontend/app/config/GoogleAuth.scala +++ b/support-frontend/app/config/GoogleAuth.scala @@ -3,11 +3,11 @@ package config import com.typesafe.config.Config class GoogleAuth(config: Config) { - lazy val clientId = config.getString("clientId") + lazy val clientId: String = config.getString("clientId") - lazy val clientSecret = config.getString("clientSecret") + lazy val clientSecret: String = config.getString("clientSecret") - lazy val redirectUrl = config.getString("redirectUrl") + lazy val redirectUrl: String = config.getString("redirectUrl") - lazy val domain = config.getString("domain") + lazy val domain: String = config.getString("domain") } diff --git a/support-frontend/app/config/Identity.scala b/support-frontend/app/config/Identity.scala index 7d460b8cd0..2867a5e2ab 100644 --- a/support-frontend/app/config/Identity.scala +++ b/support-frontend/app/config/Identity.scala @@ -6,32 +6,32 @@ import config.Configuration.IdentityUrl class Identity(config: Config) { - lazy val webappUrl = IdentityUrl(config.getString("webapp.url")) + lazy val webappUrl: IdentityUrl = IdentityUrl(config.getString("webapp.url")) - lazy val apiUrl = config.getString("api.url") + lazy val apiUrl: String = config.getString("api.url") - lazy val apiClientToken = config.getString("api.token") + lazy val apiClientToken: String = config.getString("api.token") - lazy val testUserSecret = config.getString("test.users.secret") + lazy val testUserSecret: String = config.getString("test.users.secret") - lazy val useStub = config.getOptionalBoolean("useStub").getOrElse(false) + lazy val useStub: Boolean = config.getOptionalBoolean("useStub").getOrElse(false) // This cookie indicates that user is signed in - lazy val signedInCookieName = config.getString("signed.in.cookie.name") + lazy val signedInCookieName: String = config.getString("signed.in.cookie.name") // This cookie indicates that user has recently signed out - lazy val signedOutCookieName = config.getString("signed.out.cookie.name") + lazy val signedOutCookieName: String = config.getString("signed.out.cookie.name") // These cookies are used to store OAuth tokens - lazy val idTokenCookieName = config.getString("id.token.cookie.name") - lazy val accessTokenCookieName = config.getString("access.token.cookie.name") - - lazy val oauthClientId = config.getString("oauth.client.id") - lazy val oauthIssuerUrl = config.getString("oauth.issuer.url") - lazy val oauthAudience = config.getString("oauth.audience") - lazy val oauthAuthorizeUrl = config.getString("oauth.authorize.url") - lazy val oauthTokenUrl = config.getString("oauth.token.url") - lazy val oauthCallbackUrl = config.getString("oauth.callback.url") - lazy val oauthEventsCallbackUrl = config.getString("oauth.eventsCallback.url") - lazy val oauthScopes = config.getString("oauth.scopes") + lazy val idTokenCookieName: String = config.getString("id.token.cookie.name") + lazy val accessTokenCookieName: String = config.getString("access.token.cookie.name") + + lazy val oauthClientId: String = config.getString("oauth.client.id") + lazy val oauthIssuerUrl: String = config.getString("oauth.issuer.url") + lazy val oauthAudience: String = config.getString("oauth.audience") + lazy val oauthAuthorizeUrl: String = config.getString("oauth.authorize.url") + lazy val oauthTokenUrl: String = config.getString("oauth.token.url") + lazy val oauthCallbackUrl: String = config.getString("oauth.callback.url") + lazy val oauthEventsCallbackUrl: String = config.getString("oauth.eventsCallback.url") + lazy val oauthScopes: String = config.getString("oauth.scopes") } diff --git a/support-frontend/app/config/StringsConfig.scala b/support-frontend/app/config/StringsConfig.scala index fa44472cdf..a6740d37df 100644 --- a/support-frontend/app/config/StringsConfig.scala +++ b/support-frontend/app/config/StringsConfig.scala @@ -2,13 +2,14 @@ package config import com.typesafe.config.ConfigFactory import config.ConfigImplicits._ +import com.typesafe.config.Config class StringsConfig { - val config = ConfigFactory.load("strings.conf") + val config: Config = ConfigFactory.load("strings.conf") - val contributionsLandingDescription = config.getOptionalString("contributionsLanding.description") - val subscriptionsLandingDescription = config.getOptionalString("subscriptionsLanding.description") - val digitalPackLandingDescription = config.getOptionalString("digitalPackLanding.description") - val weeklyLandingDescription = config.getOptionalString("weeklyLanding.description") - val paperLandingDescription = config.getOptionalString("paperLanding.description") + val contributionsLandingDescription: Option[String] = config.getOptionalString("contributionsLanding.description") + val subscriptionsLandingDescription: Option[String] = config.getOptionalString("subscriptionsLanding.description") + val digitalPackLandingDescription: Option[String] = config.getOptionalString("digitalPackLanding.description") + val weeklyLandingDescription: Option[String] = config.getOptionalString("weeklyLanding.description") + val paperLandingDescription: Option[String] = config.getOptionalString("paperLanding.description") } diff --git a/support-frontend/app/controllers/Application.scala b/support-frontend/app/controllers/Application.scala index e1defe116f..0eb3d95230 100644 --- a/support-frontend/app/controllers/Application.scala +++ b/support-frontend/app/controllers/Application.scala @@ -381,7 +381,7 @@ class Application( ) } - val ausMomentMapSocialImageUrl = + val ausMomentMapSocialImageUrl: String = "https://i.guim.co.uk/img/media/3c2c30cccd48c91f55217bd0d961dbd20cf07274/0_0_1000_525/1000.png?quality=85&s=b1394cf888724cd40646850b807659f0" def ausMomentMap(): Action[AnyContent] = CachedAction() { implicit request => @@ -430,7 +430,7 @@ class Application( countryGroupId: String, productCatalog: JsonObject, queryString: Map[String, Seq[String]], - ) = { + ): (String, String, Option[Int]) = { val maybeSelectedContributionType = queryString .get("selected-contribution-type") .flatMap(_.headOption) @@ -469,37 +469,38 @@ class Application( } } - def redirectContributionsCheckout(countryGroupId: String) = MaybeAuthenticatedAction { implicit request => - implicit val settings: AllSettings = settingsProvider.getAllSettings() + def redirectContributionsCheckout(countryGroupId: String): Action[AnyContent] = MaybeAuthenticatedAction { + implicit request => + implicit val settings: AllSettings = settingsProvider.getAllSettings() - val isTestUser = testUserService.isTestUser(request) - val productCatalog = cachedProductCatalogServiceProvider.fromStage(stage, isTestUser).get() + val isTestUser = testUserService.isTestUser(request) + val productCatalog = cachedProductCatalogServiceProvider.fromStage(stage, isTestUser).get() - val (product, ratePlan, maybeSelectedAmount) = - getProductParamsFromContributionParams(countryGroupId, productCatalog, request.queryString) + val (product, ratePlan, maybeSelectedAmount) = + getProductParamsFromContributionParams(countryGroupId, productCatalog, request.queryString) - /** we currently don't support one-time checkout outside of the contribution checkout. Once this is supported we - * should remove this. - */ - if (product == "OneOff") { - Ok( - contributionsHtml(countryGroupId, None), - ).withSettingsSurrogateKey - } else { - val queryString = request.queryString - "selected-contribution-type" - "selected-amount" ++ Map( - "product" -> Seq(product), - "ratePlan" -> Seq(ratePlan), - ) + /** we currently don't support one-time checkout outside of the contribution checkout. Once this is supported we + * should remove this. + */ + if (product == "OneOff") { + Ok( + contributionsHtml(countryGroupId, None), + ).withSettingsSurrogateKey + } else { + val queryString = request.queryString - "selected-contribution-type" - "selected-amount" ++ Map( + "product" -> Seq(product), + "ratePlan" -> Seq(ratePlan), + ) - val queryStringMaybeWithContributionAmount = maybeSelectedAmount - .map(selectedAmount => queryString + ("contribution" -> Seq(selectedAmount.toString))) - .getOrElse(queryString) + val queryStringMaybeWithContributionAmount = maybeSelectedAmount + .map(selectedAmount => queryString + ("contribution" -> Seq(selectedAmount.toString))) + .getOrElse(queryString) - Redirect(s"/$countryGroupId/checkout", queryStringMaybeWithContributionAmount, MOVED_PERMANENTLY) - } + Redirect(s"/$countryGroupId/checkout", queryStringMaybeWithContributionAmount, MOVED_PERMANENTLY) + } } - def productCheckoutRouter(countryGroupId: String) = MaybeAuthenticatedAction { implicit request => + def productCheckoutRouter(countryGroupId: String): Action[AnyContent] = MaybeAuthenticatedAction { implicit request => implicit val settings: AllSettings = settingsProvider.getAllSettings() val geoData = request.geoData val serversideTests = generateParticipations(Nil) @@ -544,13 +545,14 @@ class Application( ).withSettingsSurrogateKey } - def eventsRouter(countryGroupId: String, eventId: String) = MaybeAuthenticatedAction { implicit request => - implicit val settings: AllSettings = settingsProvider.getAllSettings() - Ok( - views.html.eventsRouter( - user = request.user, - ), - ).withSettingsSurrogateKey + def eventsRouter(countryGroupId: String, eventId: String): Action[AnyContent] = MaybeAuthenticatedAction { + implicit request => + implicit val settings: AllSettings = settingsProvider.getAllSettings() + Ok( + views.html.eventsRouter( + user = request.user, + ), + ).withSettingsSurrogateKey } def appConfigJson: Action[AnyContent] = MaybeAuthenticatedAction { implicit request => diff --git a/support-frontend/app/controllers/ArticleShare.scala b/support-frontend/app/controllers/ArticleShare.scala index 0fa30abea9..739430a7a1 100644 --- a/support-frontend/app/controllers/ArticleShare.scala +++ b/support-frontend/app/controllers/ArticleShare.scala @@ -13,7 +13,7 @@ import services.CapiService import scala.concurrent.{ExecutionContext, Future} object ArticleShare { - val articleIds = List( + val articleIds: List[String] = List( "environment/ng-interactive/2020/oct/05/the-guardian-climate-pledge-2020-environment-emergency-carbon-emissions", "environment/2020/oct/05/the-guardians-climate-promise-we-will-keep-raising-the-alarm", "environment/2020/oct/05/our-world-is-facing-irreversible-destruction-and-still-theres-no-urgency-in-australian-climate-policy", diff --git a/support-frontend/app/controllers/AuthCodeFlowController.scala b/support-frontend/app/controllers/AuthCodeFlowController.scala index 58c6ce3f64..08b43f6ce9 100644 --- a/support-frontend/app/controllers/AuthCodeFlowController.scala +++ b/support-frontend/app/controllers/AuthCodeFlowController.scala @@ -175,21 +175,21 @@ object AuthCodeFlow { object SessionKey { // URL from which the auth flow was triggered, and where the flow should end up - val originUrl = "oauth.originUrl" + val originUrl: String = "oauth.originUrl" // Referring URL of the origin URL - val referringUrl = "oauth.referrerUrl" + val referringUrl: String = "oauth.referrerUrl" // To be compared with state param in callback request to avoid CSRF - val state = "oauth.state" + val state: String = "oauth.state" // Verifier for PKCE. Used to generate code challenge - val codeVerifier = "oauth.codeVerifier" + val codeVerifier: String = "oauth.codeVerifier" } object FlashKey { // Stops an infinite loop by telling authenticated actions that authentication has been tried - val authTried = "oauth.authTried" + val authTried: String = "oauth.authTried" } def urlEncode(s: String): String = URLEncoder.encode(s, UTF_8.name()) diff --git a/support-frontend/app/controllers/DiagnosticsController.scala b/support-frontend/app/controllers/DiagnosticsController.scala index 5b4af9dd82..2e1ef4aae8 100644 --- a/support-frontend/app/controllers/DiagnosticsController.scala +++ b/support-frontend/app/controllers/DiagnosticsController.scala @@ -8,7 +8,7 @@ class DiagnosticsController( actionRefiners: CustomActionBuilders, ) { - val relevantCookies = List( + val relevantCookies: List[String] = List( "gu_user_features_expiry", "gu_paying_member", "GU_AF1", diff --git a/support-frontend/app/controllers/LandingCopyProvider.scala b/support-frontend/app/controllers/LandingCopyProvider.scala index 3d3df314e8..445bdef065 100644 --- a/support-frontend/app/controllers/LandingCopyProvider.scala +++ b/support-frontend/app/controllers/LandingCopyProvider.scala @@ -28,7 +28,11 @@ class LandingCopyProvider( promoCopy <- promotionCopyForPrimaryCountry(queryPromos, productRatePlanIds, country) } yield promoCopy - def getProductRatePlanIdsForCountryGroup(product: Product, countryGroup: CountryGroup, isGift: Boolean) = { + def getProductRatePlanIdsForCountryGroup( + product: Product, + countryGroup: CountryGroup, + isGift: Boolean, + ): List[ProductRatePlanId] = { val environment = TouchPointEnvironments.fromStage(stage) val readerType = if (isGift) Gift else Direct (product, countryGroup) match { diff --git a/support-frontend/app/controllers/RedemptionController.scala b/support-frontend/app/controllers/RedemptionController.scala index fb4392ae5f..5459a69b79 100644 --- a/support-frontend/app/controllers/RedemptionController.scala +++ b/support-frontend/app/controllers/RedemptionController.scala @@ -44,10 +44,10 @@ class RedemptionController( implicit val a: AssetsResolver = assets implicit val settings: AllSettings = settingsProvider.getAllSettings() - val title = "Support the Guardian | Redeem your code" - val id = EmptyDiv("subscriptions-redemption-page") - val js = "subscriptionsRedemptionPage.js" - val css = "subscriptionsRedemptionPage.css" // TODO: Don't need this? + val title: String = "Support the Guardian | Redeem your code" + val id: EmptyDiv = EmptyDiv("subscriptions-redemption-page") + val js: String = "subscriptionsRedemptionPage.js" + val css: String = "subscriptionsRedemptionPage.css" // TODO: Don't need this? def displayForm(redemptionCode: RawRedemptionCode): Action[AnyContent] = MaybeAuthenticatedAction.async { implicit request => diff --git a/support-frontend/app/lib/CustomHttpErrorHandler.scala b/support-frontend/app/lib/CustomHttpErrorHandler.scala index 0db7ba374d..d9673a624a 100644 --- a/support-frontend/app/lib/CustomHttpErrorHandler.scala +++ b/support-frontend/app/lib/CustomHttpErrorHandler.scala @@ -66,7 +66,7 @@ class CustomHttpErrorHandler( ) } - val renderErrorInDev = onProdServerError _ + val renderErrorInDev: (RequestHeader, UsefulException) => Future[Result] = onProdServerError _ override protected def onBadRequest(request: RequestHeader, message: String): Future[Result] = super.onBadRequest(request, message).map(_.withHeaders(CacheControl.noCache)) diff --git a/support-frontend/app/models/identity/responses/IdentityErrorResponse.scala b/support-frontend/app/models/identity/responses/IdentityErrorResponse.scala index 79cc4b9ed6..c44e89cfe4 100644 --- a/support-frontend/app/models/identity/responses/IdentityErrorResponse.scala +++ b/support-frontend/app/models/identity/responses/IdentityErrorResponse.scala @@ -26,8 +26,8 @@ case class IdentityErrorResponse( object IdentityErrorResponse { implicit val reads: Reads[IdentityErrorResponse] = Json.reads[IdentityErrorResponse] - val emailProviderRejectedCode = "email_provider_rejected" - val invalidEmailAddressCode = "invalid_email_address" + val emailProviderRejectedCode: String = "email_provider_rejected" + val invalidEmailAddressCode: String = "invalid_email_address" sealed trait IdentityError { def endpoint: Option[IdentityEndpoint] diff --git a/support-frontend/app/models/identity/responses/SetGuestPasswordResponseCookie.scala b/support-frontend/app/models/identity/responses/SetGuestPasswordResponseCookie.scala index ce0cc4f38c..3bbdcc8361 100644 --- a/support-frontend/app/models/identity/responses/SetGuestPasswordResponseCookie.scala +++ b/support-frontend/app/models/identity/responses/SetGuestPasswordResponseCookie.scala @@ -12,7 +12,7 @@ import scala.concurrent.ExecutionContext // Models a cookie from the cookies field of a successful response from the set guest password endpoint // of the identity api case class SetGuestPasswordResponseCookie(key: String, value: String, sessionCookie: Option[Boolean] = None) { - val isSessionCookie = sessionCookie.getOrElse(false) + val isSessionCookie: Boolean = sessionCookie.getOrElse(false) } object SetGuestPasswordResponseCookie { @@ -23,7 +23,7 @@ object SetGuestPasswordResponseCookie { case class SetGuestPasswordResponseCookies(expiresAt: DateTime, values: List[SetGuestPasswordResponseCookie]) object SetGuestPasswordResponseCookies { - implicit val jodaDateReads = + implicit val jodaDateReads: Reads[DateTime] = Reads[DateTime](js => js.validate[String].map[DateTime](dtString => DateTime.parse(dtString))) implicit val readsCookieResponse: Reads[SetGuestPasswordResponseCookie] = Json.reads[SetGuestPasswordResponseCookie] implicit val readsCookiesResponse: Reads[SetGuestPasswordResponseCookies] = diff --git a/support-frontend/app/monitoring/SentryLogging.scala b/support-frontend/app/monitoring/SentryLogging.scala index 9f28d106cb..5d09fa9af9 100644 --- a/support-frontend/app/monitoring/SentryLogging.scala +++ b/support-frontend/app/monitoring/SentryLogging.scala @@ -43,8 +43,8 @@ object SentryLogging extends SafeLogging { object SentryFilters { - val errorLevelFilter = new ThresholdFilter { setLevel("ERROR") } - val piiFilter = new PiiFilter + val errorLevelFilter: ThresholdFilter = new ThresholdFilter { setLevel("ERROR") } + val piiFilter: PiiFilter = new PiiFilter errorLevelFilter.start() piiFilter.start() diff --git a/support-frontend/app/monitoring/StateMachineMonitor.scala b/support-frontend/app/monitoring/StateMachineMonitor.scala index a24e27a19c..1e15aa6eab 100644 --- a/support-frontend/app/monitoring/StateMachineMonitor.scala +++ b/support-frontend/app/monitoring/StateMachineMonitor.scala @@ -9,7 +9,7 @@ import scala.util.{Failure, Success} class StateMachineMonitor(client: SupportWorkersClient, actorSystem: ActorSystem) extends SafeLogging { - val cloudwatchMetricsPattern = "regular-contributions-state-machine-unavailable" + val cloudwatchMetricsPattern: String = "regular-contributions-state-machine-unavailable" def start(): Unit = { implicit val ec = actorSystem.dispatcher diff --git a/support-frontend/app/services/GoCardlessFrontendService.scala b/support-frontend/app/services/GoCardlessFrontendService.scala index 5245f4d0f5..f848c6714f 100644 --- a/support-frontend/app/services/GoCardlessFrontendService.scala +++ b/support-frontend/app/services/GoCardlessFrontendService.scala @@ -14,7 +14,7 @@ import scala.concurrent.Future class GoCardlessFrontendService(config: GoCardlessConfig) extends GoCardlessService(config) with SafeLogging { - lazy val client = GoCardlessClient.create(config.apiToken, Environment.valueOf(config.environment)) + lazy val client: GoCardlessClient = GoCardlessClient.create(config.apiToken, Environment.valueOf(config.environment)) /** @return * true if either the bank details are correct, or the rate limit for this endpoint is reached. In the latter case diff --git a/support-frontend/app/services/GoCardlessFrontendServiceProvider.scala b/support-frontend/app/services/GoCardlessFrontendServiceProvider.scala index c921e73594..faefa62555 100644 --- a/support-frontend/app/services/GoCardlessFrontendServiceProvider.scala +++ b/support-frontend/app/services/GoCardlessFrontendServiceProvider.scala @@ -8,5 +8,6 @@ import scala.concurrent.ExecutionContext class GoCardlessFrontendServiceProvider(configProvider: GoCardlessConfigProvider)(implicit executionContext: ExecutionContext, ) extends TouchpointServiceProvider[GoCardlessFrontendService, GoCardlessConfig](configProvider) { - override protected def createService(config: GoCardlessConfig) = new GoCardlessFrontendService(config) + override protected def createService(config: GoCardlessConfig): GoCardlessFrontendService = + new GoCardlessFrontendService(config) } diff --git a/support-frontend/app/services/PayPalNvpService.scala b/support-frontend/app/services/PayPalNvpService.scala index d2d89ef8d7..c424e26921 100644 --- a/support-frontend/app/services/PayPalNvpService.scala +++ b/support-frontend/app/services/PayPalNvpService.scala @@ -14,7 +14,7 @@ import scala.util.Try class PayPalNvpService(apiConfig: PayPalConfig, wsClient: WSClient) extends TouchpointService with SafeLogging { - val defaultNVPParams = Map( + val defaultNVPParams: Map[String, String] = Map( "USER" -> apiConfig.user, "PWD" -> apiConfig.password, "SIGNATURE" -> apiConfig.signature, diff --git a/support-frontend/app/services/RecaptchaService.scala b/support-frontend/app/services/RecaptchaService.scala index f24320d693..bbbbfd67f1 100644 --- a/support-frontend/app/services/RecaptchaService.scala +++ b/support-frontend/app/services/RecaptchaService.scala @@ -14,11 +14,11 @@ case class RecaptchaResponse(success: Boolean, `error-codes`: Option[List[String object RecaptchaResponse { implicit val readsGetUserTypeResponse: Reads[RecaptchaResponse] = Json.reads[RecaptchaResponse] implicit val getUserTypeEncoder: Encoder[RecaptchaResponse] = deriveEncoder - val recaptchaFailedCode = "recaptcha_validation_failed" + val recaptchaFailedCode: String = "recaptcha_validation_failed" } class RecaptchaService(wsClient: WSClient)(implicit ec: ExecutionContext) extends SafeLogging { - val recaptchaEndpoint = "https://www.google.com/recaptcha/api/siteverify" + val recaptchaEndpoint: String = "https://www.google.com/recaptcha/api/siteverify" def verify(token: String, secretKey: String): EitherT[Future, String, RecaptchaResponse] = wsClient diff --git a/support-frontend/app/services/StripeSetupIntentService.scala b/support-frontend/app/services/StripeSetupIntentService.scala index 6cf05f8622..81bca7c434 100644 --- a/support-frontend/app/services/StripeSetupIntentService.scala +++ b/support-frontend/app/services/StripeSetupIntentService.scala @@ -1,7 +1,5 @@ package services -import java.nio.charset.StandardCharsets - import cats.data.EitherT import cats.implicits._ import com.amazonaws.regions.Regions @@ -9,22 +7,22 @@ import com.amazonaws.services.lambda.AWSLambdaClientBuilder import com.amazonaws.services.lambda.model.InvokeRequest import com.gu.support.config.{Stage, Stages} import com.typesafe.scalalogging.StrictLogging -import io.circe.{Decoder, Encoder, Json} import io.circe.parser.decode +import io.circe.{Decoder, Encoder, Json} import scala.concurrent.{ExecutionContext, Future} case class LambdaResponse(body: String) object LambdaResponse { import io.circe.generic.auto._ - implicit val decoder = Decoder[LambdaResponse] + implicit val decoder: Decoder[LambdaResponse] = Decoder[LambdaResponse] } case class SetupIntent(client_secret: String) object SetupIntent { import io.circe.generic.auto._ - implicit val decoder = Decoder[SetupIntent] - implicit val encoder = Encoder[SetupIntent] + implicit val decoder: Decoder[SetupIntent] = Decoder[SetupIntent] + implicit val encoder: Encoder[SetupIntent] = Encoder[SetupIntent] } class StripeSetupIntentService(stage: Stage)(implicit ec: ExecutionContext) extends StrictLogging { diff --git a/support-frontend/app/services/TestUserService.scala b/support-frontend/app/services/TestUserService.scala index 818970ae4a..413b2ad4ff 100644 --- a/support-frontend/app/services/TestUserService.scala +++ b/support-frontend/app/services/TestUserService.scala @@ -4,15 +4,16 @@ import java.time.Duration.ofDays import actions.CustomActionBuilders import com.gu.identity.testing.usernames.TestUsernames import play.api.mvc.RequestHeader +import java.time.Duration object TestUserService { def apply(secret: String): TestUserService = new TestUserService(secret) } class TestUserService(secret: String) { - val ValidityPeriod = ofDays(2) + val ValidityPeriod: Duration = ofDays(2) - lazy val testUsers = TestUsernames( + lazy val testUsers: TestUsernames = TestUsernames( com.gu.identity.testing.usernames.Encoder.withSecret(secret), recency = ValidityPeriod, ) diff --git a/support-frontend/app/services/aws/package.scala b/support-frontend/app/services/aws/package.scala index 2c4accd3d8..fb8c1fc43f 100644 --- a/support-frontend/app/services/aws/package.scala +++ b/support-frontend/app/services/aws/package.scala @@ -6,9 +6,9 @@ import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest package object aws { - val ProfileName = "membership" + val ProfileName: String = "membership" - lazy val CredentialsProvider = new AWSCredentialsProviderChain( + lazy val CredentialsProvider: AWSCredentialsProviderChain = new AWSCredentialsProviderChain( new ProfileCredentialsProvider(ProfileName), new InstanceProfileCredentialsProvider(false), ) diff --git a/support-frontend/app/services/paypal/PayPalNvpServiceProvider.scala b/support-frontend/app/services/paypal/PayPalNvpServiceProvider.scala index 2531627772..4b765769ed 100644 --- a/support-frontend/app/services/paypal/PayPalNvpServiceProvider.scala +++ b/support-frontend/app/services/paypal/PayPalNvpServiceProvider.scala @@ -10,6 +10,6 @@ import scala.concurrent.ExecutionContext class PayPalNvpServiceProvider(configProvider: PayPalConfigProvider, wsClient: WSClient)(implicit executionContext: ExecutionContext, ) extends TouchpointServiceProvider[PayPalNvpService, PayPalConfig](configProvider) { - override protected def createService(config: PayPalConfig) = + override protected def createService(config: PayPalConfig): PayPalNvpService = new PayPalNvpService(config, wsClient) } diff --git a/support-frontend/app/services/pricing/DefaultPromotionService.scala b/support-frontend/app/services/pricing/DefaultPromotionService.scala index f2565b35f1..63012a672d 100644 --- a/support-frontend/app/services/pricing/DefaultPromotionService.scala +++ b/support-frontend/app/services/pricing/DefaultPromotionService.scala @@ -32,7 +32,7 @@ object DefaultPromotionService { tierThree: List[String], ) - implicit val decoder = Decoder[DefaultPromotions] + implicit val decoder: Decoder[DefaultPromotions] = Decoder[DefaultPromotions] } class DefaultPromotionServiceS3( diff --git a/support-frontend/app/services/stepfunctions/Client.scala b/support-frontend/app/services/stepfunctions/Client.scala index 42fa8afca8..0f9ae028e3 100644 --- a/support-frontend/app/services/stepfunctions/Client.scala +++ b/support-frontend/app/services/stepfunctions/Client.scala @@ -30,7 +30,7 @@ object Client { new Client(client, arn) } - def generateExecutionName(name: String, l: Long = System.nanoTime()) = { + def generateExecutionName(name: String, l: Long = System.nanoTime()): String = { val uniq = { val bytes = ByteBuffer.allocate(8).putLong(l).array() val encodedString = Base64.getEncoder.encodeToString(bytes) diff --git a/support-frontend/app/services/stepfunctions/ExecutionStatus.scala b/support-frontend/app/services/stepfunctions/ExecutionStatus.scala index 612952f0a1..aa1bd2119e 100644 --- a/support-frontend/app/services/stepfunctions/ExecutionStatus.scala +++ b/support-frontend/app/services/stepfunctions/ExecutionStatus.scala @@ -11,7 +11,7 @@ object ExecutionStatus { object Started extends ExecutionStatus { override def unsuccessful: Boolean = false } object Succeeded extends ExecutionStatus { override def unsuccessful: Boolean = false } - val all = Map( + val all: Map[String, ExecutionStatus] = Map( "ExecutionAborted" -> Aborted, "ExecutionFailed" -> Failed, "ExecutionStarted" -> Started, diff --git a/support-frontend/app/services/stepfunctions/StateMachineArn.scala b/support-frontend/app/services/stepfunctions/StateMachineArn.scala index b78a1216c2..5984e0b965 100644 --- a/support-frontend/app/services/stepfunctions/StateMachineArn.scala +++ b/support-frontend/app/services/stepfunctions/StateMachineArn.scala @@ -10,5 +10,5 @@ object StateMachineArn { } case class StateMachineArn(region: String, accountId: String, id: String) { - val asString = s"arn:aws:states:$region:$accountId:stateMachine:$id" + val asString: String = s"arn:aws:states:$region:$accountId:stateMachine:$id" } diff --git a/support-frontend/app/services/stepfunctions/StateWrapper.scala b/support-frontend/app/services/stepfunctions/StateWrapper.scala index be6cfd150a..5bf8f14e88 100644 --- a/support-frontend/app/services/stepfunctions/StateWrapper.scala +++ b/support-frontend/app/services/stepfunctions/StateWrapper.scala @@ -7,6 +7,7 @@ import io.circe.syntax._ import io.circe.{Decoder, Encoder} import scala.util.Try +import java.nio.charset.Charset class StateWrapper() { implicit private val executionErrorEncoder: Encoder.AsObject[ExecutionError] = deriveEncoder[ExecutionError] @@ -18,7 +19,7 @@ class StateWrapper() { implicit private val wrapperEncoder: Encoder.AsObject[JsonWrapper] = deriveEncoder[JsonWrapper] implicit private val wrapperDecoder: Decoder[JsonWrapper] = deriveDecoder[JsonWrapper] - val utf8 = java.nio.charset.StandardCharsets.UTF_8 + val utf8: Charset = java.nio.charset.StandardCharsets.UTF_8 def wrap[T](state: T, isTestUser: Boolean, isExistingAccount: Boolean)(implicit encoder: Encoder[T]): String = { JsonWrapper(state.asJson, None, RequestInfo(isTestUser, failed = false, Nil, isExistingAccount)).asJson.noSpaces diff --git a/support-frontend/app/utils/CheckoutValidationRules.scala b/support-frontend/app/utils/CheckoutValidationRules.scala index f33b750d17..2563e9a743 100644 --- a/support-frontend/app/utils/CheckoutValidationRules.scala +++ b/support-frontend/app/utils/CheckoutValidationRules.scala @@ -38,7 +38,7 @@ object CheckoutValidationRules { def checkSubscriptionPaymentMethodEnabled( switches: SubscriptionsPaymentMethodSwitches, paymentFields: Either[PaymentFields, RedemptionData], - ) = paymentFields match { + ): Result = paymentFields match { case Left(_: PayPalPaymentFields) => if (switches.paypal.contains(On)) Valid else Invalid("Invalid Payment Method") case Left(_: DirectDebitPaymentFields) => @@ -52,7 +52,7 @@ object CheckoutValidationRules { def checkContributionPaymentMethodEnabled( switches: RecurringPaymentMethodSwitches, paymentFields: Either[PaymentFields, RedemptionData], - ) = paymentFields match { + ): Result = paymentFields match { case Left(_: PayPalPaymentFields) => if (switches.payPal.contains(On)) Valid else Invalid("Invalid Payment Method") case Left(_: DirectDebitPaymentFields) => @@ -82,7 +82,7 @@ object CheckoutValidationRules { product: ProductType, paymentFields: Either[PaymentFields, RedemptionData], switches: Switches, - ) = + ): Result = product match { case _: Contribution | _: SupporterPlus => checkContributionPaymentMethodEnabled( @@ -436,7 +436,7 @@ object PaperValidation extends SafeLogging { def postcodeIsWithinHomeDeliveryArea(postcode: String): Result = M25_POSTCODE_PREFIXES.contains(getPrefix(postcode)).otherwise(s"postcode $postcode is not within M25") - val M25_POSTCODE_OLD_PREFIXES = List( + val M25_POSTCODE_OLD_PREFIXES: List[String] = List( "BR1", "BR2", "BR3", @@ -759,7 +759,7 @@ object PaperValidation extends SafeLogging { "TN16", ) - val M25_NEW_PREFIXES = List( + val M25_NEW_PREFIXES: List[String] = List( "AL2", "BR12", "BR13", @@ -1752,6 +1752,6 @@ object PaperValidation extends SafeLogging { "WD79", ) - val M25_POSTCODE_PREFIXES = M25_POSTCODE_OLD_PREFIXES ++ M25_NEW_PREFIXES + val M25_POSTCODE_PREFIXES: List[String] = M25_POSTCODE_OLD_PREFIXES ++ M25_NEW_PREFIXES } diff --git a/support-frontend/app/utils/FastlyGEOIP.scala b/support-frontend/app/utils/FastlyGEOIP.scala index 63a7cf7889..2ebccc1327 100644 --- a/support-frontend/app/utils/FastlyGEOIP.scala +++ b/support-frontend/app/utils/FastlyGEOIP.scala @@ -5,8 +5,8 @@ import play.api.mvc.Request object FastlyGEOIP { - val fastlyCountryHeader = "X-GU-GeoIP-Country-Code" - val fastlyRegionHeader = "X-GU-GeoIP-Region" + val fastlyCountryHeader: String = "X-GU-GeoIP-Country-Code" + val fastlyRegionHeader: String = "X-GU-GeoIP-Region" implicit class RequestWithFastlyGEOIP(r: Request[_]) { def fastlyCountry: Option[String] = r.headers.get(fastlyCountryHeader) diff --git a/support-frontend/app/wiring/AppComponents.scala b/support-frontend/app/wiring/AppComponents.scala index 9772cdc56c..78081c72f2 100644 --- a/support-frontend/app/wiring/AppComponents.scala +++ b/support-frontend/app/wiring/AppComponents.scala @@ -38,8 +38,8 @@ class AppComponents(context: Context) assetsResolver, allSettingsProvider, ) - override lazy val httpErrorHandler = customHandler - override lazy val errorController = new ErrorController(actionBuilders, customHandler) + override lazy val httpErrorHandler: CustomHttpErrorHandler = customHandler + override lazy val errorController: ErrorController = new ErrorController(actionBuilders, customHandler) final override lazy val corsConfig: CORSConfig = CORSConfig().withOriginsAllowed(_ == appConfig.supportUrl) diff --git a/support-frontend/app/wiring/AppLoader.scala b/support-frontend/app/wiring/AppLoader.scala index ed2c932f29..20c0e94e03 100644 --- a/support-frontend/app/wiring/AppLoader.scala +++ b/support-frontend/app/wiring/AppLoader.scala @@ -13,7 +13,7 @@ import scala.util.{Success, Try} class AppLoader extends ApplicationLoader with StrictLogging { - lazy val CredentialsProvider = AwsCredentialsProviderChain.builder + lazy val CredentialsProvider: AwsCredentialsProviderChain = AwsCredentialsProviderChain.builder .credentialsProviders( ProfileCredentialsProvider.builder.profileName(ProfileName).build, InstanceProfileCredentialsProvider.builder.asyncCredentialUpdateEnabled(false).build, diff --git a/support-frontend/app/wiring/ApplicationConfiguration.scala b/support-frontend/app/wiring/ApplicationConfiguration.scala index 10b6ddd756..fd5385531b 100644 --- a/support-frontend/app/wiring/ApplicationConfiguration.scala +++ b/support-frontend/app/wiring/ApplicationConfiguration.scala @@ -3,6 +3,6 @@ package wiring import config.{Configuration, StringsConfig} trait ApplicationConfiguration { self: AppComponents => - val appConfig = new Configuration(configuration.underlying) - val stringsConfig = new StringsConfig() + val appConfig: Configuration = new Configuration(configuration.underlying) + val stringsConfig: StringsConfig = new StringsConfig() } diff --git a/support-frontend/app/wiring/Assets.scala b/support-frontend/app/wiring/Assets.scala index 46317d9bd4..016fd1ae05 100644 --- a/support-frontend/app/wiring/Assets.scala +++ b/support-frontend/app/wiring/Assets.scala @@ -4,5 +4,5 @@ import assets.AssetsResolver import play.api.BuiltInComponentsFromContext trait Assets { self: BuiltInComponentsFromContext => - val assetsResolver = new AssetsResolver("", "assets.json", environment) + val assetsResolver: AssetsResolver = new AssetsResolver("", "assets.json", environment) } diff --git a/support-frontend/app/wiring/Controllers.scala b/support-frontend/app/wiring/Controllers.scala index 3e2cfea1ba..7b5e6683a0 100644 --- a/support-frontend/app/wiring/Controllers.scala +++ b/support-frontend/app/wiring/Controllers.scala @@ -17,11 +17,12 @@ trait Controllers { with PlayComponents with GoogleAuth => - lazy val assetController = new controllers.Assets(httpErrorHandler, assetsMetadata) - lazy val faviconController = new controllers.Favicon(actionBuilders, appConfig.stage)(fileMimeTypes, implicitly) + lazy val assetController: Assets = new controllers.Assets(httpErrorHandler, assetsMetadata) + lazy val faviconController: Favicon = + new controllers.Favicon(actionBuilders, appConfig.stage)(fileMimeTypes, implicitly) def errorController: ErrorController - lazy val applicationController = new Application( + lazy val applicationController: Application = new Application( actionBuilders, assetsResolver, testUsers, @@ -41,17 +42,17 @@ trait Controllers { appConfig.supportUrl, ) - lazy val diagnosticsController = new DiagnosticsController( + lazy val diagnosticsController: DiagnosticsController = new DiagnosticsController( actionBuilders, ) - lazy val articleShareController = new ArticleShare( + lazy val articleShareController: ArticleShare = new ArticleShare( actionBuilders, controllerComponents, capiService, ) - lazy val subscriptionsController = new SubscriptionsController( + lazy val subscriptionsController: SubscriptionsController = new SubscriptionsController( actionBuilders, priceSummaryServiceProvider, assetsResolver, @@ -61,7 +62,7 @@ trait Controllers { appConfig.supportUrl, ) - lazy val redemptionController = new RedemptionController( + lazy val redemptionController: RedemptionController = new RedemptionController( actionBuilders, assetsResolver, allSettingsProvider, @@ -75,7 +76,7 @@ trait Controllers { appConfig.stage, ) - lazy val digitalPackController = new DigitalSubscriptionController( + lazy val digitalPackController: DigitalSubscriptionController = new DigitalSubscriptionController( priceSummaryServiceProvider, landingCopyProvider, assetsResolver, @@ -92,7 +93,7 @@ trait Controllers { appConfig.supportUrl, ) - lazy val paperController = new PaperSubscriptionController( + lazy val paperController: PaperSubscriptionController = new PaperSubscriptionController( priceSummaryServiceProvider, landingCopyProvider, assetsResolver, @@ -103,7 +104,7 @@ trait Controllers { appConfig.supportUrl, ) - lazy val weeklyController = new WeeklySubscriptionController( + lazy val weeklyController: WeeklySubscriptionController = new WeeklySubscriptionController( priceSummaryServiceProvider, landingCopyProvider, assetsResolver, @@ -114,7 +115,7 @@ trait Controllers { appConfig.supportUrl, ) - lazy val digitalPackFormController = new DigitalSubscriptionFormController( + lazy val digitalPackFormController: DigitalSubscriptionFormController = new DigitalSubscriptionFormController( priceSummaryServiceProvider, assetsResolver, actionBuilders, @@ -128,7 +129,7 @@ trait Controllers { appConfig.stage, ) - lazy val paperFormController = new PaperSubscriptionFormController( + lazy val paperFormController: PaperSubscriptionFormController = new PaperSubscriptionFormController( priceSummaryServiceProvider, assetsResolver, actionBuilders, @@ -142,7 +143,7 @@ trait Controllers { appConfig.stage, ) - lazy val weeklyFormController = new WeeklySubscriptionFormController( + lazy val weeklyFormController: WeeklySubscriptionFormController = new WeeklySubscriptionFormController( priceSummaryServiceProvider, assetsResolver, actionBuilders, @@ -156,7 +157,7 @@ trait Controllers { appConfig.stage, ) - lazy val createSubscriptionController = new CreateSubscriptionController( + lazy val createSubscriptionController: CreateSubscriptionController = new CreateSubscriptionController( supportWorkersClient, actionBuilders, identityService, @@ -169,13 +170,13 @@ trait Controllers { paperRoundServiceProvider, ) - lazy val supportWorkersStatusController = new SupportWorkersStatus( + lazy val supportWorkersStatusController: SupportWorkersStatus = new SupportWorkersStatus( supportWorkersClient, controllerComponents, actionBuilders, ) - lazy val stripeController = new StripeController( + lazy val stripeController: StripeController = new StripeController( components = controllerComponents, actionRefiners = actionBuilders, recaptchaService = recaptchaService, @@ -185,7 +186,7 @@ trait Controllers { appConfig.stage, ) - lazy val payPalRegularController = new PayPalRegular( + lazy val payPalRegularController: PayPalRegular = new PayPalRegular( actionBuilders, assetsResolver, payPalNvpServiceProvider, @@ -194,7 +195,7 @@ trait Controllers { allSettingsProvider, ) - lazy val payPalOneOffController = new PayPalOneOff( + lazy val payPalOneOffController: PayPalOneOff = new PayPalOneOff( actionBuilders, assetsResolver, testUsers, @@ -203,7 +204,7 @@ trait Controllers { allSettingsProvider, ) - lazy val testUsersController = new TestUsersManagement( + lazy val testUsersController: TestUsersManagement = new TestUsersManagement( authAction, controllerComponents, testUsers, @@ -211,15 +212,15 @@ trait Controllers { appConfig.guardianDomain, ) - lazy val authCodeFlowController = + lazy val authCodeFlowController: AuthCodeFlowController = new AuthCodeFlowController(controllerComponents, asyncAuthenticationService, appConfig.identity) - lazy val siteMapController = new SiteMap( + lazy val siteMapController: SiteMap = new SiteMap( actionBuilders, controllerComponents, ) - lazy val identityController = new IdentityController( + lazy val identityController: IdentityController = new IdentityController( identityService, controllerComponents, actionBuilders, @@ -227,20 +228,20 @@ trait Controllers { () => AwsCloudWatchMetricPut(AwsCloudWatchMetricPut.client)(setupWarningRequest(appConfig.stage)), ) - lazy val directDebitController = new DirectDebit( + lazy val directDebitController: DirectDebit = new DirectDebit( actionBuilders, controllerComponents, goCardlessServiceProvider, testUsers, ) - lazy val getAddressController = new GetAddress( + lazy val getAddressController: GetAddress = new GetAddress( controllerComponents, getAddressIOService, actionBuilders, ) - lazy val paperRoundController = new PaperRound( + lazy val paperRoundController: PaperRound = new PaperRound( controllerComponents, paperRoundServiceProvider, actionBuilders, @@ -248,7 +249,7 @@ trait Controllers { appConfig.stage, ) - lazy val promotionsController = new Promotions( + lazy val promotionsController: Promotions = new Promotions( promotionServiceProvider, priceSummaryServiceProvider, assetsResolver, @@ -259,7 +260,7 @@ trait Controllers { appConfig.stage, ) - lazy val pricesController = new PricesController( + lazy val pricesController: PricesController = new PricesController( priceSummaryServiceProvider, actionBuilders, controllerComponents, diff --git a/support-frontend/app/wiring/GoogleAuth.scala b/support-frontend/app/wiring/GoogleAuth.scala index 8b31dfe229..78bf00e4a3 100644 --- a/support-frontend/app/wiring/GoogleAuth.scala +++ b/support-frontend/app/wiring/GoogleAuth.scala @@ -19,8 +19,8 @@ trait GoogleAuth { antiForgeryChecker = AntiForgeryChecker.borrowSettingsFromPlay(httpConfiguration), ) - val authAction = + val authAction: AuthAction[AnyContent] = new AuthAction[AnyContent](googleAuthConfig, routes.Login.loginAction(), controllerComponents.parsers.default) - val loginController = new Login(googleAuthConfig, wsClient, controllerComponents) + val loginController: Login = new Login(googleAuthConfig, wsClient, controllerComponents) } diff --git a/support-frontend/app/wiring/Services.scala b/support-frontend/app/wiring/Services.scala index 5dae2bf660..9c31408fa7 100644 --- a/support-frontend/app/wiring/Services.scala +++ b/support-frontend/app/wiring/Services.scala @@ -25,13 +25,16 @@ trait Services { implicit val implicitWs: WSClient = wsClient implicit private val s3Client: AwsS3Client = AwsS3Client - lazy val payPalNvpServiceProvider = new PayPalNvpServiceProvider(appConfig.regularPayPalConfigProvider, wsClient) + lazy val payPalNvpServiceProvider: PayPalNvpServiceProvider = + new PayPalNvpServiceProvider(appConfig.regularPayPalConfigProvider, wsClient) - lazy val identityService = IdentityService(appConfig.identity) + lazy val identityService: IdentityService = IdentityService(appConfig.identity) - lazy val goCardlessServiceProvider = new GoCardlessFrontendServiceProvider(appConfig.goCardlessConfigProvider) + lazy val goCardlessServiceProvider: GoCardlessFrontendServiceProvider = new GoCardlessFrontendServiceProvider( + appConfig.goCardlessConfigProvider, + ) - lazy val supportWorkersClient = { + lazy val supportWorkersClient: SupportWorkersClient = { val stateWrapper = new StateWrapper() SupportWorkersClient( appConfig.stepFunctionArn, @@ -41,43 +44,47 @@ trait Services { ) } - lazy val capiService = new CapiService(wsClient, appConfig.capiKey) + lazy val capiService: CapiService = new CapiService(wsClient, appConfig.capiKey) - lazy val testUsers = TestUserService(appConfig.identity.testUserSecret) + lazy val testUsers: TestUserService = TestUserService(appConfig.identity.testUserSecret) - lazy val asyncAuthenticationService = AsyncAuthenticationService(appConfig.identity, wsClient) + lazy val asyncAuthenticationService: AsyncAuthenticationService = + AsyncAuthenticationService(appConfig.identity, wsClient) - lazy val oktaAuthService = OktaAuthService[DefaultAccessClaims, UserClaims]( - config = OktaTokenValidationConfig( - issuerUrl = OktaIssuerUrl(appConfig.identity.oauthIssuerUrl), - audience = Some(OktaAudience(appConfig.identity.oauthAudience)), - clientId = Some(OktaClientId(appConfig.identity.oauthClientId)), - ), - defaultIdentityClaimsParser = UserClaims.parser, - ) + lazy val oktaAuthService: OktaAuthService[DefaultAccessClaims, UserClaims] = + OktaAuthService[DefaultAccessClaims, UserClaims]( + config = OktaTokenValidationConfig( + issuerUrl = OktaIssuerUrl(appConfig.identity.oauthIssuerUrl), + audience = Some(OktaAudience(appConfig.identity.oauthAudience)), + clientId = Some(OktaClientId(appConfig.identity.oauthClientId)), + ), + defaultIdentityClaimsParser = UserClaims.parser, + ) - lazy val userFromAuthCookiesOrAuthServerActionBuilder = new UserFromAuthCookiesOrAuthServerActionBuilder( - controllerComponents.parsers.defaultBodyParser, - oktaAuthService, - appConfig.identity, - isAuthServerUp = asyncAuthenticationService.isAuthServerUp, - ) + lazy val userFromAuthCookiesOrAuthServerActionBuilder: UserFromAuthCookiesOrAuthServerActionBuilder = + new UserFromAuthCookiesOrAuthServerActionBuilder( + controllerComponents.parsers.defaultBodyParser, + oktaAuthService, + appConfig.identity, + isAuthServerUp = asyncAuthenticationService.isAuthServerUp, + ) - lazy val userFromAuthCookiesActionBuilder = new UserFromAuthCookiesActionBuilder( + lazy val userFromAuthCookiesActionBuilder: UserFromAuthCookiesActionBuilder = new UserFromAuthCookiesActionBuilder( controllerComponents.parsers.defaultBodyParser, oktaAuthService, appConfig.identity, ) - lazy val paymentAPIService = new PaymentAPIService(wsClient, appConfig.paymentApiUrl) + lazy val paymentAPIService: PaymentAPIService = new PaymentAPIService(wsClient, appConfig.paymentApiUrl) - lazy val recaptchaService = new RecaptchaService(wsClient) + lazy val recaptchaService: RecaptchaService = new RecaptchaService(wsClient) - lazy val stripeService = new StripeSetupIntentService(appConfig.stage) + lazy val stripeService: StripeSetupIntentService = new StripeSetupIntentService(appConfig.stage) lazy val allSettingsProvider: AllSettingsProvider = AllSettingsProvider.fromConfig(appConfig).valueOr(throw _) - lazy val defaultPromotionService = new DefaultPromotionServiceS3(s3Client, appConfig.stage, actorSystem) + lazy val defaultPromotionService: DefaultPromotionServiceS3 = + new DefaultPromotionServiceS3(s3Client, appConfig.stage, actorSystem) lazy val priceSummaryServiceProvider: PriceSummaryServiceProvider = new PriceSummaryServiceProvider(appConfig.priceSummaryConfigProvider, defaultPromotionService) @@ -88,7 +95,9 @@ trait Services { lazy val paperRoundServiceProvider: PaperRoundServiceProvider = new PaperRoundServiceProvider(appConfig.paperRoundConfigProvider) - lazy val promotionServiceProvider = new PromotionServiceProvider(appConfig.promotionsConfigProvider) + lazy val promotionServiceProvider: PromotionServiceProvider = new PromotionServiceProvider( + appConfig.promotionsConfigProvider, + ) lazy val zuoraGiftLookupServiceProvider: ZuoraGiftLookupServiceProvider = new ZuoraGiftLookupServiceProvider(appConfig.zuoraConfigProvider, appConfig.stage) diff --git a/support-frontend/test/actions/ActionRefinerTest.scala b/support-frontend/test/actions/ActionRefinerTest.scala index e83bf1ee69..1991bbc2be 100644 --- a/support-frontend/test/actions/ActionRefinerTest.scala +++ b/support-frontend/test/actions/ActionRefinerTest.scala @@ -17,13 +17,14 @@ import services._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future +import play.api.mvc.AnyContentAsEmpty class ActionRefinerTest extends AnyWordSpec with Matchers with TestCSRFComponents with MockitoSugar { - val path = "/test-path" - val fakeRequest = FakeRequest("GET", path) - val stage = Stages.DEV - val featureSwitches = + val path: String = "/test-path" + val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest("GET", path) + val stage: Stages.DEV.type = Stages.DEV + val featureSwitches: FeatureSwitches = FeatureSwitches( enableQuantumMetric = Some(On), usStripeAccountForSingle = Some(On), @@ -31,9 +32,10 @@ class ActionRefinerTest extends AnyWordSpec with Matchers with TestCSRFComponent ) trait Mocks { - val asyncAuthenticationService = mock[AsyncAuthenticationService] - val userFromAuthCookiesOrAuthServerActionBuilder = mock[UserFromAuthCookiesOrAuthServerActionBuilder] - val userFromAuthCookiesActionBuilder = mock[UserFromAuthCookiesActionBuilder] + val asyncAuthenticationService: AsyncAuthenticationService = mock[AsyncAuthenticationService] + val userFromAuthCookiesOrAuthServerActionBuilder: UserFromAuthCookiesOrAuthServerActionBuilder = + mock[UserFromAuthCookiesOrAuthServerActionBuilder] + val userFromAuthCookiesActionBuilder: UserFromAuthCookiesActionBuilder = mock[UserFromAuthCookiesActionBuilder] } "PrivateAction" should { diff --git a/support-frontend/test/actions/CachedActionTest.scala b/support-frontend/test/actions/CachedActionTest.scala index 1edba6e6ee..47b4e82320 100644 --- a/support-frontend/test/actions/CachedActionTest.scala +++ b/support-frontend/test/actions/CachedActionTest.scala @@ -11,13 +11,14 @@ import utils.FastlyGEOIP import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global +import play.api.mvc.ControllerComponents class CachedActionTest extends AnyWordSpec with Matchers { - val cc = stubControllerComponents() - val cachedAction = new CachedAction(cc.parsers.defaultBodyParser, cc.executionContext) + val cc: ControllerComponents = stubControllerComponents() + val cachedAction: CachedAction = new CachedAction(cc.parsers.defaultBodyParser, cc.executionContext) - val geoCachedAction = new CachedAction( + val geoCachedAction: CachedAction = new CachedAction( cc.parsers.defaultBodyParser, cc.executionContext, List("Vary" -> FastlyGEOIP.fastlyCountryHeader), diff --git a/support-frontend/test/admin/settings/SwitchesSpec.scala b/support-frontend/test/admin/settings/SwitchesSpec.scala index b0f5a3e55d..28d691167a 100644 --- a/support-frontend/test/admin/settings/SwitchesSpec.scala +++ b/support-frontend/test/admin/settings/SwitchesSpec.scala @@ -152,7 +152,7 @@ class SwitchesSpec extends AnyWordSpec with Matchers { |} |""".stripMargin - decode[Switches](json) mustBe (Right( + decode[Switches](json) mustBe Right( Switches( oneOffPaymentMethods = OneOffPaymentMethodSwitches(Some(On), Some(On), Some(On), Some(On), Some(On), Some(On)), @@ -172,7 +172,7 @@ class SwitchesSpec extends AnyWordSpec with Matchers { campaignSwitches = CampaignSwitches(Some(Off), Some(Off)), recaptchaSwitches = RecaptchaSwitches(Some(On), Some(On)), ), - )) + ) } } } diff --git a/support-frontend/test/controllers/ApplicationTest.scala b/support-frontend/test/controllers/ApplicationTest.scala index 28c8119f2b..9a142fdab7 100644 --- a/support-frontend/test/controllers/ApplicationTest.scala +++ b/support-frontend/test/controllers/ApplicationTest.scala @@ -25,13 +25,14 @@ import services.pricing.{CountryGroupPrices, PriceSummaryService, PriceSummarySe import scala.concurrent.ExecutionContext import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ +import io.circe.JsonObject class ApplicationTest extends AnyWordSpec with Matchers with TestCSRFComponents with EitherValues { - implicit val timeout = Timeout(2.seconds) - val stage = Stages.DEV + implicit val timeout: Timeout = Timeout(2.seconds) + val stage: Stages.DEV.type = Stages.DEV - val actionRefiner = new CustomActionBuilders( + val actionRefiner: CustomActionBuilders = new CustomActionBuilders( asyncAuthenticationService = mock[AsyncAuthenticationService], userFromAuthCookiesOrAuthServerActionBuilder = mock[UserFromAuthCookiesOrAuthServerActionBuilder], userFromAuthCookiesActionBuilder = mock[UserFromAuthCookiesActionBuilder], @@ -43,7 +44,7 @@ class ApplicationTest extends AnyWordSpec with Matchers with TestCSRFComponents featureSwitches = FeatureSwitches(Some(On), Some(On), Some(On)), ) - val priceSummaryServiceProvider = { + val priceSummaryServiceProvider: PriceSummaryServiceProvider = { val priceSummaryService = mock[PriceSummaryService] when( priceSummaryService @@ -55,7 +56,7 @@ class ApplicationTest extends AnyWordSpec with Matchers with TestCSRFComponents priceSummaryServiceProvider } - val applicationMock = new Application( + val applicationMock: Application = new Application( actionRefiner, mock[AssetsResolver], mock[TestUserService], @@ -96,7 +97,7 @@ class ApplicationTest extends AnyWordSpec with Matchers with TestCSRFComponents } - val productCatalogJson = io.circe.parser + val productCatalogJson: JsonObject = io.circe.parser .parse(""" { "SupporterPlus": { diff --git a/support-frontend/test/controllers/CreateSubscriptionDeserialisationTest.scala b/support-frontend/test/controllers/CreateSubscriptionDeserialisationTest.scala index a8b929890d..9712beb45c 100644 --- a/support-frontend/test/controllers/CreateSubscriptionDeserialisationTest.scala +++ b/support-frontend/test/controllers/CreateSubscriptionDeserialisationTest.scala @@ -23,7 +23,7 @@ class CreateSubscriptionDeserialisationTest extends AnyFlatSpec with Matchers wi } object CreateSubscriptionDeserialisationTest { - val testData = List( + val testData: List[String] = List( """{"firstName":"FN","lastName":"LN","deliveryAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"billingAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"email":"email@gu.com","giftRecipient":{"title":"Dr","firstName":"FN","lastName":"LN","email":"email@gu.com"},"product":{"productType":"GuardianWeekly","currency":"GBP","billingPeriod":"Annual","fulfilmentOptions":"Domestic"},"firstDeliveryDate":"2024-03-15","paymentFields":{"accountHolderName":"ACNAME","sortCode":"200000","accountNumber":"55779911","recaptchaToken":"RT"},"ophanIds":{"pageviewId":"PVID","browserId":null},"referrerAcquisitionData":{"referrerPageviewId":"REFID","campaignCode":"CAMCODE","componentType":"COMTY","source":"SRC","queryParameters":[]},"supportAbTests":[],"promoCode":null,"debugInfo":"deleted"}""", """{"firstName":"FN","lastName":"LN","deliveryAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"billingAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"email":"email@gu.com","giftRecipient":{"title":"Dr","firstName":"FN","lastName":"LN","email":"email@gu.com"},"product":{"productType":"GuardianWeekly","currency":"GBP","billingPeriod":"Annual","fulfilmentOptions":"Domestic"},"firstDeliveryDate":"2024-03-15","paymentFields":{"paymentMethod":"PM","stripePaymentType":"StripeElements","recaptchaToken":"RT"},"ophanIds":{"pageviewId":"PVID","browserId":null},"referrerAcquisitionData":{"referrerPageviewId":"REFID","campaignCode":"CAMCODE","componentType":"COMTY","source":"SRC","queryParameters":[]},"supportAbTests":[],"promoCode":null,"debugInfo":"deleted"}""", """{"firstName":"FN","lastName":"LN","deliveryAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"billingAddress":{"country":"GB","state":null,"lineOne":"L1","lineTwo":null,"postCode":"N1 9GU","city":"CITY","errors":[],"errorObject":{}},"email":"email@gu.com","giftRecipient":{"title":"Dr","firstName":"FN","lastName":"LN","email":"email@gu.com"},"product":{"productType":"GuardianWeekly","currency":"GBP","billingPeriod":"Quarterly","fulfilmentOptions":"Domestic"},"firstDeliveryDate":"2024-03-15","paymentFields":{"accountHolderName":"ACNAME","sortCode":"200000","accountNumber":"55779911","recaptchaToken":"RT"},"ophanIds":{"pageviewId":"PVID","browserId":null},"referrerAcquisitionData":{"referrerPageviewId":"REFID","campaignCode":"CAMCODE","componentType":"COMTY","source":"SRC","queryParameters":[]},"supportAbTests":[],"promoCode":null,"debugInfo":"deleted"}""", diff --git a/support-frontend/test/controllers/SiteMapTest.scala b/support-frontend/test/controllers/SiteMapTest.scala index 765231f943..d9e82ce444 100644 --- a/support-frontend/test/controllers/SiteMapTest.scala +++ b/support-frontend/test/controllers/SiteMapTest.scala @@ -18,10 +18,10 @@ import scala.concurrent.duration._ class SiteMapTest extends AnyWordSpec with Matchers with TestCSRFComponents { - implicit val timeout = Timeout(2.seconds) - val stage = Stages.DEV + implicit val timeout: Timeout = Timeout(2.seconds) + val stage: Stages.DEV.type = Stages.DEV - val actionRefiner = new CustomActionBuilders( + val actionRefiner: CustomActionBuilders = new CustomActionBuilders( asyncAuthenticationService = mock[AsyncAuthenticationService], userFromAuthCookiesOrAuthServerActionBuilder = mock[UserFromAuthCookiesOrAuthServerActionBuilder], userFromAuthCookiesActionBuilder = mock[UserFromAuthCookiesActionBuilder], diff --git a/support-frontend/test/controllers/SubscriptionsTest.scala b/support-frontend/test/controllers/SubscriptionsTest.scala index c4828f5086..ed22c0b316 100644 --- a/support-frontend/test/controllers/SubscriptionsTest.scala +++ b/support-frontend/test/controllers/SubscriptionsTest.scala @@ -27,35 +27,36 @@ import play.api.test.Helpers.{contentAsString, status, stubControllerComponents, import services.{CachedProductCatalogService, CachedProductCatalogServiceProvider, TestUserService} import scala.concurrent.Future +import com.typesafe.config.Config class SubscriptionsTest extends AnyWordSpec with Matchers with TestCSRFComponents { - val appConf = ConfigFactory.load("DEV.public.conf") + val appConf: Config = ConfigFactory.load("DEV.public.conf") trait DigitalSubscriptionsDisplayForm extends DisplayFormMocks { import scala.concurrent.ExecutionContext.Implicits.global - val amount = 25 - val selection = AmountsSelection( + val amount: Int = 25 + val selection: AmountsSelection = AmountsSelection( amounts = List(amount), defaultAmount = 25, hideChooseYourAmount = Option(false), ) - val amountsCardData = ContributionAmounts( + val amountsCardData: ContributionAmounts = ContributionAmounts( ONE_OFF = selection, MONTHLY = selection, ANNUAL = selection, ) - val amountsVariant = AmountsVariant( + val amountsVariant: AmountsVariant = AmountsVariant( variantName = "subscriptions-test-variant", defaultContributionType = "MONTHLY", displayContributionType = List("ONE_OFF", "MONTHLY", "ANNUAL"), amountsCardData = amountsCardData, ) - val amountsTest = AmountsTest( + val amountsTest: AmountsTest = AmountsTest( testName = "subscriptions-default-test", liveTestName = Option("subscriptions-AB-test"), testLabel = Option("Subscription AB Test"), @@ -66,15 +67,15 @@ class SubscriptionsTest extends AnyWordSpec with Matchers with TestCSRFComponent variants = List(amountsVariant), ) - val amountsTests = List(amountsTest) + val amountsTests: List[AmountsTest] = List(amountsTest) - val contributionTypesSettings = List( + val contributionTypesSettings: List[ContributionTypeSetting] = List( ContributionTypeSetting( contributionType = ONE_OFF, isDefault = Some(true), ), ) - val contributionTypes = ContributionTypes( + val contributionTypes: ContributionTypes = ContributionTypes( GBPCountries = contributionTypesSettings, UnitedStates = contributionTypesSettings, EURCountries = contributionTypesSettings, @@ -84,7 +85,7 @@ class SubscriptionsTest extends AnyWordSpec with Matchers with TestCSRFComponent Canada = contributionTypesSettings, ) - val allSettings = AllSettings( + val allSettings: AllSettings = AllSettings( Switches( oneOffPaymentMethods = OneOffPaymentMethodSwitches(Some(On), Some(On), Some(On), Some(On), Some(On), Some(On)), recurringPaymentMethods = RecurringPaymentMethodSwitches( diff --git a/support-frontend/test/fixtures/DisplayFormMocks.scala b/support-frontend/test/fixtures/DisplayFormMocks.scala index f33c34e171..cef0bed1fd 100644 --- a/support-frontend/test/fixtures/DisplayFormMocks.scala +++ b/support-frontend/test/fixtures/DisplayFormMocks.scala @@ -16,29 +16,29 @@ import scala.concurrent.ExecutionContext.Implicits.global trait DisplayFormMocks extends TestCSRFComponents { - val authenticatedIdUser = User("testuser@thegulocal.com", "123") + val authenticatedIdUser: User = User("testuser@thegulocal.com", "123") - val testUsers = new TestUserService("test") { + val testUsers: TestUserService = new TestUserService("test") { override def isTestUser(testUserName: Option[String]): Boolean = testUserName.exists(_.startsWith("test")) } - val assetResolver = new AssetsResolver("", "", mock[Environment]) { + val assetResolver: AssetsResolver = new AssetsResolver("", "", mock[Environment]) { override def apply(path: String): String = path override def apply(path: RefPath): String = path.value override protected def loadSsrHtmlCache: Map[String, Html] = Map() } - val idUser = User( + val idUser: User = User( id = "123", primaryEmailAddress = "test@thegulocal.com", publicFields = PublicFields(displayName = Some("test-user")), ) - val asyncAuthenticationService = mock[AsyncAuthenticationService] + val asyncAuthenticationService: AsyncAuthenticationService = mock[AsyncAuthenticationService] - val stage = Stages.DEV + val stage: Stages.DEV.type = Stages.DEV - val loggedInActionRefiner = new CustomActionBuilders( + val loggedInActionRefiner: CustomActionBuilders = new CustomActionBuilders( asyncAuthenticationService, userFromAuthCookiesOrAuthServerActionBuilder = mock[UserFromAuthCookiesOrAuthServerActionBuilder], userFromAuthCookiesActionBuilder = mock[UserFromAuthCookiesActionBuilder], diff --git a/support-frontend/test/fixtures/TestCSRFComponents.scala b/support-frontend/test/fixtures/TestCSRFComponents.scala index edaa12a3e9..d8ec532793 100644 --- a/support-frontend/test/fixtures/TestCSRFComponents.scala +++ b/support-frontend/test/fixtures/TestCSRFComponents.scala @@ -8,6 +8,7 @@ import play.api.mvc.EssentialFilter import play.api.routing.Router import play.core.DefaultWebCommands import play.filters.csrf.CSRFComponents +import play.filters.csrf.{CSRFAddToken, CSRFCheck, CSRFConfig} trait TestCSRFComponents { @@ -21,7 +22,7 @@ trait TestCSRFComponents { } } - lazy val csrfConfig = appComponents.csrfConfig - lazy val csrfAddToken = appComponents.csrfAddToken - lazy val csrfCheck = appComponents.csrfCheck + lazy val csrfConfig: CSRFConfig = appComponents.csrfConfig + lazy val csrfAddToken: CSRFAddToken = appComponents.csrfAddToken + lazy val csrfCheck: CSRFCheck = appComponents.csrfCheck } diff --git a/support-frontend/test/services/ProductCatalogServiceSpec.scala b/support-frontend/test/services/ProductCatalogServiceSpec.scala index 785b51a388..3f82271c83 100644 --- a/support-frontend/test/services/ProductCatalogServiceSpec.scala +++ b/support-frontend/test/services/ProductCatalogServiceSpec.scala @@ -11,10 +11,10 @@ import org.scalatest.matchers.should.Matchers */ @IntegrationTest class ProductCatalogServiceSpec extends AsyncFlatSpec with Matchers { - val prodService = + val prodService: ProdProductCatalogService = new ProdProductCatalogService(RequestRunners.futureRunner) - val codeService = + val codeService: CodeProductCatalogService = new CodeProductCatalogService(RequestRunners.futureRunner) "ProdProductCatalogServiceSpec" should "get" in { diff --git a/support-frontend/test/services/pricing/PriceSummaryServiceIntegrationSpec.scala b/support-frontend/test/services/pricing/PriceSummaryServiceIntegrationSpec.scala index 9af494db79..4b515c189c 100644 --- a/support-frontend/test/services/pricing/PriceSummaryServiceIntegrationSpec.scala +++ b/support-frontend/test/services/pricing/PriceSummaryServiceIntegrationSpec.scala @@ -22,7 +22,7 @@ case class PromoTestData( currency: Currency, ) object PromoTestData { - val t3Promos = List( + val t3Promos: List[PromoTestData] = List( PromoTestData("TIER3_UK_MONTHLY", UK, Monthly, GBP), PromoTestData("TIER3_UK_ANNUAL", UK, Annual, GBP), PromoTestData("TIER3_US_MONTHLY", US, Monthly, USD), @@ -42,9 +42,10 @@ object PromoTestData { @IntegrationTest class PriceSummaryServiceIntegrationSpec extends AsyncFlatSpec with Matchers with LazyLogging { - val actorSystem = ActorSystem("test") - val defaultPromotionsService = new DefaultPromotionServiceS3(AwsS3Client, Stages.DEV, actorSystem) - val service = + val actorSystem: ActorSystem = ActorSystem("test") + val defaultPromotionsService: DefaultPromotionServiceS3 = + new DefaultPromotionServiceS3(AwsS3Client, Stages.DEV, actorSystem) + val service: PriceSummaryService = new PriceSummaryService( PromotionServiceSpec.serviceWithDynamo, defaultPromotionsService, diff --git a/support-frontend/test/services/pricing/PriceSummaryServiceSpec.scala b/support-frontend/test/services/pricing/PriceSummaryServiceSpec.scala index 979e0d7b3f..e31be6328f 100644 --- a/support-frontend/test/services/pricing/PriceSummaryServiceSpec.scala +++ b/support-frontend/test/services/pricing/PriceSummaryServiceSpec.scala @@ -19,7 +19,7 @@ import org.scalatest.matchers.should.Matchers class PriceSummaryServiceSpec extends AsyncFlatSpec with Matchers { - val defaultPromotionsService = new DefaultPromotionService { + val defaultPromotionsService: DefaultPromotionService = new DefaultPromotionService { def getPromoCodes(product: Product): List[String] = Nil } diff --git a/support-frontend/test/services/stepfunctions/SupportWorkersClientTest.scala b/support-frontend/test/services/stepfunctions/SupportWorkersClientTest.scala index 5d40914d0e..7903101ea1 100644 --- a/support-frontend/test/services/stepfunctions/SupportWorkersClientTest.scala +++ b/support-frontend/test/services/stepfunctions/SupportWorkersClientTest.scala @@ -14,19 +14,19 @@ import services.stepfunctions.StepFunctionExecutionStatus._ import scala.util.{Failure, Success} object StatusResults { - val success = StatusResponse(Status.Success, "tracking123", None) + val success: StatusResponse = StatusResponse(Status.Success, "tracking123", None) def failure(reason: CheckoutFailureReason): StatusResponse = StatusResponse(Status.Failure, "tracking123", Some(reason)) - val pending = StatusResponse(Status.Pending, "tracking123", None) + val pending: StatusResponse = StatusResponse(Status.Pending, "tracking123", None) } class SupportWorkersClientTest extends AnyFlatSpec with Matchers with MockitoSugar { val mockStateWrapper: StateWrapper = mock[StateWrapper] - val fillerState = new StateExitedEventDetails + val fillerState: StateExitedEventDetails = new StateExitedEventDetails fillerState.setName("CreatePaymentMethodLambda") - val failure = Failure(new AmazonServiceException("test")) + val failure: Failure[Nothing] = Failure(new AmazonServiceException("test")) "checkoutStatus" should "detect a successful execution correctly" in { val checkoutSuccessState = new StateExitedEventDetails diff --git a/support-frontend/test/utils/CheckoutValidationRulesTest.scala b/support-frontend/test/utils/CheckoutValidationRulesTest.scala index 02b2f4b2ab..d7610683c3 100644 --- a/support-frontend/test/utils/CheckoutValidationRulesTest.scala +++ b/support-frontend/test/utils/CheckoutValidationRulesTest.scala @@ -32,6 +32,7 @@ import utils.CheckoutValidationRules.{Invalid, Valid} import utils.TestData.monthlyDirectUSDProduct import scala.concurrent.Future +import com.gu.support.paperround.{AgentsEndpoint, ChargeBandsEndpoint} class PaymentSwitchValidationTest extends AnyFlatSpec with Matchers { @@ -582,8 +583,9 @@ class PaperValidationTest extends AsyncFlatSpec with Matchers { import TestData.validPaperRequest case class TestPaperRound(agentMap: Map[String, List[BigInt]]) extends PaperRoundAPI { - def toResponse(coverage: PostcodeCoverage) = CoverageEndpoint.Response(200, coverage) - def toAgentsCoverage(agentId: AgentId) = CoverageEndpoint.AgentsCoverage(agentId, "", "", 0, "", AgentId(0), "") + def toResponse(coverage: PostcodeCoverage): CoverageEndpoint.Response = CoverageEndpoint.Response(200, coverage) + def toAgentsCoverage(agentId: AgentId): CoverageEndpoint.AgentsCoverage = + CoverageEndpoint.AgentsCoverage(agentId, "", "", 0, "", AgentId(0), "") def coverage(body: CoverageEndpoint.RequestBody): Future[CoverageEndpoint.Response] = Future { agentMap @@ -592,8 +594,8 @@ class PaperValidationTest extends AsyncFlatSpec with Matchers { toResponse(PostcodeCoverage(List(), "", NC)), )(xs => toResponse(PostcodeCoverage(xs.map(x => toAgentsCoverage(AgentId(x))), "", CO))) } - def agents() = Future.failed(new NotImplementedError("Not used")) - def chargebands() = Future.failed(new NotImplementedError("Not used")) + def agents(): Future[AgentsEndpoint.Response] = Future.failed(new NotImplementedError("Not used")) + def chargebands(): Future[ChargeBandsEndpoint.Response] = Future.failed(new NotImplementedError("Not used")) } "PaperValidation.passes" should "fail if the delivery country is US" in { @@ -792,13 +794,13 @@ object TestData { RecaptchaSwitches(Some(On), Some(On)), ) - val monthlyDirectUSDProduct = DigitalPack(Currency.USD, Monthly) + val monthlyDirectUSDProduct: DigitalPack = DigitalPack(Currency.USD, Monthly) private val stripePaymentFields: StripePaymentFields = StripePaymentFields( paymentMethod = PaymentMethodId("test_token").get, stripePaymentType = Some(StripePaymentType.StripeCheckout), stripePublicKey = Some(StripePublicKey.get("pk_test_asdf")), ) - val validDigitalPackRequest = CreateSupportWorkersRequest( + val validDigitalPackRequest: CreateSupportWorkersRequest = CreateSupportWorkersRequest( title = None, firstName = "grace", lastName = "hopper", @@ -828,8 +830,8 @@ object TestData { debugInfo = None, ) - val someDateNextMonth = new LocalDate().plusMonths(1) - val paperAddress = Address( + val someDateNextMonth: LocalDate = new LocalDate().plusMonths(1) + val paperAddress: Address = Address( lineOne = Some("Address Line 1"), lineTwo = Some("Address Line 2"), city = Some("Address Town"), @@ -837,7 +839,7 @@ object TestData { postCode = Some("N1 9AG"), country = Country.UK, ) - val validPaperRequest = CreateSupportWorkersRequest( + val validPaperRequest: CreateSupportWorkersRequest = CreateSupportWorkersRequest( title = None, firstName = "grace", lastName = "hopper", @@ -860,7 +862,7 @@ object TestData { debugInfo = None, ) - val validWeeklyRequest = CreateSupportWorkersRequest( + val validWeeklyRequest: CreateSupportWorkersRequest = CreateSupportWorkersRequest( title = None, firstName = "grace", lastName = "hopper", diff --git a/support-internationalisation/src/main/scala/com/gu/i18n/Country.scala b/support-internationalisation/src/main/scala/com/gu/i18n/Country.scala index 80d438a259..35eeee15ab 100644 --- a/support-internationalisation/src/main/scala/com/gu/i18n/Country.scala +++ b/support-internationalisation/src/main/scala/com/gu/i18n/Country.scala @@ -11,7 +11,7 @@ case class Country(alpha2: String, name: String, statesByCode: Map[String, Strin object Country { - val US = Country( + val US: Country = Country( alpha2 = "US", name = "United States", statesByCode = Seq( @@ -75,7 +75,7 @@ object Country { ).toMap, ) - val Canada = Country( + val Canada: Country = Country( alpha2 = "CA", name = "Canada", statesByCode = Seq( @@ -95,9 +95,9 @@ object Country { ).toMap, ) - val UK = Country("GB", "United Kingdom") + val UK: Country = Country("GB", "United Kingdom") - val Australia = Country( + val Australia: Country = Country( alpha2 = "AU", name = "Australia", statesByCode = Seq( @@ -112,7 +112,7 @@ object Country { ).toMap, ) - val NewZealand = Country("NZ", "New Zealand") + val NewZealand: Country = Country("NZ", "New Zealand") - val Ireland = Country("IE", "Ireland") + val Ireland: Country = Country("IE", "Ireland") } diff --git a/support-internationalisation/src/main/scala/com/gu/i18n/CountryGroup.scala b/support-internationalisation/src/main/scala/com/gu/i18n/CountryGroup.scala index cd8e887528..feff34b4df 100644 --- a/support-internationalisation/src/main/scala/com/gu/i18n/CountryGroup.scala +++ b/support-internationalisation/src/main/scala/com/gu/i18n/CountryGroup.scala @@ -19,12 +19,12 @@ object CountryGroup { import Currency._ - val C = Country - val Canada = CountryGroup("Canada", "ca", Some(C.Canada), List(C.Canada), CAD, ZipCode) + val C: Country.type = Country + val Canada: CountryGroup = CountryGroup("Canada", "ca", Some(C.Canada), List(C.Canada), CAD, ZipCode) - val US = CountryGroup("United States", "us", Some(C.US), List(C.US), USD, ZipCode) + val US: CountryGroup = CountryGroup("United States", "us", Some(C.US), List(C.US), USD, ZipCode) - val UK = CountryGroup( + val UK: CountryGroup = CountryGroup( "United Kingdom", "uk", Some(C.UK), @@ -41,7 +41,7 @@ object CountryGroup { PostCode, ) - val Australia = CountryGroup( + val Australia: CountryGroup = CountryGroup( "Australia", "au", Some(C.Australia), @@ -56,7 +56,7 @@ object CountryGroup { PostCode, ) - val NewZealand = CountryGroup( + val NewZealand: CountryGroup = CountryGroup( "New Zealand", "nz", Some(C.NewZealand), @@ -68,7 +68,7 @@ object CountryGroup { PostCode, ) - val Europe = CountryGroup( + val Europe: CountryGroup = CountryGroup( "Europe", "eu", None, @@ -133,7 +133,7 @@ object CountryGroup { PostCode, ) - val RestOfTheWorld = CountryGroup( + val RestOfTheWorld: CountryGroup = CountryGroup( "International", "int", None, @@ -323,7 +323,7 @@ object CountryGroup { List(GBP), ) - val allGroups = List( + val allGroups: List[CountryGroup] = List( UK, US, Canada, @@ -337,7 +337,7 @@ object CountryGroup { val countriesByISO2: Map[String, Country] = countries.map { c => c.alpha2 -> c }.toMap - val countriesByISO3 = countries.flatMap { country => + val countriesByISO3: Map[String, Country] = countries.flatMap { country => Try { // getISO3Country will throw a MissingResourceException if the three-letter country abbreviation is not available for this locale val locale = new Locale("", country.alpha2) diff --git a/support-internationalisation/src/main/scala/com/gu/i18n/Currency.scala b/support-internationalisation/src/main/scala/com/gu/i18n/Currency.scala index cae5fdbc34..2ebfcbc009 100644 --- a/support-internationalisation/src/main/scala/com/gu/i18n/Currency.scala +++ b/support-internationalisation/src/main/scala/com/gu/i18n/Currency.scala @@ -10,7 +10,7 @@ sealed trait Currency { case class OtherCurrency(iso: String, glyph: String) extends Currency object Currency { - val websiteSupportedCurrencies = List( + val websiteSupportedCurrencies: List[Currency] = List( GBP, USD, AUD, @@ -19,7 +19,7 @@ object Currency { NZD, ) - val otherCurrencies = Map( + val otherCurrencies: Map[String, String] = Map( "SEK" -> "kr", "CHF" -> "fr.", "NOK" -> "kr", diff --git a/support-internationalisation/src/main/scala/com/gu/i18n/PostalCode.scala b/support-internationalisation/src/main/scala/com/gu/i18n/PostalCode.scala index b6f0f236a7..69f3adc4b2 100644 --- a/support-internationalisation/src/main/scala/com/gu/i18n/PostalCode.scala +++ b/support-internationalisation/src/main/scala/com/gu/i18n/PostalCode.scala @@ -13,9 +13,9 @@ sealed trait PostalCode { } case object PostCode extends PostalCode { - override val name = "Postcode" + override val name: String = "Postcode" } case object ZipCode extends PostalCode { - override val name = "Zip code" + override val name: String = "Zip code" } diff --git a/support-internationalisation/src/main/scala/com/gu/i18n/Title.scala b/support-internationalisation/src/main/scala/com/gu/i18n/Title.scala index 6f9644b37d..28c52bf603 100644 --- a/support-internationalisation/src/main/scala/com/gu/i18n/Title.scala +++ b/support-internationalisation/src/main/scala/com/gu/i18n/Title.scala @@ -3,14 +3,14 @@ package com.gu.i18n case class Title(title: String) object Title { - val Mr = Title("Mr") - val Mrs = Title("Mrs") - val Ms = Title("Ms") - val Miss = Title("Miss") - val Mx = Title("Mx") - val Dr = Title("Dr") - val Prof = Title("Prof") - val Rev = Title("Rev") - val all = Seq(Mr, Mrs, Ms, Miss, Mx, Dr, Prof, Rev) + val Mr: Title = Title("Mr") + val Mrs: Title = Title("Mrs") + val Ms: Title = Title("Ms") + val Miss: Title = Title("Miss") + val Mx: Title = Title("Mx") + val Dr: Title = Title("Dr") + val Prof: Title = Title("Prof") + val Rev: Title = Title("Rev") + val all: Seq[Title] = Seq(Mr, Mrs, Ms, Miss, Mx, Dr, Prof, Rev) def fromString(str: String): Option[Title] = all.find { _.title == str } } diff --git a/support-lambdas/acquisitions-firehose-transformer/src/main/scala/com/gu/acquisitionFirehoseTransformer/AcquisitionToJson.scala b/support-lambdas/acquisitions-firehose-transformer/src/main/scala/com/gu/acquisitionFirehoseTransformer/AcquisitionToJson.scala index bb662deacd..8a4baa61d3 100644 --- a/support-lambdas/acquisitions-firehose-transformer/src/main/scala/com/gu/acquisitionFirehoseTransformer/AcquisitionToJson.scala +++ b/support-lambdas/acquisitions-firehose-transformer/src/main/scala/com/gu/acquisitionFirehoseTransformer/AcquisitionToJson.scala @@ -7,10 +7,11 @@ import io.circe.generic.auto._ import io.circe.syntax._ import org.joda.time.format.DateTimeFormat +import org.joda.time.format.DateTimeFormatter object AcquisitionToJson { - val dtFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") + val dtFormatter: DateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") private case class AcquisitionOutput( paymentFrequency: String, diff --git a/support-lambdas/acquisitions-firehose-transformer/src/test/scala/com/gu/acquisitionFirehoseTransformer/LambdaSpec.scala b/support-lambdas/acquisitions-firehose-transformer/src/test/scala/com/gu/acquisitionFirehoseTransformer/LambdaSpec.scala index 1818b675cf..f565768231 100644 --- a/support-lambdas/acquisitions-firehose-transformer/src/test/scala/com/gu/acquisitionFirehoseTransformer/LambdaSpec.scala +++ b/support-lambdas/acquisitions-firehose-transformer/src/test/scala/com/gu/acquisitionFirehoseTransformer/LambdaSpec.scala @@ -17,7 +17,7 @@ import scala.concurrent.ExecutionContext class LambdaSpec extends AnyFlatSpec with Matchers { - val mockGBPService = new GBPConversionService { + val mockGBPService: GBPConversionService = new GBPConversionService { override def convert(currency: Currency, amount: Double, dateTime: DateTime): Either[String, Double] = Right( amount * 1.2, ) diff --git a/support-lambdas/bigquery-acquisitions-publisher/src/main/scala/com/gu/bigqueryAcquisitionsPublisher/SSMService.scala b/support-lambdas/bigquery-acquisitions-publisher/src/main/scala/com/gu/bigqueryAcquisitionsPublisher/SSMService.scala index c30e33fe60..1d67f2414d 100644 --- a/support-lambdas/bigquery-acquisitions-publisher/src/main/scala/com/gu/bigqueryAcquisitionsPublisher/SSMService.scala +++ b/support-lambdas/bigquery-acquisitions-publisher/src/main/scala/com/gu/bigqueryAcquisitionsPublisher/SSMService.scala @@ -14,18 +14,19 @@ import com.amazonaws.services.simplesystemsmanagement.model.GetParameterRequest import com.gu.aws.ProfileName import scala.util.Try +import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement object SSMService { // please update to AWS SDK 2 and use com.gu.aws.CredentialsProvider - lazy val CredentialsProviderDEPRECATEDV1 = new AWSCredentialsProviderChain( + lazy val CredentialsProviderDEPRECATEDV1: AWSCredentialsProviderChain = new AWSCredentialsProviderChain( new ProfileCredentialsProvider(ProfileName), new InstanceProfileCredentialsProvider(false), new EnvironmentVariableCredentialsProvider(), new EC2ContainerCredentialsProviderWrapper(), // for use with lambda snapstart ) - val client = AWSSimpleSystemsManagementClientBuilder + val client: AWSSimpleSystemsManagement = AWSSimpleSystemsManagementClientBuilder .standard() .withCredentials(CredentialsProviderDEPRECATEDV1) .withRegion(Regions.EU_WEST_1) diff --git a/support-lambdas/it-test-runner/src/main/scala/com/gu/RunITTests.scala b/support-lambdas/it-test-runner/src/main/scala/com/gu/RunITTests.scala index d11048479d..323ae9280f 100644 --- a/support-lambdas/it-test-runner/src/main/scala/com/gu/RunITTests.scala +++ b/support-lambdas/it-test-runner/src/main/scala/com/gu/RunITTests.scala @@ -21,7 +21,7 @@ class RunITTests extends RequestStreamHandler { } object RunITTests { - lazy val stage = System.getenv().asScala.toMap.getOrElse("Stage", "CODE") + lazy val stage: String = System.getenv().asScala.toMap.getOrElse("Stage", "CODE") // todo should we also check the build id to make sure support-workers deploy is keeping the remote jar in sync? def main(args: Array[String]): Unit = { @@ -29,7 +29,7 @@ object RunITTests { } var logger: String => Unit = null - val tempJar = "/tmp/support-workers-it.jar" + val tempJar: String = "/tmp/support-workers-it.jar" def apply(log: String => Unit): String = { logger = log @@ -83,7 +83,7 @@ class ITTestReporter extends Reporter { ), ) - val log = RunITTests.logger + val log: String => Unit = RunITTests.logger override def apply(event: Event): Unit = { event match { diff --git a/support-models/src/main/scala/com/gu/salesforce/Salesforce.scala b/support-models/src/main/scala/com/gu/salesforce/Salesforce.scala index 8322eb6066..38ecfb82c2 100644 --- a/support-models/src/main/scala/com/gu/salesforce/Salesforce.scala +++ b/support-models/src/main/scala/com/gu/salesforce/Salesforce.scala @@ -160,14 +160,15 @@ object Salesforce { def errorMessage: Option[String] = List(buyer.ErrorString, giftRecipient.flatMap(_.ErrorString)).flatten.headOption - def contactRecords = SalesforceContactRecords(buyer.ContactRecord, giftRecipient.map(_.ContactRecord)) + def contactRecords: SalesforceContactRecords = + SalesforceContactRecords(buyer.ContactRecord, giftRecipient.map(_.ContactRecord)) } object SalesforceErrorResponse { implicit val codec: Codec[SalesforceErrorResponse] = deriveCodec - val expiredAuthenticationCode = "INVALID_SESSION_ID" - val rateLimitExceeded = "REQUEST_LIMIT_EXCEEDED" - val readOnlyMaintenance = "INSERT_UPDATE_DELETE_NOT_ALLOWED_DURING_MAINTENANCE" + val expiredAuthenticationCode: String = "INVALID_SESSION_ID" + val rateLimitExceeded: String = "REQUEST_LIMIT_EXCEEDED" + val readOnlyMaintenance: String = "INSERT_UPDATE_DELETE_NOT_ALLOWED_DURING_MAINTENANCE" } case class SalesforceErrorResponse( @@ -175,7 +176,7 @@ object Salesforce { errorCode: String, ) extends Throwable { - val errorsToRetryUnlimited = List( + val errorsToRetryUnlimited: List[String] = List( SalesforceErrorResponse.expiredAuthenticationCode, SalesforceErrorResponse.rateLimitExceeded, SalesforceErrorResponse.readOnlyMaintenance, diff --git a/support-models/src/main/scala/com/gu/support/catalog/FulfilmentOptions.scala b/support-models/src/main/scala/com/gu/support/catalog/FulfilmentOptions.scala index 0d1de5ec6b..9dbacd6063 100644 --- a/support-models/src/main/scala/com/gu/support/catalog/FulfilmentOptions.scala +++ b/support-models/src/main/scala/com/gu/support/catalog/FulfilmentOptions.scala @@ -17,7 +17,7 @@ case object RestOfWorld extends FulfilmentOptions case object NoFulfilmentOptions extends FulfilmentOptions object FulfilmentOptions { - lazy val allFulfilmentOptions = + lazy val allFulfilmentOptions: List[FulfilmentOptions] = List(HomeDelivery, NationalDelivery, Collection, Domestic, RestOfWorld, NoFulfilmentOptions) def fromString(code: String): Option[FulfilmentOptions] = diff --git a/support-models/src/main/scala/com/gu/support/catalog/Product.scala b/support-models/src/main/scala/com/gu/support/catalog/Product.scala index cf1f3f8ce9..1608ae54c6 100644 --- a/support-models/src/main/scala/com/gu/support/catalog/Product.scala +++ b/support-models/src/main/scala/com/gu/support/catalog/Product.scala @@ -7,6 +7,7 @@ import com.gu.support.workers._ import com.gu.support.zuora.api.ReaderType import com.gu.support.zuora.api.ReaderType.{Direct, Gift} import io.circe.{Decoder, Encoder} +import com.gu.support.catalog.ProductRatePlanId sealed trait Product { val ratePlans: Map[TouchPointEnvironment, List[ProductRatePlan[Product]]] @@ -32,9 +33,10 @@ sealed trait Product { ) } - def getProductRatePlans(environment: TouchPointEnvironment) = ratePlans(environment) + def getProductRatePlans(environment: TouchPointEnvironment): List[ProductRatePlan[Product]] = ratePlans(environment) - def getProductRatePlanIds(environment: TouchPointEnvironment) = ratePlans(environment).map(_.id) + def getProductRatePlanIds(environment: TouchPointEnvironment): List[ProductRatePlanId] = + ratePlans(environment).map(_.id) def supportedCountries(environment: TouchPointEnvironment): List[CountryGroup] = ratePlans(environment) diff --git a/support-models/src/main/scala/com/gu/support/catalog/ProductOptions.scala b/support-models/src/main/scala/com/gu/support/catalog/ProductOptions.scala index 1c14a5fd50..b2052a3a08 100644 --- a/support-models/src/main/scala/com/gu/support/catalog/ProductOptions.scala +++ b/support-models/src/main/scala/com/gu/support/catalog/ProductOptions.scala @@ -33,7 +33,7 @@ case object Everyday extends PaperProductOptions(false) case object NewspaperArchive extends ProductOptions object ProductOptions { - val allProductOptions = + val allProductOptions: List[ProductOptions] = NoProductOptions :: NewspaperArchive :: PaperProductOptions.productOptions def fromString[T](code: String, productOptions: List[T]): Option[T] = diff --git a/support-models/src/main/scala/com/gu/support/config/TouchPointEnvironments.scala b/support-models/src/main/scala/com/gu/support/config/TouchPointEnvironments.scala index 455b881b2f..d67a0b1364 100644 --- a/support-models/src/main/scala/com/gu/support/config/TouchPointEnvironments.scala +++ b/support-models/src/main/scala/com/gu/support/config/TouchPointEnvironments.scala @@ -8,7 +8,7 @@ import com.gu.support.config.TouchPointEnvironments.{PROD, CODE} * and CODE for test users */ sealed trait TouchPointEnvironment { - val envValue = this match { + val envValue: String = this match { case CODE => "CODE" case PROD => "PROD" } diff --git a/support-models/src/main/scala/com/gu/support/paperround/PaperRound.scala b/support-models/src/main/scala/com/gu/support/paperround/PaperRound.scala index 47cd0d7dc8..84d6dc618f 100644 --- a/support-models/src/main/scala/com/gu/support/paperround/PaperRound.scala +++ b/support-models/src/main/scala/com/gu/support/paperround/PaperRound.scala @@ -15,7 +15,7 @@ trait PaperRoundAPI { def chargebands(): Future[ChargeBandsEndpoint.Response] } -case class AgentId(val id: BigInt) extends AnyVal +case class AgentId(id: BigInt) extends AnyVal object AgentId { implicit val encoder: Encoder[AgentId] = Encoder.encodeBigInt.contramap(_.id) @@ -41,11 +41,11 @@ object AgentsEndpoint { email: String, ) object AgentDetails { - implicit val config = DecoderConfiguration.lowercase + implicit val config: Configuration = DecoderConfiguration.lowercase implicit val agentDetailsDecoder: Decoder[AgentDetails] = deriveConfiguredDecoder } - implicit val config = DecoderConfiguration.snakeCase + implicit val config: Configuration = DecoderConfiguration.snakeCase implicit val responseDecoder: Decoder[Response] = deriveConfiguredDecoder implicit val agentsListDecoder: Decoder[AgentsList] = deriveConfiguredDecoder } @@ -66,7 +66,7 @@ object ChargeBandsEndpoint { sunday: Double, ) - implicit val config = DecoderConfiguration.snakeCase + implicit val config: Configuration = DecoderConfiguration.snakeCase implicit val responseDecoder: Decoder[Response] = deriveConfiguredDecoder implicit val deliveryChargeProfilesDecoder: Decoder[DeliveryChargeProfiles] = deriveConfiguredDecoder implicit val deliveryChargeProfileDecoder: Decoder[DeliveryChargeProfile] = Decoder.forProduct9( @@ -121,7 +121,7 @@ object CoverageEndpoint { summary: String, ) object AgentsCoverage { - implicit val config = DecoderConfiguration.lowercase + implicit val config: Configuration = DecoderConfiguration.lowercase implicit val decoder: Decoder[AgentsCoverage] = deriveConfiguredDecoder } @@ -142,27 +142,17 @@ object CoverageEndpoint { /** Internal PaperRound system error. */ case object IE extends CoverageStatus - implicit val config = DecoderConfiguration.snakeCase + implicit val config: Configuration = DecoderConfiguration.snakeCase implicit val responseDecoder: Decoder[Response] = deriveConfiguredDecoder implicit val postcodeCoverageDecoder: Decoder[PostcodeCoverage] = deriveConfiguredDecoder implicit val coverageStatusDecoder: Decoder[CoverageStatus] = deriveEnumerationDecoder } -object ServerStatusEndpoint { - case class Response(statusCode: Integer, data: Server) - - case class Server(status: String) - - implicit val config = DecoderConfiguration.snakeCase - implicit val responseDecoder: Decoder[Response] = deriveConfiguredDecoder - implicit val serverDecoder: Decoder[Server] = deriveConfiguredDecoder -} - object PaperRound { case class Error(statusCode: Integer, message: String, errorCode: ZonedDateTime) extends Throwable(s"Error(statusCode = $statusCode, message = $message, errorCode = $errorCode)") object Error { - implicit val config = DecoderConfiguration.snakeCase + implicit val config: Configuration = DecoderConfiguration.snakeCase implicit val errorDecoder: Decoder[Error] = deriveConfiguredDecoder } } diff --git a/support-models/src/main/scala/com/gu/support/promotions/Benefit.scala b/support-models/src/main/scala/com/gu/support/promotions/Benefit.scala index b0c97b207c..5a190d5d4a 100644 --- a/support-models/src/main/scala/com/gu/support/promotions/Benefit.scala +++ b/support-models/src/main/scala/com/gu/support/promotions/Benefit.scala @@ -13,7 +13,7 @@ sealed trait Benefit case class DiscountBenefit(amount: Double, durationMonths: Option[Months]) extends Benefit object DiscountBenefit { - val jsonName = "percent_discount" + val jsonName: String = "percent_discount" implicit val discountCodec: Codec[DiscountBenefit] = deriveCodec } @@ -21,7 +21,7 @@ object DiscountBenefit { case class FreeTrialBenefit(duration: Days) extends Benefit object FreeTrialBenefit { - val jsonName = "free_trial" + val jsonName: String = "free_trial" implicit val freeTrialCodec: Codec[FreeTrialBenefit] = deriveCodec } @@ -33,7 +33,7 @@ case class IncentiveBenefit( ) extends Benefit object IncentiveBenefit { - val jsonName = "incentive" + val jsonName: String = "incentive" implicit val incentiveCodec: Codec[IncentiveBenefit] = deriveCodec } @@ -58,7 +58,7 @@ case class IntroductoryPriceBenefit(price: Double, periodLength: Int, periodType extends Benefit object IntroductoryPriceBenefit { - val jsonName = "introductory_price" + val jsonName: String = "introductory_price" implicit val incentiveCodec: Codec[IntroductoryPriceBenefit] = deriveCodec } diff --git a/support-models/src/main/scala/com/gu/support/promotions/DefaultPromotions.scala b/support-models/src/main/scala/com/gu/support/promotions/DefaultPromotions.scala index eef35274fc..591f605388 100644 --- a/support-models/src/main/scala/com/gu/support/promotions/DefaultPromotions.scala +++ b/support-models/src/main/scala/com/gu/support/promotions/DefaultPromotions.scala @@ -4,12 +4,12 @@ object DefaultPromotions { object DigitalSubscription { object Monthly { - val fiftyPercentOff3Months = "DK0NT24WG" - def all = List(fiftyPercentOff3Months) + val fiftyPercentOff3Months: String = "DK0NT24WG" + def all: List[String] = List(fiftyPercentOff3Months) } object Annual { - def all = List( + def all: List[String] = List( "ANNUAL-INTRO-GLOBAL", ) } @@ -18,11 +18,11 @@ object DefaultPromotions { object GuardianWeekly { object Gift { - val twentyPercentOff = "GW20GIFT1Y" - def all = List(twentyPercentOff) + val twentyPercentOff: String = "GW20GIFT1Y" + def all: List[String] = List(twentyPercentOff) } object NonGift { - val sixForSix = "6FOR6" + val sixForSix: String = "6FOR6" } } diff --git a/support-models/src/main/scala/com/gu/support/promotions/PromoError.scala b/support-models/src/main/scala/com/gu/support/promotions/PromoError.scala index 42521ebc84..c3137a6206 100644 --- a/support-models/src/main/scala/com/gu/support/promotions/PromoError.scala +++ b/support-models/src/main/scala/com/gu/support/promotions/PromoError.scala @@ -5,29 +5,29 @@ sealed trait PromoError { } case object InvalidCountry extends PromoError { - override val msg = "The promo code you supplied is not applicable in this country" + override val msg: String = "The promo code you supplied is not applicable in this country" } case object InvalidProductRatePlan extends PromoError { - override val msg = "The promo code you supplied is not applicable for this product" + override val msg: String = "The promo code you supplied is not applicable for this product" } case object NotApplicable extends PromoError { - override val msg = "This promotion is not applicable" + override val msg: String = "This promotion is not applicable" } case object NoSuchCode extends PromoError { - override val msg = "Unknown or expired promo code" + override val msg: String = "Unknown or expired promo code" } case class DuplicateCode(debug: String) extends PromoError { - override val msg = s"Duplicate promo codes: $debug" + override val msg: String = s"Duplicate promo codes: $debug" } case object ExpiredPromotion extends PromoError { - override val msg = "The promo code you supplied has expired" + override val msg: String = "The promo code you supplied has expired" } case object PromotionNotActiveYet extends PromoError { - override val msg = "The promo code you supplied is not active yet" + override val msg: String = "The promo code you supplied is not active yet" } diff --git a/support-models/src/main/scala/com/gu/support/redemptions/RedemptionCode.scala b/support-models/src/main/scala/com/gu/support/redemptions/RedemptionCode.scala index 38ec36274a..81fe9b3429 100644 --- a/support-models/src/main/scala/com/gu/support/redemptions/RedemptionCode.scala +++ b/support-models/src/main/scala/com/gu/support/redemptions/RedemptionCode.scala @@ -6,10 +6,10 @@ import com.gu.support.encoding.Codec import io.circe.{Decoder, Encoder} object RedemptionCode { - val length = 13 + val length: Int = 13 // make sure no one can inject anything bad - val validChars = List('a' -> 'z', '0' -> '9', '-' -> '-') - val validCharsSet = validChars.flatMap { case (from, to) => (from to to) }.toSet + val validChars: List[(Char, Char)] = List('a' -> 'z', '0' -> '9', '-' -> '-') + val validCharsSet: Set[Char] = validChars.flatMap { case (from, to) => (from to to) }.toSet def apply(value: String): Either[String, RedemptionCode] = { val lower = value.toLowerCase(Locale.UK) diff --git a/support-models/src/main/scala/com/gu/support/workers/BillingPeriod.scala b/support-models/src/main/scala/com/gu/support/workers/BillingPeriod.scala index 58d34bac33..8a8101efd8 100644 --- a/support-models/src/main/scala/com/gu/support/workers/BillingPeriod.scala +++ b/support-models/src/main/scala/com/gu/support/workers/BillingPeriod.scala @@ -23,21 +23,21 @@ object BillingPeriod { } case object Monthly extends BillingPeriod { - override val noun = "month" - override val monthsInPeriod = 1 + override val noun: String = "month" + override val monthsInPeriod: Int = 1 } case object Quarterly extends BillingPeriod { - override val noun = "quarter" - override val monthsInPeriod = 3 + override val noun: String = "quarter" + override val monthsInPeriod: Int = 3 } case object Annual extends BillingPeriod { - override val noun = "year" - override val monthsInPeriod = 12 + override val noun: String = "year" + override val monthsInPeriod: Int = 12 } case object SixWeekly extends BillingPeriod { - override val noun = "six weeks" - override val monthsInPeriod = 1 + override val noun: String = "six weeks" + override val monthsInPeriod: Int = 1 } diff --git a/support-models/src/main/scala/com/gu/support/workers/CheckoutFailureReasons.scala b/support-models/src/main/scala/com/gu/support/workers/CheckoutFailureReasons.scala index d76fd696f6..0a805b3966 100644 --- a/support-models/src/main/scala/com/gu/support/workers/CheckoutFailureReasons.scala +++ b/support-models/src/main/scala/com/gu/support/workers/CheckoutFailureReasons.scala @@ -6,7 +6,7 @@ import scala.PartialFunction.condOpt object CheckoutFailureReasons { - val all = List( + val all: List[CheckoutFailureReason] = List( InsufficientFunds, PaymentMethodDetailsIncorrect, PaymentMethodTemporarilyDeclined, @@ -56,7 +56,7 @@ object CheckoutFailureReasons { } case object AccountMismatch extends CheckoutFailureReason { - override def asString = "production_test_account_mismatch" + override def asString: String = "production_test_account_mismatch" } case object AmazonPayTryAnotherCard extends CheckoutFailureReason { diff --git a/support-models/src/main/scala/com/gu/support/workers/GiftRecipient.scala b/support-models/src/main/scala/com/gu/support/workers/GiftRecipient.scala index b64659cd6b..7605cc6625 100644 --- a/support-models/src/main/scala/com/gu/support/workers/GiftRecipient.scala +++ b/support-models/src/main/scala/com/gu/support/workers/GiftRecipient.scala @@ -1,9 +1,10 @@ package com.gu.support.workers import com.gu.i18n.Title +import com.gu.support.encoding import com.gu.support.encoding.DiscriminatedType import com.gu.support.encoding.CustomCodecs._ -import com.gu.support.workers.GiftRecipient.{DigitalSubscriptionGiftRecipient, WeeklyGiftRecipient} +import com.gu.support.workers.GiftRecipient.{DigitalSubscriptionGiftRecipient, WeeklyGiftRecipient, discriminatedType} import io.circe._ import org.joda.time.LocalDate @@ -31,10 +32,12 @@ object GiftRecipient { deliveryDate: LocalDate, ) extends GiftRecipient - val discriminatedType = new DiscriminatedType[GiftRecipient]("giftRecipientType") - implicit val weeklyCodec = discriminatedType.variant[WeeklyGiftRecipient]("Weekly") - implicit val dsCodec = discriminatedType.variant[DigitalSubscriptionGiftRecipient]("DigitalSubscription") - implicit val codec = discriminatedType.codec(List(weeklyCodec, dsCodec)) + val discriminatedType: DiscriminatedType[GiftRecipient] = new DiscriminatedType[GiftRecipient]("giftRecipientType") + implicit val weeklyCodec: discriminatedType.VariantCodec[WeeklyGiftRecipient] = + discriminatedType.variant[WeeklyGiftRecipient]("Weekly") + implicit val dsCodec: discriminatedType.VariantCodec[DigitalSubscriptionGiftRecipient] = + discriminatedType.variant[DigitalSubscriptionGiftRecipient]("DigitalSubscription") + implicit val codec: encoding.Codec[GiftRecipient] = discriminatedType.codec(List(weeklyCodec, dsCodec)) } @@ -47,7 +50,8 @@ object GeneratedGiftCode { .filter(_.matches(raw"""gd(03|06|12)-[a-km-z02-9]{8}""")) .map(new GeneratedGiftCode(_)) - implicit val e1 = Encoder.encodeString.contramap[GeneratedGiftCode](_.value) - implicit val d1 = Decoder.decodeString.emap(GeneratedGiftCode(_).toRight("invalid gift code")) + implicit val e1: Encoder[GeneratedGiftCode] = Encoder.encodeString.contramap[GeneratedGiftCode](_.value) + implicit val d1: Decoder[GeneratedGiftCode] = + Decoder.decodeString.emap(GeneratedGiftCode(_).toRight("invalid gift code")) } diff --git a/support-models/src/main/scala/com/gu/support/workers/PaymentProvider.scala b/support-models/src/main/scala/com/gu/support/workers/PaymentProvider.scala index 6c2d69f1b4..1820e57ad0 100644 --- a/support-models/src/main/scala/com/gu/support/workers/PaymentProvider.scala +++ b/support-models/src/main/scala/com/gu/support/workers/PaymentProvider.scala @@ -24,7 +24,7 @@ case object AmazonPay extends PaymentProvider("AmazonPay") object PaymentProvider { - val all = List( + val all: List[PaymentProvider] = List( Stripe, StripeApplePay, PayPal, diff --git a/support-models/src/main/scala/com/gu/support/workers/PaymentSchedule.scala b/support-models/src/main/scala/com/gu/support/workers/PaymentSchedule.scala index 20523c726c..115be55b4f 100644 --- a/support-models/src/main/scala/com/gu/support/workers/PaymentSchedule.scala +++ b/support-models/src/main/scala/com/gu/support/workers/PaymentSchedule.scala @@ -12,7 +12,7 @@ case class Payment(date: LocalDate, amount: Double) case class PaymentSchedule(payments: List[Payment]) object PaymentSchedule { - def round(d: Double) = BigDecimal(d).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble + def round(d: Double): Double = BigDecimal(d).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble implicit val decoder: Decoder[Payment] = deriveDecoder[Payment].map(payment => payment.copy( amount = round(payment.amount), diff --git a/support-models/src/main/scala/com/gu/support/workers/Products.scala b/support-models/src/main/scala/com/gu/support/workers/Products.scala index df679a8d85..3f677c3f51 100644 --- a/support-models/src/main/scala/com/gu/support/workers/Products.scala +++ b/support-models/src/main/scala/com/gu/support/workers/Products.scala @@ -84,7 +84,7 @@ case class GuardianWeekly( object ProductType { import com.gu.support.encoding.CustomCodecs._ - val discriminatedType = new DiscriminatedType[ProductType]("productType") + val discriminatedType: DiscriminatedType[ProductType] = new DiscriminatedType[ProductType]("productType") implicit val codecContribution: discriminatedType.VariantCodec[Contribution] = discriminatedType.variant[Contribution]("Contribution") diff --git a/support-models/src/main/scala/com/gu/support/workers/Status.scala b/support-models/src/main/scala/com/gu/support/workers/Status.scala index c98ca02aad..cffbb73b38 100644 --- a/support-models/src/main/scala/com/gu/support/workers/Status.scala +++ b/support-models/src/main/scala/com/gu/support/workers/Status.scala @@ -7,7 +7,7 @@ sealed trait Status { } object Status { - val all = List(Success, Failure, Pending) + val all: List[Status] = List(Success, Failure, Pending) def fromString(s: String): Option[Status] = all.find(_.asString == s) diff --git a/support-models/src/main/scala/com/gu/support/workers/states/ExecutionTypeDiscriminators.scala b/support-models/src/main/scala/com/gu/support/workers/states/ExecutionTypeDiscriminators.scala index 009bc7289d..31c941e9f9 100644 --- a/support-models/src/main/scala/com/gu/support/workers/states/ExecutionTypeDiscriminators.scala +++ b/support-models/src/main/scala/com/gu/support/workers/states/ExecutionTypeDiscriminators.scala @@ -2,15 +2,15 @@ package com.gu.support.workers.states object ExecutionTypeDiscriminators { - val fieldName = "productType" + val fieldName: String = "productType" - val contribution = "Contribution" - val supporterPlus = "SupporterPlus" - val tierThree = "TierThree" - val digitalSubscriptionDirectPurchase = "DigitalSubscriptionDirectPurchase" - val digitalSubscriptionGiftPurchase = "DigitalSubscriptionGiftPurchase" - val digitalSubscriptionGiftRedemption = "DigitalSubscriptionGiftRedemption" - val paper = "Paper" - val guardianWeekly = "GuardianWeekly" + val contribution: String = "Contribution" + val supporterPlus: String = "SupporterPlus" + val tierThree: String = "TierThree" + val digitalSubscriptionDirectPurchase: String = "DigitalSubscriptionDirectPurchase" + val digitalSubscriptionGiftPurchase: String = "DigitalSubscriptionGiftPurchase" + val digitalSubscriptionGiftRedemption: String = "DigitalSubscriptionGiftRedemption" + val paper: String = "Paper" + val guardianWeekly: String = "GuardianWeekly" } diff --git a/support-models/src/main/scala/com/gu/support/zuora/api/PaymentGateway.scala b/support-models/src/main/scala/com/gu/support/zuora/api/PaymentGateway.scala index d873943238..0f36b301e2 100644 --- a/support-models/src/main/scala/com/gu/support/zuora/api/PaymentGateway.scala +++ b/support-models/src/main/scala/com/gu/support/zuora/api/PaymentGateway.scala @@ -40,38 +40,38 @@ object PaymentGateway { //Gateway names need to match to those set in Zuora //See: https://apisandbox.zuora.com/apps/NewGatewaySetting.do?method=list case object StripeGatewayDefault extends PaymentGateway { - val name = "Stripe Gateway 1" + val name: String = "Stripe Gateway 1" } case object StripeGatewayAUD extends PaymentGateway { - val name = "Stripe Gateway GNM Membership AUS" + val name: String = "Stripe Gateway GNM Membership AUS" } case object StripeGatewayPaymentIntentsDefault extends PaymentGateway { - val name = "Stripe PaymentIntents GNM Membership" + val name: String = "Stripe PaymentIntents GNM Membership" } case object StripeGatewayPaymentIntentsAUD extends PaymentGateway { - val name = "Stripe PaymentIntents GNM Membership AUS" + val name: String = "Stripe PaymentIntents GNM Membership AUS" } case object PayPalGateway extends PaymentGateway { - val name = "PayPal Express" + val name: String = "PayPal Express" } case object DirectDebitGateway extends PaymentGateway { - val name = "GoCardless" + val name: String = "GoCardless" } case object SepaGateway extends PaymentGateway { - val name = "Stripe Bank Transfer - GNM Membership" + val name: String = "Stripe Bank Transfer - GNM Membership" } case object ZuoraInstanceDirectDebitGateway extends PaymentGateway { // not sure why there are two GoCardless gateways in Zuora - but having it declared here allows it be re-used - val name = "GoCardless - Zuora Instance" + val name: String = "GoCardless - Zuora Instance" } case object AmazonPayGatewayUSA extends PaymentGateway { - val name = "Amazon Pay - Contributions USA" + val name: String = "Amazon Pay - Contributions USA" } diff --git a/support-models/src/main/scala/com/gu/support/zuora/api/SubscriptionData.scala b/support-models/src/main/scala/com/gu/support/zuora/api/SubscriptionData.scala index d11cb7b80f..f1cf0a4f77 100644 --- a/support-models/src/main/scala/com/gu/support/zuora/api/SubscriptionData.scala +++ b/support-models/src/main/scala/com/gu/support/zuora/api/SubscriptionData.scala @@ -15,12 +15,12 @@ import io.circe.{Decoder, Encoder, Json, parser} import org.joda.time.{LocalDate, Months} object RatePlanCharge { - val fixedPeriod = "FixedPeriod" - val subscriptionEnd = "SubscriptionEnd" - val endDateCondition = "EndDateCondition" - val upToPeriods = "UpToPeriods" - val triggerEvent = "TriggerEvent" - val specificEvent = "SpecificDate" + val fixedPeriod: String = "FixedPeriod" + val subscriptionEnd: String = "SubscriptionEnd" + val endDateCondition: String = "EndDateCondition" + val upToPeriods: String = "UpToPeriods" + val triggerEvent: String = "TriggerEvent" + val specificEvent: String = "SpecificDate" implicit val discountEncoder: Encoder[DiscountRatePlanCharge] = capitalizingEncoder[DiscountRatePlanCharge] .mapJsonObject { jo => @@ -111,19 +111,19 @@ object PeriodType { object ReaderType { case object Direct extends ReaderType { - val value = "Direct" + val value: String = "Direct" } case object Gift extends ReaderType { - val value = "Gift" + val value: String = "Gift" } case object Agent extends ReaderType { - val value = "Agent" + val value: String = "Agent" } case object Patron extends ReaderType { - val value = "Patron" + val value: String = "Patron" } case object Unknown extends ReaderType { - val value = "Unknown" + val value: String = "Unknown" } def impliedByPromoCode(promoCode: PromoCode): Option[ReaderType] = Option.when(promoCode.endsWith("PATRON"))(Patron) @@ -150,11 +150,11 @@ sealed trait ReaderType { object AcquisitionSource { case object CSR extends AcquisitionSource { - val value = "CSR" + val value: String = "CSR" } case object Unknown extends AcquisitionSource { - val value = "Unknown" + val value: String = "Unknown" } def fromString(s: String): AcquisitionSource = diff --git a/support-models/src/main/scala/com/gu/support/zuora/api/response/Responses.scala b/support-models/src/main/scala/com/gu/support/zuora/api/response/Responses.scala index 9a9e81421b..4c051e85cc 100644 --- a/support-models/src/main/scala/com/gu/support/zuora/api/response/Responses.scala +++ b/support-models/src/main/scala/com/gu/support/zuora/api/response/Responses.scala @@ -202,7 +202,7 @@ object ZuoraSuccessOrFailureResponse { } case class ZuoraSuccessOrFailureResponse(success: Boolean, reasons: Option[List[ZuoraErrorReason]]) { - def errorMessage = reasons.flatMap(_.headOption).map(_.message) + def errorMessage: Option[String] = reasons.flatMap(_.headOption).map(_.message) } object ZuoraErrorReason { diff --git a/support-models/src/test/scala/com/gu/support/paperround/SerialisationSpec.scala b/support-models/src/test/scala/com/gu/support/paperround/SerialisationSpec.scala index d25bdc85b2..9a5eb3c148 100644 --- a/support-models/src/test/scala/com/gu/support/paperround/SerialisationSpec.scala +++ b/support-models/src/test/scala/com/gu/support/paperround/SerialisationSpec.scala @@ -38,7 +38,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with testDecoding[PaperRound.Error](s"$errorJson") } - val agentsSuccessJson = + val agentsSuccessJson: String = """ { "status_code": 200, @@ -92,7 +92,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val chargeBandsSuccessJson = + val chargeBandsSuccessJson: String = """ { "status_code": 200, @@ -1050,7 +1050,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val coverageSuccessNotCoveredJson = + val coverageSuccessNotCoveredJson: String = """ { "status_code": 200, @@ -1063,7 +1063,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val coverageSuccessInputProblemJson = + val coverageSuccessInputProblemJson: String = """ { "status_code": 200, @@ -1076,7 +1076,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val coverageSuccessMissingPostcodeJson = + val coverageSuccessMissingPostcodeJson: String = """ { "status_code": 200, @@ -1089,7 +1089,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val coverageSuccessCoveredJson = + val coverageSuccessCoveredJson: String = """ { "status_code": 200, @@ -1121,7 +1121,7 @@ class SerialisationSpec extends AsyncFlatSpec with SerialisationTestHelpers with } """ - val errorJson = + val errorJson: String = """ { "error_code": "2023-07-25T10:21:41.754Z", diff --git a/support-models/src/test/scala/com/gu/support/promotions/Fixtures.scala b/support-models/src/test/scala/com/gu/support/promotions/Fixtures.scala index 3f2099573a..ff1ff5b71e 100644 --- a/support-models/src/test/scala/com/gu/support/promotions/Fixtures.scala +++ b/support-models/src/test/scala/com/gu/support/promotions/Fixtures.scala @@ -1,9 +1,9 @@ package com.gu.support.promotions object Fixtures { - val startDate = "2018-10-03T00:00:00.000+01:00" + val startDate: String = "2018-10-03T00:00:00.000+01:00" - val doublePromotionType = + val doublePromotionType: String = """ { "a": { @@ -18,7 +18,7 @@ object Fixtures { "name": "double" } """ - val discountPromotion = + val discountPromotion: String = s""" { "codes": { @@ -54,7 +54,7 @@ object Fixtures { } """ - val freeTrialPromotion = + val freeTrialPromotion: String = s""" { "codes": { @@ -107,7 +107,7 @@ object Fixtures { } """ - val doublePromotion = + val doublePromotion: String = s""" { "codes": { @@ -183,7 +183,7 @@ object Fixtures { } """ - val renewal = + val renewal: String = """ { "codes": { @@ -224,7 +224,7 @@ object Fixtures { } """ - val doubleWithRenewal = + val doubleWithRenewal: String = """ { "codes": { @@ -264,7 +264,7 @@ object Fixtures { } """ - val incentivePromotion = + val incentivePromotion: String = """ { "codes": { @@ -301,7 +301,7 @@ object Fixtures { } """ - val doubleWithIncentive = + val doubleWithIncentive: String = """ { "codes": { @@ -382,7 +382,7 @@ object Fixtures { } """ - val introductoryPricePromotion = + val introductoryPricePromotion: String = s""" { "codes": { diff --git a/support-models/src/test/scala/com/gu/support/redemptions/RedemptionCodeSpec.scala b/support-models/src/test/scala/com/gu/support/redemptions/RedemptionCodeSpec.scala index 884c4ea776..fc33c360a5 100644 --- a/support-models/src/test/scala/com/gu/support/redemptions/RedemptionCodeSpec.scala +++ b/support-models/src/test/scala/com/gu/support/redemptions/RedemptionCodeSpec.scala @@ -5,7 +5,7 @@ import org.scalatest.matchers.should.Matchers class RedemptionCodeSpec extends AnyFlatSpec with Matchers { - val codePrefix = "code-123456-" + val codePrefix: String = "code-123456-" "RedemptionCode" should "disallow invalid chars" in { val badCodes = """ !"#$%&'()*+,./:;<=>?@[\]^_`{|}~""" diff --git a/support-models/src/test/scala/com/gu/support/workers/Fixtures.scala b/support-models/src/test/scala/com/gu/support/workers/Fixtures.scala index 1f585a66a5..338a80b69b 100644 --- a/support-models/src/test/scala/com/gu/support/workers/Fixtures.scala +++ b/support-models/src/test/scala/com/gu/support/workers/Fixtures.scala @@ -5,9 +5,9 @@ import com.gu.i18n.Currency.GBP //noinspection TypeAnnotation object Fixtures { - val idId = "12345" - val email = "test@thegulocal.com" - val userJson = + val idId: String = "12345" + val email: String = "test@thegulocal.com" + val userJson: String = s""" "user":{ "id": "$idId", @@ -22,10 +22,10 @@ object Fixtures { "isTestUser": false } """ - val requestIdJson = "\"requestId\": \"e18f6418-45f2-11e7-8bfa-8faac2182601\"" - val validBaid = "B-23637766K5365543J" - val payPalEmail = "test@paypal.com" - val payPalPaymentMethod = + val requestIdJson: String = "\"requestId\": \"e18f6418-45f2-11e7-8bfa-8faac2182601\"" + val validBaid: String = "B-23637766K5365543J" + val payPalEmail: String = "test@paypal.com" + val payPalPaymentMethod: String = s""" { "PaypalBaid": "$validBaid", @@ -36,7 +36,7 @@ object Fixtures { } """ - val stripePaymentMethod = // test env card and cus token, not prod ones + val stripePaymentMethod: String = // test env card and cus token, not prod ones s""" { "TokenId": "card_E0zitFfsO2wTEn", @@ -61,7 +61,7 @@ object Fixtures { } """ - val digitalPackJson = + val digitalPackJson: String = """ { "productType": "DigitalPack", @@ -72,12 +72,12 @@ object Fixtures { } """ - val digitalPackProductJson = + val digitalPackProductJson: String = s""" "product": $digitalPackJson """ - val guardianWeeklyJson = + val guardianWeeklyJson: String = s""" "product": { "productType": "GuardianWeekly", @@ -86,14 +86,14 @@ object Fixtures { "fulfilmentOptions": "RestOfWorld" } """ - val payPalJson = + val payPalJson: String = s""" { "baid": "$validBaid" } """ - val acquisitionData = + val acquisitionData: String = s""" { "ophanIds":{ @@ -121,8 +121,8 @@ object Fixtures { } """ - val mickeyMouse = "Mickey Mouse" - val directDebitJson = + val mickeyMouse: String = "Mickey Mouse" + val directDebitJson: String = s""" { "accountHolderName": "$mickeyMouse", @@ -132,8 +132,8 @@ object Fixtures { } """ - val stripePM = "pm_AXY4M16p60c2sg" - val stripeJson = + val stripePM: String = "pm_AXY4M16p60c2sg" + val stripeJson: String = s""" { "paymentMethod": "$stripePM" @@ -174,7 +174,7 @@ object Fixtures { "userAgent": "TestAgent" }""" - val createPayPalPaymentMethodDigitalPackJson = + val createPayPalPaymentMethodDigitalPackJson: String = s"""{ $requestIdJson, $userJson, @@ -189,7 +189,7 @@ object Fixtures { "userAgent": "TestAgent" }""" - val createDirectDebitDigitalPackJson = + val createDirectDebitDigitalPackJson: String = s"""{ $requestIdJson, $userJson, @@ -204,7 +204,7 @@ object Fixtures { "userAgent": "TestAgent" }""" - val createDirectDebitGuardianWeeklyJson = + val createDirectDebitGuardianWeeklyJson: String = s"""{ $requestIdJson, $userJson, @@ -219,7 +219,7 @@ object Fixtures { "userAgent": "TestAgent" }""" - val createSalesforceContactJson = + val createSalesforceContactJson: String = s""" { $requestIdJson, @@ -234,7 +234,7 @@ object Fixtures { } """ - val salesforceContactJson = + val salesforceContactJson: String = """ { "Id": "0033E00001Cq8D2QAJ", @@ -242,7 +242,7 @@ object Fixtures { } """ - val salesforceContactsJson = + val salesforceContactsJson: String = """{ "buyer": { "Id": "0033E00001Cq8D2QAJ", @@ -277,7 +277,7 @@ object Fixtures { } """ - val zuoraErrorResponse = + val zuoraErrorResponse: String = """[{"Code": "TRANSACTION_FAILED","Message": "Transaction declined.do_not_honor - Your card was declined."}]""" } diff --git a/support-models/src/test/scala/com/gu/support/workers/SendThankYouEmailStateSerialisationSpec.scala b/support-models/src/test/scala/com/gu/support/workers/SendThankYouEmailStateSerialisationSpec.scala index 2419402bb9..0fe0479487 100644 --- a/support-models/src/test/scala/com/gu/support/workers/SendThankYouEmailStateSerialisationSpec.scala +++ b/support-models/src/test/scala/com/gu/support/workers/SendThankYouEmailStateSerialisationSpec.scala @@ -29,7 +29,7 @@ class SendThankYouEmailStateSerialisationSpec extends AnyFlatSpec with Matchers object ProductTypeCreatedTestData { - val contributionCreated = SendThankYouEmailContributionState( + val contributionCreated: SendThankYouEmailContributionState = SendThankYouEmailContributionState( user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), Contribution(1, GBP, Monthly), PayPalReferenceTransaction("baid", "email@emaail.com"), @@ -37,47 +37,53 @@ object ProductTypeCreatedTestData { "subno", ) - val digitalSubscriptionDirectPurchaseCreated = SendThankYouEmailDigitalSubscriptionDirectPurchaseState( - user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), - DigitalPack(GBP, Monthly, ReaderType.Direct), - PayPalReferenceTransaction("baid", "email@emaail.com"), - PaymentSchedule(List(Payment(new LocalDate(2020, 6, 16), 1.49))), - None, - "acno", - "subno", - ) + val digitalSubscriptionDirectPurchaseCreated: SendThankYouEmailDigitalSubscriptionDirectPurchaseState = + SendThankYouEmailDigitalSubscriptionDirectPurchaseState( + user = + User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), + DigitalPack(GBP, Monthly, ReaderType.Direct), + PayPalReferenceTransaction("baid", "email@emaail.com"), + PaymentSchedule(List(Payment(new LocalDate(2020, 6, 16), 1.49))), + None, + "acno", + "subno", + ) - val digitalSubscriptionGiftPurchaseCreated = SendThankYouEmailDigitalSubscriptionGiftPurchaseState( - user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), - recipientSFContactId = SfContactId("sfrecip"), - DigitalPack(GBP, Monthly, ReaderType.Gift), - GiftRecipient - .DigitalSubscriptionGiftRecipient( - "bob", - "builder", - "bob@thegulocal.com", - Some("message"), - new LocalDate(2020, 10, 2), + val digitalSubscriptionGiftPurchaseCreated: SendThankYouEmailDigitalSubscriptionGiftPurchaseState = + SendThankYouEmailDigitalSubscriptionGiftPurchaseState( + user = + User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), + recipientSFContactId = SfContactId("sfrecip"), + DigitalPack(GBP, Monthly, ReaderType.Gift), + GiftRecipient + .DigitalSubscriptionGiftRecipient( + "bob", + "builder", + "bob@thegulocal.com", + Some("message"), + new LocalDate(2020, 10, 2), + ), + GeneratedGiftCode("gd12-23456789").get, + new LocalDate(2020, 10, 14), + PayPalReferenceTransaction("baid", "email@emaail.com"), + PaymentSchedule(List(Payment(new LocalDate(2020, 6, 16), 1.49))), + None, + "acno", + "subno", + ) + val digitalSubscriptionGiftRedemptionCreated: SendThankYouEmailDigitalSubscriptionGiftRedemptionState = + SendThankYouEmailDigitalSubscriptionGiftRedemptionState( + user = + User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), + DigitalPack(GBP, Monthly, ReaderType.Gift), + "subno", + TermDates( + new LocalDate(2020, 10, 24), + new LocalDate(2021, 1, 24), + 3, ), - GeneratedGiftCode("gd12-23456789").get, - new LocalDate(2020, 10, 14), - PayPalReferenceTransaction("baid", "email@emaail.com"), - PaymentSchedule(List(Payment(new LocalDate(2020, 6, 16), 1.49))), - None, - "acno", - "subno", - ) - val digitalSubscriptionGiftRedemptionCreated = SendThankYouEmailDigitalSubscriptionGiftRedemptionState( - user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), - DigitalPack(GBP, Monthly, ReaderType.Gift), - "subno", - TermDates( - new LocalDate(2020, 10, 24), - new LocalDate(2021, 1, 24), - 3, - ), - ) - val paperCreated = SendThankYouEmailPaperState( + ) + val paperCreated: SendThankYouEmailPaperState = SendThankYouEmailPaperState( user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), Paper( fulfilmentOptions = Collection, @@ -92,7 +98,7 @@ object ProductTypeCreatedTestData { new LocalDate(2020, 10, 22), ) - val guardianWeeklyCreated = SendThankYouEmailGuardianWeeklyState( + val guardianWeeklyCreated: SendThankYouEmailGuardianWeeklyState = SendThankYouEmailGuardianWeeklyState( user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), GuardianWeekly(GBP, Monthly, Domestic), Some(GiftRecipient.WeeklyGiftRecipient(None, "bob", "builder", Some("bob@thegulocal.com"))), diff --git a/support-models/src/test/scala/com/gu/support/workers/SerialisationSpec.scala b/support-models/src/test/scala/com/gu/support/workers/SerialisationSpec.scala index 4104790c76..4e3ed1224f 100644 --- a/support-models/src/test/scala/com/gu/support/workers/SerialisationSpec.scala +++ b/support-models/src/test/scala/com/gu/support/workers/SerialisationSpec.scala @@ -72,7 +72,7 @@ object StatesTestData { promoCode = None, ) - val createPaymentMethodState = CreatePaymentMethodState( + val createPaymentMethodState: CreatePaymentMethodState = CreatePaymentMethodState( requestId = UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), giftRecipient = None, @@ -88,7 +88,7 @@ object StatesTestData { userAgent = "TestAgent", ) - val createSalesforceContactState = CreateSalesforceContactState( + val createSalesforceContactState: CreateSalesforceContactState = CreateSalesforceContactState( requestId = UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), giftRecipient = None, @@ -131,7 +131,7 @@ object StatesTestData { acquisitionData = None, ) - val preparePaymentMethodForReuseState = PreparePaymentMethodForReuseState( + val preparePaymentMethodForReuseState: PreparePaymentMethodForReuseState = PreparePaymentMethodForReuseState( requestId = UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), user = User("111222", "email@blah.com", None, "bertha", "smith", Address(None, None, None, None, None, Country.UK)), giftRecipient = None, diff --git a/support-models/src/test/scala/com/gu/support/zuora/api/Fixtures.scala b/support-models/src/test/scala/com/gu/support/zuora/api/Fixtures.scala index a2b8cfa948..d79f0d9b92 100644 --- a/support-models/src/test/scala/com/gu/support/zuora/api/Fixtures.scala +++ b/support-models/src/test/scala/com/gu/support/zuora/api/Fixtures.scala @@ -12,10 +12,10 @@ import org.joda.time.LocalDate //noinspection TypeAnnotation object Fixtures { - val accountNumber = "A00071408" - val promoCode = "TEST_CODE" + val accountNumber: String = "A00071408" + val promoCode: String = "TEST_CODE" - val soldToContact = s"""{ + val soldToContact: String = s"""{ "address1" : "Test", "address2" : "Test", "city" : "Test", @@ -38,7 +38,7 @@ object Fixtures { "SpecialDeliveryInstructions__c" : "Stick it in the shed" }""" - val getAccountResponse = + val getAccountResponse: String = s""" { "basicInfo" : { @@ -97,16 +97,16 @@ object Fixtures { } """ - val salesforceAccountId = "0013E00001ASmI6QAL" - val salesforceId = "0033E00001CpBZaQAN" - val identityId = "30000311" - val paymentGateway = "Stripe Gateway 1" - val tokenId = "card_Aaynm1dIeDH1zp" - val secondTokenId = "cus_AaynKIp19IIGDz" - val cardNumber = "4242" - val payPalBaid = "B-23637766K5365543J" + val salesforceAccountId: String = "0013E00001ASmI6QAL" + val salesforceId: String = "0033E00001CpBZaQAN" + val identityId: String = "30000311" + val paymentGateway: String = "Stripe Gateway 1" + val tokenId: String = "card_Aaynm1dIeDH1zp" + val secondTokenId: String = "cus_AaynKIp19IIGDz" + val cardNumber: String = "4242" + val payPalBaid: String = "B-23637766K5365543J" - val date = new LocalDate(2017, 5, 4) + val date: LocalDate = new LocalDate(2017, 5, 4) def account( currency: Currency = GBP, @@ -134,8 +134,8 @@ object Fixtures { createdRequestId__c = "createdreqid_hi", ) - val deliveryInstructions = "Leave behind the dustbin" - val contactDetails = + val deliveryInstructions: String = "Leave behind the dustbin" + val contactDetails: ContactDetails = ContactDetails( "Test-FirstName", "Test-LastName", @@ -143,7 +143,7 @@ object Fixtures { Country.UK, deliveryInstructions = Some(deliveryInstructions), ) - val creditCardPaymentMethod = CreditCardReferenceTransaction( + val creditCardPaymentMethod: CreditCardReferenceTransaction = CreditCardReferenceTransaction( tokenId, secondTokenId, cardNumber, @@ -154,8 +154,8 @@ object Fixtures { StripeGatewayDefault, StripePaymentType = Some(StripePaymentType.StripeCheckout), ) - val payPalPaymentMethod = PayPalReferenceTransaction(payPalBaid, "test@paypal.com") - val directDebitPaymentMethod = DirectDebitPaymentMethod( + val payPalPaymentMethod: PayPalReferenceTransaction = PayPalReferenceTransaction(payPalBaid, "test@paypal.com") + val directDebitPaymentMethod: DirectDebitPaymentMethod = DirectDebitPaymentMethod( FirstName = "Barry", LastName = "Humphreys", BankTransferAccountName = "Barry Humphreys", @@ -167,11 +167,11 @@ object Fixtures { StreetName = Some("easy street"), StreetNumber = None, ) - val productRatePlanId = "12345" - val productRatePlanChargeId = "67890" + val productRatePlanId: String = "12345" + val productRatePlanChargeId: String = "67890" - val subscription = Subscription(date, date, date, "id123", promoCode = Some(promoCode)) - val monthlySubscriptionData = SubscriptionData( + val subscription: Subscription = Subscription(date, date, date, "id123", promoCode = Some(promoCode)) + val monthlySubscriptionData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(productRatePlanId), // Contribution product @@ -186,7 +186,7 @@ object Fixtures { subscription, ) - val dsSubscriptionData = SubscriptionData( + val dsSubscriptionData: SubscriptionData = SubscriptionData( List(RatePlanData(RatePlan(productRatePlanId), Nil, Nil)), Subscription( contractEffectiveDate = new LocalDate(2020, 12, 1), @@ -202,7 +202,7 @@ object Fixtures { ), ) - val dsGiftSubscriptionData = SubscriptionData( + val dsGiftSubscriptionData: SubscriptionData = SubscriptionData( List(RatePlanData(RatePlan(productRatePlanId), Nil, Nil)), Subscription( contractEffectiveDate = new LocalDate(2020, 12, 1), @@ -218,7 +218,7 @@ object Fixtures { ), ) - val accountJson = + val accountJson: String = """ { "Name" : "0013E00001AU6xcQAD", @@ -235,7 +235,7 @@ object Fixtures { "Batch" : "Batch1" } """ - val subscriptionJson = + val subscriptionJson: String = s""" { "ContractEffectiveDate" : "2018-11-28", @@ -253,7 +253,7 @@ object Fixtures { } """ - val subscribeItemJson = + val subscribeItemJson: String = s""" { "Account" : $accountJson, @@ -299,7 +299,7 @@ object Fixtures { } } """ - val subscribeRequestJson = + val subscribeRequestJson: String = s""" { "subscribes": [$subscribeItemJson] @@ -334,7 +334,7 @@ object Fixtures { ), ) - val invalidMonthlySubsData = SubscriptionData( + val invalidMonthlySubsData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(productRatePlanId), @@ -348,7 +348,7 @@ object Fixtures { ), Subscription(date, date, date, "id123", termType = "Invalid term type"), ) - val invalidSubscriptionRequest = SubscribeRequest( + val invalidSubscriptionRequest: SubscribeRequest = SubscribeRequest( List( SubscribeItem( account(), @@ -361,7 +361,7 @@ object Fixtures { ), ) - val incorrectPaymentMethod = SubscribeRequest( + val incorrectPaymentMethod: SubscribeRequest = SubscribeRequest( List( SubscribeItem( account(), @@ -374,7 +374,7 @@ object Fixtures { ), ) - val invoiceResult = + val invoiceResult: String = """ { "Invoice": [ @@ -386,7 +386,7 @@ object Fixtures { } """ - val subscribeResponseAccount = + val subscribeResponseAccount: String = s""" { "SubscriptionId": "2c92c0f86716797001671754520357f2", @@ -398,13 +398,13 @@ object Fixtures { "TotalTcv": 115.387634411 } """ - val subscribeResponse = + val subscribeResponse: String = s""" [ $subscribeResponseAccount ] """ - val subscribeResponseAnnual = + val subscribeResponseAnnual: String = """ [ { @@ -433,14 +433,14 @@ object Fixtures { ] """ - val previewSubscribeResponseNoInvoice = + val previewSubscribeResponseNoInvoice: String = """ [ {"Success":true,"TotalMrr":0,"TotalTcv":37.5} ] """ - val previewSubscribeResponseJson = + val previewSubscribeResponseJson: String = """ [ { @@ -461,7 +461,7 @@ object Fixtures { ] """ - val error = + val error: String = """ { "Code": "53100320", @@ -469,7 +469,7 @@ object Fixtures { } """ - val errorResponse = + val errorResponse: String = s""" [ { @@ -484,7 +484,7 @@ object Fixtures { ] """ - val directDebitPaymentFieldsJson = + val directDebitPaymentFieldsJson: String = s""" { "accountHolderName": "Mickey Mouse", @@ -494,7 +494,7 @@ object Fixtures { } """ - val contributionRatePlanCharge = + val contributionRatePlanCharge: String = """ { "ProductRatePlanChargeId" : "12345", diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionDataRowMapper.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionDataRowMapper.scala index 803415b9b9..e43fc61c14 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionDataRowMapper.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionDataRowMapper.scala @@ -55,7 +55,7 @@ object AcquisitionDataRowMapper { ) } - def mapPlatformName(name: String) = + def mapPlatformName(name: String): String = name.toLowerCase match { case "iosnativeapp" => "IOS_NATIVE_APP" case "androidnativeapp" => "ANDROID_NATIVE_APP" diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionEventTable.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionEventTable.scala index 84eff266f1..a280e788c9 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionEventTable.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/AcquisitionEventTable.scala @@ -1,6 +1,6 @@ package com.gu.support.acquisitions object AcquisitionEventTable { - val datasetName = "datalake" - val tableName = "fact_acquisition_event" + val datasetName: String = "datalake" + val tableName: String = "fact_acquisition_event" } diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/BigQueryService.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/BigQueryService.scala index 49a6f90b67..b9ba8d876c 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/BigQueryService.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/bigquery/BigQueryService.scala @@ -20,11 +20,12 @@ import java.io.ByteArrayInputStream import java.util.concurrent.Executors import scala.concurrent.{Future, Promise} import scala.jdk.CollectionConverters._ +import java.util.concurrent.ExecutorService class BigQueryService(stage: Stage, credentials: Credentials) extends SafeLogging { private val projectId = s"datatech-platform-${stage.toString.toLowerCase}" - lazy val bigQueryWriteSettings = + lazy val bigQueryWriteSettings: BigQueryWriteSettings = BigQueryWriteSettings .newBuilder() .setQuotaProjectId(projectId) @@ -32,9 +33,9 @@ class BigQueryService(stage: Stage, credentials: Credentials) extends SafeLoggin FixedCredentialsProvider.create(credentials), ) .build() - lazy val bigQueryWriteClient = BigQueryWriteClient.create(bigQueryWriteSettings) - lazy val tableId = TableName.of(projectId, datasetName, tableName) - lazy val streamWriter = JsonStreamWriter.newBuilder(tableId.toString, bigQueryWriteClient).build() + lazy val bigQueryWriteClient: BigQueryWriteClient = BigQueryWriteClient.create(bigQueryWriteSettings) + lazy val tableId: TableName = TableName.of(projectId, datasetName, tableName) + lazy val streamWriter: JsonStreamWriter = JsonStreamWriter.newBuilder(tableId.toString, bigQueryWriteClient).build() def sendAcquisition(acquisitionDataRow: AcquisitionDataRow): EitherT[Future, String, Unit] = EitherT( @@ -84,7 +85,7 @@ object BigQueryService { case class AppendCompleteCallback(stage: Stage, promise: Promise[Either[String, Unit]]) extends ApiFutureCallback[AppendRowsResponse] with SafeLogging { - val executor = Executors.newSingleThreadExecutor() + val executor: ExecutorService = Executors.newSingleThreadExecutor() def onSuccess(response: AppendRowsResponse): Unit = { logger.info(s"Rows successfully inserted into table $tableName") diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/calculator/AnnualisedValueTwoCalculator.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/calculator/AnnualisedValueTwoCalculator.scala index b5adc37711..3a30c5c388 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/calculator/AnnualisedValueTwoCalculator.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/calculator/AnnualisedValueTwoCalculator.scala @@ -28,19 +28,18 @@ import com.gu.support.acquisitions.models.PrintProduct.{ VoucherWeekendPlus, } import com.gu.support.acquisitions.models.{AcquisitionProduct, PaymentFrequency} -import com.gu.support.catalog.NationalDelivery object AnnualisedValueTwoCalculator { // Currencies - All other currencies are treated as ROW - val GBP = "GBP" - val USD = "USD" - val AUD = "AUD" + val GBP: String = "GBP" + val USD: String = "USD" + val AUD: String = "AUD" // Country codes - All other countries are treated as ROW - val GB = "GB" - val US = "US" - val AU = "AU" + val GB: String = "GB" + val US: String = "US" + val AU: String = "AU" def getPaymentFrequencyMultiplyer(paymentFrequency: PaymentFrequency): Either[String, Double] = paymentFrequency match { @@ -153,7 +152,7 @@ object AnnualisedValueTwoCalculator { }) .getOrElse(Left("No print options supplied")) - def getMargin(a: AcquisitionModel) = + private def getMargin(a: AcquisitionModel) = a.product match { case AcquisitionProduct.Contribution => getContributionMargin(a) case AcquisitionProduct.RecurringContribution => getRecurringMargin(a) diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/eventbridge/AcquisitionsEventBusService.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/eventbridge/AcquisitionsEventBusService.scala index 5e71143660..fae315433f 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/eventbridge/AcquisitionsEventBusService.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/eventbridge/AcquisitionsEventBusService.scala @@ -14,11 +14,12 @@ import software.amazon.awssdk.services.eventbridge.model.{PutEventsRequest, PutE import java.time.Instant import scala.concurrent.Promise import scala.jdk.CollectionConverters.SeqHasAsJava +import scala.concurrent.Future class AcquisitionsEventBusService(source: String, stage: Stage, client: EventBridgeClient) extends SafeLogging { - val eventBusName = s"acquisitions-bus-${stage.toString}" - val detailType = "AcquisitionsEvent" - def putAcquisitionEvent(acquisition: AcquisitionDataRow) = { + val eventBusName: String = s"acquisitions-bus-${stage.toString}" + val detailType: String = "AcquisitionsEvent" + def putAcquisitionEvent(acquisition: AcquisitionDataRow): Future[Either[String, Unit]] = { val acquisitionJson = acquisition.asJson logger.info(s"Attempting to send event ${acquisitionJson.spaces2}") val entry = PutEventsRequestEntry @@ -60,8 +61,8 @@ class AcquisitionsEventBusService(source: String, stage: Stage, client: EventBri object AcquisitionsEventBusService { object Sources { - val paymentApi = "payment-api.1" - val supportWorkers = "support-workers.1" + val paymentApi: String = "payment-api.1" + val supportWorkers: String = "support-workers.1" } private lazy val eventBridgeClient = EventBridgeClient @@ -78,7 +79,7 @@ object AcquisitionsEventBusService { * \- Whether the current user is a test user * @return */ - def apply(source: String, stage: Stage, isTestUser: Boolean = false) = + def apply(source: String, stage: Stage, isTestUser: Boolean = false): AcquisitionsEventBusService = new AcquisitionsEventBusService(source, if (isTestUser) CODE else stage, eventBridgeClient) } diff --git a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/models/AcquisitionDataRow.scala b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/models/AcquisitionDataRow.scala index 0c218bf66b..0acec0f3e4 100644 --- a/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/models/AcquisitionDataRow.scala +++ b/support-modules/acquisition-events/src/main/scala/com/gu/support/acquisitions/models/AcquisitionDataRow.scala @@ -56,7 +56,7 @@ object AcquisitionDataRow { implicit val encodeDateTime: Encoder[DateTime] = Encoder.encodeString.contramap[DateTime](dt => ISODateTimeFormat.dateTime().print(dt)) - implicit val codec = deriveCodec[AcquisitionDataRow] + implicit val codec: Codec[AcquisitionDataRow] = deriveCodec[AcquisitionDataRow] } case class PrintOptions( diff --git a/support-modules/aws/src/main/scala/com/gu/aws/aws.scala b/support-modules/aws/src/main/scala/com/gu/aws/aws.scala index 17d47c409a..05e6e2e437 100644 --- a/support-modules/aws/src/main/scala/com/gu/aws/aws.scala +++ b/support-modules/aws/src/main/scala/com/gu/aws/aws.scala @@ -4,7 +4,7 @@ import software.amazon.awssdk.auth.credentials import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain package object aws { - val ProfileName = "membership" + val ProfileName: String = "membership" lazy val CredentialsProvider: AwsCredentialsProviderChain = credentials.AwsCredentialsProviderChain diff --git a/support-modules/rest/src/main/scala/com.gu.okhttp/RequestRunners.scala b/support-modules/rest/src/main/scala/com.gu.okhttp/RequestRunners.scala index 1d57f00c1f..c800a4eaea 100644 --- a/support-modules/rest/src/main/scala/com.gu.okhttp/RequestRunners.scala +++ b/support-modules/rest/src/main/scala/com.gu.okhttp/RequestRunners.scala @@ -14,7 +14,7 @@ import scala.jdk.CollectionConverters._ * determine how they process HTTP requests */ object RequestRunners extends LazyLogging { - lazy val client = new OkHttpClient() + lazy val client: OkHttpClient = new OkHttpClient() type FutureHttpClient = Request => Future[OkResponse] /** Standard no frills run this request and return a response asynchronously A solid choice for the beginner diff --git a/support-modules/rest/src/main/scala/com/gu/monitoring/SafeLogger.scala b/support-modules/rest/src/main/scala/com/gu/monitoring/SafeLogger.scala index 85f92c46b0..0bba68de26 100644 --- a/support-modules/rest/src/main/scala/com/gu/monitoring/SafeLogger.scala +++ b/support-modules/rest/src/main/scala/com/gu/monitoring/SafeLogger.scala @@ -22,7 +22,7 @@ object SafeLogger { val sanitizedLogMessage: Marker = MarkerFactory.getMarker("SENTRY") case class LogMessage(withPersonalData: String, withoutPersonalData: String) { - override val toString = withoutPersonalData + override val toString: String = withoutPersonalData } } diff --git a/support-modules/rest/src/main/scala/com/gu/stripe/StripeError.scala b/support-modules/rest/src/main/scala/com/gu/stripe/StripeError.scala index 4ffb8fc0d6..176690d40f 100644 --- a/support-modules/rest/src/main/scala/com/gu/stripe/StripeError.scala +++ b/support-modules/rest/src/main/scala/com/gu/stripe/StripeError.scala @@ -1,6 +1,6 @@ package com.gu.stripe -import io.circe.Json +import io.circe.{Decoder, Encoder, Json} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} //See docs here: https://stripe.com/docs/api/curl#errors @@ -22,8 +22,10 @@ case class StripeError( object StripeError { - implicit val encoder = deriveEncoder[StripeError].mapJson { json => Json.fromFields(List("error" -> json)) } + implicit val encoder: Encoder[StripeError] = deriveEncoder[StripeError].mapJson { json => + Json.fromFields(List("error" -> json)) + } - implicit val decoder = deriveDecoder[StripeError].prepare { _.downField("error") } + implicit val decoder: Decoder[StripeError] = deriveDecoder[StripeError].prepare { _.downField("error") } } diff --git a/support-modules/retry/src/test/scala/com/gu/retry/RetrySpec.scala b/support-modules/retry/src/test/scala/com/gu/retry/RetrySpec.scala index 7f04011a5e..396b4447de 100644 --- a/support-modules/retry/src/test/scala/com/gu/retry/RetrySpec.scala +++ b/support-modules/retry/src/test/scala/com/gu/retry/RetrySpec.scala @@ -94,9 +94,9 @@ class RetrySpec extends AnyFlatSpec with Matchers { } } - def countTries[A, B](f: Int => EitherT[Future, A, B]) = { + private def countTries[A, B](f: Int => EitherT[Future, A, B]) = { class Wrapped(var tries: Int = 0) { - def apply() = { + def apply(): EitherT[Future, A, B] = { tries += 1 f(tries) } diff --git a/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/model/FieldNames.scala b/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/model/FieldNames.scala index ecb48ab7c8..8a3a9550f2 100644 --- a/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/model/FieldNames.scala +++ b/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/model/FieldNames.scala @@ -1,24 +1,24 @@ package com.gu.supporterdata.model object FieldNames { - val subscriptionNameField = "subscriptionName" + val subscriptionNameField: String = "subscriptionName" - val identityIdField = "identityId" + val identityIdField: String = "identityId" - val productRatePlanNameField = "productRatePlanName" + val productRatePlanNameField: String = "productRatePlanName" - val productRatePlanIdField = "productRatePlanId" + val productRatePlanIdField: String = "productRatePlanId" - val termEndDateField = "termEndDate" + val termEndDateField: String = "termEndDate" - val contractEffectiveDateField = "contractEffectiveDate" + val contractEffectiveDateField: String = "contractEffectiveDate" - val cancellationDateField = "cancellationDate" + val cancellationDateField: String = "cancellationDate" - val expiryDateNameField = "expiryDate" + val expiryDateNameField: String = "expiryDate" - val contributionAmountField = "contributionAmount" + val contributionAmountField: String = "contributionAmount" - val contributionCurrencyField = "contributionCurrency" + val contributionCurrencyField: String = "contributionCurrency" } diff --git a/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/services/SupporterDataDynamoService.scala b/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/services/SupporterDataDynamoService.scala index 17c5771d58..b5cea4ca2c 100644 --- a/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/services/SupporterDataDynamoService.scala +++ b/support-modules/supporter-product-data-dynamo/src/main/scala/com/gu/supporterdata/services/SupporterDataDynamoService.scala @@ -25,7 +25,9 @@ import scala.util.{Failure, Success, Try} class SupporterDataDynamoService(client: DynamoDbAsyncClient, tableName: String) { - def subscriptionExists(identityId: String, subscriptionId: String)(implicit executionContext: ExecutionContext) = { + def subscriptionExists(identityId: String, subscriptionId: String)(implicit + executionContext: ExecutionContext, + ): Future[Either[String, Boolean]] = { val key = Map( identityIdField -> AttributeValue.builder.s(identityId).build, subscriptionNameField -> AttributeValue.builder.s(subscriptionId).build, @@ -125,18 +127,18 @@ class SupporterDataDynamoService(client: DynamoDbAsyncClient, tableName: String) client.updateItem(updateItemRequest).toScala } - def asEpochSecond(date: LocalDate) = + def asEpochSecond(date: LocalDate): String = date.atStartOfDay .toEpochSecond(ZoneOffset.UTC) .toString - def asIso(date: LocalDate) = + def asIso(date: LocalDate): String = date.format(DateTimeFormatter.ISO_LOCAL_DATE) } object SupporterDataDynamoService { private val ProfileName = "membership" - lazy val CredentialsProvider = AwsCredentialsProviderChain.builder + lazy val CredentialsProvider: AwsCredentialsProviderChain = AwsCredentialsProviderChain.builder .credentialsProviders( ProfileCredentialsProvider.builder.profileName(ProfileName).build, InstanceProfileCredentialsProvider.builder.asyncCredentialUpdateEnabled(false).build, @@ -145,7 +147,7 @@ object SupporterDataDynamoService { ) .build - val clientOverrideConfiguration = ClientOverrideConfiguration.builder + val clientOverrideConfiguration: ClientOverrideConfiguration = ClientOverrideConfiguration.builder .retryPolicy( RetryPolicy .defaultRetryPolicy() @@ -161,7 +163,7 @@ object SupporterDataDynamoService { ) .build - val dynamoDBClient = DynamoDbAsyncClient.builder + val dynamoDBClient: DynamoDbAsyncClient = DynamoDbAsyncClient.builder .overrideConfiguration( clientOverrideConfiguration, ) @@ -169,5 +171,6 @@ object SupporterDataDynamoService { .region(Region.EU_WEST_1) .build - def apply(stage: Stage) = new SupporterDataDynamoService(dynamoDBClient, s"SupporterProductData-${stage.value}") + def apply(stage: Stage): SupporterDataDynamoService = + new SupporterDataDynamoService(dynamoDBClient, s"SupporterProductData-${stage.value}") } diff --git a/support-payment-api/src/main/resources/routes b/support-payment-api/src/main/resources/routes index e9c91b5faf..f468b02127 100644 --- a/support-payment-api/src/main/resources/routes +++ b/support-payment-api/src/main/resources/routes @@ -15,16 +15,16 @@ GET /acquisition/a.gif controllers.AppCon # Execute a pre-authorised Stripe payment POST /contribute/one-off/stripe/execute-payment controllers.StripeController.executePayment -OPTIONS /contribute/one-off/stripe/execute-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/stripe/execute-payment controllers.AppController.corsOptions() # This endpoint is called by Stripe via a webhook to notify us of refunds POST /contribute/one-off/stripe/refund controllers.StripeController.processRefund POST /contribute/one-off/stripe/create-payment controllers.StripeController.createPayment -OPTIONS /contribute/one-off/stripe/create-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/stripe/create-payment controllers.AppController.corsOptions() POST /contribute/one-off/stripe/confirm-payment controllers.StripeController.confirmPayment -OPTIONS /contribute/one-off/stripe/confirm-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/stripe/confirm-payment controllers.AppController.corsOptions() ############################################# # PAYPAL @@ -32,17 +32,17 @@ OPTIONS /contribute/one-off/stripe/confirm-payment controllers.AppCon # Create a payment which can then be authorised via the PayPal web interface POST /contribute/one-off/paypal/create-payment controllers.PaypalController.createPayment -OPTIONS /contribute/one-off/paypal/create-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/paypal/create-payment controllers.AppController.corsOptions() # Execute a payment created with /contribute/one-off/paypal/create-payment # and authorised via the PayPal web interface POST /contribute/one-off/paypal/execute-payment controllers.PaypalController.executePayment -OPTIONS /contribute/one-off/paypal/execute-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/paypal/execute-payment controllers.AppController.corsOptions() # Captures the funds from a payment which has been created & authorised directly via # the PayPal API (not via /contribute/one-off/paypal/create-payment in this API). # This is only used by the mobile app. -POST /contribute/one-off/paypal/capture-payment controllers.PaypalController.capturePayment +POST /contribute/one-off/paypal/capture-payment controllers.PaypalController.capturePayment() # This endpoint is called by PayPal via a webhook to notify us of refunds POST /contribute/one-off/paypal/refund controllers.PaypalController.processRefund @@ -53,13 +53,13 @@ POST /contribute/one-off/paypal/refund controllers.Paypal # Performs a bank details validation check against GoCardless POST /direct-debit/check-account controllers.GoCardlessController.checkBankAccount -OPTIONS /direct-debit/check-account controllers.AppController.corsOptions +OPTIONS /direct-debit/check-account controllers.AppController.corsOptions() ############################################# # Amazon Pay ############################################# POST /contribute/one-off/amazon-pay/execute-payment controllers.AmazonPayController.executePayment -OPTIONS /contribute/one-off/amazon-pay/execute-payment controllers.AppController.corsOptions +OPTIONS /contribute/one-off/amazon-pay/execute-payment controllers.AppController.corsOptions() -POST /contribute/one-off/amazon-pay/notifications controllers.AmazonPayController.notification -OPTIONS /contribute/one-off/amazon-pay/notifications controllers.AppController.corsOptions +POST /contribute/one-off/amazon-pay/notifications controllers.AmazonPayController.notification() +OPTIONS /contribute/one-off/amazon-pay/notifications controllers.AppController.corsOptions() diff --git a/support-payment-api/src/main/scala/MyApplicationLoader.scala b/support-payment-api/src/main/scala/MyApplicationLoader.scala index 5d9897da34..91528a66df 100644 --- a/support-payment-api/src/main/scala/MyApplicationLoader.scala +++ b/support-payment-api/src/main/scala/MyApplicationLoader.scala @@ -1,5 +1,4 @@ import _root_.controllers._ -import org.apache.pekko.actor.ActorSystem import aws.AWSClientBuilder import backend._ import com.amazon.pay.impl.ipn.NotificationFactory @@ -10,6 +9,7 @@ import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement import com.typesafe.scalalogging.StrictLogging import conf.{ConfigLoader, PlayConfigUpdater} import model.{AppThreadPools, AppThreadPoolsProvider, RequestEnvironments} +import org.apache.pekko.actor.ActorSystem import play.api.ApplicationLoader.Context import play.api._ import play.api.db.{DBComponents, HikariCPComponents} @@ -30,10 +30,9 @@ class MyApplicationLoader extends ApplicationLoader with StrictLogging { try { new MyComponents(context).application } catch { - case err: Throwable => { + case err: Throwable => logger.error("Could not start application", err) throw err - } } } } @@ -49,12 +48,12 @@ class MyComponents(context: Context) // At this point, the app either gets two request environments that differ // (Live and Test), or two that are the same (Test and Test). // This will determine, later on, whether passing the "?mode=test" param has any effect - val requestEnvironments: RequestEnvironments = RequestEnvironments.fromAppStage + private val requestEnvironments: RequestEnvironments = RequestEnvironments.fromAppStage val ssm: AWSSimpleSystemsManagement = AWSClientBuilder.buildAWSSimpleSystemsManagementClient() val configLoader: ConfigLoader = new ConfigLoader(ssm) - val playConfigUpdater = new PlayConfigUpdater(configLoader) + private val playConfigUpdater = new PlayConfigUpdater(configLoader) // I guess it could be nice if a given config knew whether it was // request-environment-dependent or app-mode-dependent @@ -68,9 +67,10 @@ class MyComponents(context: Context) implicit val s3Client: AmazonS3 = AWSClientBuilder.buildS3Client() private implicit val system: ActorSystem = ActorSystem() - override lazy val httpErrorHandler = new ErrorHandler(environment, configuration, sourceMapper, Some(router)) + override lazy val httpErrorHandler: ErrorHandler = + new ErrorHandler(environment, configuration, devContext.map(_.sourceMapper), Some(router)) - val cloudWatchClient: AmazonCloudWatchAsync = AWSClientBuilder.buildCloudWatchAsyncClient() + private val cloudWatchClient: AmazonCloudWatchAsync = AWSClientBuilder.buildCloudWatchAsyncClient() val stripeBackendProvider: RequestBasedProvider[StripeBackend] = new StripeBackend.Builder(configLoader, cloudWatchClient) @@ -87,21 +87,21 @@ class MyComponents(context: Context) .buildRequestBasedProvider(requestEnvironments) .valueOr(throw _) - val amazonPayBackendProvider: RequestBasedProvider[AmazonPayBackend] = + private val amazonPayBackendProvider: RequestBasedProvider[AmazonPayBackend] = new AmazonPayBackend.Builder(configLoader, cloudWatchClient) .buildRequestBasedProvider(requestEnvironments) .valueOr(throw _) - implicit val allowedCorsUrl = configuration.get[Seq[String]](s"cors.allowedOrigins").toList + implicit val allowedCorsUrl: List[String] = configuration.get[Seq[String]](s"cors.allowedOrigins").toList // Usually the cloudWatchService is determined based on the request (live vs test). But inside the controllers // we may not know the environment, so we just use live. Note - in DEV/CODE, there is no difference between test/live - val liveCloudWatchService = new CloudWatchService(cloudWatchClient, requestEnvironments.live) + private val liveCloudWatchService = new CloudWatchService(cloudWatchClient, requestEnvironments.live) def parseNotification(headers: Map[String, String], body: String): Notification = NotificationFactory.parseNotification(headers.asJava, body) - override val router = + override val router: Routes = new Routes( httpErrorHandler, new AppController(controllerComponents), diff --git a/support-payment-api/src/main/scala/conf/PlayConfigEncoder.scala b/support-payment-api/src/main/scala/conf/PlayConfigEncoder.scala index 7b7d940019..47055271d4 100644 --- a/support-payment-api/src/main/scala/conf/PlayConfigEncoder.scala +++ b/support-payment-api/src/main/scala/conf/PlayConfigEncoder.scala @@ -18,6 +18,6 @@ class PlayConfigUpdater(configLoader: ConfigLoader) { environments: RequestEnvironments, mode: Mode, ): InitializationResult[Configuration] = { - configLoader.loadConfig[Mode, AppConfig](mode).map(appMode => configuration ++ appMode.asPlayConfig) + configLoader.loadConfig[Mode, AppConfig](mode).map(appMode => configuration.withFallback(appMode.asPlayConfig)) } } diff --git a/support-payment-api/src/main/scala/controllers/ActionOps.scala b/support-payment-api/src/main/scala/controllers/ActionOps.scala index dc1bba2bc3..6a284c783e 100644 --- a/support-payment-api/src/main/scala/controllers/ActionOps.scala +++ b/support-payment-api/src/main/scala/controllers/ActionOps.scala @@ -7,10 +7,11 @@ import play.api.mvc._ import scala.concurrent.{ExecutionContext, Future} import scala.util.Random +import pprint.PPrinter object ActionOps { - val formatter = + val formatter: PPrinter = pprint.copy( additionalHandlers = { case value: ByteString => pprint.Tree.Literal(s"""ByteString("${value.utf8String}")""") diff --git a/support-payment-api/src/main/scala/controllers/AppController.scala b/support-payment-api/src/main/scala/controllers/AppController.scala index b9015b73f5..69c0214a36 100644 --- a/support-payment-api/src/main/scala/controllers/AppController.scala +++ b/support-payment-api/src/main/scala/controllers/AppController.scala @@ -28,7 +28,7 @@ class AppController( Ok("Acquisition received") } - def corsOptions() = CorsAction { request => + def corsOptions(): Action[AnyContent] = CorsAction { request => NoContent.withHeaders("Vary" -> "Origin") } diff --git a/support-payment-api/src/main/scala/controllers/StripeController.scala b/support-payment-api/src/main/scala/controllers/StripeController.scala index d574e8e0da..e1744452e6 100644 --- a/support-payment-api/src/main/scala/controllers/StripeController.scala +++ b/support-payment-api/src/main/scala/controllers/StripeController.scala @@ -30,7 +30,7 @@ class StripeController( import model.stripe.StripeJsonDecoder._ import util.RequestTypeDecoder.instances._ - private val RateLimitingAction = new RateLimitingAction( + private val RateLimitingAction: RateLimitingAction = new RateLimitingAction( cc.parsers, cc.executionContext, cloudWatchService, @@ -39,7 +39,7 @@ class StripeController( stage = RequestEnvironments.stage, ) - lazy val CorsAndRateLimitAction = CorsAction andThen RateLimitingAction + lazy val CorsAndRateLimitAction: ActionBuilder[Request, AnyContent] = CorsAction andThen RateLimitingAction // Stripe Checkout handler, still required for mobile apps payments def executePayment: Action[LegacyStripeChargeRequest] = CorsAndRateLimitAction diff --git a/support-payment-api/src/main/scala/model/amazonpay/AmazonPayApiError.scala b/support-payment-api/src/main/scala/model/amazonpay/AmazonPayApiError.scala index cdf3b03285..4546c029ba 100644 --- a/support-payment-api/src/main/scala/model/amazonpay/AmazonPayApiError.scala +++ b/support-payment-api/src/main/scala/model/amazonpay/AmazonPayApiError.scala @@ -11,7 +11,7 @@ case class AmazonPayApiError(responseCode: Option[Int], message: String, failure object AmazonPayApiError { - val amazonPayErrorText = "Amazon Pay Switch not enabled" + val amazonPayErrorText: String = "Amazon Pay Switch not enabled" def fromString(message: String): AmazonPayApiError = AmazonPayApiError(None, message) def withReason(code: Int, message: String, reason: String): AmazonPayApiError = { diff --git a/support-payment-api/src/main/scala/model/amazonpay/AmazonPaymentData.scala b/support-payment-api/src/main/scala/model/amazonpay/AmazonPaymentData.scala index 0b5eead2f1..868fa082cd 100644 --- a/support-payment-api/src/main/scala/model/amazonpay/AmazonPaymentData.scala +++ b/support-payment-api/src/main/scala/model/amazonpay/AmazonPaymentData.scala @@ -1,5 +1,6 @@ package model.amazonpay +import io.circe.Decoder import io.circe.generic.JsonCodec import io.circe.generic.semiauto._ import model.{AcquisitionData, Currency} @@ -10,5 +11,5 @@ object BundledAmazonPayRequest { case class AmazonPayRequest(paymentData: AmazonPaymentData, acquisitionData: Option[AcquisitionData]) import controllers.JsonReadableOps._ - implicit val bundledAmazonPayRequestDecoder = deriveDecoder[AmazonPayRequest] + implicit val bundledAmazonPayRequestDecoder: Decoder[AmazonPayRequest] = deriveDecoder[AmazonPayRequest] } diff --git a/support-payment-api/src/main/scala/model/paypal/PaypalApiError.scala b/support-payment-api/src/main/scala/model/paypal/PaypalApiError.scala index 6fa391f3f2..7b0add8998 100644 --- a/support-payment-api/src/main/scala/model/paypal/PaypalApiError.scala +++ b/support-payment-api/src/main/scala/model/paypal/PaypalApiError.scala @@ -16,7 +16,7 @@ import scala.jdk.CollectionConverters._ object PaypalApiError { - val paypalErrorText = "Paypal Switch not enabled" + val paypalErrorText: String = "Paypal Switch not enabled" def fromString(message: String): PaypalApiError = PaypalApiError(None, None, message) diff --git a/support-payment-api/src/main/scala/model/stripe/StripeApiError.scala b/support-payment-api/src/main/scala/model/stripe/StripeApiError.scala index b57439c115..c4642a43f3 100644 --- a/support-payment-api/src/main/scala/model/stripe/StripeApiError.scala +++ b/support-payment-api/src/main/scala/model/stripe/StripeApiError.scala @@ -30,8 +30,8 @@ case class StripeApiError( object StripeApiError { - val recaptchaErrorText = "Recaptcha failed" - val stripeDisabledErrorText = "Stripe payments are currently disabled" + val recaptchaErrorText: String = "Recaptcha failed" + val stripeDisabledErrorText: String = "Stripe payments are currently disabled" def fromString(message: String, publicKey: Option[String]): StripeApiError = StripeApiError(None, None, None, message, publicKey) diff --git a/support-payment-api/src/main/scala/model/stripe/StripePaymentIntentsApiResponse.scala b/support-payment-api/src/main/scala/model/stripe/StripePaymentIntentsApiResponse.scala index d3f4574a7d..f6a28e2452 100644 --- a/support-payment-api/src/main/scala/model/stripe/StripePaymentIntentsApiResponse.scala +++ b/support-payment-api/src/main/scala/model/stripe/StripePaymentIntentsApiResponse.scala @@ -1,5 +1,6 @@ package model.stripe +import io.circe.Encoder import io.circe.generic.semiauto._ sealed trait StripePaymentIntentsApiResponse @@ -9,6 +10,6 @@ object StripePaymentIntentsApiResponse { case class RequiresAction(clientSecret: String) extends StripePaymentIntentsApiResponse - implicit val successEncoder = deriveEncoder[Success] - implicit val requiresActionEncoder = deriveEncoder[RequiresAction] + implicit val successEncoder: Encoder.AsObject[Success] = deriveEncoder[Success] + implicit val requiresActionEncoder: Encoder.AsObject[RequiresAction] = deriveEncoder[RequiresAction] } diff --git a/support-payment-api/src/main/scala/model/stripe/StripeRequest.scala b/support-payment-api/src/main/scala/model/stripe/StripeRequest.scala index 12c073d2f1..efde9f2266 100644 --- a/support-payment-api/src/main/scala/model/stripe/StripeRequest.scala +++ b/support-payment-api/src/main/scala/model/stripe/StripeRequest.scala @@ -82,7 +82,7 @@ object StripeJsonDecoder { // Private because it should only be constructed using the accompanying Decoder class NonEmptyString private (val value: String) extends AnyVal { - override def toString(): String = value + override def toString: String = value } object NonEmptyString { @@ -169,6 +169,6 @@ object StripePaymentIntentRequest { ) extends StripeRequest import controllers.JsonReadableOps._ - implicit val createPaymentIntentDecoder = deriveDecoder[CreatePaymentIntent] - implicit val confirmPaymentIntent = deriveDecoder[ConfirmPaymentIntent] + implicit val createPaymentIntentDecoder: Decoder[CreatePaymentIntent] = deriveDecoder[CreatePaymentIntent] + implicit val confirmPaymentIntent: Decoder[ConfirmPaymentIntent] = deriveDecoder[ConfirmPaymentIntent] } diff --git a/support-payment-api/src/main/scala/services/AmazonPayService.scala b/support-payment-api/src/main/scala/services/AmazonPayService.scala index 535e866172..2f160b5364 100644 --- a/support-payment-api/src/main/scala/services/AmazonPayService.scala +++ b/support-payment-api/src/main/scala/services/AmazonPayService.scala @@ -13,6 +13,7 @@ import conf.AmazonPayConfig import model.amazonpay._ import model.{Currency, DefaultThreadPool} import services.AmazonPayService.CurrencyNotFoundException +import com.amazon.pay.response.parser.CancelOrderReferenceResponseData /* Based on the sample implementation found here @@ -21,12 +22,12 @@ https://github.com/amzn/amazon-pay-sdk-java#one-time-transaction-api-flow */ class AmazonPayService(config: AmazonPayConfig)(implicit pool: DefaultThreadPool) extends StrictLogging { - val copyForEmail = + val copyForEmail: String = "Thank you for making a contribution. Your support helps protect the Guardian’s independence and means we can keep delivering quality journalism that’s open for all." - val storeName = "The Guardian" + val storeName: String = "The Guardian" - val clientConfig = new PayConfig() + val clientConfig: PayConfig = new PayConfig() .withSellerId(config.merchantId) .withAccessKey(config.accessKey) .withSecretKey(config.secretKey) @@ -35,9 +36,9 @@ class AmazonPayService(config: AmazonPayConfig)(implicit pool: DefaultThreadPool import com.amazon.pay.impl.PayClient - val client = new PayClient(clientConfig) + val client: PayClient = new PayClient(clientConfig) - def getOrderReference(orderReferenceId: String) = { + def getOrderReference(orderReferenceId: String): Either[AmazonPayApiError, OrderReferenceDetails] = { Either .catchNonFatal { client.getOrderReferenceDetails(new GetOrderReferenceDetailsRequest(orderReferenceId)).getDetails @@ -47,7 +48,9 @@ class AmazonPayService(config: AmazonPayConfig)(implicit pool: DefaultThreadPool } } - def cancelOrderReference(orderRef: OrderReferenceDetails) = { + def cancelOrderReference( + orderRef: OrderReferenceDetails, + ): Either[AmazonPayApiError, CancelOrderReferenceResponseData] = { Either .catchNonFatal { client.cancelOrderReference(new CancelOrderReferenceRequest(orderRef.getAmazonOrderReferenceId)) diff --git a/support-payment-api/src/main/scala/services/ContributionsStoreService.scala b/support-payment-api/src/main/scala/services/ContributionsStoreService.scala index c0e780f9ef..9aa394fcad 100644 --- a/support-payment-api/src/main/scala/services/ContributionsStoreService.scala +++ b/support-payment-api/src/main/scala/services/ContributionsStoreService.scala @@ -13,7 +13,7 @@ import model.{InitializationError, InitializationResult, SQSThreadPool} import services.ContributionsStoreQueueService.Message import java.time.LocalDateTime -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.Future import scala.util.control.NonFatal @@ -55,7 +55,7 @@ object ContributionsStoreQueueService { case class RefundedPaymentId(paymentId: String) extends Message object Message { - private implicit val messageEncoder = Encoder[Message] { message => + private implicit val messageEncoder: Encoder[Message] = Encoder[Message] { message => import io.circe.generic.auto._ // copied from earlier version of circe-core to prevent seconds appearing in the serialised form @@ -86,7 +86,7 @@ object ContributionsStoreQueueService { ) } -class ContributionsStoreQueueService(queueUrl: String, keyId: String, region: String = "eu-west-1")(implicit +class ContributionsStoreQueueService(queueUrl: String, keyId: String)(implicit pool: SQSThreadPool, ) extends ContributionsStoreService with StrictLogging { diff --git a/support-payment-api/src/main/scala/services/EmailService.scala b/support-payment-api/src/main/scala/services/EmailService.scala index 0b317287ac..196439b978 100644 --- a/support-payment-api/src/main/scala/services/EmailService.scala +++ b/support-payment-api/src/main/scala/services/EmailService.scala @@ -14,7 +14,7 @@ import scala.concurrent.Future class EmailService(sqsClient: AmazonSQSAsync, queueName: String)(implicit pool: DefaultThreadPool) extends StrictLogging { - val thankYouQueueUrl = sqsClient.getQueueUrl(queueName).getQueueUrl + val thankYouQueueUrl: String = sqsClient.getQueueUrl(queueName).getQueueUrl /* * No need to provide an AsyncHandler as the process is fire and forget and it's not required any action if the message diff --git a/support-payment-api/src/main/scala/services/IdentityService.scala b/support-payment-api/src/main/scala/services/IdentityService.scala index 6e137d549d..9a670f3792 100644 --- a/support-payment-api/src/main/scala/services/IdentityService.scala +++ b/support-payment-api/src/main/scala/services/IdentityService.scala @@ -1,15 +1,12 @@ package services -import cats.Monad import cats.data.EitherT import cats.instances.future._ -import com.gu.retry.EitherTRetry import com.gu.retry.EitherTRetry.retry import com.typesafe.scalalogging.StrictLogging import conf.IdentityConfig import model.DefaultThreadPool import play.api.libs.ws.WSClient -import services.IdentityClient.{ApiError, ContextualError} import scala.concurrent.Future import scala.concurrent.duration.DurationInt diff --git a/support-payment-api/src/main/scala/services/RecaptchaService.scala b/support-payment-api/src/main/scala/services/RecaptchaService.scala index d27c6eeb53..bab24104e9 100644 --- a/support-payment-api/src/main/scala/services/RecaptchaService.scala +++ b/support-payment-api/src/main/scala/services/RecaptchaService.scala @@ -19,7 +19,7 @@ object RecaptchaResponse { } class RecaptchaService(wsClient: WSClient, config: RecaptchaConfig)(implicit ec: ExecutionContext) { - val recaptchaEndpoint = "https://www.google.com/recaptcha/api/siteverify" + val recaptchaEndpoint: String = "https://www.google.com/recaptcha/api/siteverify" def verify(token: String): EitherT[Future, StripeApiError, RecaptchaResponse] = wsClient @@ -41,7 +41,9 @@ class RecaptchaService(wsClient: WSClient, config: RecaptchaConfig)(implicit ec: } object RecaptchaService { - def fromRecaptchaConfig(config: RecaptchaConfig)(implicit ws: WSClient, pool: DefaultThreadPool) = + def fromRecaptchaConfig( + config: RecaptchaConfig, + )(implicit ws: WSClient, pool: DefaultThreadPool): Validated[InitializationError, RecaptchaService] = Validated .catchNonFatal { new RecaptchaService(ws, config) diff --git a/support-payment-api/src/main/scala/services/SupporterProductDataService.scala b/support-payment-api/src/main/scala/services/SupporterProductDataService.scala index c265ec2aa8..9cd13bf492 100644 --- a/support-payment-api/src/main/scala/services/SupporterProductDataService.scala +++ b/support-payment-api/src/main/scala/services/SupporterProductDataService.scala @@ -13,7 +13,7 @@ import java.time.LocalDate import scala.concurrent.{ExecutionContext, Future} class SupporterProductDataService(environment: Environment) extends StrictLogging { - val dynamoService = SupporterDataDynamoService(environment match { + val dynamoService: SupporterDataDynamoService = SupporterDataDynamoService(environment match { case Live => PROD case _ => CODE }) diff --git a/support-payment-api/src/main/scala/services/SwitchService.scala b/support-payment-api/src/main/scala/services/SwitchService.scala index 1bae53d1e7..1e390e72ee 100644 --- a/support-payment-api/src/main/scala/services/SwitchService.scala +++ b/support-payment-api/src/main/scala/services/SwitchService.scala @@ -24,9 +24,9 @@ sealed trait SwitchState { object SwitchState { def fromString(s: String): SwitchState = if (s.toLowerCase == "on") On else Off - case object On extends SwitchState { val isOn = true } + case object On extends SwitchState { val isOn: Boolean = true } - case object Off extends SwitchState { val isOn = false } + case object Off extends SwitchState { val isOn: Boolean = false } implicit val switchStateEncoder: Encoder[SwitchState] = Encoder.encodeString.contramap[SwitchState](_.toString) implicit val switchStateDecoder: Decoder[SwitchState] = Decoder.decodeString.map(SwitchState.fromString) diff --git a/support-payment-api/src/test/scala/actions/RateLimitingActionSpec.scala b/support-payment-api/src/test/scala/actions/RateLimitingActionSpec.scala index 252de67811..f797349229 100644 --- a/support-payment-api/src/test/scala/actions/RateLimitingActionSpec.scala +++ b/support-payment-api/src/test/scala/actions/RateLimitingActionSpec.scala @@ -13,9 +13,10 @@ import scala.concurrent.{Await, Future} import scala.concurrent.duration.FiniteDuration import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global +import play.api.mvc.ControllerComponents class RateLimitingActionSpec extends AnyWordSpec with Matchers with Results with MockitoSugar { - val cc = stubControllerComponents() + val cc: ControllerComponents = stubControllerComponents() val mockCloudWatchService: CloudWatchService = mock[CloudWatchService] private def newAction(maxRequests: Int, interval: FiniteDuration) = diff --git a/support-payment-api/src/test/scala/backend/AmazonPayBackendIntegrationSpec.scala b/support-payment-api/src/test/scala/backend/AmazonPayBackendIntegrationSpec.scala index 9a0b65351f..cf48bd896b 100644 --- a/support-payment-api/src/test/scala/backend/AmazonPayBackendIntegrationSpec.scala +++ b/support-payment-api/src/test/scala/backend/AmazonPayBackendIntegrationSpec.scala @@ -85,10 +85,10 @@ class AmazonPayBackendIntegrationSpec val mockSoftOptInsService: SoftOptInsService = mock[SoftOptInsService] val mockSwitchService: SwitchService = mock[SwitchService] - val paymentdata = AmazonPaymentData("refId", BigDecimal(25), Currency.USD, "email@thegulocal.com") - val amazonPayRequest = AmazonPayRequest(paymentdata, None) - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, None) - val paymentError = AmazonPayApiError.fromString("Error response") + val paymentdata: AmazonPaymentData = AmazonPaymentData("refId", BigDecimal(25), Currency.USD, "email@thegulocal.com") + val amazonPayRequest: AmazonPayRequest = AmazonPayRequest(paymentdata, None) + val clientBrowserInfo: ClientBrowserInfo = ClientBrowserInfo("", "", None, None, None) + val paymentError: AmazonPayApiError = AmazonPayApiError.fromString("Error response") "AmazonPayBackend.makePayment" should "not returning an XML marshalling error" in { lazy val config: AmazonPayConfig = configForTestEnvironment[AmazonPayConfig]() diff --git a/support-payment-api/src/test/scala/backend/AmazonPayBackendSpec.scala b/support-payment-api/src/test/scala/backend/AmazonPayBackendSpec.scala index a0ff34c078..82778e5bad 100644 --- a/support-payment-api/src/test/scala/backend/AmazonPayBackendSpec.scala +++ b/support-payment-api/src/test/scala/backend/AmazonPayBackendSpec.scala @@ -24,11 +24,12 @@ import util.FutureEitherValues import javax.xml.datatype.DatatypeFactory import scala.concurrent.{ExecutionContext, Future} +import scala.xml.Elem class AmazonPayBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { // -- entities - val acquisitionData = + val acquisitionData: AcquisitionData = AcquisitionData( Some("platform"), None, @@ -45,18 +46,18 @@ class AmazonPayBackendFixture(implicit ec: ExecutionContext) extends MockitoSuga None, Some("N1 9GU"), ) - val countrySubdivisionCode = Some("NY") - val dbError = ContributionsStoreService.Error(new Exception("DB error response")) - val identityError = IdentityClient.ContextualError( + val countrySubdivisionCode: Some[String] = Some("NY") + val dbError: ContributionsStoreService.Error = ContributionsStoreService.Error(new Exception("DB error response")) + val identityError: IdentityClient.ContextualError = IdentityClient.ContextualError( IdentityClient.Error.fromThrowable(new Exception("Identity error response")), IdentityClient.GetUser("test@theguardian.com"), ) - val expectedGuestToken = Some("guest-token") + val expectedGuestToken: Some[String] = Some("guest-token") - val paymentError = AmazonPayApiError.fromString("Error response") - val amazonPaySwitchError = AmazonPayApiError.fromString("Amazon Pay Switch not enabled") + val paymentError: AmazonPayApiError = AmazonPayApiError.fromString("Error response") + val amazonPaySwitchError: AmazonPayApiError = AmazonPayApiError.fromString("Amazon Pay Switch not enabled") val emailError: EmailService.Error = EmailService.Error(new Exception("Email error response")) - val responseXml = + val responseXml: Elem = P01-0000000-0000000-000000 P01-0000000-0000000-Ref SellerInitiated @@ -79,16 +80,17 @@ class AmazonPayBackendFixture(implicit ec: ExecutionContext) extends MockitoSuga val paymentServiceResponseError: Either[AmazonPayApiError, OrderReferenceDetails] = Either.left(paymentError) - val mockOrderRef = mock[OrderReferenceDetails] - - val mockConfirmOrderResponse = mock[ConfirmOrderReferenceResponse] - val mockOrderTotal = mock[OrderTotal] - val responseData = new ResponseData(200, responseXml.toString) - val confirmOrderData = new ConfirmOrderReferenceResponseData(mockConfirmOrderResponse, responseData) - val mockAuthorizationDetails = mock[AuthorizationDetails] - val mockCloseResponseDetails = mock[CloseOrderReferenceResponse] - val mockOrderReferenceStatus = mock[OrderReferenceStatus] - val mockAuthStatus = mock[Status] + val mockOrderRef: OrderReferenceDetails = mock[OrderReferenceDetails] + + val mockConfirmOrderResponse: ConfirmOrderReferenceResponse = mock[ConfirmOrderReferenceResponse] + val mockOrderTotal: OrderTotal = mock[OrderTotal] + val responseData: ResponseData = new ResponseData(200, responseXml.toString) + val confirmOrderData: ConfirmOrderReferenceResponseData = + new ConfirmOrderReferenceResponseData(mockConfirmOrderResponse, responseData) + val mockAuthorizationDetails: AuthorizationDetails = mock[AuthorizationDetails] + val mockCloseResponseDetails: CloseOrderReferenceResponse = mock[CloseOrderReferenceResponse] + val mockOrderReferenceStatus: OrderReferenceStatus = mock[OrderReferenceStatus] + val mockAuthStatus: Status = mock[Status] val setOrderRefRes: Either[AmazonPayApiError, OrderReferenceDetails] = Either.right(mockOrderRef) val getOrderRefRes: Either[AmazonPayApiError, OrderReferenceDetails] = Either.right(mockOrderRef) @@ -153,7 +155,7 @@ class AmazonPayBackendFixture(implicit ec: ExecutionContext) extends MockitoSuga val mockSwitchService: SwitchService = mock[SwitchService] // -- test obj - val amazonPayBackend = new AmazonPayBackend( + val amazonPayBackend: AmazonPayBackend = new AmazonPayBackend( mockCloudWatchService, mockAmazonPayService, mockIdentityService, @@ -165,8 +167,8 @@ class AmazonPayBackendFixture(implicit ec: ExecutionContext) extends MockitoSuga mockSwitchService, )(DefaultThreadPool(ec)) - val paymentdata = AmazonPaymentData("refId", BigDecimal(25), Currency.USD, "email@thegulocal.com") - val amazonPayRequest = AmazonPayRequest(paymentdata, Some(acquisitionData)) + val paymentdata: AmazonPaymentData = AmazonPaymentData("refId", BigDecimal(25), Currency.USD, "email@thegulocal.com") + val amazonPayRequest: AmazonPayRequest = AmazonPayRequest(paymentdata, Some(acquisitionData)) } @@ -174,7 +176,7 @@ class AmazonPayBackendSpec extends AnyWordSpec with Matchers with FutureEitherVa implicit val executionContext: ExecutionContext = ExecutionContext.global - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, None) + val clientBrowserInfo: ClientBrowserInfo = ClientBrowserInfo("", "", None, None, None) "Amazon Pay Backend" when { "A request is made to create a charge/payment " should { diff --git a/support-payment-api/src/test/scala/backend/PaypalBackendSpec.scala b/support-payment-api/src/test/scala/backend/PaypalBackendSpec.scala index e6c0ba553a..d5f2090949 100644 --- a/support-payment-api/src/test/scala/backend/PaypalBackendSpec.scala +++ b/support-payment-api/src/test/scala/backend/PaypalBackendSpec.scala @@ -21,11 +21,13 @@ import util.FutureEitherValues import scala.concurrent.{ExecutionContext, Future} import scala.jdk.CollectionConverters._ +import com.paypal.api.payments.Transaction +import java.{util => ju} class PaypalBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { // -- entities - val acquisitionData = + val acquisitionData: AcquisitionData = AcquisitionData( Some("platform"), None, @@ -42,39 +44,39 @@ class PaypalBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { None, Some("N1 9GU"), ) - val capturePaypalPaymentData = + val capturePaypalPaymentData: CapturePaypalPaymentData = CapturePaypalPaymentData(CapturePaymentData("paymentId"), acquisitionData, Some("email@email.com")) - val countrySubdivisionCode = Some("NY") - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, countrySubdivisionCode) - val executePaypalPaymentData = ExecutePaypalPaymentData( + val countrySubdivisionCode: Some[String] = Some("NY") + val clientBrowserInfo: ClientBrowserInfo = ClientBrowserInfo("", "", None, None, countrySubdivisionCode) + val executePaypalPaymentData: ExecutePaypalPaymentData = ExecutePaypalPaymentData( ExecutePaymentData("paymentId", "payerId"), acquisitionData, "email@email.com", ) - val paypalRefundWebHookData = PaypalRefundWebHookData( + val paypalRefundWebHookData: PaypalRefundWebHookData = PaypalRefundWebHookData( body = PaypalRefundWebHookBody("parent_payment_id", "{}"), headers = Map.empty, ) - val dbError = ContributionsStoreService.Error(new Exception("DB error response")) + val dbError: ContributionsStoreService.Error = ContributionsStoreService.Error(new Exception("DB error response")) - val identityError = IdentityClient.ContextualError( + val identityError: IdentityClient.ContextualError = IdentityClient.ContextualError( IdentityClient.Error.fromThrowable(new Exception("Identity error response")), IdentityClient.GetUser("test@theguardian.com"), ) - val payPalSwitchError = PaypalApiError.fromString("Paypal Switch not enabled") - val paymentError = PaypalApiError.fromString("Error response") - val backendPaymentError = BackendError.fromPaypalAPIError(paymentError) - val backendDbError = BackendError.fromDatabaseError(dbError) + val payPalSwitchError: PaypalApiError = PaypalApiError.fromString("Paypal Switch not enabled") + val paymentError: PaypalApiError = PaypalApiError.fromString("Error response") + val backendPaymentError: BackendError = BackendError.fromPaypalAPIError(paymentError) + val backendDbError: BackendError = BackendError.fromDatabaseError(dbError) val emailError: EmailService.Error = EmailService.Error(new Exception("Email error response")) // -- mocks val paymentMock: Payment = mock[Payment] val enrichedPaymentMock: EnrichedPaypalPayment = mock[EnrichedPaypalPayment] - val amount = mock[Amount] - val payer = mock[Payer] - val payerInfo = mock[PayerInfo] - val transaction = mock[com.paypal.api.payments.Transaction] - val transactions = List(transaction).asJava + val amount: Amount = mock[Amount] + val payer: Payer = mock[Payer] + val payerInfo: PayerInfo = mock[PayerInfo] + val transaction: Transaction = mock[com.paypal.api.payments.Transaction] + val transactions: ju.List[Transaction] = List(transaction).asJava // -- service responses val paypalSwitchFailResponse: EitherT[Future, PaypalApiError, Payment] = @@ -103,7 +105,7 @@ class PaypalBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { EitherT.left(Future.successful(SoftOptInsServiceError("an error from soft opt-ins"))) val acquisitionsEventBusResponse: Future[Either[String, Unit]] = Future.successful(Right(())) - val acquisitionsEventBusErrorMessage = "an event bus error" + val acquisitionsEventBusErrorMessage: String = "an event bus error" val acquisitionsEventBusResponseError: Future[Either[String, Unit]] = Future.successful(Left(acquisitionsEventBusErrorMessage)) val identityResponse: EitherT[Future, IdentityClient.ContextualError, String] = @@ -146,7 +148,7 @@ class PaypalBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { val mockSwitchService: SwitchService = mock[SwitchService] // -- test obj - val paypalBackend = new PaypalBackend( + val paypalBackend: PaypalBackend = new PaypalBackend( mockPaypalService, mockDatabaseService, mockIdentityService, @@ -180,7 +182,7 @@ class PaypalBackendSpec extends AnyWordSpec with Matchers with FutureEitherValue implicit val executionContext: ExecutionContext = ExecutionContext.global - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, None) + val clientBrowserInfo: ClientBrowserInfo = ClientBrowserInfo("", "", None, None, None) "Paypal Backend" when { diff --git a/support-payment-api/src/test/scala/backend/StripeBackendSpec.scala b/support-payment-api/src/test/scala/backend/StripeBackendSpec.scala index 74bf199fdf..67a3e1f226 100644 --- a/support-payment-api/src/test/scala/backend/StripeBackendSpec.scala +++ b/support-payment-api/src/test/scala/backend/StripeBackendSpec.scala @@ -33,10 +33,10 @@ import scala.concurrent.{ExecutionContext, Future} class StripeBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { // -- entities - val email = Json.fromString("email@email.com").as[NonEmptyString].toOption.get - val token = Json.fromString("token").as[NonEmptyString].toOption.get - val recaptchaToken = "recaptchaToken" - val acquisitionData = + val email: NonEmptyString = Json.fromString("email@email.com").as[NonEmptyString].toOption.get + val token: NonEmptyString = Json.fromString("token").as[NonEmptyString].toOption.get + val recaptchaToken: String = "recaptchaToken" + val acquisitionData: AcquisitionData = AcquisitionData( Some("platform"), None, @@ -53,11 +53,12 @@ class StripeBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { None, Some("N1 9GU"), ) - val stripePaymentData = StripePaymentData(email, Currency.USD, 12, None) - val legacyStripePaymentData = LegacyStripePaymentData(email, Currency.USD, 12, None, token) - val stripePublicKey = StripePublicKey("pk_test_FOOBAR") - val stripeChargeRequest = LegacyStripeChargeRequest(legacyStripePaymentData, acquisitionData, Some(stripePublicKey)) - val createPaymentIntent = + val stripePaymentData: StripePaymentData = StripePaymentData(email, Currency.USD, 12, None) + val legacyStripePaymentData: LegacyStripePaymentData = LegacyStripePaymentData(email, Currency.USD, 12, None, token) + val stripePublicKey: StripePublicKey = StripePublicKey("pk_test_FOOBAR") + val stripeChargeRequest: LegacyStripeChargeRequest = + LegacyStripeChargeRequest(legacyStripePaymentData, acquisitionData, Some(stripePublicKey)) + val createPaymentIntent: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentData, @@ -65,30 +66,30 @@ class StripeBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { Some(stripePublicKey), recaptchaToken, ) - val confirmPaymentIntent = + val confirmPaymentIntent: ConfirmPaymentIntent = ConfirmPaymentIntent("id", stripePaymentData, acquisitionData, Some(stripePublicKey)) - val countrySubdivisionCode = Some("NY") - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, countrySubdivisionCode) - val stripeHookObject = StripeHookObject("id", "GBP") - val stripeHookData = StripeHookData(stripeHookObject) - val stripeHook = StripeRefundHook("id", PaymentStatus.Paid, stripeHookData) - val dbError = ContributionsStoreService.Error(new Exception("DB error response")) + val countrySubdivisionCode: Option[String] = Some("NY") + val clientBrowserInfo: ClientBrowserInfo = ClientBrowserInfo("", "", None, None, countrySubdivisionCode) + val stripeHookObject: StripeHookObject = StripeHookObject("id", "GBP") + val stripeHookData: StripeHookData = StripeHookData(stripeHookObject) + val stripeHook: StripeRefundHook = StripeRefundHook("id", PaymentStatus.Paid, stripeHookData) + val dbError: ContributionsStoreService.Error = ContributionsStoreService.Error(new Exception("DB error response")) - val identityError = IdentityClient.ContextualError( + val identityError: IdentityClient.ContextualError = IdentityClient.ContextualError( IdentityClient.Error.fromThrowable(new Exception("Identity error response")), IdentityClient.GetUser("test@theguardian.com"), ) - val stripeDisabledErrorText = "Stripe payments are currently disabled" - val paymentError = PaypalApiError.fromString("Error response") - val stripeApiError = StripeApiError.fromThrowable(new Exception("Stripe error"), None) - val backendError = BackendError.fromStripeApiError(stripeApiError) + val stripeDisabledErrorText: String = "Stripe payments are currently disabled" + val paymentError: PaypalApiError = PaypalApiError.fromString("Error response") + val stripeApiError: StripeApiError = StripeApiError.fromThrowable(new Exception("Stripe error"), None) + val backendError: BackendError = BackendError.fromStripeApiError(stripeApiError) val emailError: EmailService.Error = EmailService.Error(new Exception("Email error response")) // -- mocks val chargeMock: Charge = mock[Charge] - val eventMock = mock[Event] - val paymentIntentMock = mock[PaymentIntent] + val eventMock: Event = mock[Event] + val paymentIntentMock: PaymentIntent = mock[PaymentIntent] // -- service responses val paymentServiceResponse: EitherT[Future, StripeApiError, Charge] = @@ -119,7 +120,7 @@ class StripeBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { EitherT.right(Future.successful(())) val acquisitionsEventBusResponse: Future[Either[String, Unit]] = Future.successful(Right(())) - val acquisitionsEventBusErrorMessage = "an event bus error" + val acquisitionsEventBusErrorMessage: String = "an event bus error" val acquisitionsEventBusResponseError: Future[Either[String, Unit]] = Future.successful(Left(acquisitionsEventBusErrorMessage)) val emailResponseError: EitherT[Future, EmailService.Error, SendMessageResult] = @@ -194,7 +195,7 @@ class StripeBackendFixture(implicit ec: ExecutionContext) extends MockitoSugar { when(mockSwitchService.allSwitches).thenReturn(switchServiceOnResponse) // -- test obj - val stripeBackend = new StripeBackend( + val stripeBackend: StripeBackend = new StripeBackend( mockStripeService, mockDatabaseService, mockIdentityService, @@ -246,14 +247,13 @@ class StripeBackendSpec implicit val executionContext: ExecutionContext = ExecutionContext.global - val clientBrowserInfo = ClientBrowserInfo("", "", None, None, None) - "Stripe Backend" when { "a request is made to create a Payment Intent" should { "return Stripe payments are currently disabled response if stripe checkout switch is off in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithStripe = StripePaymentData(email, Currency.USD, 12, Some(StripeCheckout)) - val createPaymentIntentWithStripeCheckout = + val stripePaymentDataWithStripe: StripePaymentData = + StripePaymentData(email, Currency.USD, 12, Some(StripeCheckout)) + val createPaymentIntentWithStripeCheckout: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripe, @@ -268,8 +268,9 @@ class StripeBackendSpec } "return Stripe payments are currently disabled response if stripe Apple Pay switch is off in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithApplePay = StripePaymentData(email, Currency.USD, 12, Some(StripeApplePay)) - val createPaymentIntentWithStripeApplePay = + val stripePaymentDataWithApplePay: StripePaymentData = + StripePaymentData(email, Currency.USD, 12, Some(StripeApplePay)) + val createPaymentIntentWithStripeApplePay: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithApplePay, @@ -283,9 +284,9 @@ class StripeBackendSpec StripeApiError.fromString(stripeDisabledErrorText, None) } "return Stripe payments are currently disabled response if stripe payment request button switch is off in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithStripePaymentRequest = + val stripePaymentDataWithStripePaymentRequest: StripePaymentData = StripePaymentData(email, Currency.USD, 12, Some(StripePaymentRequestButton)) - val createPaymentIntentWithStripePaymentRequest = + val createPaymentIntentWithStripePaymentRequest: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripePaymentRequest, @@ -301,8 +302,9 @@ class StripeBackendSpec StripeApiError.fromString(stripeDisabledErrorText, None) } "return Success if stripe checkout switch is On in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithStripe = StripePaymentData(email, Currency.USD, 12, Some(StripeCheckout)) - val createPaymentIntentWithStripeCheckout = + val stripePaymentDataWithStripe: StripePaymentData = + StripePaymentData(email, Currency.USD, 12, Some(StripeCheckout)) + val createPaymentIntentWithStripeCheckout: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripe, @@ -333,8 +335,9 @@ class StripeBackendSpec } "return Success if stripe apple pay switch is On in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithStripeApplePay = StripePaymentData(email, Currency.USD, 12, Some(StripeApplePay)) - val createPaymentIntentWithStripeApplePay = + val stripePaymentDataWithStripeApplePay: StripePaymentData = + StripePaymentData(email, Currency.USD, 12, Some(StripeApplePay)) + val createPaymentIntentWithStripeApplePay: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripeApplePay, @@ -363,9 +366,9 @@ class StripeBackendSpec StripePaymentIntentsApiResponse.Success() } "return Success if stripe payment request button switch is On in support-admin-console" in new StripeBackendFixture { - val stripePaymentDataWithStripePaymentRequest = + val stripePaymentDataWithStripePaymentRequest: StripePaymentData = StripePaymentData(email, Currency.USD, 12, Some(StripePaymentRequestButton)) - val createPaymentIntentWithStripePaymentRequest = + val createPaymentIntentWithStripePaymentRequest: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripePaymentRequest, @@ -400,9 +403,10 @@ class StripeBackendSpec "a request is made to create a charge/payment" should { "return error if the email address is invalid due to a comma in it" in new StripeBackendFixture { - val emailWithComma = Json.fromString("email,address@email.com").as[NonEmptyString].toOption.get - val stripePaymentDataWithStripe = StripePaymentData(emailWithComma, Currency.USD, 12, Some(StripeCheckout)) - val createPaymentIntentWithStripeCheckout = + val emailWithComma: NonEmptyString = Json.fromString("email,address@email.com").as[NonEmptyString].toOption.get + val stripePaymentDataWithStripe: StripePaymentData = + StripePaymentData(emailWithComma, Currency.USD, 12, Some(StripeCheckout)) + val createPaymentIntentWithStripeCheckout: CreatePaymentIntent = CreatePaymentIntent( "payment-method-id", stripePaymentDataWithStripe, @@ -493,8 +497,9 @@ class StripeBackendSpec when(mockSoftOptInsService.sendMessage(any(), any())(any())).thenReturn(softOptInsResponse) when(mockAcquisitionsEventBusService.putAcquisitionEvent(any())) .thenReturn(acquisitionsEventBusResponse) - val trackContribution = PrivateMethod[Future[List[BackendError]]](Symbol("trackContribution")) - val result = + val trackContribution: PrivateMethod[Future[List[BackendError]]] = + PrivateMethod[Future[List[BackendError]]](Symbol("trackContribution")) + val result: Future[List[BackendError]] = stripeBackend invokePrivate trackContribution(chargeMock, stripeChargeRequest, None, clientBrowserInfo) result.futureValue mustBe List(BackendError.Database(dbError)) @@ -510,10 +515,11 @@ class StripeBackendSpec when(mockSoftOptInsService.sendMessage(any(), any())(any())).thenReturn(softOptInsResponse) when(mockAcquisitionsEventBusService.putAcquisitionEvent(any())) .thenReturn(acquisitionsEventBusResponseError) - val trackContribution = PrivateMethod[Future[List[BackendError]]](Symbol("trackContribution")) - val result = + val trackContribution: PrivateMethod[Future[List[BackendError]]] = + PrivateMethod[Future[List[BackendError]]](Symbol("trackContribution")) + val result: Future[List[BackendError]] = stripeBackend invokePrivate trackContribution(chargeMock, stripeChargeRequest, None, clientBrowserInfo) - val error = List( + val error: List[BackendError] = List( BackendError.AcquisitionsEventBusError(acquisitionsEventBusErrorMessage), BackendError.Database(dbError), ) diff --git a/support-payment-api/src/test/scala/controllers/AmazonPayControllerSpec.scala b/support-payment-api/src/test/scala/controllers/AmazonPayControllerSpec.scala index 794a5e6f48..877a31c868 100644 --- a/support-payment-api/src/test/scala/controllers/AmazonPayControllerSpec.scala +++ b/support-payment-api/src/test/scala/controllers/AmazonPayControllerSpec.scala @@ -34,7 +34,8 @@ class AmazonPayControllerFixture(implicit ec: ExecutionContext, context: Applica val mockAmazonPayBackend: AmazonPayBackend = mock[AmazonPayBackend] - val mockNotificationFactory = mock[(Map[String, String], String) => Notification] + val mockNotificationFactory: (Map[String, String], String) => Notification = + mock[(Map[String, String], String) => Notification] val mockAmazonPayRequestBasedProvider: RequestBasedProvider[AmazonPayBackend] = mock[RequestBasedProvider[AmazonPayBackend]] @@ -64,7 +65,7 @@ class AmazonPayControllerFixture(implicit ec: ExecutionContext, context: Applica val goCardlessBackendProvider: RequestBasedProvider[GoCardlessBackend] = mock[RequestBasedProvider[GoCardlessBackend]] - val mockStripeController = mock[StripeController] + val mockStripeController: StripeController = mock[StripeController] override def router: Router = new Routes( httpErrorHandler, @@ -80,11 +81,11 @@ class AmazonPayControllerFixture(implicit ec: ExecutionContext, context: Applica class AmazonPayControllerSpec extends AnyWordSpec with Status with Matchers { - implicit val actorSystem = ActorSystem("rest-server") + implicit val actorSystem: ActorSystem = ActorSystem("rest-server") implicit val materializer: Materializer = ActorMaterializer() implicit val executionContext: ExecutionContext = ExecutionContext.global - val context = ApplicationLoader.Context.create(Environment.simple()) + val context: ApplicationLoader.Context = ApplicationLoader.Context.create(Environment.simple()) "AmazonPayController" when { diff --git a/support-payment-api/src/test/scala/controllers/GoCardlessControllerSpec.scala b/support-payment-api/src/test/scala/controllers/GoCardlessControllerSpec.scala index 113dcbd81a..035fbbe162 100644 --- a/support-payment-api/src/test/scala/controllers/GoCardlessControllerSpec.scala +++ b/support-payment-api/src/test/scala/controllers/GoCardlessControllerSpec.scala @@ -86,11 +86,11 @@ class GoCardlessControllerFixture(implicit ec: ExecutionContext, context: Applic class GoCardlessControllerSpec extends AnyWordSpec with Status with Matchers { - implicit val actorSystem = ActorSystem("rest-server") + implicit val actorSystem: ActorSystem = ActorSystem("rest-server") implicit val materializer: Materializer = ActorMaterializer() implicit val executionContext: ExecutionContext = ExecutionContext.global - val context = ApplicationLoader.Context.create(Environment.simple()) + val context: ApplicationLoader.Context = ApplicationLoader.Context.create(Environment.simple()) "GoCardless Controller" when { diff --git a/support-payment-api/src/test/scala/controllers/PaypalControllerSpec.scala b/support-payment-api/src/test/scala/controllers/PaypalControllerSpec.scala index 28925a0d46..c5c295f002 100644 --- a/support-payment-api/src/test/scala/controllers/PaypalControllerSpec.scala +++ b/support-payment-api/src/test/scala/controllers/PaypalControllerSpec.scala @@ -92,17 +92,17 @@ class PaypalControllerFixture(implicit ec: ExecutionContext, context: Applicatio class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { - implicit val actorSystem = ActorSystem("rest-server") + implicit val actorSystem: ActorSystem = ActorSystem("rest-server") implicit val materializer: Materializer = ActorMaterializer() implicit val executionContext: ExecutionContext = ExecutionContext.global - val context = ApplicationLoader.Context.create(Environment.simple()) + val context: ApplicationLoader.Context = ApplicationLoader.Context.create(Environment.simple()) "Paypal Controller" when { "a request is made to create a payment" should { - val fixtureFor200Response = new PaypalControllerFixture()(executionContext, context) { + val fixtureFor200Response: PaypalControllerFixture = new PaypalControllerFixture()(executionContext, context) { val link = new Links("http://return-url.com", "approval_url") val links: java.util.List[Links] = List(link).asJava when(enrichedPaymentMock.payment) @@ -188,7 +188,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { } "return a 500 response if the response contains an invalid return url" in { - val fixture = new PaypalControllerFixture()(executionContext, context) { + val fixture: PaypalControllerFixture = new PaypalControllerFixture()(executionContext, context) { import scala.jdk.CollectionConverters._ @@ -283,7 +283,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(200) } @@ -308,7 +308,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(200) } @@ -352,7 +352,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(200) } @@ -376,7 +376,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(400) } @@ -414,7 +414,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(400) } @@ -454,7 +454,7 @@ class PaypalControllerSpec extends AnyWordSpec with Status with Matchers { """.stripMargin)) val paypalControllerResult: Future[play.api.mvc.Result] = - Helpers.call(fixture.payPalController.capturePayment, capturePaymentRequest) + Helpers.call(fixture.payPalController.capturePayment(), capturePaymentRequest) status(paypalControllerResult).mustBe(500) } diff --git a/support-payment-api/src/test/scala/controllers/StripeControllerSpec.scala b/support-payment-api/src/test/scala/controllers/StripeControllerSpec.scala index f42d917c6e..0eb110ae3a 100644 --- a/support-payment-api/src/test/scala/controllers/StripeControllerSpec.scala +++ b/support-payment-api/src/test/scala/controllers/StripeControllerSpec.scala @@ -1,7 +1,5 @@ package controllers -import org.apache.pekko.actor.ActorSystem -import org.apache.pekko.stream.{ActorMaterializer, Materializer} import backend._ import cats.data.EitherT import cats.implicits._ @@ -9,21 +7,21 @@ import com.stripe.exception.{CardException, InvalidRequestException} import com.stripe.model.{Charge, Event} import model.DefaultThreadPool import model.stripe.{StripeApiError, StripeCreateChargeResponse} -import org.mockito.Mockito._ +import org.apache.pekko.actor.ActorSystem +import org.apache.pekko.stream.{ActorMaterializer, Materializer} import org.mockito.ArgumentMatchers.any +import org.mockito.Mockito._ import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.mockito.MockitoSugar import play.api._ import play.api.http.Status -import play.api.inject.DefaultApplicationLifecycle import play.api.libs.json.Json import play.api.libs.json.Json._ import play.api.mvc._ import play.api.routing.Router import play.api.test.Helpers._ import play.api.test._ -import play.core.DefaultWebCommands import router.Routes import services.CloudWatchService import util.RequestBasedProvider @@ -103,11 +101,11 @@ class StripeControllerFixture(implicit ec: ExecutionContext, context: Applicatio class StripeControllerSpec extends AnyWordSpec with Status with Matchers { - implicit val actorSystem = ActorSystem("rest-server") + implicit val actorSystem: ActorSystem = ActorSystem("rest-server") implicit val materializer: Materializer = ActorMaterializer() implicit val executionContext: ExecutionContext = ExecutionContext.global - val context = ApplicationLoader.Context.create(Environment.simple()) + val context: ApplicationLoader.Context = ApplicationLoader.Context.create(Environment.simple()) "StripeController" when { diff --git a/support-payment-api/src/test/scala/model/paypal/PaypalRefundWebHookBodySpec.scala b/support-payment-api/src/test/scala/model/paypal/PaypalRefundWebHookBodySpec.scala index ca2763c7b7..042c2a507d 100644 --- a/support-payment-api/src/test/scala/model/paypal/PaypalRefundWebHookBodySpec.scala +++ b/support-payment-api/src/test/scala/model/paypal/PaypalRefundWebHookBodySpec.scala @@ -80,7 +80,7 @@ class PaypalRefundWebHookBodySpec extends AnyWordSpec with Matchers with EitherV val paymentId = testPaymentId() val event = buildEvent("PAYMENT.SALE.REFUNDED", paymentId) - val body = io.circe.parser.decode[PaypalRefundWebHookBody](event).right.value + val body = io.circe.parser.decode[PaypalRefundWebHookBody](event).value body.parentPaymentId mustEqual paymentId body.rawBody mustEqual compressEvent(event) @@ -94,7 +94,7 @@ class PaypalRefundWebHookBodySpec extends AnyWordSpec with Matchers with EitherV val paymentId = testPaymentId() val event = buildEvent("PAYMENT.CAPTURE.REFUNDED", paymentId) - val body = io.circe.parser.decode[PaypalRefundWebHookBody](event).right.value + val body = io.circe.parser.decode[PaypalRefundWebHookBody](event).value body.parentPaymentId mustEqual paymentId body.rawBody mustEqual compressEvent(event) diff --git a/support-payment-api/src/test/scala/services/ContributionsStoreServiceSpec.scala b/support-payment-api/src/test/scala/services/ContributionsStoreServiceSpec.scala index c7770f1542..ecb6176e24 100644 --- a/support-payment-api/src/test/scala/services/ContributionsStoreServiceSpec.scala +++ b/support-payment-api/src/test/scala/services/ContributionsStoreServiceSpec.scala @@ -1,8 +1,9 @@ package services +import io.circe.Json + import java.time.LocalDateTime import java.util.UUID - import model.{Currency, PaymentProvider, PaymentStatus} import model.db.ContributionData import services.ContributionsStoreQueueService.NewContributionData @@ -12,9 +13,9 @@ import org.scalatest.matchers.must.Matchers class ContributionsStoreServiceSpec extends AnyFlatSpec with Matchers { - val uuid = UUID.randomUUID() + val uuid: UUID = UUID.randomUUID() - val contributionData = ContributionData( + val contributionData: ContributionData = ContributionData( paymentProvider = PaymentProvider.Paypal, paymentStatus = PaymentStatus.Paid, paymentId = "paymentId", @@ -29,7 +30,7 @@ class ContributionsStoreServiceSpec extends AnyFlatSpec with Matchers { postalCode = Some("N1 9GU"), ) - val expectedJson = parse( + val expectedJson: Json = parse( s"""|{ | "newContributionData" : { | "paymentProvider" : "Paypal", @@ -46,7 +47,7 @@ class ContributionsStoreServiceSpec extends AnyFlatSpec with Matchers { | "postalCode" : "N1 9GU" | } |}""".stripMargin, - ).right.get + ).toOption.get it should "serialize ContributionData" in { ContributionsStoreQueueService.Message.toJson(NewContributionData(contributionData)) must be(expectedJson) diff --git a/support-payment-api/src/test/scala/services/EmailServiceSpec.scala b/support-payment-api/src/test/scala/services/EmailServiceSpec.scala index 669b33ae32..58e5dc9179 100644 --- a/support-payment-api/src/test/scala/services/EmailServiceSpec.scala +++ b/support-payment-api/src/test/scala/services/EmailServiceSpec.scala @@ -1,19 +1,21 @@ package services +import cats.data.EitherT import com.amazonaws.services.sqs.AmazonSQSAsync import com.amazonaws.services.sqs.model.{GetQueueUrlResult, SendMessageResult} -import com.paypal.api.payments.{Amount, Payer, PayerInfo, Payment} +import com.paypal.api.payments.{Amount, Payer, PayerInfo, Payment, Transaction} import model.{DefaultThreadPool, PaymentProvider} import org.mockito.Mockito._ import org.mockito.ArgumentMatchers.any import org.scalatest.concurrent.ScalaFutures -import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletableFuture import model.email.ContributorRow import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import org.scalatestplus.mockito.MockitoSugar +import java.util import scala.compat.java8.FutureConverters._ import scala.concurrent.Future import scala.jdk.CollectionConverters._ @@ -24,22 +26,21 @@ class EmailServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with behavior of "Email Service" trait EmailServiceTestFixture { - implicit val executionContextTest = DefaultThreadPool(ExecutionContext.global) - val sqsClient = mock[AmazonSQSAsync] - val getQueueUrlResult = mock[GetQueueUrlResult] - when(getQueueUrlResult.getQueueUrl()).thenReturn("test-queue-name") + implicit val executionContextTest: DefaultThreadPool = DefaultThreadPool(ExecutionContext.global) + val sqsClient: AmazonSQSAsync = mock[AmazonSQSAsync] + val getQueueUrlResult: GetQueueUrlResult = mock[GetQueueUrlResult] + when(getQueueUrlResult.getQueueUrl).thenReturn("test-queue-name") when(sqsClient.getQueueUrl("test-queue-name")).thenReturn(getQueueUrlResult) - val emailService = new EmailService(sqsClient, "test-queue-name") + val emailService: EmailService = new EmailService(sqsClient, "test-queue-name") } it should "send an email" in new EmailServiceTestFixture { - val payment = mock[Payment] - val amount = mock[Amount] - val payer = mock[Payer] - val payerInfo = mock[PayerInfo] - val transaction = mock[com.paypal.api.payments.Transaction] - val transactions = List(transaction).asJava - val identityId = 666L + val payment: Payment = mock[Payment] + val amount: Amount = mock[Amount] + val payer: Payer = mock[Payer] + val payerInfo: PayerInfo = mock[PayerInfo] + val transaction: Transaction = mock[com.paypal.api.payments.Transaction] + val transactions: util.List[Transaction] = List(transaction).asJava when(transaction.getAmount).thenReturn(amount) when(amount.getCurrency).thenReturn("GBP") when(amount.getTotal).thenReturn("2") @@ -50,12 +51,12 @@ class EmailServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with when(payment.getTransactions).thenReturn(transactions) when(payment.getCreateTime).thenReturn("01-01-2018T12:12:12") - val scalaFuture = Future.successful(new SendMessageResult) + val scalaFuture: Future[SendMessageResult] = Future.successful(new SendMessageResult) val javaFuture: CompletableFuture[SendMessageResult] = scalaFuture.toJava.toCompletableFuture when(sqsClient.sendMessageAsync(any())).thenReturn(javaFuture) - val emailResult = emailService.sendThankYouEmail( + val emailResult: EitherT[Future, EmailService.Error, SendMessageResult] = emailService.sendThankYouEmail( ContributorRow("email@email.com", "GBP", "1", PaymentProvider.Paypal, None, BigDecimal(2)), ) whenReady(emailResult.value) { result => @@ -64,13 +65,12 @@ class EmailServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with } it should "return an error if the sqs client throws an exception" in new EmailServiceTestFixture { - val payment = mock[Payment] - val amount = mock[Amount] - val payer = mock[Payer] - val payerInfo = mock[PayerInfo] - val transaction = mock[com.paypal.api.payments.Transaction] - val transactions = List(transaction).asJava - val identityId = 666L + val payment: Payment = mock[Payment] + val amount: Amount = mock[Amount] + val payer: Payer = mock[Payer] + val payerInfo: PayerInfo = mock[PayerInfo] + val transaction: Transaction = mock[com.paypal.api.payments.Transaction] + val transactions: util.List[Transaction] = List(transaction).asJava when(transaction.getAmount).thenReturn(amount) when(amount.getCurrency).thenReturn("GBP") when(amount.getTotal).thenReturn("2") @@ -83,8 +83,7 @@ class EmailServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with val errorString = "Any sqs client error" val exception = new Exception(errorString) - val emailError = EmailService.Error(exception) - val scalaFuture = Future.failed[SendMessageResult](exception) + val scalaFuture: Future[SendMessageResult] = Future.failed[SendMessageResult](exception) val javaFuture: CompletableFuture[SendMessageResult] = scalaFuture.toJava.toCompletableFuture when(sqsClient.sendMessageAsync(any())).thenReturn(javaFuture) @@ -99,7 +98,7 @@ class EmailServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with // TODO: understand how this java.lang.Exception bit gets added error.getMessage mustBe s"java.lang.Exception: $errorString" }, - success => fail, + _ => fail(), ) } } diff --git a/support-payment-api/src/test/scala/services/IdentityClientErrorMatchers.scala b/support-payment-api/src/test/scala/services/IdentityClientErrorMatchers.scala index 53f8860e3d..c39df7e4b8 100644 --- a/support-payment-api/src/test/scala/services/IdentityClientErrorMatchers.scala +++ b/support-payment-api/src/test/scala/services/IdentityClientErrorMatchers.scala @@ -19,7 +19,7 @@ trait IdentityClientErrorMatchers { } } - val beANotFoundApiError = new IsAnApiError("Not found", _.isNotFound) + val beANotFoundApiError: IsAnApiError = new IsAnApiError("Not found", _.isNotFound) - val beAnEmailInUseApiError = new IsAnApiError("Email in use", _.isEmailInUse) + val beAnEmailInUseApiError: IsAnApiError = new IsAnApiError("Email in use", _.isEmailInUse) } diff --git a/support-payment-api/src/test/scala/services/IdentityClientSpec.scala b/support-payment-api/src/test/scala/services/IdentityClientSpec.scala index 09ff5aaff6..080651a47c 100644 --- a/support-payment-api/src/test/scala/services/IdentityClientSpec.scala +++ b/support-payment-api/src/test/scala/services/IdentityClientSpec.scala @@ -75,7 +75,7 @@ object IdentityClientSpec { case class PreExistingIdentityAccount(emailAddress: String, identityId: String) // An account for this email address has been created on the identity CODE environment. - val preExistingIdentityAccount = PreExistingIdentityAccount( + val preExistingIdentityAccount: PreExistingIdentityAccount = PreExistingIdentityAccount( emailAddress = "test.user@payment-api.gu.com", identityId = "100000253", ) diff --git a/support-payment-api/src/test/scala/services/PaypalServiceSpec.scala b/support-payment-api/src/test/scala/services/PaypalServiceSpec.scala index 180a9c0d3f..bcadb3734c 100644 --- a/support-payment-api/src/test/scala/services/PaypalServiceSpec.scala +++ b/support-payment-api/src/test/scala/services/PaypalServiceSpec.scala @@ -13,19 +13,25 @@ import org.scalatestplus.mockito.MockitoSugar import scala.jdk.CollectionConverters._ import scala.concurrent.ExecutionContext +import java.{util => ju} class PaypalServiceSpec extends AnyFlatSpec with Matchers with MockitoSugar with ScalaFutures { trait PaypalServiceTestFixture { - val paypalConfig = PaypalConfig("clientIdTest", "clientSecretTest", "hookId", PaypalMode.Sandbox) - implicit val executionContextTest = PaypalThreadPool(ExecutionContext.global) - val buildPaypalTransactions = PrivateMethod[java.util.List[Transaction]]('buildPaypalTransactions) - val buildCaptureByTransaction = PrivateMethod[Capture]('buildCaptureByTransaction) - val getTransaction = PrivateMethod[Either[PaypalApiError, Transaction]]('getTransaction) - val getRelatedResources = PrivateMethod[Either[PaypalApiError, RelatedResources]]('getRelatedResources) - val validateCapture = PrivateMethod[Either[PaypalApiError, Capture]]('validateCapture) - val validatePayment = PrivateMethod[Either[PaypalApiError, Payment]]('validatePayment) - val paypalService = new PaypalService(paypalConfig) + val paypalConfig: PaypalConfig = PaypalConfig("clientIdTest", "clientSecretTest", "hookId", PaypalMode.Sandbox) + implicit val executionContextTest: PaypalThreadPool = PaypalThreadPool(ExecutionContext.global) + val buildPaypalTransactions: PrivateMethod[ju.List[Transaction]] = + PrivateMethod[java.util.List[Transaction]]('buildPaypalTransactions) + val buildCaptureByTransaction: PrivateMethod[Capture] = PrivateMethod[Capture]('buildCaptureByTransaction) + val getTransaction: PrivateMethod[Either[PaypalApiError, Transaction]] = + PrivateMethod[Either[PaypalApiError, Transaction]]('getTransaction) + val getRelatedResources: PrivateMethod[Either[PaypalApiError, RelatedResources]] = + PrivateMethod[Either[PaypalApiError, RelatedResources]]('getRelatedResources) + val validateCapture: PrivateMethod[Either[PaypalApiError, Capture]] = + PrivateMethod[Either[PaypalApiError, Capture]]('validateCapture) + val validatePayment: PrivateMethod[Either[PaypalApiError, Payment]] = + PrivateMethod[Either[PaypalApiError, Payment]]('validatePayment) + val paypalService: PaypalService = new PaypalService(paypalConfig) } behavior of "Paypal Service" diff --git a/support-payment-api/src/test/scala/util/FutureEitherValues.scala b/support-payment-api/src/test/scala/util/FutureEitherValues.scala index 8ec07a4b5f..f7cd859318 100644 --- a/support-payment-api/src/test/scala/util/FutureEitherValues.scala +++ b/support-payment-api/src/test/scala/util/FutureEitherValues.scala @@ -10,6 +10,6 @@ trait FutureEitherValues extends ScalaFutures with EitherValues { implicit class FutureEitherOps[A, B](data: EitherT[Future, A, B]) { def futureLeft: A = data.value.futureValue.left.value - def futureRight: B = data.value.futureValue.right.value + def futureRight: B = data.value.futureValue.value } } diff --git a/support-services/src/main/scala/com/gu/support/abtests/BenefitsTest.scala b/support-services/src/main/scala/com/gu/support/abtests/BenefitsTest.scala index 9fc4a74bb9..c81e1a6c32 100644 --- a/support-services/src/main/scala/com/gu/support/abtests/BenefitsTest.scala +++ b/support-services/src/main/scala/com/gu/support/abtests/BenefitsTest.scala @@ -6,16 +6,16 @@ import com.gu.support.acquisitions.AbTest import com.gu.support.workers.{Annual, BillingPeriod, DigitalPack, Monthly} object BenefitsTest { - def isValidBenefitsTestPurchase(product: DigitalPack, maybeAbTests: Option[Set[AbTest]]) = + def isValidBenefitsTestPurchase(product: DigitalPack, maybeAbTests: Option[Set[AbTest]]): Boolean = isUserInBenefitsTestVariants(maybeAbTests) && product.amount.exists(amount => priceIsHighEnough(amount, product.billingPeriod, product.currency)) - def isUserInBenefitsTestVariants(maybeAbTests: Option[Set[AbTest]]) = + def isUserInBenefitsTestVariants(maybeAbTests: Option[Set[AbTest]]): Boolean = maybeAbTests.exists( _.toList.exists(test => test.name == "PP_V3" && (test.variant == "V2_BULLET" || test.variant == "V1_PARAGRAPH")), ) - def priceIsHighEnough(amount: BigDecimal, billingPeriod: BillingPeriod, currency: Currency) = { + def priceIsHighEnough(amount: BigDecimal, billingPeriod: BillingPeriod, currency: Currency): Boolean = { val requiredAmount = (billingPeriod, currency) match { case (Monthly, GBP) => 12 case (Annual, GBP) => 119 diff --git a/support-services/src/main/scala/com/gu/support/catalog/CatalogService.scala b/support-services/src/main/scala/com/gu/support/catalog/CatalogService.scala index 9d3c25bccb..be554d0a29 100644 --- a/support-services/src/main/scala/com/gu/support/catalog/CatalogService.scala +++ b/support-services/src/main/scala/com/gu/support/catalog/CatalogService.scala @@ -21,7 +21,7 @@ class CatalogService(val environment: TouchPointEnvironment, jsonProvider: Catal fulfilmentOptions: FulfilmentOptions, productOptions: ProductOptions, readerType: ReaderType = Direct, - ) = + ): Option[ProductRatePlan[Product]] = product.getProductRatePlan(environment, billingPeriod, fulfilmentOptions, productOptions, readerType) private[this] def getGWRatePlanId(billingPeriod: BillingPeriod, fulfilmentOptions: FulfilmentOptions) = diff --git a/support-services/src/main/scala/com/gu/support/paperround/PaperRoundService.scala b/support-services/src/main/scala/com/gu/support/paperround/PaperRoundService.scala index b17fe6a188..d0a66395ba 100644 --- a/support-services/src/main/scala/com/gu/support/paperround/PaperRoundService.scala +++ b/support-services/src/main/scala/com/gu/support/paperround/PaperRoundService.scala @@ -11,7 +11,7 @@ import scala.concurrent.{ExecutionContext, Future} class PaperRoundServiceProvider(configProvider: PaperRoundConfigProvider)(implicit ec: ExecutionContext) extends TouchpointServiceProvider[PaperRoundService, PaperRoundConfig](configProvider) { - override protected def createService(config: PaperRoundConfig) = { + override protected def createService(config: PaperRoundConfig): PaperRoundService = { new PaperRoundService(config, futureRunner) } } diff --git a/support-services/src/main/scala/com/gu/support/promotions/PromotionCache.scala b/support-services/src/main/scala/com/gu/support/promotions/PromotionCache.scala index f3f82c15ab..6a47dad508 100644 --- a/support-services/src/main/scala/com/gu/support/promotions/PromotionCache.scala +++ b/support-services/src/main/scala/com/gu/support/promotions/PromotionCache.scala @@ -6,13 +6,13 @@ import org.joda.time.{DateTime, Minutes} import scala.concurrent.stm.{Ref, atomic} case class PromotionCacheResponse(fetched: DateTime, promotions: Iterable[Promotion]) { - val maxAge = Minutes.ONE.toStandardDuration.getMillis + val maxAge: Long = Minutes.ONE.toStandardDuration.getMillis def isFresh: Boolean = DateTime.now.getMillis - fetched.getMillis < maxAge } class PromotionCache { // this val contains the mutable cache contents - val promotionsRef = Ref[Option[PromotionCacheResponse]](None) + val promotionsRef: Ref[Option[PromotionCacheResponse]] = Ref[Option[PromotionCacheResponse]](None) def get: Option[Iterable[Promotion]] = promotionsRef.single().filter(_.isFresh).map(_.promotions) diff --git a/support-services/src/main/scala/com/gu/support/promotions/PromotionCollection.scala b/support-services/src/main/scala/com/gu/support/promotions/PromotionCollection.scala index 6493b69841..24ca22482f 100644 --- a/support-services/src/main/scala/com/gu/support/promotions/PromotionCollection.scala +++ b/support-services/src/main/scala/com/gu/support/promotions/PromotionCollection.scala @@ -19,7 +19,7 @@ class CachedDynamoPromotionCollection(config: PromotionsTablesConfig) extends DynamoPromotionCollection(config) with PromotionCollection { - val cache = new PromotionCache + val cache: PromotionCache = new PromotionCache override def all: Iterator[Promotion] = cache.get.getOrElse(fetchAndCache).toIterator private def fetchAndCache = { diff --git a/support-services/src/main/scala/com/gu/support/promotions/PromotionService.scala b/support-services/src/main/scala/com/gu/support/promotions/PromotionService.scala index 918134ccfc..689f5febe9 100644 --- a/support-services/src/main/scala/com/gu/support/promotions/PromotionService.scala +++ b/support-services/src/main/scala/com/gu/support/promotions/PromotionService.scala @@ -11,12 +11,13 @@ import com.typesafe.scalalogging.LazyLogging class PromotionService(config: PromotionsConfig, maybeCollection: Option[PromotionCollection] = None) extends TouchpointService with LazyLogging { - val promotionCollection = maybeCollection.getOrElse(new CachedDynamoPromotionCollection(config.tables)) + val promotionCollection: PromotionCollection = + maybeCollection.getOrElse(new CachedDynamoPromotionCollection(config.tables)) // This is a small hack to allow us to start using promotions to handle 6 for 6 without having to build the tooling private def allWith6For6 = promotionCollection.all.toList :+ Promotions.SixForSixPromotion - def environment = if (config.tables.promotions.contains("PROD")) { "PROD" } + def environment: String = if (config.tables.promotions.contains("PROD")) { "PROD" } else { "CODE" } def findPromotion(promoCode: PromoCode): Either[PromoError, PromotionWithCode] = diff --git a/support-services/src/main/scala/com/gu/support/promotions/PromotionServiceProvider.scala b/support-services/src/main/scala/com/gu/support/promotions/PromotionServiceProvider.scala index 8f1a945107..7f87738507 100644 --- a/support-services/src/main/scala/com/gu/support/promotions/PromotionServiceProvider.scala +++ b/support-services/src/main/scala/com/gu/support/promotions/PromotionServiceProvider.scala @@ -5,7 +5,7 @@ import com.gu.support.touchpoint.TouchpointServiceProvider class PromotionServiceProvider(configProvider: PromotionsConfigProvider) extends TouchpointServiceProvider[PromotionService, PromotionsConfig](configProvider) { - override protected def createService(config: PromotionsConfig) = { + override protected def createService(config: PromotionsConfig): PromotionService = { new PromotionService(config) } } diff --git a/support-services/src/main/scala/com/gu/support/redemption/CodeStatus.scala b/support-services/src/main/scala/com/gu/support/redemption/CodeStatus.scala index 028cc4094b..ead083b4fd 100644 --- a/support-services/src/main/scala/com/gu/support/redemption/CodeStatus.scala +++ b/support-services/src/main/scala/com/gu/support/redemption/CodeStatus.scala @@ -16,8 +16,8 @@ case object CodeExpired extends InvalidCode("code_expired") case object InvalidReaderType extends InvalidCode("invalid_reader_type") -object ValidGiftCode { val clientCode = "valid_gift_code" } -object CodeRedeemedInThisRequest { val clientCode = "redeemed_in_this_request" } +object ValidGiftCode { val clientCode: String = "valid_gift_code" } +object CodeRedeemedInThisRequest { val clientCode: String = "redeemed_in_this_request" } case class ValidGiftCode(subscriptionId: String) extends ValidCode(ValidGiftCode.clientCode) diff --git a/support-services/src/main/scala/com/gu/support/redemption/gifting/GiftCodeValidator.scala b/support-services/src/main/scala/com/gu/support/redemption/gifting/GiftCodeValidator.scala index 39ebc3a53f..6f249211cd 100644 --- a/support-services/src/main/scala/com/gu/support/redemption/gifting/GiftCodeValidator.scala +++ b/support-services/src/main/scala/com/gu/support/redemption/gifting/GiftCodeValidator.scala @@ -17,7 +17,7 @@ import org.joda.time.LocalDate import scala.concurrent.{ExecutionContext, Future} object GiftCodeValidator { - val expirationTimeInMonths = 12 + val expirationTimeInMonths: Int = 12 def getSubscriptionState(existingSub: SubscriptionRedemptionQueryResponse, requestId: Option[String]): CodeStatus = existingSub.records match { diff --git a/support-services/src/main/scala/com/gu/zuora/ZuoraGiftLookupServiceProvider.scala b/support-services/src/main/scala/com/gu/zuora/ZuoraGiftLookupServiceProvider.scala index 32d3c56c38..2c364e4ff0 100644 --- a/support-services/src/main/scala/com/gu/zuora/ZuoraGiftLookupServiceProvider.scala +++ b/support-services/src/main/scala/com/gu/zuora/ZuoraGiftLookupServiceProvider.scala @@ -10,6 +10,6 @@ import scala.concurrent.duration.DurationInt class ZuoraGiftLookupServiceProvider(configProvider: ZuoraConfigProvider, stage: Stage)(implicit ec: ExecutionContext) extends TouchpointServiceProvider[ZuoraGiftLookupService, ZuoraConfig](configProvider) { - override protected def createService(config: ZuoraConfig) = + override protected def createService(config: ZuoraConfig): ZuoraGiftService = new ZuoraGiftService(config, stage, configurableFutureRunner(60.seconds)) } diff --git a/support-services/src/main/scala/com/gu/zuora/ZuoraGiftService.scala b/support-services/src/main/scala/com/gu/zuora/ZuoraGiftService.scala index 439187affe..c345d0a0b5 100644 --- a/support-services/src/main/scala/com/gu/zuora/ZuoraGiftService.scala +++ b/support-services/src/main/scala/com/gu/zuora/ZuoraGiftService.scala @@ -29,7 +29,7 @@ class ZuoraGiftService(val config: ZuoraConfig, stage: Stage, client: FutureHttp override val wsUrl: String = config.url override val httpClient: FutureHttpClient = client - val authHeaders = Map( + val authHeaders: Map[String, String] = Map( "apiSecretAccessKey" -> config.password, "apiAccessKeyId" -> config.username, ) diff --git a/support-services/src/main/scala/com/gu/zuora/ZuoraService.scala b/support-services/src/main/scala/com/gu/zuora/ZuoraService.scala index d0c98a990c..ee62372ed0 100644 --- a/support-services/src/main/scala/com/gu/zuora/ZuoraService.scala +++ b/support-services/src/main/scala/com/gu/zuora/ZuoraService.scala @@ -38,7 +38,7 @@ class ZuoraService(val config: ZuoraConfig, client: FutureHttpClient, baseUrl: O override val wsUrl: String = baseUrl.getOrElse(config.url) override val httpClient: FutureHttpClient = client - val authHeaders = Map( + val authHeaders: Map[String, String] = Map( "apiSecretAccessKey" -> config.password, "apiAccessKeyId" -> config.username, ) diff --git a/support-services/src/test/scala/com/gu/support/catalog/CatalogServiceSpec.scala b/support-services/src/test/scala/com/gu/support/catalog/CatalogServiceSpec.scala index 7046f094e6..96df11b7a0 100644 --- a/support-services/src/test/scala/com/gu/support/catalog/CatalogServiceSpec.scala +++ b/support-services/src/test/scala/com/gu/support/catalog/CatalogServiceSpec.scala @@ -84,5 +84,5 @@ class SimpleJsonProvider(json: Json) extends CatalogJsonProvider { object CatalogServiceSpec { private val json = parse(ServiceFixtures.loadCatalog).right.get private val jsonProvider = new SimpleJsonProvider(json) - val serviceWithFixtures = new CatalogService(PROD, jsonProvider) + val serviceWithFixtures: CatalogService = new CatalogService(PROD, jsonProvider) } diff --git a/support-services/src/test/scala/com/gu/support/catalog/ProductRatePlanSpec.scala b/support-services/src/test/scala/com/gu/support/catalog/ProductRatePlanSpec.scala index 70b1f45f4b..8a23179610 100644 --- a/support-services/src/test/scala/com/gu/support/catalog/ProductRatePlanSpec.scala +++ b/support-services/src/test/scala/com/gu/support/catalog/ProductRatePlanSpec.scala @@ -6,6 +6,7 @@ import com.gu.support.workers.{Annual, BillingPeriod, Monthly, Quarterly} import com.typesafe.scalalogging.LazyLogging import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers +import org.scalatest.Assertion case class TestData( product: Product, @@ -16,7 +17,7 @@ case class TestData( class ProductRatePlanSpec extends AnyFlatSpec with Matchers { - val testData = List( + val testData: List[TestData] = List( TestData( DigitalPack, List(Monthly, Annual), @@ -60,7 +61,7 @@ class ProductRatePlanSpec extends AnyFlatSpec with Matchers { succeed } - def testProduct(environment: TouchPointEnvironment, testDatum: TestData) = { + def testProduct(environment: TouchPointEnvironment, testDatum: TestData): List[Assertion] = { for { billingPeriod <- testDatum.billingPeriods fulfilmentOption <- testDatum.fulfilmentOptions diff --git a/support-services/src/test/scala/com/gu/support/getaddressio/GetAddressIOServiceSpec.scala b/support-services/src/test/scala/com/gu/support/getaddressio/GetAddressIOServiceSpec.scala index e1ac28edc3..a418aaedb9 100644 --- a/support-services/src/test/scala/com/gu/support/getaddressio/GetAddressIOServiceSpec.scala +++ b/support-services/src/test/scala/com/gu/support/getaddressio/GetAddressIOServiceSpec.scala @@ -10,7 +10,7 @@ import org.scalatest.matchers.should.Matchers @IntegrationTest class GetAddressIOServiceSpec extends AsyncFlatSpec with Matchers { - val service = + val service: GetAddressIOService = new GetAddressIOService(GetAddressIOConfig.fromConfig(ConfigFactory.load()), RequestRunners.futureRunner) // This test is ignored because the test key is only valid for a few requests a day "GetAddressService" should "be able to find a postcode" ignore { diff --git a/support-services/src/test/scala/com/gu/support/promotions/PromotionApplicatorSpec.scala b/support-services/src/test/scala/com/gu/support/promotions/PromotionApplicatorSpec.scala index c38ab59686..0cb9cf3527 100644 --- a/support-services/src/test/scala/com/gu/support/promotions/PromotionApplicatorSpec.scala +++ b/support-services/src/test/scala/com/gu/support/promotions/PromotionApplicatorSpec.scala @@ -4,10 +4,11 @@ import com.gu.support.config.PromotionsDiscountConfig import com.gu.support.promotions.ServicesFixtures._ import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers +import org.joda.time.LocalDate class PromotionApplicatorSpec extends AsyncFlatSpec with Matchers { - val config = PromotionsDiscountConfig(validProductRatePlanId, "112233") - val correctDate = + val config: PromotionsDiscountConfig = PromotionsDiscountConfig(validProductRatePlanId, "112233") + val correctDate: LocalDate = subscriptionData.subscription.contractEffectiveDate.plusDays(freeTrial.freeTrial.get.duration.getDays) "PromotionApplicator" should "add a discount rate plan" in { diff --git a/support-services/src/test/scala/com/gu/support/promotions/PromotionServiceSpec.scala b/support-services/src/test/scala/com/gu/support/promotions/PromotionServiceSpec.scala index 4750ccc85f..2eb4c5248a 100644 --- a/support-services/src/test/scala/com/gu/support/promotions/PromotionServiceSpec.scala +++ b/support-services/src/test/scala/com/gu/support/promotions/PromotionServiceSpec.scala @@ -9,6 +9,7 @@ import com.gu.support.promotions.ServicesFixtures.{freeTrialPromoCode, _} import com.typesafe.config.ConfigFactory import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers +import com.gu.support.config.PromotionsConfig //noinspection NameBooleanParameters class PromotionServiceSpec extends AsyncFlatSpec with Matchers { @@ -131,8 +132,8 @@ class PromotionServiceSpec extends AsyncFlatSpec with Matchers { } object PromotionServiceSpec { - val config = new PromotionsConfigProvider(ConfigFactory.load(), Stages.DEV).get() - val serviceWithFixtures = new PromotionService( + val config: PromotionsConfig = new PromotionsConfigProvider(ConfigFactory.load(), Stages.DEV).get() + val serviceWithFixtures: PromotionService = new PromotionService( config, Some( new SimplePromotionCollection( @@ -150,7 +151,7 @@ object PromotionServiceSpec { ), ) - val serviceWithDynamo = new PromotionService( + val serviceWithDynamo: PromotionService = new PromotionService( config, None, ) diff --git a/support-services/src/test/scala/com/gu/support/promotions/PromotionValidatorSpec.scala b/support-services/src/test/scala/com/gu/support/promotions/PromotionValidatorSpec.scala index 7ca5e5151f..7fd085ada4 100644 --- a/support-services/src/test/scala/com/gu/support/promotions/PromotionValidatorSpec.scala +++ b/support-services/src/test/scala/com/gu/support/promotions/PromotionValidatorSpec.scala @@ -9,16 +9,16 @@ import org.scalatest.matchers.should.Matchers //noinspection NameBooleanParameters class PromotionValidatorSpec extends AsyncFlatSpec with Matchers { - val NoErrors = Nil + val NoErrors: Nil.type = Nil - val thisMorning = DateTime.now().withTimeAtStartOfDay() - val tomorrowMorning = thisMorning.plusDays(1) - val expiredPromotion = promotion(expires = thisMorning) - val activePromotion = promotion() - val futurePromotion = promotion(starts = tomorrowMorning, expires = tomorrowMorning.plusDays(1)) + val thisMorning: DateTime = DateTime.now().withTimeAtStartOfDay() + val tomorrowMorning: DateTime = thisMorning.plusDays(1) + val expiredPromotion: Promotion = promotion(expires = thisMorning) + val activePromotion: Promotion = promotion() + val futurePromotion: Promotion = promotion(starts = tomorrowMorning, expires = tomorrowMorning.plusDays(1)) - val providedStarts = futurePromotion.starts - val providedExpires = futurePromotion.expires.get + val providedStarts: DateTime = futurePromotion.starts + val providedExpires: DateTime = futurePromotion.expires.get "PromotionValidator" should "validate correctly" in { diff --git a/support-services/src/test/scala/com/gu/support/promotions/ServicesFixtures.scala b/support-services/src/test/scala/com/gu/support/promotions/ServicesFixtures.scala index 10aaf8facc..2e53b46b2f 100644 --- a/support-services/src/test/scala/com/gu/support/promotions/ServicesFixtures.scala +++ b/support-services/src/test/scala/com/gu/support/promotions/ServicesFixtures.scala @@ -7,38 +7,39 @@ import com.gu.support.workers.Annual import com.gu.support.zuora.api.ReaderType.{Direct, Gift} import com.gu.support.zuora.api.{RatePlan, RatePlanData, Subscription, SubscriptionData} import org.joda.time.{DateTime, Days, LocalDate, Months} +import com.gu.support.catalog.ProductRatePlanId /** Promotions are quite laborious to construct So these are helper methods for unit tests */ object ServicesFixtures { - val freeTrialPromoCode = "FREE_TRIAL_CODE" - val discountPromoCode = "DISCOUNT_CODE" - val doublePromoCode = "DOUBLE_CODE" - val invalidPromoCode = "INVALID_CODE" - val renewalPromoCode = "RENEWAL_CODE" - val trackingPromoCode = "TRACKING_CODE" - val duplicatedPromoCode = "DUPLICATED_CODE" - val tenAnnual = "10ANNUAL" - val sixForSix = "6FOR6" + val freeTrialPromoCode: String = "FREE_TRIAL_CODE" + val discountPromoCode: String = "DISCOUNT_CODE" + val doublePromoCode: String = "DOUBLE_CODE" + val invalidPromoCode: String = "INVALID_CODE" + val renewalPromoCode: String = "RENEWAL_CODE" + val trackingPromoCode: String = "TRACKING_CODE" + val duplicatedPromoCode: String = "DUPLICATED_CODE" + val tenAnnual: String = "10ANNUAL" + val sixForSix: String = "6FOR6" - val validProductRatePlanIds = Product.allProducts.flatMap(_.ratePlans(PROD).map(_.id)) - val validProductRatePlanId = validProductRatePlanIds.head - val secondValidProductRatePlanId = validProductRatePlanIds.tail.head - val invalidProductRatePlanId = "67890" + val validProductRatePlanIds: List[ProductRatePlanId] = Product.allProducts.flatMap(_.ratePlans(PROD).map(_.id)) + val validProductRatePlanId: ProductRatePlanId = validProductRatePlanIds.head + val secondValidProductRatePlanId: ProductRatePlanId = validProductRatePlanIds.tail.head + val invalidProductRatePlanId: String = "67890" - val freeTrialBenefit = Some(FreeTrialBenefit(Days.days(5))) - val discountBenefit = Some(DiscountBenefit(30, Some(Months.months(3)))) + val freeTrialBenefit: Some[FreeTrialBenefit] = Some(FreeTrialBenefit(Days.days(5))) + val discountBenefit: Some[DiscountBenefit] = Some(DiscountBenefit(30, Some(Months.months(3)))) val freeTrial = promotion(validProductRatePlanIds, freeTrialPromoCode, freeTrial = freeTrialBenefit) - val freeTrialWithCode = PromotionWithCode(freeTrialPromoCode, freeTrial) + val freeTrialWithCode: PromotionWithCode = PromotionWithCode(freeTrialPromoCode, freeTrial) val discount = promotion(validProductRatePlanIds, discountPromoCode, discountBenefit) - val discountWithCode = PromotionWithCode(discountPromoCode, discount) + val discountWithCode: PromotionWithCode = PromotionWithCode(discountPromoCode, discount) val double = promotion(validProductRatePlanIds, doublePromoCode, discountBenefit, freeTrialBenefit) - val doubleWithCode = PromotionWithCode(doublePromoCode, double) - val tracking = + val doubleWithCode: PromotionWithCode = PromotionWithCode(doublePromoCode, double) + val tracking: PromotionWithCode = PromotionWithCode(trackingPromoCode, promotion(validProductRatePlanIds, trackingPromoCode, tracking = true)) - val renewal = PromotionWithCode( + val renewal: PromotionWithCode = PromotionWithCode( renewalPromoCode, promotion(validProductRatePlanIds, renewalPromoCode, discountBenefit, renewal = true), ) @@ -59,12 +60,12 @@ object ServicesFixtures { .toSet, ), ) - val guardianWeeklyWithCode = PromotionWithCode(tenAnnual, guardianWeeklyAnnual) + val guardianWeeklyWithCode: PromotionWithCode = PromotionWithCode(tenAnnual, guardianWeeklyAnnual) val duplicate1 = promotion(validProductRatePlanIds, duplicatedPromoCode, discountBenefit) val duplicate2 = promotion(validProductRatePlanIds, duplicatedPromoCode, freeTrial = freeTrialBenefit) - val now = LocalDate.now() - val subscriptionData = SubscriptionData( + val now: LocalDate = LocalDate.now() + val subscriptionData: SubscriptionData = SubscriptionData( List( RatePlanData(RatePlan(validProductRatePlanId), Nil, Nil), ), diff --git a/support-workers/src/main/scala/com/gu/config/Configuration.scala b/support-workers/src/main/scala/com/gu/config/Configuration.scala index f10fd51bbc..7cf997e232 100644 --- a/support-workers/src/main/scala/com/gu/config/Configuration.scala +++ b/support-workers/src/main/scala/com/gu/config/Configuration.scala @@ -19,7 +19,7 @@ object Configuration extends SafeLogging { ) .getOrElse(true) // Should we load config from S3 - val stage = Stage + val stage: Stage = Stage .fromString( Option(System.getenv("GU_SUPPORT_WORKERS_STAGE")) .getOrElse("DEV"), @@ -33,20 +33,20 @@ object Configuration extends SafeLogging { .forEnvironment(Configuration.loadFromS3) .load(Configuration.stage, ConfigFactory.load(this.getClass.getClassLoader)) - lazy val emailQueueName = System.getenv("EMAIL_QUEUE_NAME") + lazy val emailQueueName: String = System.getenv("EMAIL_QUEUE_NAME") } case class Configuration(config: Config) { import Configuration.stage - val stripeConfigProvider = new StripeConfigProvider(config, stage) - val payPalConfigProvider = new PayPalConfigProvider(config, stage) - val salesforceConfigProvider = new SalesforceConfigProvider(config, stage) - val zuoraConfigProvider = new ZuoraConfigProvider(config, stage) - val promotionsConfigProvider = new PromotionsConfigProvider(config, stage) - val goCardlessConfigProvider = new GoCardlessConfigProvider(config, stage) - val paperRoundConfigProvider = new PaperRoundConfigProvider(config, stage) + val stripeConfigProvider: StripeConfigProvider = new StripeConfigProvider(config, stage) + val payPalConfigProvider: PayPalConfigProvider = new PayPalConfigProvider(config, stage) + val salesforceConfigProvider: SalesforceConfigProvider = new SalesforceConfigProvider(config, stage) + val zuoraConfigProvider: ZuoraConfigProvider = new ZuoraConfigProvider(config, stage) + val promotionsConfigProvider: PromotionsConfigProvider = new PromotionsConfigProvider(config, stage) + val goCardlessConfigProvider: GoCardlessConfigProvider = new GoCardlessConfigProvider(config, stage) + val paperRoundConfigProvider: PaperRoundConfigProvider = new PaperRoundConfigProvider(config, stage) - val acquisitionsKinesisStreamName = config.getString("kinesis.streamName") + val acquisitionsKinesisStreamName: String = config.getString("kinesis.streamName") } diff --git a/support-workers/src/main/scala/com/gu/emailservices/DigitalPackEmailFields.scala b/support-workers/src/main/scala/com/gu/emailservices/DigitalPackEmailFields.scala index 679134e3e8..5a196e6b37 100644 --- a/support-workers/src/main/scala/com/gu/emailservices/DigitalPackEmailFields.scala +++ b/support-workers/src/main/scala/com/gu/emailservices/DigitalPackEmailFields.scala @@ -142,7 +142,7 @@ class DigitalPackEmailFields( import DigitalSubscriptionEmailAttributes._ - val digitalPackPaymentEmailFields = new DigitalPackPaymentEmailFields(getMandate) + val digitalPackPaymentEmailFields: DigitalPackPaymentEmailFields = new DigitalPackPaymentEmailFields(getMandate) private def directOrCorpFields(details: String, subscriptionNumber: String, user: User) = BasicDSAttributes( zuorasubscriberid = subscriptionNumber, diff --git a/support-workers/src/main/scala/com/gu/emailservices/PaperFieldsGenerator.scala b/support-workers/src/main/scala/com/gu/emailservices/PaperFieldsGenerator.scala index 72d4a30d22..968e013f4d 100644 --- a/support-workers/src/main/scala/com/gu/emailservices/PaperFieldsGenerator.scala +++ b/support-workers/src/main/scala/com/gu/emailservices/PaperFieldsGenerator.scala @@ -74,7 +74,7 @@ class PaperFieldsGenerator( } - protected def getAddressFields(user: User) = { + protected def getAddressFields(user: User): List[(String, String)] = { val address = user.deliveryAddress.getOrElse(user.billingAddress) List( diff --git a/support-workers/src/main/scala/com/gu/emailservices/SubscriptionEmailFieldHelpers.scala b/support-workers/src/main/scala/com/gu/emailservices/SubscriptionEmailFieldHelpers.scala index c9e403ceb2..3624e4cb71 100644 --- a/support-workers/src/main/scala/com/gu/emailservices/SubscriptionEmailFieldHelpers.scala +++ b/support-workers/src/main/scala/com/gu/emailservices/SubscriptionEmailFieldHelpers.scala @@ -13,7 +13,7 @@ object SubscriptionEmailFieldHelpers { implicit def localDateOrdering: Ordering[LocalDate] = Ordering.fromLessThan(_ isBefore _) - val formatter = new DecimalFormat("#.00") + val formatter: DecimalFormat = new DecimalFormat("#.00") def formatPrice(price: Double): String = formatter.format(price) diff --git a/support-workers/src/main/scala/com/gu/gocardless/GoCardlessWorkersService.scala b/support-workers/src/main/scala/com/gu/gocardless/GoCardlessWorkersService.scala index 010b456148..3e6d94af18 100644 --- a/support-workers/src/main/scala/com/gu/gocardless/GoCardlessWorkersService.scala +++ b/support-workers/src/main/scala/com/gu/gocardless/GoCardlessWorkersService.scala @@ -10,7 +10,7 @@ import scala.concurrent.Future case class GoCardlessWorkersService(config: GoCardlessConfig) extends GoCardlessService(config) { - lazy val client = GoCardlessClient.create(config.apiToken, Environment.valueOf(config.environment)) + lazy val client: GoCardlessClient = GoCardlessClient.create(config.apiToken, Environment.valueOf(config.environment)) def getCustomerAccountIdFromMandateId(mandateId: String): Future[String] = Future { diff --git a/support-workers/src/main/scala/com/gu/paypal/PayPalService.scala b/support-workers/src/main/scala/com/gu/paypal/PayPalService.scala index 8de232610d..7c4c017071 100644 --- a/support-workers/src/main/scala/com/gu/paypal/PayPalService.scala +++ b/support-workers/src/main/scala/com/gu/paypal/PayPalService.scala @@ -14,9 +14,9 @@ import scala.util.Try class PayPalService(apiConfig: PayPalConfig, client: FutureHttpClient) extends SafeLogging { - val config = apiConfig + val config: PayPalConfig = apiConfig // The parameters sent with every NVP request. - val defaultNVPParams = Map( + val defaultNVPParams: Map[String, String] = Map( "USER" -> config.user, "PWD" -> config.password, "SIGNATURE" -> config.signature, diff --git a/support-workers/src/main/scala/com/gu/salesforce/SalesforceService.scala b/support-workers/src/main/scala/com/gu/salesforce/SalesforceService.scala index 3058f1f588..ade882ed01 100644 --- a/support-workers/src/main/scala/com/gu/salesforce/SalesforceService.scala +++ b/support-workers/src/main/scala/com/gu/salesforce/SalesforceService.scala @@ -20,10 +20,10 @@ import scala.concurrent.{ExecutionContext, Future} class SalesforceService(config: SalesforceConfig, client: FutureHttpClient)(implicit ec: ExecutionContext) extends WebServiceHelper[SalesforceErrorResponse] { - val sfConfig = config - val wsUrl = sfConfig.url + val sfConfig: SalesforceConfig = config + val wsUrl: String = sfConfig.url val httpClient: FutureHttpClient = client - val upsertEndpoint = "services/apexrest/RegisterCustomer/v1/" + val upsertEndpoint: String = "services/apexrest/RegisterCustomer/v1/" override def wsPreExecute(req: Request.Builder): Future[Request.Builder] = { logger.info(s"Issuing request to wsPreExecute: $config") @@ -208,8 +208,8 @@ object AuthService extends SafeLogging { class AuthService(config: SalesforceConfig)(implicit ec: ExecutionContext) extends WebServiceHelper[SalesforceAuthenticationErrorResponse] { - val sfConfig = config - val wsUrl = sfConfig.url + val sfConfig: SalesforceConfig = config + val wsUrl: String = sfConfig.url val httpClient: FutureHttpClient = RequestRunners.configurableFutureRunner(10.seconds) def authorize: Future[Authentication] = { diff --git a/support-workers/src/main/scala/com/gu/services/Services.scala b/support-workers/src/main/scala/com/gu/services/Services.scala index df1a6c741e..95d5da3ae2 100644 --- a/support-workers/src/main/scala/com/gu/services/Services.scala +++ b/support-workers/src/main/scala/com/gu/services/Services.scala @@ -21,6 +21,7 @@ import com.gu.zuora.{ZuoraGiftService, ZuoraService} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ +import com.gu.supporterdata.model.Stage trait ServiceProvider { private lazy val config = Configuration.load() @@ -38,22 +39,26 @@ class Services(isTestUser: Boolean, val config: Configuration) { new StripeService(stripeConfigProvider.get(isTestUser), configurableFutureRunner(40.seconds)) lazy val payPalService: PayPalService = new PayPalService(payPalConfigProvider.get(isTestUser), configurableFutureRunner(40.seconds)) - lazy val salesforceService = + lazy val salesforceService: SalesforceService = new SalesforceService(salesforceConfigProvider.get(isTestUser), configurableFutureRunner(40.seconds)) - lazy val zuoraService = new ZuoraService(zuoraConfigProvider.get(isTestUser), configurableFutureRunner(60.seconds)) - lazy val zuoraGiftService = + lazy val zuoraService: ZuoraService = + new ZuoraService(zuoraConfigProvider.get(isTestUser), configurableFutureRunner(60.seconds)) + lazy val zuoraGiftService: ZuoraGiftService = new ZuoraGiftService(zuoraConfigProvider.get(isTestUser), Configuration.stage, configurableFutureRunner(60.seconds)) - lazy val promotionService = new PromotionService(promotionsConfigProvider.get(isTestUser)) - lazy val goCardlessService = GoCardlessWorkersService(goCardlessConfigProvider.get(isTestUser)) - lazy val catalogService = CatalogService(TouchPointEnvironments.fromStage(stage, isTestUser)) - lazy val giftCodeGenerator = new GiftCodeGeneratorService - lazy val acquisitionsEventBusService = AcquisitionsEventBusService(Sources.supportWorkers, stage, isTestUser) - lazy val paperRoundService = + lazy val promotionService: PromotionService = new PromotionService(promotionsConfigProvider.get(isTestUser)) + lazy val goCardlessService: GoCardlessWorkersService = GoCardlessWorkersService( + goCardlessConfigProvider.get(isTestUser), + ) + lazy val catalogService: CatalogService = CatalogService(TouchPointEnvironments.fromStage(stage, isTestUser)) + lazy val giftCodeGenerator: GiftCodeGeneratorService = new GiftCodeGeneratorService + lazy val acquisitionsEventBusService: AcquisitionsEventBusService = + AcquisitionsEventBusService(Sources.supportWorkers, stage, isTestUser) + lazy val paperRoundService: PaperRoundService = new PaperRoundService(paperRoundConfigProvider.get(isTestUser), configurableFutureRunner(40.seconds)) - val supporterDynamoStage = (Configuration.stage, isTestUser) match { + val supporterDynamoStage: Stage = (Configuration.stage, isTestUser) match { case (PROD, false) => DynamoStagePROD case _ => DynamoStageCODE } - lazy val supporterDataDynamoService = SupporterDataDynamoService(supporterDynamoStage) + lazy val supporterDataDynamoService: SupporterDataDynamoService = SupporterDataDynamoService(supporterDynamoStage) } diff --git a/support-workers/src/main/scala/com/gu/stripe/StripeBrand.scala b/support-workers/src/main/scala/com/gu/stripe/StripeBrand.scala index 3c1ce284f2..8fa59cc2e4 100644 --- a/support-workers/src/main/scala/com/gu/stripe/StripeBrand.scala +++ b/support-workers/src/main/scala/com/gu/stripe/StripeBrand.scala @@ -22,7 +22,7 @@ object StripeBrand { case object Visa extends StripeBrand("Visa", "visa", Some("Visa")) case object Unknown extends StripeBrand("Unknown", "unknown", None) - val all = Seq(Amex, Diners, Discover, Jcb, Mastercard, Unionpay, Visa, Unknown) + val all: Seq[StripeBrand] = Seq(Amex, Diners, Discover, Jcb, Mastercard, Unionpay, Visa, Unknown) def decoder(field: StripeBrand => String): Decoder[StripeBrand] = Decoder.decodeString.emap { str => all.find(field(_) == str).toRight("StripeBrand") diff --git a/support-workers/src/main/scala/com/gu/stripe/StripeService.scala b/support-workers/src/main/scala/com/gu/stripe/StripeService.scala index b16d6e178f..e0e012a285 100644 --- a/support-workers/src/main/scala/com/gu/stripe/StripeService.scala +++ b/support-workers/src/main/scala/com/gu/stripe/StripeService.scala @@ -13,12 +13,13 @@ import io.circe.Decoder import scala.concurrent.Future import scala.reflect.ClassTag +import com.gu.support.workers.PaymentMethodId class StripeService(val config: StripeConfig, client: FutureHttpClient, baseUrl: String = "https://api.stripe.com/v1") extends WebServiceHelper[StripeError] { // Stripe URL is the same in all environments - val wsUrl = baseUrl + val wsUrl: String = baseUrl val httpClient: FutureHttpClient = client def withCurrency(currency: Currency): StripeServiceForCurrency = { @@ -61,8 +62,11 @@ class StripeServiceForCurrency( List(Some(authorizationHeader), versionHeader).flatten.toMap } - val createCustomerFromPaymentMethod = com.gu.stripe.createCustomerFromPaymentMethod.apply(this) _ + val createCustomerFromPaymentMethod + : PaymentMethodId => Future[com.gu.stripe.createCustomerFromPaymentMethod.Customer] = + com.gu.stripe.createCustomerFromPaymentMethod.apply(this) _ - val getPaymentMethod = com.gu.stripe.getPaymentMethod.apply(this) _ + val getPaymentMethod: PaymentMethodId => Future[com.gu.stripe.getPaymentMethod.StripePaymentMethod] = + com.gu.stripe.getPaymentMethod.apply(this) _ } diff --git a/support-workers/src/main/scala/com/gu/support/workers/encoding/package.scala b/support-workers/src/main/scala/com/gu/support/workers/encoding/package.scala index c327da0293..d669929fb8 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/encoding/package.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/encoding/package.scala @@ -1,5 +1,6 @@ package com.gu.support.workers +import java.nio.charset.Charset package object encoding { - val utf8 = java.nio.charset.StandardCharsets.UTF_8 + val utf8: Charset = java.nio.charset.StandardCharsets.UTF_8 } diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateSalesforceContact.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateSalesforceContact.scala index 7a64162546..b29fe36029 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateSalesforceContact.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateSalesforceContact.scala @@ -49,7 +49,7 @@ class NextState(state: CreateSalesforceContactState) { import state._ - val Purchase = Left + val Purchase: Left.type = Left type Redemption = Right[PaymentMethod, RedemptionData] // scalastyle:off cyclomatic.complexity diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateZuoraSubscription.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateZuoraSubscription.scala index 772270d388..541fe5d06e 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateZuoraSubscription.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/CreateZuoraSubscription.scala @@ -85,41 +85,44 @@ class CreateZuoraSubscription(servicesProvider: ServiceProvider = ServiceProvide class ZuoraProductHandlers(services: Services, state: CreateZuoraSubscriptionState) { - lazy val zuoraDigitalSubscriptionGiftRedemptionHandler = new ZuoraDigitalSubscriptionGiftRedemptionHandler( - services.zuoraGiftService, - services.catalogService, - state.user, - state.requestId, - ) - lazy val subscribeItemBuilder = new SubscribeItemBuilder( + lazy val zuoraDigitalSubscriptionGiftRedemptionHandler: ZuoraDigitalSubscriptionGiftRedemptionHandler = + new ZuoraDigitalSubscriptionGiftRedemptionHandler( + services.zuoraGiftService, + services.catalogService, + state.user, + state.requestId, + ) + lazy val subscribeItemBuilder: SubscribeItemBuilder = new SubscribeItemBuilder( state.requestId, state.user, state.product.currency, ) - lazy val zuoraDigitalSubscriptionGiftPurchaseHandler = new ZuoraDigitalSubscriptionGiftPurchaseHandler( - zuoraSubscriptionCreator, - dateGenerator, - new DigitalSubscriptionGiftPurchaseBuilder( - services.promotionService, + lazy val zuoraDigitalSubscriptionGiftPurchaseHandler: ZuoraDigitalSubscriptionGiftPurchaseHandler = + new ZuoraDigitalSubscriptionGiftPurchaseHandler( + zuoraSubscriptionCreator, dateGenerator, - services.giftCodeGenerator, - touchPointEnvironment, - subscribeItemBuilder, - ), - state.user, - ) - lazy val zuoraDigitalSubscriptionDirectHandler = new ZuoraDigitalSubscriptionDirectHandler( - zuoraSubscriptionCreator, - new DigitalSubscriptionDirectPurchaseBuilder( - services.config.zuoraConfigProvider.get(isTestUser).digitalPack, - services.promotionService, - dateGenerator, - touchPointEnvironment, - subscribeItemBuilder, - ), - state.user, - ) - lazy val zuoraContributionHandler = new ZuoraContributionHandler( + new DigitalSubscriptionGiftPurchaseBuilder( + services.promotionService, + dateGenerator, + services.giftCodeGenerator, + touchPointEnvironment, + subscribeItemBuilder, + ), + state.user, + ) + lazy val zuoraDigitalSubscriptionDirectHandler: ZuoraDigitalSubscriptionDirectHandler = + new ZuoraDigitalSubscriptionDirectHandler( + zuoraSubscriptionCreator, + new DigitalSubscriptionDirectPurchaseBuilder( + services.config.zuoraConfigProvider.get(isTestUser).digitalPack, + services.promotionService, + dateGenerator, + touchPointEnvironment, + subscribeItemBuilder, + ), + state.user, + ) + lazy val zuoraContributionHandler: ZuoraContributionHandler = new ZuoraContributionHandler( zuoraSubscriptionCreator, new ContributionSubscriptionBuilder( services.config.zuoraConfigProvider.get(isTestUser).contributionConfig, @@ -127,7 +130,7 @@ class ZuoraProductHandlers(services: Services, state: CreateZuoraSubscriptionSta ), state.user, ) - lazy val zuoraSupporterPlusHandler = new ZuoraSupporterPlusHandler( + lazy val zuoraSupporterPlusHandler: ZuoraSupporterPlusHandler = new ZuoraSupporterPlusHandler( zuoraSubscriptionCreator, new SupporterPlusSubcriptionBuilder( services.config.zuoraConfigProvider.get(isTestUser).supporterPlusConfig, @@ -139,7 +142,7 @@ class ZuoraProductHandlers(services: Services, state: CreateZuoraSubscriptionSta ), state.user, ) - lazy val zuoraTierThreeHandler = new ZuoraTierThreeHandler( + lazy val zuoraTierThreeHandler: ZuoraTierThreeHandler = new ZuoraTierThreeHandler( zuoraSubscriptionCreator, new TierThreeSubscriptionBuilder( services.promotionService, @@ -148,11 +151,11 @@ class ZuoraProductHandlers(services: Services, state: CreateZuoraSubscriptionSta subscribeItemBuilder, ), ) - lazy val zuoraPaperHandler = new ZuoraPaperHandler( + lazy val zuoraPaperHandler: ZuoraPaperHandler = new ZuoraPaperHandler( zuoraSubscriptionCreator, new PaperSubscriptionBuilder(services.promotionService, touchPointEnvironment, subscribeItemBuilder), ) - lazy val zuoraGuardianWeeklyHandler = new ZuoraGuardianWeeklyHandler( + lazy val zuoraGuardianWeeklyHandler: ZuoraGuardianWeeklyHandler = new ZuoraGuardianWeeklyHandler( zuoraSubscriptionCreator, new GuardianWeeklySubscriptionBuilder( services.promotionService, diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/PreparePaymentMethodForReuse.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/PreparePaymentMethodForReuse.scala index 1724c8041c..8989b083b1 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/PreparePaymentMethodForReuse.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/PreparePaymentMethodForReuse.scala @@ -29,7 +29,7 @@ class PreparePaymentMethodForReuse(servicesProvider: ServiceProvider = ServicePr requestInfo: RequestInfo, context: Context, services: Services, - ) = { + ): Future[HandlerResult[CreateZuoraSubscriptionState]] = { import com.gu.WithLoggingSugar._ diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/SendThankYouEmail.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/SendThankYouEmail.scala index 7fd1586767..b9cbde2d76 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/SendThankYouEmail.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/SendThankYouEmail.scala @@ -63,7 +63,7 @@ class EmailBuilder( promotionService: PromotionService, stage: Stage, ) { - val paperFieldsGenerator = new PaperFieldsGenerator(promotionService, getMandate) + val paperFieldsGenerator: PaperFieldsGenerator = new PaperFieldsGenerator(promotionService, getMandate) def buildEmail(state: SendThankYouEmailState): Future[List[EmailFields]] = { val touchpointEnvironment = TouchPointEnvironments.fromStage(stage, state.user.isTestUser) diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/ServicesHandler.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/ServicesHandler.scala index 222ed797ff..0d5fd955c9 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/ServicesHandler.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/ServicesHandler.scala @@ -20,7 +20,7 @@ abstract class ServicesHandler[IN <: StepFunctionUserState, OUT](servicesProvide error: Option[ExecutionError], requestInfo: RequestInfo, context: Context, - ) = { + ): FutureHandlerResult = { servicesHandler(input, requestInfo, context, servicesProvider.forUser(input.user.isTestUser)) } @@ -42,7 +42,12 @@ abstract class SubsetServicesHandler[IN <: StepFunctionUserState, OUT, SUBSET]( ec: ExecutionContext, ) extends ServicesHandler[IN, OUT](servicesProvider) { - override protected def servicesHandler(input: IN, requestInfo: RequestInfo, context: Context, services: Services) = { + override protected def servicesHandler( + input: IN, + requestInfo: RequestInfo, + context: Context, + services: Services, + ): FutureHandlerResult = { subsetHandler(makeSubset(input), requestInfo, context, services) } diff --git a/support-workers/src/main/scala/com/gu/support/workers/lambdas/UpdateSupporterProductData.scala b/support-workers/src/main/scala/com/gu/support/workers/lambdas/UpdateSupporterProductData.scala index 13eab17a1b..91a54828b9 100644 --- a/support-workers/src/main/scala/com/gu/support/workers/lambdas/UpdateSupporterProductData.scala +++ b/support-workers/src/main/scala/com/gu/support/workers/lambdas/UpdateSupporterProductData.scala @@ -46,7 +46,7 @@ class UpdateSupporterProductData(serviceProvider: ServiceProvider) state: SendThankYouEmailState, catalogService: CatalogService, supporterDataDynamoService: SupporterDataDynamoService, - ) = { + ): Future[Unit] = { logger.info(s"Attempting to update user ${state.user.id}") getSupporterRatePlanItemFromState(state, catalogService) match { case Right(Some(supporterRatePlanItem)) => diff --git a/support-workers/src/main/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionDirectPurchaseBuilder.scala b/support-workers/src/main/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionDirectPurchaseBuilder.scala index 6c27e70e80..e69eca4f6d 100644 --- a/support-workers/src/main/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionDirectPurchaseBuilder.scala +++ b/support-workers/src/main/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionDirectPurchaseBuilder.scala @@ -55,7 +55,7 @@ class DigitalSubscriptionDirectPurchaseBuilder( } - def overridePricingIfRequired(product: DigitalPack, maybeAbTests: Option[Set[AbTest]]) = + def overridePricingIfRequired(product: DigitalPack, maybeAbTests: Option[Set[AbTest]]): List[RatePlanChargeData] = if (isValidBenefitsTestPurchase(product, maybeAbTests)) { product.amount .map { amount => diff --git a/support-workers/src/test/scala/com/gu/emailservices/SubscriptionEmailFieldHelpersSpec.scala b/support-workers/src/test/scala/com/gu/emailservices/SubscriptionEmailFieldHelpersSpec.scala index a020abbc48..a91cf5ccf6 100644 --- a/support-workers/src/test/scala/com/gu/emailservices/SubscriptionEmailFieldHelpersSpec.scala +++ b/support-workers/src/test/scala/com/gu/emailservices/SubscriptionEmailFieldHelpersSpec.scala @@ -16,7 +16,7 @@ class SubscriptionEmailFieldHelpersSpec extends AnyFlatSpec with Matchers { List(original) ++ subsequentPayments } - val referenceDate = new LocalDate(2019, 1, 14) + val referenceDate: LocalDate = new LocalDate(2019, 1, 14) "describe" should "explain a simple annual payment schedule correctly" in { val standardDigitalPackPayment = Payment(referenceDate, 119.90) diff --git a/support-workers/src/test/scala/com/gu/salesforce/Fixtures.scala b/support-workers/src/test/scala/com/gu/salesforce/Fixtures.scala index 957fc6f936..5510f86348 100644 --- a/support-workers/src/test/scala/com/gu/salesforce/Fixtures.scala +++ b/support-workers/src/test/scala/com/gu/salesforce/Fixtures.scala @@ -4,22 +4,22 @@ import com.gu.i18n.Title import com.gu.salesforce.Salesforce.{DeliveryContact, NewContact} object Fixtures { - val idId = "9999999" - val salesforceId = "0039E000017tZVkQAM" - val salesforceAccountId = "0019E00001JJ9ZMQA1" - val emailAddress = "integration-test@thegulocal.com" - val telephoneNumber = "0123456789" - val title = Title.Mrs - val name = "integration-test" - val street = "123 trash alley" - val city = "London" - val postCode = "n1 9gu" - val uk = "UK" - val us = "US" - val state = "CA" - val allowMail = false + val idId: String = "9999999" + val salesforceId: String = "0039E000017tZVkQAM" + val salesforceAccountId: String = "0019E00001JJ9ZMQA1" + val emailAddress: String = "integration-test@thegulocal.com" + val telephoneNumber: String = "0123456789" + val title: Title = Title.Mrs + val name: String = "integration-test" + val street: String = "123 trash alley" + val city: String = "London" + val postCode: String = "n1 9gu" + val uk: String = "UK" + val us: String = "US" + val state: String = "CA" + val allowMail: Boolean = false - val newContactUK = NewContact( + val newContactUK: NewContact = NewContact( IdentityID__c = idId, Email = emailAddress, Salutation = Some(Title.Mrs), @@ -37,14 +37,14 @@ object Fixtures { MailingCountry = None, Phone = None, ) - val newContactUKWithBillingAddress = newContactUK.copy( + val newContactUKWithBillingAddress: NewContact = newContactUK.copy( OtherStreet = Some("123 trash alley"), OtherCity = Some("London"), OtherState = None, OtherPostalCode = Some("n1 9gu"), OtherCountry = uk, ) - val newContactUKWithBothAddressesAndTelephone = newContactUKWithBillingAddress.copy( + val newContactUKWithBothAddressesAndTelephone: NewContact = newContactUKWithBillingAddress.copy( MailingStreet = Some("123 trash alley"), MailingCity = Some("London"), MailingState = None, @@ -52,9 +52,9 @@ object Fixtures { MailingCountry = Some(uk), Phone = Some(telephoneNumber), ) - val newContactUS = newContactUK.copy(OtherCountry = us, OtherState = Some(state)) + val newContactUS: NewContact = newContactUK.copy(OtherCountry = us, OtherState = Some(state)) - val giftRecipientUpsert = DeliveryContact( + val giftRecipientUpsert: DeliveryContact = DeliveryContact( AccountId = salesforceId, Email = Some(emailAddress), Salutation = Some(Title.Mr), @@ -67,7 +67,7 @@ object Fixtures { MailingCountry = Some(uk), ) - val upsertJson = + val upsertJson: String = s"""{ "newContact": { "IdentityID__c": "$idId", @@ -78,7 +78,7 @@ object Fixtures { "OtherCountry": "$uk" } }""" - val upsertJsonWithState = + val upsertJsonWithState: String = s"""{ "newContact": { "IdentityID__c": "$idId", @@ -91,7 +91,7 @@ object Fixtures { } }""" - val upsertJsonWithTelephoneNumber = + val upsertJsonWithTelephoneNumber: String = s"""{ "newContact": { "IdentityID__c": "$idId", @@ -104,7 +104,7 @@ object Fixtures { } }""" - val upsertJsonWithBillingAddress = + val upsertJsonWithBillingAddress: String = s"""{ "newContact": { "IdentityID__c": "$idId", @@ -119,7 +119,7 @@ object Fixtures { } }""" - val upsertJsonWithBillingAndDeliveryAddresses = + val upsertJsonWithBillingAndDeliveryAddresses: String = s"""{ "newContact": { "IdentityID__c": "$idId", @@ -139,7 +139,7 @@ object Fixtures { } }""" - val giftRecipientUpsertJson = + val giftRecipientUpsertJson: String = s"""{ "newContact": { "AccountId": "$salesforceId", @@ -155,7 +155,7 @@ object Fixtures { } }""" - val authJson = + val authJson: String = """ { "access_token": "00Dg0000006RDAM!AREAQKDFKQ.ZPdIxWp4Z55tyVgs0D_kPhaiCMndEOk7WVB8yRffLVNK9TFbtZk34cWAfaaeojHL2ndURQounCzhRfBE_nMct", @@ -167,12 +167,12 @@ object Fixtures { } """ - val expiredTokenResponse = + val expiredTokenResponse: String = """ [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}] """ - val authenticationErrorResponse = + val authenticationErrorResponse: String = """ 400: {"error":"invalid_client_id","error_description":"client identifier invalid"} """ diff --git a/support-workers/src/test/scala/com/gu/salesforce/SalesforceSpec.scala b/support-workers/src/test/scala/com/gu/salesforce/SalesforceSpec.scala index 12fc4435c9..81aa484179 100644 --- a/support-workers/src/test/scala/com/gu/salesforce/SalesforceSpec.scala +++ b/support-workers/src/test/scala/com/gu/salesforce/SalesforceSpec.scala @@ -27,7 +27,7 @@ import scala.util.{Failure, Success} @IntegrationTest class SalesforceSpec extends AsyncFlatSpec with Matchers with LazyLogging { - val customer = NewContact( + val customer: NewContact = NewContact( IdentityID__c = idId, Email = emailAddress, Salutation = Some(Title.Mr), diff --git a/support-workers/src/test/scala/com/gu/support/workers/AddressLineTransformerTest.scala b/support-workers/src/test/scala/com/gu/support/workers/AddressLineTransformerTest.scala index 47c538150f..c7a0a63038 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/AddressLineTransformerTest.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/AddressLineTransformerTest.scala @@ -10,12 +10,12 @@ import org.scalatestplus.mockito.MockitoSugar class AddressLineTransformerTest extends AnyFlatSpec with Matchers with MockitoSugar { - val digitalPackProduct = DigitalPack( + val digitalPackProduct: DigitalPack = DigitalPack( currency = Currency.USD, billingPeriod = Monthly, ) - val directDebitPaymentFieldsFromClient = DirectDebitPaymentFields( + val directDebitPaymentFieldsFromClient: DirectDebitPaymentFields = DirectDebitPaymentFields( accountHolderName = "oscar the grouch", sortCode = "200000", accountNumber = "55779911", diff --git a/support-workers/src/test/scala/com/gu/support/workers/JsonFixtures.scala b/support-workers/src/test/scala/com/gu/support/workers/JsonFixtures.scala index 12e86e16ba..f77aa690ed 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/JsonFixtures.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/JsonFixtures.scala @@ -113,7 +113,7 @@ object JsonFixtures { } """ - val userJsonWithDeliveryAddress = + val userJsonWithDeliveryAddress: User = User( idId, emailAddress, @@ -141,7 +141,7 @@ object JsonFixtures { deliveryInstructions = Some("Leave with neighbour"), ) - val userJsonWithDeliveryAddressOutsideLondon = + val userJsonWithDeliveryAddressOutsideLondon: User = User( idId, emailAddress, @@ -169,9 +169,9 @@ object JsonFixtures { deliveryInstructions = Some("Leave with neighbour - support-frontend"), ) def requestIdJson: String = s""""requestId": "${UUID.randomUUID()}\"""" - val validBaid = "B-23637766K5365543J" - val payPalEmail = "test@paypal.com" - val payPalPaymentMethod = + val validBaid: String = "B-23637766K5365543J" + val payPalEmail: String = "test@paypal.com" + val payPalPaymentMethod: String = s""" { "PaypalBaid": "$validBaid", @@ -182,7 +182,7 @@ object JsonFixtures { } """ - val stripePaymentMethodObj = + val stripePaymentMethodObj: CreditCardReferenceTransaction = CreditCardReferenceTransaction( "card_E0zitFfsO2wTEn", "cus_E0zic0cedDT5MZ", @@ -194,7 +194,7 @@ object JsonFixtures { StripeGatewayDefault, StripePaymentType = None, ) - val stripePaymentMethod = // test env card and cus token, not prod ones + val stripePaymentMethod: String = // test env card and cus token, not prod ones s""" { "TokenId": "card_E0zitFfsO2wTEn", @@ -219,7 +219,7 @@ object JsonFixtures { } """ - val digitalPackJson = + val digitalPackJson: String = """ { "productType": "DigitalPack", @@ -229,7 +229,7 @@ object JsonFixtures { } """ - val digitalPackGiftJson = + val digitalPackGiftJson: String = """ { "productType": "DigitalPack", @@ -239,7 +239,7 @@ object JsonFixtures { } """ - val everydayPaperJson = + val everydayPaperJson: String = """ { "productType": "Paper", @@ -250,21 +250,21 @@ object JsonFixtures { } """ - val weeklyJson = GuardianWeekly(GBP, Monthly, Domestic).asJson.spaces2 + val weeklyJson: String = GuardianWeekly(GBP, Monthly, Domestic).asJson.spaces2 - val digitalPackProductJson = + val digitalPackProductJson: String = s""" "product": $digitalPackJson """ - val payPalJson = + val payPalJson: String = s""" { "baid": "$validBaid" } """ - val acquisitionData = + val acquisitionData: String = s""" { "ophanIds":{ @@ -291,8 +291,8 @@ object JsonFixtures { } """ - val mickeyMouse = "Mickey Mouse" - val directDebitJson = + val mickeyMouse: String = "Mickey Mouse" + val directDebitJson: String = s""" { "accountHolderName": "$mickeyMouse", @@ -301,10 +301,10 @@ object JsonFixtures { } """ - val stripeToken = PaymentMethodId("pm_card_visa").get - val stripePublicKey = StripePublicKey.get("pk_test_Qm3CGRdrV4WfGYCpm0sftR0f") + val stripeToken: PaymentMethodId = PaymentMethodId("pm_card_visa").get + val stripePublicKey: StripePublicKey = StripePublicKey.get("pk_test_Qm3CGRdrV4WfGYCpm0sftR0f") - val stripeJson = + val stripeJson: String = s""" { "paymentMethod": "${stripeToken.value}", @@ -348,7 +348,7 @@ object JsonFixtures { "userAgent": "Test" }""" - val createPayPalPaymentMethodDigitalPackJson = + val createPayPalPaymentMethodDigitalPackJson: String = s"""{ $requestIdJson, ${userJson()}, @@ -362,7 +362,7 @@ object JsonFixtures { "userAgent": "Test" }""" - val createDirectDebitDigitalPackJson = + val createDirectDebitDigitalPackJson: String = s"""{ $requestIdJson, ${userJson()}, @@ -374,7 +374,7 @@ object JsonFixtures { "paymentFields": $directDebitJson }""" - val createSalesForceContactJson = + val createSalesForceContactJson: String = s""" { $requestIdJson, @@ -388,7 +388,7 @@ object JsonFixtures { } """ - val createSalesForceGiftContactJson = + val createSalesForceGiftContactJson: String = s""" { $requestIdJson, @@ -410,12 +410,12 @@ object JsonFixtures { } """ - val salesforceContact = + val salesforceContact: SalesforceContactRecord = SalesforceContactRecord( "0033E00001Cq8D2QAJ", "0013E00001AU6xcQAD", ) - val salesforceContacts = { + val salesforceContacts: SalesforceContactRecords = { SalesforceContactRecords( SalesforceContactRecord( "0033E00001Cq8D2QAJ", @@ -429,7 +429,7 @@ object JsonFixtures { ), ) } - val salesforceContactJson = + val salesforceContactJson: String = """ { "Id": "0033E00001Cq8D2QAJ", @@ -437,7 +437,7 @@ object JsonFixtures { } """ - val salesforceContactsJson = + val salesforceContactsJson: String = """ "salesforceContacts": { "buyer": { @@ -520,7 +520,7 @@ object JsonFixtures { acquisitionData = None, ).asJson.spaces2 - val createDigiPackZuoraSubscriptionJson = + val createDigiPackZuoraSubscriptionJson: String = CreateZuoraSubscriptionState( DigitalSubscriptionDirectPurchaseState( Country.UK, @@ -574,7 +574,7 @@ object JsonFixtures { RedemptionData(RedemptionCode(code).toOption.get), ): CreateZuoraSubscriptionProductState).asJson.spaces2 - val createDigiPackSubscriptionWithPromoJson = + val createDigiPackSubscriptionWithPromoJson: String = CreateZuoraSubscriptionState( DigitalSubscriptionDirectPurchaseState( Country.UK, @@ -594,7 +594,7 @@ object JsonFixtures { None, ).asJson.spaces2 - val createEverydayPaperSubscriptionJson = + val createEverydayPaperSubscriptionJson: String = CreateZuoraSubscriptionState( PaperState( userJsonWithDeliveryAddress, @@ -615,7 +615,7 @@ object JsonFixtures { None, ).asJson.spaces2 - val createEverydayNationalDeliveryPaperSubscriptionJson = { + val createEverydayNationalDeliveryPaperSubscriptionJson: String = { val paper = Paper(GBP, Monthly, NationalDelivery, Everyday, Some(AgentId(deliveryAgentId))) CreateZuoraSubscriptionState( PaperState( @@ -663,7 +663,7 @@ object JsonFixtures { None, ).asJson.spaces2 - val guardianWeeklyGiftJson = + val guardianWeeklyGiftJson: String = CreateZuoraSubscriptionState( GuardianWeeklyState( userJsonWithDeliveryAddress, @@ -692,7 +692,7 @@ object JsonFixtures { None, ).asJson.spaces2 - val failureJson = + val failureJson: String = """{ "state": {"requestId":"e18f6418-45f2-11e7-8bfa-8faac2182601","user":{"id":"12345","primaryEmailAddress":"test@thegulocal.com","firstName":"test","lastName":"user","country":"GB","billingAddress":{"country":"GB"},"isTestUser":false},"product":{"productType":"Contribution","amount":5,"currency":"GBP","billingPeriod":"Annual"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentMethod":{"TokenId":"card_E0zitFfsO2wTEn","SecondTokenId":"cus_E0zic0cedDT5MZ","CreditCardNumber":"4242","CreditCardCountry":"US","CreditCardExpirationMonth":2,"CreditCardExpirationYear":2029,"CreditCardType":"Visa","Type":"CreditCardReferenceTransaction","PaymentGateway":"Stripe Gateway 1"},"salesForceContact":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"},"salesforceContacts":{"buyer":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"},"giftRecipient":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"}}}, "error": { @@ -709,7 +709,7 @@ object JsonFixtures { """ // This Json uses a test Stripe token which causes Stripe to return a card_declined response, but the product is a digital pack - val digipackCardDeclinedStripeJson = + val digipackCardDeclinedStripeJson: String = """ { "state": {"requestId":"299f0204-8f82-f479-0000-00000000e33d","user":{"id":"30001643","primaryEmailAddress":"test@thegulocal.com","firstName":"FygxilMxB5QMoAkmuIc","lastName":"FygxilMxB5QMoAkmuIc","billingAddress":{"country":"GB"},"country":"GB","state":null,"isTestUser":false},"product":{"productType":"DigitalPack","currency":"GBP","billingPeriod":"Annual","readerType":"Direct"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentFields":{"userId":"30001643","stripeToken":"tok_chargeDeclined"},"acquisitionData":{"ophanIds":{"pageviewId":"jaignx8mlwazhhpaq9tk","browserId":null},"referrerAcquisitionData":{"campaignCode":null,"referrerPageviewId":null,"referrerUrl":null,"componentId":null,"componentType":null,"source":null,"abTest":null},"supportAbTests":[{"name":"usRecurringCopyTest","variant":"notintest"},{"name":"ukRecurringAmountsTest","variant":"lower"},{"name":"usRecurringAmountsTest","variant":"notintest"}]}}, @@ -726,10 +726,10 @@ object JsonFixtures { } """ - val zuoraErrorResponse = + val zuoraErrorResponse: String = """[{"Code": "TRANSACTION_FAILED","Message": "Transaction declined.do_not_honor - Your card was declined."}]""" - val cardDeclinedJsonZuora = + val cardDeclinedJsonZuora: String = """ { "state": {"requestId":"e18f6418-45f2-11e7-8bfa-8faac2182601","user":{"id":"12345","primaryEmailAddress":"test@thegulocal.com","firstName":"test","lastName":"user","country":"GB","billingAddress":{"country":"GB"},"isTestUser":false},"product":{"productType":"Contribution","amount":5,"currency":"GBP","billingPeriod":"Annual"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentMethod":{"TokenId":"card_E0zitFfsO2wTEn","SecondTokenId":"cus_E0zic0cedDT5MZ","CreditCardNumber":"4242","CreditCardCountry":"US","CreditCardExpirationMonth":2,"CreditCardExpirationYear":2029,"CreditCardType":"Visa","Type":"CreditCardReferenceTransaction","PaymentGateway":"Stripe Gateway 1"},"salesForceContact":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"},"salesforceContacts":{"buyer":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"},"giftRecipient":{"Id":"0033E00001Cq8D2QAJ","AccountId":"0013E00001AU6xcQAD"}}}, @@ -745,7 +745,7 @@ object JsonFixtures { } } """ - val cardDeclinedJsonStripe = + val cardDeclinedJsonStripe: String = """ { "state": {"requestId":"299f0204-8f82-f479-0000-00000000e33d","user":{"id":"30001643","primaryEmailAddress":"fygxilmxb5qmoakmuic@thegulocal.com","firstName":"FygxilMxB5QMoAkmuIc","lastName":"FygxilMxB5QMoAkmuIc","country":"GB","billingAddress":{"country":"GB"},"state":null,"isTestUser":false},"product":{"productType":"Contribution","currency":"GBP","billingPeriod":"Monthly","amount":5,"type":"Contribution"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentFields":{"userId":"30001643","stripeToken":"tok_chargeDeclined"},"acquisitionData":{"ophanIds":{"pageviewId":"jaignx8mlwazhhpaq9tk","browserId":null},"referrerAcquisitionData":{"campaignCode":null,"referrerPageviewId":null,"referrerUrl":null,"componentId":null,"componentType":null,"source":null,"abTest":null},"supportAbTests":[{"name":"usRecurringCopyTest","variant":"notintest"},{"name":"ukRecurringAmountsTest","variant":"lower"},{"name":"usRecurringAmountsTest","variant":"notintest"}]}}, @@ -761,7 +761,7 @@ object JsonFixtures { } } """ - val testTokenInProdJsonStripe = + val testTokenInProdJsonStripe: String = """ { "state": {"requestId":"299f0204-8f82-f479-0000-00000000e33d","user":{"id":"30001643","primaryEmailAddress":"fygxilmxb5qmoakmuic@thegulocal.com","firstName":"FygxilMxB5QMoAkmuIc","lastName":"FygxilMxB5QMoAkmuIc","country":"GB","billingAddress":{"country":"GB"},"state":null,"isTestUser":false},"product":{"productType":"Contribution","currency":"GBP","billingPeriod":"Monthly","amount":5,"type":"Contribution"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentFields":{"userId":"30001643","stripeToken":"tok_chargeDeclined"},"acquisitionData":{"ophanIds":{"pageviewId":"jaignx8mlwazhhpaq9tk","browserId":null},"referrerAcquisitionData":{"campaignCode":null,"referrerPageviewId":null,"referrerUrl":null,"componentId":null,"componentType":null,"source":null,"abTest":null},"supportAbTests":[{"name":"usRecurringCopyTest","variant":"notintest"},{"name":"ukRecurringAmountsTest","variant":"lower"},{"name":"usRecurringAmountsTest","variant":"notintest"}]}}, @@ -778,7 +778,7 @@ object JsonFixtures { } """ - val wrapperWithMessages = + val wrapperWithMessages: String = """ { "state": {"requestId":"a64ad98e-5d39-4ffc-a4a9-217357dc2b19","user":{"id":"9999999","primaryEmailAddress":"integration-test@thegulocal.com","firstName":"test","lastName":"user","country":"GB","billingAddress":{"country":"GB"},"isTestUser":false},"product":{"productType":"Contribution","amount":5,"currency":"GBP","billingPeriod":"Monthly"},"analyticsInfo":{"paymentProvider": "Stripe","isGiftPurchase":false},"paymentMethod":{"PaypalBaid":"B-23637766K5365543J","PaypalEmail":"test@paypal.com","PaypalType":"ExpressCheckout","Type":"PayPal","PaymentGateway":"PayPal Express"},"giftRecipient":{"title":"Mr","firstName":"Gifty","lastName":"McRecipent","email":"gift.recipient@thegulocal.com","giftRecipientType":"Weekly"}}, @@ -794,7 +794,7 @@ object JsonFixtures { } """ - val sendAcquisitionEventJson = + val sendAcquisitionEventJson: String = s"""{ $requestIdJson, "analyticsInfo": { @@ -815,7 +815,7 @@ object JsonFixtures { }, "acquisitionData": $acquisitionData }""" - val sendAcquisitionEventPrintJson = + val sendAcquisitionEventPrintJson: String = s""" { "requestId": "1a94c891-e98a-13ae-0000-0000000038a3", @@ -883,7 +883,7 @@ object JsonFixtures { } """ - val sendAcquisitionEventGWJson = + val sendAcquisitionEventGWJson: String = """ { "requestId": "1a94c891-e98a-13ae-0000-000000003f18", @@ -970,7 +970,7 @@ object JsonFixtures { } } """ - val digipackSubscriptionWithDiscountAndFreeTrialJson = + val digipackSubscriptionWithDiscountAndFreeTrialJson: String = CreateZuoraSubscriptionState( DigitalSubscriptionDirectPurchaseState( Country.UK, @@ -1004,7 +1004,7 @@ object JsonFixtures { } """ - val previewSubscribeResponseJson = """ + val previewSubscribeResponseJson: String = """ { "Success": true, "InvoiceData": [ diff --git a/support-workers/src/test/scala/com/gu/support/workers/LambdaSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/LambdaSpec.scala index 70871237cd..657f8c6a22 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/LambdaSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/LambdaSpec.scala @@ -10,6 +10,6 @@ abstract class LambdaSpec extends AnyFlatSpec with Matchers with MockContext abstract class AsyncLambdaSpec extends AsyncFlatSpec with Matchers trait MockContext extends MockitoSugar { - val context = mock[Context] + val context: Context = mock[Context] when(context.getRemainingTimeInMillis).thenReturn(60000) } diff --git a/support-workers/src/test/scala/com/gu/support/workers/PreviewPaymentScheduleSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/PreviewPaymentScheduleSpec.scala index 395c13aea1..bd842e7dd8 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/PreviewPaymentScheduleSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/PreviewPaymentScheduleSpec.scala @@ -9,7 +9,7 @@ import JsonFixtures.previewSubscribeResponseJson class PreviewPaymentScheduleSpec extends AnyFlatSpec with Matchers { - val firstPaymentDate = new LocalDate(2019, 1, 14) + val firstPaymentDate: LocalDate = new LocalDate(2019, 1, 14) "paymentSchedule" should "calculate a payment schedule correctly for products without tax" in { val taxExclusiveCharge = Charge(firstPaymentDate, firstPaymentDate.plusMonths(1), 0, 5.00) diff --git a/support-workers/src/test/scala/com/gu/support/workers/errors/MockWebServerCreator.scala b/support-workers/src/test/scala/com/gu/support/workers/errors/MockWebServerCreator.scala index b004b1b6a3..9973d3cc65 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/errors/MockWebServerCreator.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/errors/MockWebServerCreator.scala @@ -3,7 +3,11 @@ package com.gu.support.workers.errors import okhttp3.mockwebserver.{MockResponse, MockWebServer} trait MockWebServerCreator { - protected def createMockServer(responseCode: Int, body: String, contentType: String = "application/json") = { + protected def createMockServer( + responseCode: Int, + body: String, + contentType: String = "application/json", + ): MockWebServer = { // Create a MockWebServer. These are lean enough that you can create a new // instance for every unit test. val server = new MockWebServer diff --git a/support-workers/src/test/scala/com/gu/support/workers/errors/SalesforceErrorsSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/errors/SalesforceErrorsSpec.scala index 92bfed202b..869fc460c4 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/errors/SalesforceErrorsSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/errors/SalesforceErrorsSpec.scala @@ -32,7 +32,7 @@ class SalesforceErrorsSpec extends AsyncLambdaSpec with Matchers { } } - val upsertData = NewContact( + val upsertData: NewContact = NewContact( IdentityID__c = idId, Email = emailAddress, Salutation = Some(Title.Ms), diff --git a/support-workers/src/test/scala/com/gu/support/workers/errors/ZuoraErrorsSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/errors/ZuoraErrorsSpec.scala index 1ff9620a11..8f3bd6892e 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/errors/ZuoraErrorsSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/errors/ZuoraErrorsSpec.scala @@ -184,7 +184,7 @@ class ZuoraErrorsITSpec assertion } - val realConfig = Configuration.load() + val realConfig: Configuration = Configuration.load() private val timeoutServices = errorServices(None, 1.milliseconds) diff --git a/support-workers/src/test/scala/com/gu/support/workers/integration/CreateZuoraSubscriptionSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/integration/CreateZuoraSubscriptionSpec.scala index 1c5e8f251e..f2f5e7c8e3 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/integration/CreateZuoraSubscriptionSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/integration/CreateZuoraSubscriptionSpec.scala @@ -35,7 +35,7 @@ import com.gu.support.catalog.Domestic @IntegrationTest class CreateZuoraSubscriptionSpec extends AsyncLambdaSpec with MockServicesCreator with MockContext { - val createZuoraHelper = new CreateZuoraSubscriptionHelper() + val createZuoraHelper: CreateZuoraSubscriptionHelper = new CreateZuoraSubscriptionHelper() "CreateZuoraSubscription lambda" should "create a monthly contribution" in { createZuoraHelper @@ -198,19 +198,20 @@ class CreateZuoraSubscriptionHelper(implicit executionContext: ExecutionContext) } } - val realConfig = Configuration.load() + val realConfig: Configuration = Configuration.load() - val realZuoraService = new ZuoraService(realConfig.zuoraConfigProvider.get(), configurableFutureRunner(60.seconds)) + val realZuoraService: ZuoraService = + new ZuoraService(realConfig.zuoraConfigProvider.get(), configurableFutureRunner(60.seconds)) - val realZuoraGiftService = + val realZuoraGiftService: ZuoraGiftService = new ZuoraGiftService(realConfig.zuoraConfigProvider.get(), Stages.DEV, configurableFutureRunner(60.seconds)) - val realPromotionService = new PromotionService(realConfig.promotionsConfigProvider.get()) + val realPromotionService: PromotionService = new PromotionService(realConfig.promotionsConfigProvider.get()) private val jsonProvider = new S3CatalogProvider(TouchPointEnvironments.CODE) - lazy val realCatalogService = new CatalogService(TouchPointEnvironments.CODE, jsonProvider) + lazy val realCatalogService: CatalogService = new CatalogService(TouchPointEnvironments.CODE, jsonProvider) - lazy val mockZuoraService = { + lazy val mockZuoraService: ZuoraService = { val mockZuora = mock[ZuoraService] // Need to return None from the Zuora service `getRecurringSubscription` // method or the subscribe step gets skipped diff --git a/support-workers/src/test/scala/com/gu/support/workers/integration/PreparePaymentMethodForReuseSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/integration/PreparePaymentMethodForReuseSpec.scala index cf3d4c0033..df367a1523 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/integration/PreparePaymentMethodForReuseSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/integration/PreparePaymentMethodForReuseSpec.scala @@ -21,6 +21,7 @@ import org.scalatest.Inside.inside import java.io.ByteArrayOutputStream import scala.concurrent.duration._ +import com.gu.services.ServiceProvider @IntegrationTest class PreparePaymentMethodForReuseSpec extends AsyncLambdaSpec with MockServicesCreator with MockContext { @@ -52,14 +53,14 @@ class PreparePaymentMethodForReuseSpec extends AsyncLambdaSpec with MockServices } - val realConfig = Configuration.load() + val realConfig: Configuration = Configuration.load() - val realZuoraService = + val realZuoraService: ZuoraService = new ZuoraService(realConfig.zuoraConfigProvider.get(false), configurableFutureRunner(60.seconds)) - val realPromotionService = new PromotionService(realConfig.promotionsConfigProvider.get(false)) + val realPromotionService: PromotionService = new PromotionService(realConfig.promotionsConfigProvider.get(false)) - val mockZuoraService = { + val mockZuoraService: ZuoraService = { val mockZuora = mock[ZuoraService] // Need to return None from the Zuora service `getRecurringSubscription` // method or the subscribe step gets skipped @@ -76,7 +77,7 @@ class PreparePaymentMethodForReuseSpec extends AsyncLambdaSpec with MockServices mockZuora } - lazy val mockServiceProvider = mockServices[Any]( + lazy val mockServiceProvider: ServiceProvider = mockServices[Any]( (s => s.zuoraService, mockZuoraService), (s => s.promotionService, realPromotionService), ) diff --git a/support-workers/src/test/scala/com/gu/support/workers/integration/SendThankYouEmailSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/integration/SendThankYouEmailSpec.scala index 9416c6ff42..651c312fd2 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/integration/SendThankYouEmailSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/integration/SendThankYouEmailSpec.scala @@ -93,9 +93,9 @@ class SendThankYouEmailSpec extends AsyncLambdaSpec { object SendThankYouEmailManualTest { // This test will send a thank you email to the address/SF contact below - useful for quickly testing changes - val addressToSendTo = "john.duffell@guardian.co.uk" - val identityIdToSendTo = "200004242" - val giftRecipientSFContactIdToSendTo = SfContactId("0039E000018EoTHQA0") + val addressToSendTo: String = "john.duffell@guardian.co.uk" + val identityIdToSendTo: String = "200004242" + val giftRecipientSFContactIdToSendTo: SfContactId = SfContactId("0039E000018EoTHQA0") def main(args: Array[String]): Unit = { SendContributionEmail.main(args) @@ -122,7 +122,7 @@ import com.gu.support.workers.integration.SendThankYouEmailManualTest._ import com.gu.support.workers.integration.TestData._ object SendContributionEmail extends App { - val ef = new ContributionEmailFields( + val ef: Future[EmailFields] = new ContributionEmailFields( getMandate, new DateTime(1999, 12, 31, 11, 59), ).build( @@ -140,7 +140,7 @@ object SendContributionEmail extends App { object SendSupporterPlusEmail extends App { - val supporterPlusPaymentSchedule = PaymentSchedule( + val supporterPlusPaymentSchedule: PaymentSchedule = PaymentSchedule( List( Payment(new LocalDate(2024, 1, 8), 10), Payment(new LocalDate(2024, 2, 8), 10), @@ -151,7 +151,7 @@ object SendSupporterPlusEmail extends App { ), ) - val ef = new SupporterPlusEmailFields( + val ef: Future[EmailFields] = new SupporterPlusEmailFields( new PaperFieldsGenerator(supporterPlusPromotionService, getMandate), getMandate, CODE, @@ -173,7 +173,7 @@ object SendSupporterPlusEmail extends App { object SendTierThreeEmail extends App { - val paymentSchedule = PaymentSchedule( + val paymentSchedule: PaymentSchedule = PaymentSchedule( List( Payment(new LocalDate(2024, 1, 8), 10), Payment(new LocalDate(2024, 2, 8), 10), @@ -184,7 +184,7 @@ object SendTierThreeEmail extends App { ), ) - val ef = new TierThreeEmailFields( + val ef: Future[EmailFields] = new TierThreeEmailFields( new PaperFieldsGenerator(promotionService, getMandate), CODE, ).build( @@ -349,17 +349,17 @@ object SendWeeklySubscriptionGiftEmail extends App { object TestData { - val paymentSchedule = PaymentSchedule(List(Payment(new LocalDate(2019, 3, 25), 37.50))) - val subno = "A-S00045678" - val acno = "A123456" + val paymentSchedule: PaymentSchedule = PaymentSchedule(List(Payment(new LocalDate(2019, 3, 25), 37.50))) + val subno: String = "A-S00045678" + val acno: String = "A123456" - val countryOnlyAddress = + val countryOnlyAddress: Address = Address(lineOne = None, lineTwo = None, city = None, state = None, postCode = None, country = UK) - val billingOnlyUser = + val billingOnlyUser: User = User(identityIdToSendTo, addressToSendTo, None, "Mickey", "Mouse", billingAddress = countryOnlyAddress) - val officeAddress = Address( + val officeAddress: Address = Address( lineOne = Some("90 York Way"), lineTwo = None, city = Some("London"), @@ -368,7 +368,7 @@ object TestData { country = UK, ) - val officeUser = User( + val officeUser: User = User( identityIdToSendTo, addressToSendTo, None, @@ -378,9 +378,9 @@ object TestData { deliveryAddress = Some(officeAddress), ) - val getMandate = (_: String) => Future.successful(Some("65HK26E")) + val getMandate: String => Future[Some[String]] = (_: String) => Future.successful(Some("65HK26E")) - val supporterPlusPromotionService = new PromotionService( + val supporterPlusPromotionService: PromotionService = new PromotionService( PromotionsConfig(PromotionsDiscountConfig("", ""), PromotionsTablesConfig("", "")), Some( new SimplePromotionCollection( @@ -406,14 +406,14 @@ object TestData { ), ) - val promotionService = new PromotionService( + val promotionService: PromotionService = new PromotionService( PromotionsConfig(PromotionsDiscountConfig("", ""), PromotionsTablesConfig("", "")), Some(new SimplePromotionCollection(Nil)), ) - val paperFieldsGenerator = new PaperFieldsGenerator(promotionService, getMandate) + val paperFieldsGenerator: PaperFieldsGenerator = new PaperFieldsGenerator(promotionService, getMandate) - val directDebitPaymentMethod = DirectDebitPaymentMethod( + val directDebitPaymentMethod: DirectDebitPaymentMethod = DirectDebitPaymentMethod( FirstName = "Mickey", LastName = "Mouse", BankTransferAccountName = "Mickey Mouse", @@ -427,7 +427,7 @@ object TestData { StreetNumber = Some("123"), ) - val digitalPackEmailFields = new DigitalPackEmailFields( + val digitalPackEmailFields: DigitalPackEmailFields = new DigitalPackEmailFields( new PaperFieldsGenerator( promotionService, getMandate, diff --git a/support-workers/src/test/scala/com/gu/support/workers/integration/util/EmailQueueName.scala b/support-workers/src/test/scala/com/gu/support/workers/integration/util/EmailQueueName.scala index fedad8a83a..12b7d2459e 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/integration/util/EmailQueueName.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/integration/util/EmailQueueName.scala @@ -1,5 +1,5 @@ package com.gu.support.workers.integration.util object EmailQueueName { - val emailQueueName = "braze-emails-CODE" + val emailQueueName: String = "braze-emails-CODE" } diff --git a/support-workers/src/test/scala/com/gu/support/workers/lambdas/SendAcquisitionEventSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/lambdas/SendAcquisitionEventSpec.scala index 9ca475d033..de14d2e4d6 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/lambdas/SendAcquisitionEventSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/lambdas/SendAcquisitionEventSpec.scala @@ -45,7 +45,7 @@ class SendAcquisitionEventSpec extends AsyncLambdaSpec with MockContext { object MockAcquisitionHelper extends MockitoSugar { - lazy val mockServices = { + lazy val mockServices: ServiceProvider = { val configuration = Configuration.load() // Mock the Acquisition service val serviceProvider = mock[ServiceProvider] diff --git a/support-workers/src/test/scala/com/gu/support/workers/lambdas/UpdateSupporterProductDataSpec.scala b/support-workers/src/test/scala/com/gu/support/workers/lambdas/UpdateSupporterProductDataSpec.scala index 8a48ad199d..ee24d23545 100644 --- a/support-workers/src/test/scala/com/gu/support/workers/lambdas/UpdateSupporterProductDataSpec.scala +++ b/support-workers/src/test/scala/com/gu/support/workers/lambdas/UpdateSupporterProductDataSpec.scala @@ -18,6 +18,7 @@ import org.scalatest.matchers.should.Matchers.convertToAnyShouldWrapper import org.scalatest.OptionValues._ import scala.io.Source +import scala.io.BufferedSource class UpdateSupporterProductDataSpec extends AnyFlatSpec with EitherValues { @@ -48,7 +49,7 @@ class UpdateSupporterProductDataSpec extends AnyFlatSpec with EitherValues { object UpdateSupporterProductDataSpec { - val supporterPlusState = + val supporterPlusState: String = """ { "user": { @@ -103,7 +104,7 @@ object UpdateSupporterProductDataSpec { } """ - val digitalSubscriptionGiftRedemptionState = """ + val digitalSubscriptionGiftRedemptionState: String = """ { "user": { "id": "102803446", @@ -140,7 +141,7 @@ object UpdateSupporterProductDataSpec { } """ - val digitalSusbcriptionGiftPurchaseState = """ + val digitalSusbcriptionGiftPurchaseState: String = """ { "user": { "id": "100569339", @@ -204,7 +205,7 @@ object UpdateSupporterProductDataSpec { "productType": "DigitalSubscriptionGiftPurchase" } """ - lazy val catalogSource = Source.fromURL(getClass.getResource("/catalog.json")) + lazy val catalogSource: BufferedSource = Source.fromURL(getClass.getResource("/catalog.json")) lazy val catalog: String = { val catalogString = catalogSource.mkString catalogSource.close() @@ -213,5 +214,5 @@ object UpdateSupporterProductDataSpec { private val json = parse(catalog).toOption.get private val jsonProvider = new SimpleJsonProvider(json) - val serviceWithFixtures = new CatalogService(PROD, jsonProvider) + val serviceWithFixtures: CatalogService = new CatalogService(PROD, jsonProvider) } diff --git a/support-workers/src/test/scala/com/gu/zuora/Fixtures.scala b/support-workers/src/test/scala/com/gu/zuora/Fixtures.scala index 7e6d1eb047..faa5a710f9 100644 --- a/support-workers/src/test/scala/com/gu/zuora/Fixtures.scala +++ b/support-workers/src/test/scala/com/gu/zuora/Fixtures.scala @@ -12,21 +12,23 @@ import com.gu.support.paperround.AgentId import com.gu.support.workers._ import com.gu.support.zuora.api._ import org.joda.time.LocalDate +import com.gu.support.catalog.ProductRatePlanId +import com.gu.support.config.{TouchPointEnvironment, ZuoraConfig} //noinspection TypeAnnotation object Fixtures { - val accountNumber = "A00084679" + val accountNumber: String = "A00084679" - val salesforceAccountId = "0013E00001ASmI6QAL" - val salesforceId = "0033E00001CpBZaQAN" - val identityId = "30000311" - val tokenId = "card_Aaynm1dIeDH1zp" - val secondTokenId = "cus_AaynKIp19IIGDz" - val cardNumber = "4242" - val payPalBaid = "B-23637766K5365543J" - val deliveryAgentId = 2532 + val salesforceAccountId: String = "0013E00001ASmI6QAL" + val salesforceId: String = "0033E00001CpBZaQAN" + val identityId: String = "30000311" + val tokenId: String = "card_Aaynm1dIeDH1zp" + val secondTokenId: String = "cus_AaynKIp19IIGDz" + val cardNumber: String = "4242" + val payPalBaid: String = "B-23637766K5365543J" + val deliveryAgentId: Int = 2532 - val date = new LocalDate(2017, 5, 4) + val date: LocalDate = new LocalDate(2017, 5, 4) def account( currency: Currency = GBP, @@ -41,8 +43,9 @@ object Fixtures { createdRequestId__c = "createdreqid_hi", ) - val contactDetails = ContactDetails("Test-FirstName", "Test-LastName", Some("test@thegulocal.com"), Country.UK) - val differentContactDetails = ContactDetails( + val contactDetails: ContactDetails = + ContactDetails("Test-FirstName", "Test-LastName", Some("test@thegulocal.com"), Country.UK) + val differentContactDetails: ContactDetails = ContactDetails( "Test-FirstName", "from support-frontend integration tests", Some("test@thegulocal.com"), @@ -54,7 +57,7 @@ object Fixtures { None, Some("Leave with neighbour - support-frontend"), ) - val differentContactDetailsOutsideLondon = ContactDetails( + val differentContactDetailsOutsideLondon: ContactDetails = ContactDetails( "Test-FirstName", "from support-frontend integration tests", Some("test@thegulocal.com"), @@ -66,7 +69,7 @@ object Fixtures { None, Some("Leave with neighbour - support-frontend"), ) - val creditCardPaymentMethod = CreditCardReferenceTransaction( + val creditCardPaymentMethod: PaymentGateway => CreditCardReferenceTransaction = CreditCardReferenceTransaction( tokenId, secondTokenId, cardNumber, @@ -77,8 +80,8 @@ object Fixtures { _: PaymentGateway, StripePaymentType = Some(StripePaymentType.StripeCheckout), ) - val payPalPaymentMethod = PayPalReferenceTransaction(payPalBaid, "test@paypal.com") - val directDebitPaymentMethod = DirectDebitPaymentMethod( + val payPalPaymentMethod: PayPalReferenceTransaction = PayPalReferenceTransaction(payPalBaid, "test@paypal.com") + val directDebitPaymentMethod: DirectDebitPaymentMethod = DirectDebitPaymentMethod( "Barry", "Humphreys", "Barry Humphreys", @@ -91,8 +94,8 @@ object Fixtures { StreetNumber = Some("123"), ) - val config = Configuration.load().zuoraConfigProvider.get() - val monthlySubscriptionData = SubscriptionData( + val config: ZuoraConfig = Configuration.load().zuoraConfigProvider.get() + val monthlySubscriptionData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(config.monthlyContribution.productRatePlanId), // Contribution product @@ -106,16 +109,16 @@ object Fixtures { ), Subscription(date, date, date, "id123"), ) - val blankReferrerAcquisitionData = + val blankReferrerAcquisitionData: ReferrerAcquisitionData = ReferrerAcquisitionData(None, None, None, None, None, None, None, None, None, None, None, None, None) - val touchpointEnvironment = TouchPointEnvironments.fromStage(Configuration.stage) - val everydayHomeDeliveryProductRatePlanId = + val touchpointEnvironment: TouchPointEnvironment = TouchPointEnvironments.fromStage(Configuration.stage) + val everydayHomeDeliveryProductRatePlanId: Option[ProductRatePlanId] = catalog.Paper.getProductRatePlan(touchpointEnvironment, Monthly, HomeDelivery, Everyday) map (_.id) - val everydayNationalDeliveryProductRatePlanId = + val everydayNationalDeliveryProductRatePlanId: Option[ProductRatePlanId] = catalog.Paper.getProductRatePlan(touchpointEnvironment, Monthly, NationalDelivery, Everyday) map (_.id) - val everydayPaperSubscriptionData = SubscriptionData( + val everydayPaperSubscriptionData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(everydayHomeDeliveryProductRatePlanId.get), @@ -126,7 +129,7 @@ object Fixtures { Subscription(date, date, date, "id123"), ) - val everydayNationalDeliveryPaperSubscriptionData = SubscriptionData( + val everydayNationalDeliveryPaperSubscriptionData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(everydayNationalDeliveryProductRatePlanId.get), @@ -196,7 +199,7 @@ object Fixtures { ), ) - val invalidMonthlySubsData = SubscriptionData( + val invalidMonthlySubsData: SubscriptionData = SubscriptionData( List( RatePlanData( RatePlan(config.monthlyContribution.productRatePlanId), @@ -210,7 +213,7 @@ object Fixtures { ), Subscription(date, date, date, "id123", termType = "Invalid term type"), ) - val invalidSubscriptionRequest = SubscribeRequest( + val invalidSubscriptionRequest: SubscribeRequest = SubscribeRequest( List( SubscribeItem( account(), @@ -223,7 +226,7 @@ object Fixtures { ), ) - val incorrectPaymentMethod = SubscribeRequest( + val incorrectPaymentMethod: SubscribeRequest = SubscribeRequest( List( SubscribeItem( account(), diff --git a/support-workers/src/test/scala/com/gu/zuora/ZuoraITSpec.scala b/support-workers/src/test/scala/com/gu/zuora/ZuoraITSpec.scala index aad9bd63b5..c30d126b85 100644 --- a/support-workers/src/test/scala/com/gu/zuora/ZuoraITSpec.scala +++ b/support-workers/src/test/scala/com/gu/zuora/ZuoraITSpec.scala @@ -35,7 +35,7 @@ class ZuoraITSpec extends AsyncFlatSpec with Matchers { ) // actual sub "CreatedDate": "2017-12-07T15:47:21.000+00:00", - val earlyDate = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC) + val earlyDate: DateTime = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC) "ZuoraService" should "retrieve an account" in { codeService.getAccount(Fixtures.accountNumber).map { response => diff --git a/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionBuilderSpec.scala b/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionBuilderSpec.scala index 974ba30bbd..1c1ea07e42 100644 --- a/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionBuilderSpec.scala +++ b/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/DigitalSubscriptionBuilderSpec.scala @@ -189,35 +189,37 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { ) } - lazy val promotionService = mock[PromotionService] - lazy val saleDate = new LocalDate(2020, 6, 5) - lazy val giftCodeGeneratorService = new GiftCodeGeneratorService + lazy val promotionService: PromotionService = mock[PromotionService] + lazy val saleDate: LocalDate = new LocalDate(2020, 6, 5) + lazy val giftCodeGeneratorService: GiftCodeGeneratorService = new GiftCodeGeneratorService - lazy val subscriptionDirectPurchaseBuilder = new DigitalSubscriptionDirectPurchaseBuilder( - ZuoraDigitalPackConfig(14, 2, monthlyChargeId = "monthlyChargeId", annualChargeId = "annualChargeId"), - promotionService, - DateGenerator(saleDate), - CODE, - new SubscribeItemBuilder( - UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), - User("1234", "hi@thegulocal.com", None, "bob", "smith", Address(None, None, None, None, None, Country.UK)), - GBP, - ), - ) + lazy val subscriptionDirectPurchaseBuilder: DigitalSubscriptionDirectPurchaseBuilder = + new DigitalSubscriptionDirectPurchaseBuilder( + ZuoraDigitalPackConfig(14, 2, monthlyChargeId = "monthlyChargeId", annualChargeId = "annualChargeId"), + promotionService, + DateGenerator(saleDate), + CODE, + new SubscribeItemBuilder( + UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), + User("1234", "hi@thegulocal.com", None, "bob", "smith", Address(None, None, None, None, None, Country.UK)), + GBP, + ), + ) - lazy val subscriptionGiftPurchaseBuilder = new DigitalSubscriptionGiftPurchaseBuilder( - promotionService, - DateGenerator(saleDate), - new GiftCodeGeneratorService, - CODE, - new SubscribeItemBuilder( - UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), - User("1234", "hi@thegulocal.com", None, "bob", "smith", Address(None, None, None, None, None, Country.UK)), - GBP, - ), - ) + lazy val subscriptionGiftPurchaseBuilder: DigitalSubscriptionGiftPurchaseBuilder = + new DigitalSubscriptionGiftPurchaseBuilder( + promotionService, + DateGenerator(saleDate), + new GiftCodeGeneratorService, + CODE, + new SubscribeItemBuilder( + UUID.fromString("f7651338-5d94-4f57-85fd-262030de9ad5"), + User("1234", "hi@thegulocal.com", None, "bob", "smith", Address(None, None, None, None, None, Country.UK)), + GBP, + ), + ) - lazy val monthly = + lazy val monthly: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( @@ -234,7 +236,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val validMonthlyBenefitsTest = + lazy val validMonthlyBenefitsTest: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( @@ -253,7 +255,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val lowAmountMonthlyBenefitsTest = + lazy val lowAmountMonthlyBenefitsTest: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( @@ -272,7 +274,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val monthlyNotInBenefitsTest = + lazy val monthlyNotInBenefitsTest: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( @@ -289,7 +291,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val threeMonthGiftPurchase = + lazy val threeMonthGiftPurchase: (SubscribeItem, GeneratedGiftCode) = subscriptionGiftPurchaseBuilder .build( DigitalSubscriptionGiftPurchaseState( @@ -306,7 +308,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val csrSubscription = subscriptionDirectPurchaseBuilder + lazy val csrSubscription: SubscriptionData = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( Country.UK, @@ -323,7 +325,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .get .subscriptionData - lazy val monthlyWithPromo = + lazy val monthlyWithPromo: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( @@ -340,7 +342,7 @@ class DigitalSubscriptionBuilderSpec extends AsyncFlatSpec with Matchers { .toOption .get - lazy val monthlyPatron = + lazy val monthlyPatron: SubscribeItem = subscriptionDirectPurchaseBuilder .build( DigitalSubscriptionDirectPurchaseState( diff --git a/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/GuardianWeeklySubscriptionBuildersSpec.scala b/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/GuardianWeeklySubscriptionBuildersSpec.scala index ed8403f695..1cfa3f70cc 100644 --- a/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/GuardianWeeklySubscriptionBuildersSpec.scala +++ b/support-workers/src/test/scala/com/gu/zuora/subscriptionBuilders/GuardianWeeklySubscriptionBuildersSpec.scala @@ -133,12 +133,12 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { nonGiftPatron.subscription.readerType shouldBe Patron } - lazy val weekly = GuardianWeekly(GBP, Quarterly, Domestic) - lazy val promotionService = mock[PromotionService] - lazy val saleDate = new LocalDate(2019, 10, 24) - lazy val firstDeliveryDate = saleDate.plusDays(3) + lazy val weekly: GuardianWeekly = GuardianWeekly(GBP, Quarterly, Domestic) + lazy val promotionService: PromotionService = mock[PromotionService] + lazy val saleDate: LocalDate = new LocalDate(2019, 10, 24) + lazy val firstDeliveryDate: LocalDate = saleDate.plusDays(3) - lazy val subscribeItemBuilder = new SubscribeItemBuilder( + lazy val subscribeItemBuilder: SubscribeItemBuilder = new SubscribeItemBuilder( UUID.randomUUID(), User( "1234", @@ -181,7 +181,7 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { .get .subscriptionData - val nonGiftState = GuardianWeeklyState( + val nonGiftState: GuardianWeeklyState = GuardianWeeklyState( User( "1234", "hi@thegulocal.com", @@ -199,7 +199,7 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { SalesforceContactRecords(SalesforceContactRecord("", ""), Some(SalesforceContactRecord("", ""))), ); - lazy val nonGift = new GuardianWeeklySubscriptionBuilder( + lazy val nonGift: SubscriptionData = new GuardianWeeklySubscriptionBuilder( promotionService, CODE, DateGenerator(saleDate), @@ -212,7 +212,7 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { .get .subscriptionData - lazy val csrSubscription = new GuardianWeeklySubscriptionBuilder( + lazy val csrSubscription: SubscriptionData = new GuardianWeeklySubscriptionBuilder( promotionService, CODE, DateGenerator(saleDate), @@ -241,7 +241,7 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { .get .subscriptionData - lazy val nonGiftPatron = new GuardianWeeklySubscriptionBuilder( + lazy val nonGiftPatron: SubscriptionData = new GuardianWeeklySubscriptionBuilder( promotionService, CODE, DateGenerator(saleDate), @@ -254,7 +254,7 @@ class GuardianWeeklySubscriptionBuildersSpec extends AnyFlatSpec with Matchers { .get .subscriptionData - lazy val nonGiftPromo = new GuardianWeeklySubscriptionBuilder( + lazy val nonGiftPromo: SubscriptionData = new GuardianWeeklySubscriptionBuilder( promotionService, CODE, DateGenerator(saleDate), diff --git a/supporter-product-data/src/main/scala/com/gu/lambdas/AddSupporterRatePlanItemToQueueLambda.scala b/supporter-product-data/src/main/scala/com/gu/lambdas/AddSupporterRatePlanItemToQueueLambda.scala index 2afe747037..e6af99b409 100644 --- a/supporter-product-data/src/main/scala/com/gu/lambdas/AddSupporterRatePlanItemToQueueLambda.scala +++ b/supporter-product-data/src/main/scala/com/gu/lambdas/AddSupporterRatePlanItemToQueueLambda.scala @@ -19,19 +19,22 @@ trait TimeOutCheck { } class ContextTimeOutCheck(context: Context) extends TimeOutCheck { - override def timeRemainingMillis = context.getRemainingTimeInMillis + override def timeRemainingMillis: Int = context.getRemainingTimeInMillis } class AddSupporterRatePlanItemToQueueLambda extends Handler[AddSupporterRatePlanItemToQueueState, AddSupporterRatePlanItemToQueueState] { - override protected def handlerFuture(input: AddSupporterRatePlanItemToQueueState, context: Context) = { + override protected def handlerFuture( + input: AddSupporterRatePlanItemToQueueState, + context: Context, + ): Future[AddSupporterRatePlanItemToQueueState] = { addToQueue(StageConstructors.fromEnvironment, input, new ContextTimeOutCheck(context)) } } object AddSupporterRatePlanItemToQueueLambda extends StrictLogging { - val maxBatchSize = 5 - val timeoutBufferInMillis = maxBatchSize * 5 * 1000 + val maxBatchSize: Int = 5 + val timeoutBufferInMillis: Int = maxBatchSize * 5 * 1000 def addToQueue( stage: Stage, @@ -84,7 +87,7 @@ object AddSupporterRatePlanItemToQueueLambda extends StrictLogging { maybeSaveSuccessTime.map(_ => state.copy(processedCount = processedCount)) } - def alarmAndExit(alarmService: AlarmService, message: String) = { + def alarmAndExit(alarmService: AlarmService, message: String): Nothing = { logger.error( s"CSV read failure: $message", ) @@ -92,7 +95,10 @@ object AddSupporterRatePlanItemToQueueLambda extends StrictLogging { throw new RuntimeException(message) } - def getUnprocessedItems(csvReader: CsvReader[ReadResult[SupporterRatePlanItem]], processedCount: Int) = + def getUnprocessedItems( + csvReader: CsvReader[ReadResult[SupporterRatePlanItem]], + processedCount: Int, + ): List[(ReadResult[SupporterRatePlanItem], Int)] = csvReader.zipWithIndex.drop(processedCount).toList def writeBatchesUntilTimeout( diff --git a/supporter-product-data/src/main/scala/com/gu/lambdas/FetchResultsLambda.scala b/supporter-product-data/src/main/scala/com/gu/lambdas/FetchResultsLambda.scala index ffeb1adb73..efdded6f3b 100644 --- a/supporter-product-data/src/main/scala/com/gu/lambdas/FetchResultsLambda.scala +++ b/supporter-product-data/src/main/scala/com/gu/lambdas/FetchResultsLambda.scala @@ -14,18 +14,27 @@ import java.time.{ZoneOffset, ZonedDateTime} import java.time.format.DateTimeFormatter import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.DurationInt +import com.gu.conf.ZuoraQuerierConfig +import scala.concurrent.Future class FetchResultsLambda extends Handler[FetchResultsState, AddSupporterRatePlanItemToQueueState] { - override protected def handlerFuture(input: FetchResultsState, context: Context) = + override protected def handlerFuture( + input: FetchResultsState, + context: Context, + ): Future[AddSupporterRatePlanItemToQueueState] = fetchResults(StageConstructors.fromEnvironment, input.jobId, input.attemptedQueryTime) } object FetchResultsLambda extends StrictLogging { - val stage = StageConstructors.fromEnvironment - val config = ConfigService(stage).load - val service = new ZuoraQuerierService(config, configurableFutureRunner(60.seconds)) + val stage: Stage = StageConstructors.fromEnvironment + val config: ZuoraQuerierConfig = ConfigService(stage).load + val service: ZuoraQuerierService = new ZuoraQuerierService(config, configurableFutureRunner(60.seconds)) - def fetchResults(stage: Stage, jobId: String, attemptedQueryTime: ZonedDateTime) = { + def fetchResults( + stage: Stage, + jobId: String, + attemptedQueryTime: ZonedDateTime, + ): Future[AddSupporterRatePlanItemToQueueState] = { logger.info(s"Attempting to fetch results for jobId $jobId") for { result <- service.getResults(jobId) @@ -57,7 +66,7 @@ object FetchResultsLambda extends StrictLogging { } } - def getValueOrThrow[T](maybeValue: Option[T], errorMessage: String) = + def getValueOrThrow[T](maybeValue: Option[T], errorMessage: String): T = maybeValue match { case Some(value) => value case None => throw new RuntimeException(errorMessage) diff --git a/supporter-product-data/src/main/scala/com/gu/lambdas/ProcessSupporterRatePlanItemLambda.scala b/supporter-product-data/src/main/scala/com/gu/lambdas/ProcessSupporterRatePlanItemLambda.scala index ed586b52cb..21a34d0c10 100644 --- a/supporter-product-data/src/main/scala/com/gu/lambdas/ProcessSupporterRatePlanItemLambda.scala +++ b/supporter-product-data/src/main/scala/com/gu/lambdas/ProcessSupporterRatePlanItemLambda.scala @@ -21,7 +21,7 @@ import scala.util.{Failure, Success} class ProcessSupporterRatePlanItemLambda extends Handler[SqsEvent, Unit] { - override protected def handlerFuture(input: SqsEvent, context: Context) = { + override protected def handlerFuture(input: SqsEvent, context: Context): Future[Unit] = { logger.info(s"Received ${input.Records.length} records from the queue") Future .sequence(input.Records.map { record => @@ -38,13 +38,13 @@ class ProcessSupporterRatePlanItemLambda extends Handler[SqsEvent, Unit] { } object ProcessSupporterRatePlanItemLambda extends SafeLogging { - val stage = StageConstructors.fromEnvironment - val config = ConfigService(stage).load - val dynamoService = SupporterDataDynamoService(stage) - val contributionIds = ContributionIds.forStage(stage) - val discountIds = DiscountService(stage).getDiscountProductRatePlanIds.get - lazy val contributionAmountFetcher = new ContributionAmountFetcher(config) - lazy val alarmService = AlarmService(stage) + val stage: Stage = StageConstructors.fromEnvironment + val config: ZuoraQuerierConfig = ConfigService(stage).load + val dynamoService: SupporterDataDynamoService = SupporterDataDynamoService(stage) + val contributionIds: List[String] = ContributionIds.forStage(stage) + val discountIds: List[String] = DiscountService(stage).getDiscountProductRatePlanIds.get + lazy val contributionAmountFetcher: ContributionAmountFetcher = new ContributionAmountFetcher(config) + lazy val alarmService: AlarmService = AlarmService(stage) private def isRecurringContribution(supporterRatePlanItem: SupporterRatePlanItem) = contributionIds.contains(supporterRatePlanItem.productRatePlanId) @@ -59,7 +59,7 @@ object ProcessSupporterRatePlanItemLambda extends SafeLogging { private def itemIsDiscount(supporterRatePlanItem: SupporterRatePlanItem) = discountIds.contains(supporterRatePlanItem.productRatePlanId) - def processItem(supporterRatePlanItem: SupporterRatePlanItem) = { + def processItem(supporterRatePlanItem: SupporterRatePlanItem): Future[Any] = { if (itemIsDiscount(supporterRatePlanItem)) { logger.info(s"Supporter rate plan item ${supporterRatePlanItem.asJson.spaces2} is a discount") Future.successful(()) @@ -89,9 +89,10 @@ object ProcessSupporterRatePlanItemLambda extends SafeLogging { } class ContributionAmountFetcher(config: ZuoraQuerierConfig) extends SafeLogging { - lazy val zuoraService = new ZuoraSubscriptionService(config, configurableFutureRunner(60.seconds)) + lazy val zuoraService: ZuoraSubscriptionService = + new ZuoraSubscriptionService(config, configurableFutureRunner(60.seconds)) - def fetchContributionAmountFromZuora(supporterRatePlanItem: SupporterRatePlanItem) = + def fetchContributionAmountFromZuora(supporterRatePlanItem: SupporterRatePlanItem): Future[SupporterRatePlanItem] = zuoraService .getSubscription(supporterRatePlanItem.subscriptionName) .map { sub => @@ -104,7 +105,7 @@ class ContributionAmountFetcher(config: ZuoraQuerierConfig) extends SafeLogging } object ContributionIds { - def forStage(stage: Stage) = stage match { + def forStage(stage: Stage): List[String] = stage match { case PROD => List("2c92a0fc5aacfadd015ad24db4ff5e97", "2c92a0fc5e1dc084015e37f58c200eea") case CODE => List("2c92c0f85a6b134e015a7fcd9f0c7855", "2c92c0f85e2d19af015e3896e824092c") } diff --git a/supporter-product-data/src/main/scala/com/gu/lambdas/QueryZuoraLambda.scala b/supporter-product-data/src/main/scala/com/gu/lambdas/QueryZuoraLambda.scala index b88052a1f5..d2170906ec 100644 --- a/supporter-product-data/src/main/scala/com/gu/lambdas/QueryZuoraLambda.scala +++ b/supporter-product-data/src/main/scala/com/gu/lambdas/QueryZuoraLambda.scala @@ -12,20 +12,22 @@ import com.typesafe.scalalogging.StrictLogging import java.time.{ZoneId, ZonedDateTime} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ +import com.gu.conf.ZuoraQuerierConfig +import scala.concurrent.Future class QueryZuoraLambda extends Handler[QueryZuoraState, FetchResultsState] { - override protected def handlerFuture(input: QueryZuoraState, context: Context) = + override protected def handlerFuture(input: QueryZuoraState, context: Context): Future[FetchResultsState] = queryZuora(StageConstructors.fromEnvironment, input.queryType) } object QueryZuoraLambda extends StrictLogging { - val stage = StageConstructors.fromEnvironment - val config = ConfigService(stage).load - val service = new ZuoraQuerierService(config, configurableFutureRunner(60.seconds)) + val stage: Stage = StageConstructors.fromEnvironment + val config: ZuoraQuerierConfig = ConfigService(stage).load + val service: ZuoraQuerierService = new ZuoraQuerierService(config, configurableFutureRunner(60.seconds)) - def queryZuora(stage: Stage, queryType: QueryType) = { + def queryZuora(stage: Stage, queryType: QueryType): Future[FetchResultsState] = { logger.info(s"Attempting to submit ${queryType.value} query to Zuora") // Get the time we started the query. Docs for why we need to do this are here: diff --git a/supporter-product-data/src/main/scala/com/gu/model/ZuoraFieldNames.scala b/supporter-product-data/src/main/scala/com/gu/model/ZuoraFieldNames.scala index 930177aea3..5df8a7758e 100644 --- a/supporter-product-data/src/main/scala/com/gu/model/ZuoraFieldNames.scala +++ b/supporter-product-data/src/main/scala/com/gu/model/ZuoraFieldNames.scala @@ -2,20 +2,20 @@ package com.gu.model object ZuoraFieldNames { - val subscriptionName = "Subscription.Name" + val subscriptionName: String = "Subscription.Name" - val identityId = "Account.IdentityId__c" + val identityId: String = "Account.IdentityId__c" - val gifteeIdentityId = "Subscription.GifteeIdentityId__c" + val gifteeIdentityId: String = "Subscription.GifteeIdentityId__c" - val productRatePlanName = "ProductRatePlan.Name" + val productRatePlanName: String = "ProductRatePlan.Name" - val productRatePlanId = "ProductRatePlan.Id" + val productRatePlanId: String = "ProductRatePlan.Id" - val termEndDate = "Subscription.TermEndDate" + val termEndDate: String = "Subscription.TermEndDate" - val contractEffectiveDate = "Subscription.ContractEffectiveDate" + val contractEffectiveDate: String = "Subscription.ContractEffectiveDate" - val subscriptionStatus = "Subscription.Status" + val subscriptionStatus: String = "Subscription.Status" } diff --git a/supporter-product-data/src/main/scala/com/gu/model/zuora/response/MinimalZuoraSubscription.scala b/supporter-product-data/src/main/scala/com/gu/model/zuora/response/MinimalZuoraSubscription.scala index 5c8cb69477..4d8a54e7ca 100644 --- a/supporter-product-data/src/main/scala/com/gu/model/zuora/response/MinimalZuoraSubscription.scala +++ b/supporter-product-data/src/main/scala/com/gu/model/zuora/response/MinimalZuoraSubscription.scala @@ -5,7 +5,7 @@ import io.circe.Decoder import io.circe.generic.semiauto.deriveDecoder case class MinimalZuoraSubscription(ratePlans: List[RatePlan]) { - def contributionAmount = for { + def contributionAmount: Option[ContributionAmount] = for { ratePlans <- ratePlans.headOption charges <- ratePlans.ratePlanCharges.headOption } yield ContributionAmount(charges.price, charges.currency) diff --git a/supporter-product-data/src/main/scala/com/gu/services/AlarmService.scala b/supporter-product-data/src/main/scala/com/gu/services/AlarmService.scala index 486efb6bcf..5974da7bae 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/AlarmService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/AlarmService.scala @@ -9,10 +9,11 @@ import com.gu.aws.AwsCloudWatchMetricPut.{ MetricRequest, } import com.gu.supporterdata.model.Stage +import scala.util.Try class AlarmService(stage: Stage) { - def triggerCsvReadAlarm = { + def triggerCsvReadAlarm: Try[Unit] = { AwsCloudWatchMetricPut(AwsCloudWatchMetricPut.client)( MetricRequest( MetricNamespace("supporter-product-data"), @@ -22,7 +23,7 @@ class AlarmService(stage: Stage) { ) } - def triggerDynamoWriteAlarm = { + def triggerDynamoWriteAlarm: Try[Unit] = { AwsCloudWatchMetricPut(AwsCloudWatchMetricPut.client)( MetricRequest( MetricNamespace("supporter-product-data"), @@ -32,7 +33,7 @@ class AlarmService(stage: Stage) { ) } - def triggerSQSWriteAlarm = { + def triggerSQSWriteAlarm: Try[Unit] = { AwsCloudWatchMetricPut(AwsCloudWatchMetricPut.client)( MetricRequest( MetricNamespace("supporter-product-data"), @@ -44,5 +45,5 @@ class AlarmService(stage: Stage) { } object AlarmService { - def apply(stage: Stage) = new AlarmService(stage) + def apply(stage: Stage): AlarmService = new AlarmService(stage) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/ConfigService.scala b/supporter-product-data/src/main/scala/com/gu/services/ConfigService.scala index 6e903999b3..1e70b15a47 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/ConfigService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/ConfigService.scala @@ -11,9 +11,10 @@ import com.typesafe.scalalogging.StrictLogging import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import scala.concurrent.{ExecutionContext, Future} +import com.amazonaws.services.simplesystemsmanagement.model.PutParameterResult class ConfigService(stage: Stage) extends StrictLogging { - val parameterStoreService = ParameterStoreService(stage) + val parameterStoreService: ParameterStoreService = ParameterStoreService(stage) def load(implicit ec: ExecutionContext): ZuoraQuerierConfig = { val params = parameterStoreService.getParametersByPath(zuoraConfigPath) @@ -83,7 +84,7 @@ class ConfigService(stage: Stage) extends StrictLogging { .find(_.getName.split('/').last == name) .map(_.getValue) - def putLastSuccessfulQueryTime(time: ZonedDateTime) = { + def putLastSuccessfulQueryTime(time: ZonedDateTime): Future[PutParameterResult] = { val timeAsString = time.format(DateTimeFormatter.ISO_DATE_TIME) val fullPath = s"$zuoraConfigPath/$lastSuccessfulQueryTime" @@ -97,8 +98,8 @@ class ConfigService(stage: Stage) extends StrictLogging { } object ConfigService { - val zuoraConfigPath = "zuora-config" - val lastSuccessfulQueryTime = "lastSuccessfulQueryTime" + val zuoraConfigPath: String = "zuora-config" + val lastSuccessfulQueryTime: String = "lastSuccessfulQueryTime" - def apply(stage: Stage) = new ConfigService(stage) + def apply(stage: Stage): ConfigService = new ConfigService(stage) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/DiscountService.scala b/supporter-product-data/src/main/scala/com/gu/services/DiscountService.scala index a19ca976c8..2425aa4655 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/DiscountService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/DiscountService.scala @@ -36,5 +36,5 @@ class S3CatalogLoader(stage: Stage) extends CatalogLoader with LazyLogging { } object DiscountService extends LazyLogging { - def apply(stage: Stage) = new DiscountService(new S3CatalogLoader(stage)) + def apply(stage: Stage): DiscountService = new DiscountService(new S3CatalogLoader(stage)) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/ParameterStoreService.scala b/supporter-product-data/src/main/scala/com/gu/services/ParameterStoreService.scala index 9b908d31cf..7c9d635728 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/ParameterStoreService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/ParameterStoreService.scala @@ -24,11 +24,13 @@ import com.gu.supporterdata.model.Stage import scala.concurrent.ExecutionContext import scala.jdk.CollectionConverters._ +import com.amazonaws.services.simplesystemsmanagement.model.{Parameter, PutParameterResult} +import scala.concurrent.Future class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stage) { - val configRoot = s"/supporter-product-data/${stage.value}" + val configRoot: String = s"/supporter-product-data/${stage.value}" - def getParametersByPath(path: String)(implicit executionContext: ExecutionContext) = { + def getParametersByPath(path: String)(implicit executionContext: ExecutionContext): List[Parameter] = { val request: GetParametersByPathRequest = new GetParametersByPathRequest() .withPath(s"$configRoot/$path/") .withRecursive(false) @@ -36,7 +38,7 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag client.getParametersByPath(request).getParameters.asScala.toList } - def getParameter(name: String)(implicit executionContext: ExecutionContext) = { + def getParameter(name: String)(implicit executionContext: ExecutionContext): Future[String] = { val request = new GetParameterRequest() .withName(s"$configRoot/$name") .withWithDecryption(true) @@ -44,7 +46,11 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag AwsAsync(client.getParameterAsync, request).map(_.getParameter.getValue) } - def putParameter(name: String, value: String, parameterType: ParameterType = ParameterType.String) = { + def putParameter( + name: String, + value: String, + parameterType: ParameterType = ParameterType.String, + ): Future[PutParameterResult] = { val putParameterRequest = new PutParameterRequest() .withName(s"$configRoot/$name") @@ -59,18 +65,18 @@ class ParameterStoreService(client: AWSSimpleSystemsManagementAsync, stage: Stag object ParameterStoreService { // please update to AWS SDK 2 and use com.gu.aws.CredentialsProvider - lazy val CredentialsProviderDEPRECATEDV1 = new AWSCredentialsProviderChain( + lazy val CredentialsProviderDEPRECATEDV1: AWSCredentialsProviderChain = new AWSCredentialsProviderChain( new ProfileCredentialsProvider(ProfileName), new InstanceProfileCredentialsProvider(false), new EnvironmentVariableCredentialsProvider(), new EC2ContainerCredentialsProviderWrapper(), // for use with lambda snapstart ) - lazy val client = AWSSimpleSystemsManagementAsyncClientBuilder + lazy val client: AWSSimpleSystemsManagementAsync = AWSSimpleSystemsManagementAsyncClientBuilder .standard() .withRegion(Regions.EU_WEST_1) .withCredentials(CredentialsProviderDEPRECATEDV1) .build() - def apply(stage: Stage) = new ParameterStoreService(client, stage) + def apply(stage: Stage): ParameterStoreService = new ParameterStoreService(client, stage) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/S3Service.scala b/supporter-product-data/src/main/scala/com/gu/services/S3Service.scala index c4956f4731..230692fa2a 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/S3Service.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/S3Service.scala @@ -9,19 +9,22 @@ import com.gu.supporterdata.model.Stage import com.typesafe.scalalogging.StrictLogging import java.io.InputStream +import com.amazonaws.services.s3.AmazonS3 +import com.amazonaws.services.s3.model.S3Object +import com.amazonaws.services.s3.transfer.TransferManager object S3Service extends StrictLogging { - val s3Client = AmazonS3ClientBuilder.standard + val s3Client: AmazonS3 = AmazonS3ClientBuilder.standard .withRegion(Regions.EU_WEST_1) .withCredentials(CredentialsProviderDEPRECATEDV1) .build - val transferManager = TransferManagerBuilder.standard + val transferManager: TransferManager = TransferManagerBuilder.standard .withS3Client(s3Client) .build - def bucketName(stage: Stage) = s"supporter-product-data-export-${stage.value.toLowerCase}" + def bucketName(stage: Stage): String = s"supporter-product-data-export-${stage.value.toLowerCase}" - def streamToS3(stage: Stage, filename: String, inputStream: InputStream, length: Option[Long]) = { + def streamToS3(stage: Stage, filename: String, inputStream: InputStream, length: Option[Long]): Unit = { logger.info(s"Trying to stream to S3 - bucketName: ${bucketName(stage)}, filename: $filename, length: $length") val objectMetadata = new ObjectMetadata() if (length.isDefined) { @@ -33,7 +36,7 @@ object S3Service extends StrictLogging { transfer.waitForCompletion() } - def streamFromS3(stage: Stage, filename: String) = { + def streamFromS3(stage: Stage, filename: String): S3Object = { logger.info(s"Trying to stream from S3 - bucketName: ${bucketName(stage)}, filename: $filename") s3Client.getObject(new GetObjectRequest(bucketName(stage), filename)) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/SelectActiveRatePlansQuery.scala b/supporter-product-data/src/main/scala/com/gu/services/SelectActiveRatePlansQuery.scala index b351176c71..2ecfc0c47f 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/SelectActiveRatePlansQuery.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/SelectActiveRatePlansQuery.scala @@ -9,13 +9,13 @@ import java.time.format.DateTimeFormatter object SelectActiveRatePlansQuery { - val name = "select-active-rate-plans" + val name: String = "select-active-rate-plans" - val isNotDSGift = "(Subscription.RedemptionCode__c = '' OR Subscription.RedemptionCode__c is null)" + val isNotDSGift: String = "(Subscription.RedemptionCode__c = '' OR Subscription.RedemptionCode__c is null)" // _% in a like clause checks that the field has at least one character ie. not '' or null - val isRedeemedDSGift = s"(Subscription.RedemptionCode__c like '_%' AND $gifteeIdentityId like '_%')" + val isRedeemedDSGift: String = s"(Subscription.RedemptionCode__c like '_%' AND $gifteeIdentityId like '_%')" - def excludeDiscountProductRatePlans(discountProductRatePlanIds: List[String]) = + def excludeDiscountProductRatePlans(discountProductRatePlanIds: List[String]): String = discountProductRatePlanIds .map(id => s"$productRatePlanId != '$id'") .mkString(" AND\n") diff --git a/supporter-product-data/src/main/scala/com/gu/services/SqsService.scala b/supporter-product-data/src/main/scala/com/gu/services/SqsService.scala index 2c1a7d1fdf..036498a543 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/SqsService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/SqsService.scala @@ -25,7 +25,7 @@ class SqsService(queueName: String, alarmService: AlarmService)(implicit val exe private val queueUrl = sqsClient.getQueueUrl(queueName).getQueueUrl - def sendBatch(supporterRatePlanItems: List[(SupporterRatePlanItem, Int)]) = { + def sendBatch(supporterRatePlanItems: List[(SupporterRatePlanItem, Int)]): Unit = { logger.info(s"Sending message batch with ${supporterRatePlanItems.length} items to SQS queue $queueUrl") val batchRequestEntries = supporterRatePlanItems.map { case (item, index) => @@ -60,7 +60,7 @@ class SqsService(queueName: String, alarmService: AlarmService)(implicit val exe object SqsService extends SafeLogging { import scala.concurrent.ExecutionContext.Implicits.global - def apply(stage: Stage) = { + def apply(stage: Stage): SqsService = { val queueName = s"supporter-product-data-${stage.value}" logger.info(s"Creating SqsService for SQS queue $queueName") new SqsService(queueName, new AlarmService(stage)) diff --git a/supporter-product-data/src/main/scala/com/gu/services/ZuoraQuerierService.scala b/supporter-product-data/src/main/scala/com/gu/services/ZuoraQuerierService.scala index 8e4463cd75..a086e5aa2c 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/ZuoraQuerierService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/ZuoraQuerierService.scala @@ -13,13 +13,14 @@ import java.time.format.DateTimeFormatter import java.time.{LocalDate, LocalDateTime, ZonedDateTime} import scala.collection.immutable.Map.empty import scala.concurrent.{ExecutionContext, Future} +import okhttp3.Response class ZuoraQuerierService(val config: ZuoraQuerierConfig, client: FutureHttpClient)(implicit ec: ExecutionContext) extends WebServiceHelper[BatchQueryErrorResponse] { - override val wsUrl = config.url + override val wsUrl: String = config.url override val httpClient: FutureHttpClient = client - val authHeaders = Map( + val authHeaders: Map[String, String] = Map( "apiSecretAccessKey" -> config.password, "apiAccessKeyId" -> config.username, "Accept-Encoding" -> "identity", // Required to ensure that response content-length header is available. We need this when we transfer results to S3. See https://github.com/square/okhttp/issues/1542 for details @@ -51,7 +52,7 @@ class ZuoraQuerierService(val config: ZuoraQuerierConfig, client: FutureHttpClie def getResults(id: String): Future[BatchQueryResponse] = get[BatchQueryResponse](s"batch-query/jobs/$id", authHeaders) - def getResultFileResponse(fileId: String) = { + def getResultFileResponse(fileId: String): Future[Response] = { val endpoint = s"/batch-query/file/$fileId" getResponse(buildRequest(endpoint, authHeaders, empty)) } diff --git a/supporter-product-data/src/main/scala/com/gu/services/ZuoraSubscriptionService.scala b/supporter-product-data/src/main/scala/com/gu/services/ZuoraSubscriptionService.scala index 27a20cc5c1..ab040b2234 100644 --- a/supporter-product-data/src/main/scala/com/gu/services/ZuoraSubscriptionService.scala +++ b/supporter-product-data/src/main/scala/com/gu/services/ZuoraSubscriptionService.scala @@ -22,9 +22,9 @@ import scala.concurrent.{ExecutionContext, Future} class ZuoraSubscriptionService(val config: ZuoraQuerierConfig, client: FutureHttpClient)(implicit ec: ExecutionContext) extends WebServiceHelper[MinimalZuoraError] { - override val wsUrl = config.url + override val wsUrl: String = config.url override val httpClient: FutureHttpClient = client - val authHeaders = Map( + val authHeaders: Map[String, String] = Map( "apiSecretAccessKey" -> config.password, "apiAccessKeyId" -> config.username, ) diff --git a/supporter-product-data/src/test/scala/com/gu/Fixtures.scala b/supporter-product-data/src/test/scala/com/gu/Fixtures.scala index c5b2ee6926..2ff725c624 100644 --- a/supporter-product-data/src/test/scala/com/gu/Fixtures.scala +++ b/supporter-product-data/src/test/scala/com/gu/Fixtures.scala @@ -6,7 +6,7 @@ import scala.io.Source object Fixtures { def loadQueryResults: String = Source.fromURL(getClass.getResource("/query-results.csv")).mkString - def sqsEventJson = """ + def sqsEventJson: String = """ { "Records": [ { diff --git a/supporter-product-data/src/test/scala/com/gu/lambdas/RunFullExportSpec.scala b/supporter-product-data/src/test/scala/com/gu/lambdas/RunFullExportSpec.scala index e859471dbc..bc99125cef 100644 --- a/supporter-product-data/src/test/scala/com/gu/lambdas/RunFullExportSpec.scala +++ b/supporter-product-data/src/test/scala/com/gu/lambdas/RunFullExportSpec.scala @@ -24,10 +24,10 @@ import scala.io.Source @IntegrationTest class RunFullExportSpec extends AsyncFlatSpec with Matchers with LazyLogging { - val stage = PROD - val queryType = Full - val sanitizeFieldNamesAfterDownload = false - val updateLastSuccessfulQueryTime = false + val stage: PROD.type = PROD + val queryType: Full.type = Full + val sanitizeFieldNamesAfterDownload: Boolean = false + val updateLastSuccessfulQueryTime: Boolean = false "This test is just an easy way to run an aqua query. It" should "save the results to a csv in supporter-product-data/data-extracts" ignore { val attemptedQueryTime = @@ -67,7 +67,10 @@ class RunFullExportSpec extends AsyncFlatSpec with Matchers with LazyLogging { } } - def downloadResults(result: BatchQueryResponse, service: ZuoraQuerierService) = { + def downloadResults( + result: BatchQueryResponse, + service: ZuoraQuerierService, + ): Future[AddSupporterRatePlanItemToQueueState] = { val batch = getValueOrThrow(result.batches.headOption, s"No batches were returned in the batch query response") val fileId = getValueOrThrow(batch.fileId, s"Batch.fileId was missing in the job") for { @@ -92,7 +95,7 @@ class RunFullExportSpec extends AsyncFlatSpec with Matchers with LazyLogging { } } - def sanitizeFieldNames(filename: String) = { + def sanitizeFieldNames(filename: String): Boolean = { val tempPath = FileSystems.getDefault.getPath( System.getProperty("user.dir"), "supporter-product-data",