diff --git a/app/connectors/EtmpDetailsConnector.scala b/app/connectors/EtmpDetailsConnector.scala index 640cc9a..6901f32 100644 --- a/app/connectors/EtmpDetailsConnector.scala +++ b/app/connectors/EtmpDetailsConnector.scala @@ -95,50 +95,6 @@ trait EtmpDetailsConnector extends Auditable with Logging { } } - - def getSubscriptionData(atedReferenceNo: String)(implicit hc: HeaderCarrier): Future[HttpResponse] = { - val getUrl = s"""$serviceUrl/$atedBaseURI/$retrieveSubscriptionData/$atedReferenceNo""" - - val timerContext = metrics.startTimer(MetricsEnum.EtmpGetSubscriptionData) - http.get(url"$getUrl").setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - response.status match { - case OK => - metrics.incrementSuccessCounter(MetricsEnum.EtmpGetSubscriptionData) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpGetSubscriptionData) - logger.warn(s"[EtmpDetailsConnector][getSummaryReturns] - status: $status") - doHeaderEvent("getSubscriptionDataFailedHeaders", response.headers) - doFailedAudit("getSubscriptionDataFailed", getUrl, None, response.body) - response - } - } - } - - def updateSubscriptionData(atedReferenceNo: String, updatedData: UpdateEtmpSubscriptionDataRequest) - (implicit hc: HeaderCarrier): Future[HttpResponse] = { - val putUrl = s"""$serviceUrl/$atedBaseURI/$saveSubscriptionData/$atedReferenceNo""" - - val timerContext = metrics.startTimer(MetricsEnum.EtmpUpdateSubscriptionData) - val jsonData = Json.toJson(updatedData) - http.put(url"$putUrl").withBody(jsonData).setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - auditUpdateSubscriptionData(atedReferenceNo, updatedData, response) - response.status match { - case OK => - metrics.incrementSuccessCounter(MetricsEnum.EtmpUpdateSubscriptionData) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpUpdateSubscriptionData) - logger.warn(s"[EtmpDetailsConnector][updateSubscriptionData] - status: $status") - doHeaderEvent("updateSubscriptionDataFailedHeaders", response.headers) - doFailedAudit("updateSubscriptionDataFailed", putUrl, Some(jsonData.toString), response.body) - response - } - } - } - def updateRegistrationDetails(atedReferenceNo: String, safeId: String, updatedData: UpdateRegistrationDetailsRequest) (implicit hc: HeaderCarrier): Future[HttpResponse] = { val putUrl = s"""$serviceUrl/$saveRegistrationDetails/$safeId""" @@ -168,24 +124,6 @@ trait EtmpDetailsConnector extends Auditable with Logging { ) } - private def auditUpdateSubscriptionData(atedReferenceNo: String, - updateData: UpdateEtmpSubscriptionDataRequest, - response: HttpResponse)(implicit hc: HeaderCarrier): Unit = { - val eventType = response.status match { - case OK => EventTypes.Succeeded - case _ => EventTypes.Failed - } - sendDataEvent(transactionName = "etmpUpdateSubscription", - detail = Map("txName" -> "etmpUpdateSubscription", - "atedReferenceNo" -> s"$atedReferenceNo", - "agentReferenceNumber" -> s"${updateData.agentReferenceNumber}", - "requestData" -> s"${Json.toJson(updateData)}", - "responseStatus" -> s"${response.status}", - "responseBody" -> s"${response.body}", - "status" -> s"$eventType")) - } - - private def auditUpdateRegistrationDetails(atedReferenceNo: String, safeId: String, updateData: UpdateRegistrationDetailsRequest, diff --git a/app/connectors/EtmpReturnsConnector.scala b/app/connectors/EtmpReturnsConnector.scala deleted file mode 100644 index bb90349..0000000 --- a/app/connectors/EtmpReturnsConnector.scala +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright 2023 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package connectors - -import audit.Auditable -import metrics.{MetricsEnum, ServiceMetrics} -import models._ -import play.api.Logging -import play.api.http.Status._ -import play.api.libs.json.Json -import uk.gov.hmrc.http._ -import uk.gov.hmrc.http.client.HttpClientV2 -import uk.gov.hmrc.play.audit.http.connector.AuditConnector -import uk.gov.hmrc.play.audit.model.{Audit, EventTypes} -import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import uk.gov.hmrc.http.HttpReads.Implicits._ - -import javax.inject.Inject -import scala.concurrent.{ExecutionContext, Future} - -class EtmpReturnsConnectorImpl @Inject()(val servicesConfig: ServicesConfig, - val http: HttpClientV2, - val auditConnector: AuditConnector, - val metrics: ServiceMetrics) extends EtmpReturnsConnector { - val serviceUrl: String = servicesConfig.baseUrl("etmp-hod") - val urlHeaderEnvironment: String = servicesConfig.getConfString("etmp-hod.environment", "") - val urlHeaderAuthorization: String = s"Bearer ${servicesConfig.getConfString("etmp-hod.authorization-token", "")}" - - val audit: Audit = new Audit("ated", auditConnector) - - val baseURI: String = "annual-tax-enveloped-dwellings" - val submitReturnsURI: String = "returns" - val submitEditedLiabilityReturnsURI: String = "returns" - val submitClientRelationship: String = "relationship" - val getSummaryReturns: String = "returns" - val formBundleReturns: String = "form-bundle" -} - -trait EtmpReturnsConnector extends Auditable with Logging { - def serviceUrl: String - def urlHeaderEnvironment: String - def urlHeaderAuthorization: String - - def metrics: ServiceMetrics - def http: HttpClientV2 - - val baseURI: String - val submitReturnsURI: String - val submitEditedLiabilityReturnsURI: String - val submitClientRelationship: String - val getSummaryReturns: String - val formBundleReturns: String - - def submitReturns(atedReferenceNo: String, submitReturns: SubmitEtmpReturnsRequest) - (implicit ec: ExecutionContext, hc: HeaderCarrier): Future[HttpResponse] = { - val postUrl = s"""$serviceUrl/$baseURI/$submitReturnsURI/$atedReferenceNo""" - - val jsonData = Json.toJson(submitReturns) - val timerContext = metrics.startTimer(MetricsEnum.EtmpSubmitReturns) - http.post(url"$postUrl").withBody(jsonData).setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - auditSubmitReturns(atedReferenceNo, submitReturns, response) - if (submitReturns.liabilityReturns.isDefined) { - auditAddress(submitReturns.liabilityReturns.get.head.propertyDetails) - } - response.status match { - case OK => - metrics.incrementSuccessCounter(MetricsEnum.EtmpSubmitReturns) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpSubmitReturns) - logger.warn(s"[EtmpReturnsConnector][submitReturns] - status: $status") - doHeaderEvent("submitReturnsFailedHeaders", response.headers) - doFailedAudit("submitReturnsFailed", postUrl, Some(jsonData.toString), response.body) - response - } - } - } - - def getSummaryReturns(atedReferenceNo: String, years: Int)(implicit ec: ExecutionContext, hc: HeaderCarrier): Future[HttpResponse] = { - val getUrl = s"""$serviceUrl/$baseURI/$getSummaryReturns/$atedReferenceNo?years=$years""" - - val timerContext = metrics.startTimer(MetricsEnum.EtmpGetSummaryReturns) - http.get(url"$getUrl").setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - response.status match { - case OK | NOT_FOUND => - metrics.incrementSuccessCounter(MetricsEnum.EtmpGetSummaryReturns) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpGetSummaryReturns) - logger.warn(s"[EtmpReturnsConnector][getSummaryReturns] - status: $status") - doHeaderEvent("getSummaryReturnsFailedHeaders", response.headers) - doFailedAudit("getSummaryReturnsFailed", getUrl, None, response.body) - response - } - } - } - - def getFormBundleReturns(atedReferenceNo: String, formBundleNumber: String)(implicit ec: ExecutionContext, hc: HeaderCarrier): Future[HttpResponse] = { - val getUrl = s"""$serviceUrl/$baseURI/$getSummaryReturns/$atedReferenceNo/$formBundleReturns/$formBundleNumber""" - - val timerContext = metrics.startTimer(MetricsEnum.EtmpGetFormBundleReturns) - http.get(url"$getUrl").setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - response.status match { - case OK => - metrics.incrementSuccessCounter(MetricsEnum.EtmpGetFormBundleReturns) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpGetFormBundleReturns) - logger.warn(s"[EtmpReturnsConnector][getFormBundleReturns] - status: $status") - doHeaderEvent("getFormBundleReturnsFailedHeaders", response.headers) - doFailedAudit("getFormBundleReturnsFailed", getUrl, None, response.body) - response - } - } - } - - def submitEditedLiabilityReturns(atedReferenceNo: String, - editedLiabilityReturns: EditLiabilityReturnsRequestModel, - disposal: Boolean = false)(implicit ec: ExecutionContext, headerCarrier: HeaderCarrier): Future[HttpResponse] = { - val putUrl = s"""$serviceUrl/$baseURI/$submitEditedLiabilityReturnsURI/$atedReferenceNo""" - - val jsonData = Json.toJson(editedLiabilityReturns) - val timerContext = metrics.startTimer(MetricsEnum.EtmpSubmitEditedLiabilityReturns) - http.put(url"$putUrl").withBody(jsonData).setHeader(createHeaders: _*).execute[HttpResponse].map{ response => - timerContext.stop() - auditSubmitEditedLiabilityReturns(atedReferenceNo, editedLiabilityReturns, response, disposal) - response.status match { - case OK => - metrics.incrementSuccessCounter(MetricsEnum.EtmpSubmitEditedLiabilityReturns) - response - case status => - metrics.incrementFailedCounter(MetricsEnum.EtmpSubmitEditedLiabilityReturns) - logger.warn(s"[EtmpReturnsConnector][submitEditedLiabilityReturns] - status: $status, reason - ${response.json}") - doHeaderEvent("getSummaryReturnsFailed", response.headers) - doFailedAudit("submitEditedLiabilityReturnsFailed", putUrl, Some(jsonData.toString), response.body) - response - } - } - - } - - private def createHeaders: Seq[(String, String)] = { - Seq( - "Environment" -> urlHeaderEnvironment, - "Authorization" -> urlHeaderAuthorization - ) - } - - private def auditSubmitReturns(atedReferenceNo: String, - returns: SubmitEtmpReturnsRequest, - response: HttpResponse)(implicit hc: HeaderCarrier, ec: ExecutionContext): Unit = { - val eventType = response.status match { - case OK => EventTypes.Succeeded - case _ => EventTypes.Failed - } - sendDataEvent(transactionName = "etmpSubmitReturns", - detail = Map("txName" -> "etmpSubmitReturns", - "atedRefNumber" -> s"$atedReferenceNo", - "agentRefNo" -> s"${returns.agentReferenceNumber.getOrElse("")}", - "liabilityReturns_count" -> s"${if (returns.liabilityReturns.isDefined) returns.liabilityReturns.get.size else 0}", - "reliefReturns_count" -> s"${ if (returns.reliefReturns.isDefined) returns.reliefReturns.get.size else 0 }", - "reliefReturnCodes" -> s"${ returns.reliefReturns match { - case Some(reliefReturns) => reliefReturns.map(x => x.reliefDescription).mkString(";") - case None => "" - }}", - "requestBody" -> s"${Json.toJson(returns)}", - "responseStatus" -> s"${response.status}", - "responseBody" -> s"${response.body}", - "status" -> s"$eventType")) - } - - - private def auditSubmitEditedLiabilityReturns(atedReferenceNo: String, - returns: EditLiabilityReturnsRequestModel, - response: HttpResponse, - disposal: Boolean)(implicit hc: HeaderCarrier, ec: ExecutionContext): Unit = { - val eventType = response.status match { - case OK => EventTypes.Succeeded - case _ => EventTypes.Failed - } - - val typeOfReturn = { - if (disposal) "D" - else { - val amountField = (Json.parse(response.body) \\ "amountDueOrRefund").headOption - amountField match { - case Some(x) => - val y = x.as[BigDecimal] - if (y > 0) "F" - else if (y < 0) "A" - else "C" - case None => "" - } - } - } - sendDataEvent(transactionName = "etmpSubmitEditedLiabilityReturns", - detail = Map("txName" -> "etmpSubmitEditedLiabilityReturns", - "atedRefNumber" -> s"$atedReferenceNo", - "agentRefNo" -> s"${returns.agentReferenceNumber.getOrElse("")}", - "liabilityReturns count" -> s"${returns.liabilityReturn.size}", - "amended_further_changed_return" -> typeOfReturn, - "requestBody" -> s"${Json.toJson(returns)}", - "responseStatus" -> s"${response.status}", - "responseBody" -> s"${response.body}", - "status" -> s"$eventType")) - - auditLiabilityReturnsBankDetails(atedReferenceNo, returns, eventType, typeOfReturn) - } - - private def auditAddress(addressDetails: Option[EtmpPropertyDetails])(implicit hc: HeaderCarrier, ec: ExecutionContext) = { - addressDetails.map { _ => - sendDataEvent(transactionName = "manualAddressSubmitted", - detail = Map( - "submittedLine1" -> addressDetails.get.address.addressLine1, - "submittedLine2" -> addressDetails.get.address.addressLine2, - "submittedLine3" -> addressDetails.get.address.addressLine3.getOrElse(""), - "submittedLine4" -> addressDetails.get.address.addressLine4.getOrElse(""), - "submittedPostcode" -> addressDetails.get.address.postalCode.getOrElse(""), - "submittedCountry" -> addressDetails.get.address.countryCode)) - } - } - - private def auditLiabilityReturnsBankDetails(atedReferenceNo: String, - editedLiabilityReturns: EditLiabilityReturnsRequestModel, - eventType: String, - typeOfReturn: String)(implicit hc: HeaderCarrier, ec: ExecutionContext) = { - - //Only Audit the Bank Details from the Head - val headBankDetails = editedLiabilityReturns.liabilityReturn.headOption.flatMap(_.bankDetails) - headBankDetails.map{ bankDetailsData => - sendDataEvent("etmpLiabilityReturnsBankDetails", - detail = Map( - "txName" -> "etmpLiabilityReturnsBankDetails", - "atedRefNumber" -> atedReferenceNo, - "accountName" -> bankDetailsData.accountName, - "sortCode" -> bankDetailsData.ukAccount.map(_.sortCode).getOrElse(""), - "accountNumber" -> bankDetailsData.ukAccount.map(_.accountNumber).getOrElse(""), - "iban" -> bankDetailsData.internationalAccount.map(_.iban).getOrElse(""), - "bicSwiftCode" -> bankDetailsData.internationalAccount.map(_.bicSwiftCode).getOrElse(""), - "amended_further_changed_return" -> typeOfReturn, - "status" -> s"$eventType") - ) - } - } -} \ No newline at end of file diff --git a/app/module/ServiceBindings.scala b/app/module/ServiceBindings.scala index c5f52e4..ef1b365 100644 --- a/app/module/ServiceBindings.scala +++ b/app/module/ServiceBindings.scala @@ -37,7 +37,6 @@ class ServiceBindings extends Module { playBind(classOf[AuthConnector]).to(classOf[DefaultAuthConnector]), playBind(classOf[EmailConnector]).to(classOf[EmailConnectorImpl]), playBind(classOf[EtmpDetailsConnector]).to(classOf[EtmpDetailsConnectorImpl]), - playBind(classOf[EtmpReturnsConnector]).to(classOf[EtmpReturnsConnectorImpl]), playBind(classOf[HipDetailsConnector]).to(classOf[HipDetailsConnectorImpl]), playBind(classOf[HipReturnsConnector]).to(classOf[HipReturnsConnectorImpl]), playBind(classOf[ServiceMetrics]).to(classOf[ServiceMetricsImpl]), diff --git a/app/services/ChangeLiabilityService.scala b/app/services/ChangeLiabilityService.scala index 31f7f46..c37611e 100644 --- a/app/services/ChangeLiabilityService.scala +++ b/app/services/ChangeLiabilityService.scala @@ -16,7 +16,7 @@ package services -import connectors.{EmailConnector, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, HipReturnsConnector} import javax.inject.Inject import models._ @@ -32,7 +32,6 @@ import utils._ import scala.concurrent.{ExecutionContext, Future} class ChangeLiabilityServiceImpl @Inject()(val propertyDetailsMongoWrapper: PropertyDetailsMongoWrapper, - val etmpConnector: EtmpReturnsConnector, val hipConnector: HipReturnsConnector, val authConnector: AuthConnector, val subscriptionDataService: SubscriptionDataService, @@ -58,85 +57,44 @@ trait ChangeLiabilityService extends PropertyDetailsBaseService with ReliefConst cachedData match { case Some(x) if fromSelectedPrevReturn.isEmpty | fromSelectedPrevReturn.contains(false) => Future.successful(Option(x)) case _ => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) map { - response => - response.status match { - case OK => - val liabilityReturn = response.json.as[FormBundleReturn] - val address = ChangeLiabilityUtils.generateAddressFromLiabilityReturn(liabilityReturn) - val title = ChangeLiabilityUtils.generateTitleFromLiabilityReturn(liabilityReturn) - val periodData = ChangeLiabilityUtils.generatePeriodFromLiabilityReturn(liabilityReturn) - val changeLiability = PropertyDetails(atedRefNo, - id = fromSelectedPrevReturn match { - case Some(true) => createPropertyKey - case _ => oldFormBundleNo - }, - periodKey = fromSelectedPrevReturn match { - case Some(true) => period.get - case _ => liabilityReturn.periodKey.trim.toInt - }, - address, - title, - period = fromSelectedPrevReturn match { - case Some(true) => None - case _ => Some(periodData) - }, - value = Some(PropertyDetailsValue(isValuedByAgent = Some(liabilityReturn.professionalValuation), - isPropertyRevalued = Some(false), - partAcqDispDate = liabilityReturn.dateOfAcquisition, - revaluedValue = liabilityReturn.valueAtAcquisition)), - formBundleReturn = Some(liabilityReturn) - ) - retrieveDraftPropertyDetails(atedRefNo) map { - list => - val updatedList = list :+ changeLiability - updatedList.map(updateProp => propertyDetailsCache.cachePropertyDetails(updateProp)) - } - Some(changeLiability) - case _ => None - } + hipConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) map { + response => + response.status match { + case OK => + val liabilityReturn = response.json.as[FormBundleReturn] + val address = ChangeLiabilityUtils.generateAddressFromLiabilityReturn(liabilityReturn) + val title = ChangeLiabilityUtils.generateTitleFromLiabilityReturn(liabilityReturn) + val periodData = ChangeLiabilityUtils.generatePeriodFromLiabilityReturn(liabilityReturn) + val changeLiability = PropertyDetails(atedRefNo, + id = fromSelectedPrevReturn match { + case Some(true) => createPropertyKey + case _ => oldFormBundleNo + }, + periodKey = fromSelectedPrevReturn match { + case Some(true) => period.get + case _ => liabilityReturn.periodKey.trim.toInt + }, + address, + title, + period = fromSelectedPrevReturn match { + case Some(true) => None + case _ => Some(periodData) + }, + value = Some(PropertyDetailsValue(isValuedByAgent = Some(liabilityReturn.professionalValuation), + isPropertyRevalued = Some(false), + partAcqDispDate = liabilityReturn.dateOfAcquisition, + revaluedValue = liabilityReturn.valueAtAcquisition)), + formBundleReturn = Some(liabilityReturn) + ) + retrieveDraftPropertyDetails(atedRefNo) map { + list => + val updatedList = list :+ changeLiability + updatedList.map(updateProp => propertyDetailsCache.cachePropertyDetails(updateProp)) + } + Some(changeLiability) + case _ => None + } } - } else { - etmpConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) map { - response => - response.status match { - case OK => - val liabilityReturn = response.json.as[FormBundleReturn] - val address = ChangeLiabilityUtils.generateAddressFromLiabilityReturn(liabilityReturn) - val title = ChangeLiabilityUtils.generateTitleFromLiabilityReturn(liabilityReturn) - val periodData = ChangeLiabilityUtils.generatePeriodFromLiabilityReturn(liabilityReturn) - val changeLiability = PropertyDetails(atedRefNo, - id = fromSelectedPrevReturn match { - case Some(true) => createPropertyKey - case _ => oldFormBundleNo - }, - periodKey = fromSelectedPrevReturn match { - case Some(true) => period.get - case _ => liabilityReturn.periodKey.trim.toInt - }, - address, - title, - period = fromSelectedPrevReturn match { - case Some(true) => None - case _ => Some(periodData) - }, - value = Some(PropertyDetailsValue(isValuedByAgent = Some(liabilityReturn.professionalValuation), - isPropertyRevalued = Some(false), - partAcqDispDate = liabilityReturn.dateOfAcquisition, - revaluedValue = liabilityReturn.valueAtAcquisition)), - formBundleReturn = Some(liabilityReturn) - ) - retrieveDraftPropertyDetails(atedRefNo) map { - list => - val updatedList = list :+ changeLiability - updatedList.map(updateProp => propertyDetailsCache.cachePropertyDetails(updateProp)) - } - Some(changeLiability) - case _ => None - } - } - } } } } yield { @@ -155,8 +113,7 @@ trait ChangeLiabilityService extends PropertyDetailsBaseService with ReliefConst ChangeLiabilityUtils.createPreCalculationRequest(propertyDetails, agentRefNo) match { case Some(requestModel) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.submitEditedLiabilityReturns(atedRefNo, requestModel) map { + hipConnector.submitEditedLiabilityReturns(atedRefNo, requestModel) map { response => response.status match { case OK => getLiabilityAmount(response.json) @@ -166,18 +123,6 @@ trait ChangeLiabilityService extends PropertyDetailsBaseService with ReliefConst throw new InternalServerException(s"[ChangeLiabilityService][getAmountDueOrRefund] Error - status: $status") } } - } else { - etmpConnector.submitEditedLiabilityReturns(atedRefNo, requestModel) map { - response => - response.status match { - case OK => getLiabilityAmount(response.json) - case BAD_REQUEST => - throw NoLiabilityAmountException("[ChangeLiabilityService][getAmountDueOrRefund] No Liability Amount Found") - case status => - throw new InternalServerException(s"[ChangeLiabilityService][getAmountDueOrRefund] Error - status: $status") - } - } - } case None => throw NoLiabilityAmountException("[ChangeLiabilityService][getAmountDueOrRefund] Invalid Data for the request") } } @@ -228,12 +173,7 @@ trait ChangeLiabilityService extends PropertyDetailsBaseService with ReliefConst case Some(x) => val editLiabilityRequest = ChangeLiabilityUtils.createPostRequest(x, agentRefNo) editLiabilityRequest match { - case Some(a) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.submitEditedLiabilityReturns(atedRefNo, a) - } else { - etmpConnector.submitEditedLiabilityReturns(atedRefNo, a) - } + case Some(a) => hipConnector.submitEditedLiabilityReturns(atedRefNo, a) case None => Future.successful(HttpResponse(NOT_FOUND, "")) } case None => Future.successful(HttpResponse(NOT_FOUND, "")) @@ -258,4 +198,4 @@ trait ChangeLiabilityService extends PropertyDetailsBaseService with ReliefConst }).flatten } } -} +} \ No newline at end of file diff --git a/app/services/DisposeLiabilityReturnService.scala b/app/services/DisposeLiabilityReturnService.scala index 0857f2b..d7469bc 100644 --- a/app/services/DisposeLiabilityReturnService.scala +++ b/app/services/DisposeLiabilityReturnService.scala @@ -16,7 +16,7 @@ package services -import connectors.{EmailConnector, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, HipReturnsConnector} import javax.inject.Inject import models._ @@ -29,12 +29,11 @@ import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig import utils.ReliefUtils._ import utils.SessionUtils._ -import utils.{ATEDFeatureSwitches, AuthFunctionality, ChangeLiabilityUtils, PropertyDetailsUtils} +import utils.{AuthFunctionality, ChangeLiabilityUtils, PropertyDetailsUtils} import scala.concurrent.{ExecutionContext, Future} -class DisposeLiabilityReturnServiceImpl @Inject()(val etmpReturnsConnector: EtmpReturnsConnector, - val hipReturnsConnector: HipReturnsConnector, +class DisposeLiabilityReturnServiceImpl @Inject()(val hipReturnsConnector: HipReturnsConnector, val disposeLiabilityReturnMongoWrapper: DisposeLiabilityReturnMongoWrapper, val authConnector: AuthConnector, val subscriptionDataService: SubscriptionDataService, @@ -51,8 +50,6 @@ trait DisposeLiabilityReturnService extends NotificationService with AuthFunctio def disposeLiabilityReturnRepository: DisposeLiabilityReturnMongoRepository - def etmpReturnsConnector: EtmpReturnsConnector - def hipReturnsConnector: HipReturnsConnector def authConnector: AuthConnector @@ -78,40 +75,21 @@ trait DisposeLiabilityReturnService extends NotificationService with AuthFunctio case Some(x) => Future.successful(Option(convertBankDetails(x))) case None => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipReturnsConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) flatMap { - response => - response.status match { - case OK => - val formBundleReturn = response.json.as[FormBundleReturn] - val dispose = DisposeLiability(dateOfDisposal = None, periodKey = formBundleReturn.periodKey.trim.toInt) - val disposeLiability = DisposeLiabilityReturn(atedRefNo = atedRefNo, - id = oldFormBundleNo, - formBundleReturn = formBundleReturn, - disposeLiability = Some(dispose)) - disposeLiabilityReturnRepository.cacheDisposeLiabilityReturns(disposeLiability).flatMap { _ => - retrieveDraftDisposeLiabilityReturn(atedRefNo, oldFormBundleNo) - } - case _ => Future.successful(None) - } - } - } else { - etmpReturnsConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) flatMap { - response => - response.status match { - case OK => - val formBundleReturn = response.json.as[FormBundleReturn] - val dispose = DisposeLiability(dateOfDisposal = None, periodKey = formBundleReturn.periodKey.trim.toInt) - val disposeLiability = DisposeLiabilityReturn(atedRefNo = atedRefNo, - id = oldFormBundleNo, - formBundleReturn = formBundleReturn, - disposeLiability = Some(dispose)) - disposeLiabilityReturnRepository.cacheDisposeLiabilityReturns(disposeLiability).flatMap { _ => - retrieveDraftDisposeLiabilityReturn(atedRefNo, oldFormBundleNo) - } - case _ => Future.successful(None) - } - } + hipReturnsConnector.getFormBundleReturns(atedRefNo, oldFormBundleNo) flatMap { + response => + response.status match { + case OK => + val formBundleReturn = response.json.as[FormBundleReturn] + val dispose = DisposeLiability(dateOfDisposal = None, periodKey = formBundleReturn.periodKey.trim.toInt) + val disposeLiability = DisposeLiabilityReturn(atedRefNo = atedRefNo, + id = oldFormBundleNo, + formBundleReturn = formBundleReturn, + disposeLiability = Some(dispose)) + disposeLiabilityReturnRepository.cacheDisposeLiabilityReturns(disposeLiability).flatMap { _ => + retrieveDraftDisposeLiabilityReturn(atedRefNo, oldFormBundleNo) + } + case _ => Future.successful(None) + } } } } @@ -272,34 +250,18 @@ trait DisposeLiabilityReturnService extends NotificationService with AuthFunctio EditLiabilityReturnsRequestModel(acknowledgmentReference = getUniqueAckNo, agentReferenceNumber = agentRefNo, liabilityReturn = Seq(liabilityReturn)) } - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipReturnsConnector.submitEditedLiabilityReturns(atedRefNo, editedLiabilityReturns = generateEditReturnRequest, disposal = true) map { - response => - response.status match { - case OK => - val responseData = response.json.as[EditLiabilityReturnsResponseModel] - responseData.liabilityReturnResponse.find(_.oldFormBundleNumber == oldFormBNo) - .fold(DisposeCalculated(BigDecimal(0), BigDecimal(0)))(a => DisposeCalculated(liabilityAmount = a.liabilityAmount, - amountDueOrRefund = a.amountDueOrRefund)) - case status => - logger.warn(s"[DisposeLiabilityReturnService][getPreCalculationAmounts] - response status = $status, response body = ${response.body}") - throw new RuntimeException("pre-calculation-request returned wrong status") - } - } - } else { - etmpReturnsConnector.submitEditedLiabilityReturns(atedRefNo, editedLiabilityReturns = generateEditReturnRequest, disposal = true) map { - response => - response.status match { - case OK => - val responseData = response.json.as[EditLiabilityReturnsResponseModel] - responseData.liabilityReturnResponse.find(_.oldFormBundleNumber == oldFormBNo) - .fold(DisposeCalculated(BigDecimal(0), BigDecimal(0)))(a => DisposeCalculated(liabilityAmount = a.liabilityAmount, - amountDueOrRefund = a.amountDueOrRefund)) - case status => - logger.warn(s"[DisposeLiabilityReturnService][getPreCalculationAmounts] - response status = $status, response body = ${response.body}") - throw new RuntimeException("pre-calculation-request returned wrong status") - } - } + hipReturnsConnector.submitEditedLiabilityReturns(atedRefNo, editedLiabilityReturns = generateEditReturnRequest, disposal = true) map { + response => + response.status match { + case OK => + val responseData = response.json.as[EditLiabilityReturnsResponseModel] + responseData.liabilityReturnResponse.find(_.oldFormBundleNumber == oldFormBNo) + .fold(DisposeCalculated(BigDecimal(0), BigDecimal(0)))(a => DisposeCalculated(liabilityAmount = a.liabilityAmount, + amountDueOrRefund = a.amountDueOrRefund)) + case status => + logger.warn(s"[DisposeLiabilityReturnService][getPreCalculationAmounts] - response status = $status, response body = ${response.body}") + throw new RuntimeException("pre-calculation-request returned wrong status") + } } } @@ -357,11 +319,7 @@ trait DisposeLiabilityReturnService extends NotificationService with AuthFunctio submitStatus: HttpResponse <- { disposeLiabilityReturnList.find(_.id == oldFormBundleNo) match { case Some(x) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { hipReturnsConnector.submitEditedLiabilityReturns(atedRefNo, generateEditReturnRequest(x, agentRefNo), disposal = true) - } else { - etmpReturnsConnector.submitEditedLiabilityReturns(atedRefNo, generateEditReturnRequest(x, agentRefNo), disposal = true) - } case None => Future.successful(HttpResponse(NOT_FOUND, "")) } } diff --git a/app/services/FormBundleService.scala b/app/services/FormBundleService.scala index 3dbcf5c..26c91aa 100644 --- a/app/services/FormBundleService.scala +++ b/app/services/FormBundleService.scala @@ -16,32 +16,23 @@ package services -import connectors.{EtmpReturnsConnector, HipReturnsConnector} +import connectors.{HipReturnsConnector} import javax.inject.Inject import scala.concurrent.{ExecutionContext, Future} import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.ATEDFeatureSwitches -class FormBundleServiceImpl @Inject()(val etmpReturnsConnector: EtmpReturnsConnector, - val hipReturnsConnector: HipReturnsConnector)( +class FormBundleServiceImpl @Inject()(val hipReturnsConnector: HipReturnsConnector)( override implicit val ec: ExecutionContext, override implicit val sc: ServicesConfig) extends FormBundleService trait FormBundleService { implicit val ec: ExecutionContext implicit val sc: ServicesConfig - def etmpReturnsConnector: EtmpReturnsConnector - def hipReturnsConnector: HipReturnsConnector def getFormBundleReturns(atedReferenceNo: String, formBundleNumber: String)(implicit hc: HeaderCarrier): Future[HttpResponse] = { - - if (ATEDFeatureSwitches.hipSwitch().enabled) { hipReturnsConnector.getFormBundleReturns(atedReferenceNo, formBundleNumber) - } else { - etmpReturnsConnector.getFormBundleReturns(atedReferenceNo, formBundleNumber) - } } -} +} \ No newline at end of file diff --git a/app/services/PropertyDetailsBaseService.scala b/app/services/PropertyDetailsBaseService.scala index 5af385d..09f1fe8 100644 --- a/app/services/PropertyDetailsBaseService.scala +++ b/app/services/PropertyDetailsBaseService.scala @@ -17,7 +17,7 @@ package services -import connectors.{EtmpReturnsConnector, HipReturnsConnector} +import connectors.{HipReturnsConnector} import models._ import repository.{PropertyDetailsDelete, PropertyDetailsMongoRepository} import uk.gov.hmrc.auth.core.AuthConnector @@ -27,7 +27,6 @@ import scala.concurrent.{ExecutionContext, Future} trait PropertyDetailsBaseService extends ReliefConstants { - def etmpConnector: EtmpReturnsConnector def hipConnector: HipReturnsConnector def authConnector: AuthConnector def propertyDetailsCache: PropertyDetailsMongoRepository diff --git a/app/services/PropertyDetailsService.scala b/app/services/PropertyDetailsService.scala index b0adf20..6a88542 100644 --- a/app/services/PropertyDetailsService.scala +++ b/app/services/PropertyDetailsService.scala @@ -17,7 +17,7 @@ package services import audit.Auditable -import connectors.{EmailConnector, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, HipReturnsConnector} import models._ import play.api.Logging import play.api.http.Status._ @@ -34,8 +34,7 @@ import utils._ import javax.inject.Inject import scala.concurrent.{ExecutionContext, Future} -class PropertyDetailsServiceImpl @Inject()(val etmpConnector: EtmpReturnsConnector, - val hipConnector: HipReturnsConnector, +class PropertyDetailsServiceImpl @Inject()(val hipConnector: HipReturnsConnector, val authConnector: AuthConnector, val subscriptionDataService: SubscriptionDataService, val emailConnector: EmailConnector, @@ -145,39 +144,20 @@ trait PropertyDetailsService val etmpSubmitReturnRequest = LiabilityUtils.createPreCalculationReturnsRequest(id, propertyDetails, agentRefNo) etmpSubmitReturnRequest match { case Some(returnRequest) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.submitReturns(atedRefNo, returnRequest).map { response => - response.status match { - case OK => getLiabilityAmount(response.json) - case BAD_REQUEST => - sendDataEvent("getLiabilityAmountFailed", - detail = Map("Id" -> s"""$id""", - "Property Details" -> s"""$propertyDetails""", - "agentRefNo" -> s"""$agentRefNo""", - "returnRequest" -> s"""$returnRequest""", - "Response" -> s"""$response""")) - logger.warn( - s"""[PropertyDetailsService][getLiabilityAmount]: failed with status 400""") - throw new BadRequestException(response.body) - case _ => throw new InternalServerException("[PropertyDetailsService][getLiabilityAmount] No Liability Amount Found") - } - } - } else { - etmpConnector.submitReturns(atedRefNo, returnRequest).map { response => - response.status match { - case OK => getLiabilityAmount(response.json) - case BAD_REQUEST => - sendDataEvent("getLiabilityAmountFailed", - detail = Map("Id" -> s"""$id""", - "Property Details" -> s"""$propertyDetails""", - "agentRefNo" -> s"""$agentRefNo""", - "returnRequest" -> s"""$returnRequest""", - "Response" -> s"""$response""")) - logger.warn( - s"""[PropertyDetailsService][getLiabilityAmount]: failed with status 400""") - throw new BadRequestException(response.body) - case _ => throw new InternalServerException("[PropertyDetailsService][getLiabilityAmount] No Liability Amount Found") - } + hipConnector.submitReturns(atedRefNo, returnRequest).map { response => + response.status match { + case OK => getLiabilityAmount(response.json) + case BAD_REQUEST => + sendDataEvent("getLiabilityAmountFailed", + detail = Map("Id" -> s"""$id""", + "Property Details" -> s"""$propertyDetails""", + "agentRefNo" -> s"""$agentRefNo""", + "returnRequest" -> s"""$returnRequest""", + "Response" -> s"""$response""")) + logger.warn( + s"""[PropertyDetailsService][getLiabilityAmount]: failed with status 400""") + throw new BadRequestException(response.body) + case _ => throw new InternalServerException("[PropertyDetailsService][getLiabilityAmount] No Liability Amount Found") } } case None => throw new InternalServerException("[PropertyDetailsService][getLiabilityAmount] Invalid Data for the request") @@ -336,12 +316,7 @@ trait PropertyDetailsService case Some(x) => val etmpSubmitReturnRequest = LiabilityUtils.createPostReturnsRequest(id, x, agentRefNo) etmpSubmitReturnRequest match { - case Some(returnRequest) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.submitReturns(atedRefNo, returnRequest) - } else { - etmpConnector.submitReturns(atedRefNo, returnRequest) - } + case Some(returnRequest) => hipConnector.submitReturns(atedRefNo, returnRequest) case None => Future.successful(HttpResponse(NOT_FOUND, "")) } case None => Future.successful(HttpResponse(NOT_FOUND, "")) @@ -373,5 +348,4 @@ trait PropertyDetailsService reliefsList } } - } \ No newline at end of file diff --git a/app/services/ReliefsService.scala b/app/services/ReliefsService.scala index 5b2c9ae..c095b5b 100644 --- a/app/services/ReliefsService.scala +++ b/app/services/ReliefsService.scala @@ -16,7 +16,7 @@ package services -import connectors.{EmailConnector, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, HipReturnsConnector} import javax.inject.Inject import models.{ReliefsTaxAvoidance, SubmitEtmpReturnsRequest} @@ -26,12 +26,11 @@ import repository.{ReliefsMongoRepository, ReliefsMongoWrapper} import uk.gov.hmrc.auth.core.AuthConnector import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.{ATEDFeatureSwitches, AuthFunctionality, ReliefUtils} +import utils.{AuthFunctionality, ReliefUtils} import scala.concurrent.{ExecutionContext, Future} -class ReliefsServiceImpl @Inject()(val etmpConnector: EtmpReturnsConnector, - val hipConnector: HipReturnsConnector, +class ReliefsServiceImpl @Inject()(val hipConnector: HipReturnsConnector, val authConnector: AuthConnector, val subscriptionDataService: SubscriptionDataService, val emailConnector: EmailConnector, @@ -47,7 +46,6 @@ trait ReliefsService extends NotificationService with AuthFunctionality { implicit val sc: ServicesConfig def reliefsCache: ReliefsMongoRepository - def etmpConnector: EtmpReturnsConnector def hipConnector: HipReturnsConnector def authConnector: AuthConnector def subscriptionDataService: SubscriptionDataService @@ -71,11 +69,7 @@ trait ReliefsService extends NotificationService with AuthFunctionality { reliefRequest <- getSubmitReliefsRequest(atedRefNo, periodKey, agentRefNo) submitResponse <- reliefRequest match { case Some(x) => - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.submitReturns(atedRefNo, x) - } else { - etmpConnector.submitReturns(atedRefNo, x) - } + hipConnector.submitReturns(atedRefNo, x) case _ => val notFound = Json.parse("""{"reason" : "No Reliefs to submit"}""") Future.successful(HttpResponse(NOT_FOUND, notFound, Map.empty[String, Seq[String]])) diff --git a/app/services/ReturnSummaryService.scala b/app/services/ReturnSummaryService.scala index 1558fcc..6a577e3 100644 --- a/app/services/ReturnSummaryService.scala +++ b/app/services/ReturnSummaryService.scala @@ -16,21 +16,19 @@ package services -import connectors.{EtmpReturnsConnector, HipReturnsConnector} +import connectors.HipReturnsConnector import javax.inject.Inject import models._ import play.api.http.Status._ import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.ATEDFeatureSwitches import utils.AtedConstants._ import utils.ReliefUtils._ import scala.concurrent.{ExecutionContext, Future} -class ReturnSummaryServiceImpl @Inject()(val etmpConnector: EtmpReturnsConnector, - val hipConnector: HipReturnsConnector, +class ReturnSummaryServiceImpl @Inject()(val hipConnector: HipReturnsConnector, val propertyDetailsService: PropertyDetailsService, val reliefsService: ReliefsService, val disposeLiabilityReturnService: DisposeLiabilityReturnService, @@ -40,7 +38,6 @@ trait ReturnSummaryService { implicit val sc: ServicesConfig - def etmpConnector: EtmpReturnsConnector def hipConnector: HipReturnsConnector def propertyDetailsService: PropertyDetailsService def reliefsService: ReliefsService @@ -98,13 +95,7 @@ trait ReturnSummaryService { } def getFullSummaryReturns(atedRef: String)(implicit ec: ExecutionContext, hc: HeaderCarrier): Future[SummaryReturnsModel] = { - val etmpReturnsFuture = { - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.getSummaryReturns(atedRef, years) - } else { - etmpConnector.getSummaryReturns(atedRef, years) - } - } + val etmpReturnsFuture = hipConnector.getSummaryReturns(atedRef, years) val reliefDraftsFuture = reliefsService.retrieveDraftReliefs(atedRef) val liabilityDraftsFuture = propertyDetailsService.retrieveDraftPropertyDetails(atedRef) val disposeLiabilityDraftsFuture = disposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(atedRef) diff --git a/app/services/SubscriptionDataService.scala b/app/services/SubscriptionDataService.scala index e31fb8c..6a31a69 100644 --- a/app/services/SubscriptionDataService.scala +++ b/app/services/SubscriptionDataService.scala @@ -23,7 +23,7 @@ import models._ import uk.gov.hmrc.auth.core.AuthConnector import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.{ATEDFeatureSwitches, AuthFunctionality, SessionUtils} +import utils.{AuthFunctionality, SessionUtils} import scala.concurrent.{ExecutionContext, Future} @@ -43,12 +43,7 @@ trait SubscriptionDataService extends AuthFunctionality { def authConnector: AuthConnector def retrieveSubscriptionData(atedReferenceNo: String)(implicit hc: HeaderCarrier): Future[HttpResponse] = { - - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.getSubscriptionData(atedReferenceNo) - } else { - etmpConnector.getSubscriptionData(atedReferenceNo) - } + hipConnector.getSubscriptionData(atedReferenceNo) } def updateSubscriptionData(atedReferenceNo: String, updateData: UpdateSubscriptionDataRequest) @@ -61,11 +56,8 @@ trait SubscriptionDataService extends AuthFunctionality { agentRefNo, updateData.address ) - if (ATEDFeatureSwitches.hipSwitch().enabled) { - hipConnector.updateSubscriptionData(atedReferenceNo, request) - }else { - etmpConnector.updateSubscriptionData(atedReferenceNo, request) - } + + hipConnector.updateSubscriptionData(atedReferenceNo, request) } } diff --git a/app/utils/FeatureSwitch.scala b/app/utils/FeatureSwitch.scala deleted file mode 100644 index e3d3068..0000000 --- a/app/utils/FeatureSwitch.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2026 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package utils - -import uk.gov.hmrc.play.bootstrap.config.ServicesConfig - -sealed trait FeatureSwitch { - def name: String - def enabled: Boolean -} - -case class BooleanFeatureSwitch(name: String, enabled: Boolean) extends FeatureSwitch - -object FeatureSwitch { - - private[utils] def getProperty(name: String)(implicit config: ServicesConfig): FeatureSwitch = { - val value = sys.props.get(systemPropertyName(name)) - value match { - case Some("true") => BooleanFeatureSwitch(name, enabled = true) - case _ => BooleanFeatureSwitch(name, enabled = config.getBoolean(s"feature.$name")) - } - } - - private[utils] def setProperty(name: String, value: String)(implicit config: ServicesConfig): FeatureSwitch = { - sys.props += ((systemPropertyName(name), value)) - getProperty(name) - } - - private[utils] def systemPropertyName(name: String) = s"feature.$name" - - def enable(fs: FeatureSwitch)(implicit config: ServicesConfig): FeatureSwitch = setProperty(fs.name, "true") - def disable(fs: FeatureSwitch)(implicit config: ServicesConfig): FeatureSwitch = setProperty(fs.name, "false") - - def apply(name: String, enabled: Boolean = false)(implicit config: ServicesConfig): FeatureSwitch = getProperty(name) - def unapply(fs: FeatureSwitch): Option[(String, Boolean)] = Some(fs.name -> fs.enabled) -} - -object ATEDFeatureSwitches extends ATEDFeatureSwitches - -trait ATEDFeatureSwitches { - - def hipSwitch()(implicit config: ServicesConfig): FeatureSwitch = FeatureSwitch.getProperty("hipSwitch") - - def apply(name: String)(implicit config: ServicesConfig): Option[FeatureSwitch] = name match { - case "hipSwitch" => Some(hipSwitch()) - case _ => None - } - - def all: Seq[FeatureSwitch] = { - Seq.empty - } -} diff --git a/conf/application.conf b/conf/application.conf index ceca14a..9fd4571 100644 --- a/conf/application.conf +++ b/conf/application.conf @@ -33,8 +33,6 @@ play.i18n.langs = ["en"] play.http.router = prod.Routes -feature.hipSwitch = true - schedules.delete-property-details-job { cleardown.batchSize = 1 enabled = false diff --git a/it/test/service/DeleteLiabilityReturnsServiceISpec.scala b/it/test/service/DeleteLiabilityReturnsServiceISpec.scala deleted file mode 100644 index 6e0b95b..0000000 --- a/it/test/service/DeleteLiabilityReturnsServiceISpec.scala +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright 2024 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.service - -import helpers.{AssertionHelpers, IntegrationSpec} -import models._ -import play.api.http.Status._ -import play.api.libs.json.{Format, Json, OFormat} -import play.api.libs.ws.WSResponse -import play.api.test.FutureAwaits -import repository.{DisposeLiabilityReturnMongoRepository, DisposeLiabilityReturnMongoWrapper} -import scheduler.DeleteLiabilityReturnsService -import uk.gov.hmrc.crypto.{Decrypter, Encrypter} -import crypto.MongoCryptoProvider - -import java.time.{LocalDate, ZoneId, ZonedDateTime} -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future - -class DeleteLiabilityReturnsServiceISpec extends IntegrationSpec with AssertionHelpers with FutureAwaits { - private val mongoCrypto: MongoCryptoProvider = app.injector.instanceOf[MongoCryptoProvider] - - implicit val crypto: Encrypter with Decrypter = mongoCrypto.crypto - implicit val bankDetailsModelFormat: Format[BankDetailsModel] = BankDetailsModel.format - implicit val formats: OFormat[DisposeLiability] = DisposeLiability.formats - - val deleteLiabilityReturnsService: DeleteLiabilityReturnsService = app.injector.instanceOf[DeleteLiabilityReturnsService] - val justAdded: ZonedDateTime = ZonedDateTime.now(ZoneId.of("UTC")).minusMinutes(1) - val date59DaysAgo: ZonedDateTime = ZonedDateTime.now(ZoneId.of("UTC")).withHour(0).minusDays(59) - val date60DaysAgo: ZonedDateTime = date59DaysAgo.minusDays(1) - val date60DaysHrsMinsAgo: ZonedDateTime = date59DaysAgo.minusDays(1).minusHours(23).minusMinutes(59) - val date61DaysAgo: ZonedDateTime = date59DaysAgo.minusDays(2) - val date61DaysMinsAgo: ZonedDateTime = date59DaysAgo.minusDays(2).minusMinutes(1) - val periodKey = 2019 - - override def additionalConfig(a: Map[String, Any]): Map[String, Any] = Map( - "microservice.services.etmp-hod.host" -> wireMockHost, - "microservice.services.etmp-hod.port" -> wireMockPort, - "schedules.delete-liability-returns-job.cleardown.batchSize" -> 20 - ) - - def generateFormBundleResponse(periodKey: Int): FormBundleReturn = { - val formBundleAddress = FormBundleAddress("line1", "line2", None, None, None, "GB") - val x = FormBundlePropertyDetails(Some("12345678"), formBundleAddress, additionalDetails = Some("supportingInfo")) - val lineItem1 = FormBundleProperty(BigDecimal(5000000), LocalDate.of(periodKey, 4, 1), LocalDate.of(periodKey, 8, 31), "Liability", None) - val lineItem2 = FormBundleProperty(BigDecimal(5000000), LocalDate.of(periodKey, 9, 1), LocalDate.of(periodKey + 1, 3, 31), "Relief", Some("Relief")) - - FormBundleReturn(periodKey = periodKey.toString, - propertyDetails = x, - dateOfAcquisition = None, - valueAtAcquisition = None, - dateOfValuation = LocalDate.of(periodKey, 5, 5), - localAuthorityCode = None, - professionalValuation = true, - taxAvoidanceScheme = Some("taxAvoidanceScheme"), - ninetyDayRuleApplies = true, - dateOfSubmission = LocalDate.of(periodKey, 5, 5), - liabilityAmount = BigDecimal(123.23), - paymentReference = "payment-ref-123", - lineItem = Seq(lineItem1, lineItem2)) - } - - val formBundle: FormBundleReturn = generateFormBundleResponse(periodKey) - val liabilityReturn: DisposeLiabilityReturn = DisposeLiabilityReturn(atedRefNo = "ATE1234567XX", id = "101010", formBundle) - val liabilityReturn2: DisposeLiabilityReturn = DisposeLiabilityReturn(atedRefNo = "ATE7654321XX", id = "010101", formBundle) - val liabilityReturn3: DisposeLiabilityReturn = DisposeLiabilityReturn(atedRefNo = "ATE1234568XX", id = "101012", formBundle) - - val disposeLiability: DisposeLiability = DisposeLiability(Option(LocalDate.now()), periodKey) - - class Setup { - val repo: DisposeLiabilityReturnMongoRepository = app.injector.instanceOf[DisposeLiabilityReturnMongoWrapper].apply() - - await(repo.collection.drop().toFuture()) - await(repo.ensureIndexes()) - } - - "deleteLiabilityReturnsService" should { - def createAndRetrieveLiabilityReturn: Future[WSResponse] = hitApplicationEndpoint("/ated/ATE1234567XX/dispose-liability/101010").get() - - def createAndRetrieveLiabilityReturn2: Future[WSResponse] = hitApplicationEndpoint("/ated/ATE7654321XX/dispose-liability/010101").get() - - def createAndRetrieveLiabilityReturn3: Future[WSResponse] = hitApplicationEndpoint("/ated/ATE1234568XX/dispose-liability/101012").get() - - def updateLiabilityReturn() = hitApplicationEndpoint("/ated/ATE1234567XX/dispose-liability/101010/update-date").post(Json.toJson(disposeLiability)) - - def updateLiabilityReturn2() = hitApplicationEndpoint("/ated/ATE7654321XX/dispose-liability/010101/update-date").post(Json.toJson(disposeLiability)) - - def updateLiabilityReturn3() = hitApplicationEndpoint("/ated/ATE1234568XX/dispose-liability/101012/update-date").post(Json.toJson(disposeLiability)) - - "not delete any drafts 60 days" when { - "the draft has only just been added" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - val insert: WSResponse = await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, justAdded)) - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val foundDraft: WSResponse = await(createAndRetrieveLiabilityReturn) - - insert.status mustBe OK - deleteCount mustBe 0 - foundDraft.status mustBe OK - } - - "the draft has been stored for 59 days" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - val insert: WSResponse = await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, date59DaysAgo)) - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val foundDraft: WSResponse = await(createAndRetrieveLiabilityReturn) - - insert.status mustBe OK - deleteCount mustBe 0 - foundDraft.status mustBe OK - } - - "the draft has been stored for 60 days" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, date60DaysAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 1 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val retrieve: WSResponse = await(updateLiabilityReturn()) - - deleteCount mustBe 0 - retrieve.status mustBe OK - } - - "the draft has been stored for 60 days 23hr and 59mins" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, date60DaysHrsMinsAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 1 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val retrieve: WSResponse = await(updateLiabilityReturn()) - - deleteCount mustBe 0 - retrieve.status mustBe OK - } - } - - "delete the liability return drafts" when { - "the draft has been stored for 61 days" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, date61DaysAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 1 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val retrieve: WSResponse = await(updateLiabilityReturn()) - - deleteCount mustBe 1 - retrieve.status mustBe NOT_FOUND - } - - "the draft has been stored for 61 days and 1 min" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(repo.updateTimeStamp(liabilityReturn, date61DaysMinsAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 1 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val retrieve: WSResponse = await(updateLiabilityReturn()) - - deleteCount mustBe 1 - retrieve.status mustBe NOT_FOUND - } - } - - "only delete outdated reliefs when multiple reliefs exist for 60 days" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE7654321XX/form-bundle/010101", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(createAndRetrieveLiabilityReturn2) - await(repo.updateTimeStamp(liabilityReturn, date61DaysAgo)) - await(repo.updateTimeStamp(liabilityReturn2, date60DaysHrsMinsAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 2 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val deletedDraft: WSResponse = await(updateLiabilityReturn()) - val foundDraft: WSResponse = await(updateLiabilityReturn2()) - - deleteCount mustBe 1 - deletedDraft.status mustBe NOT_FOUND - foundDraft.status mustBe OK - } - - "delete multiple drafts when the batchSize is >1 for 60 days" in new Setup { - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234567XX/form-bundle/101010", OK, Json.toJson(formBundle).toString) - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE7654321XX/form-bundle/010101", OK, Json.toJson(formBundle).toString) - stubbedGet("/annual-tax-enveloped-dwellings/returns/ATE1234568XX/form-bundle/101012", OK, Json.toJson(formBundle).toString) - - await(createAndRetrieveLiabilityReturn) - await(createAndRetrieveLiabilityReturn2) - await(createAndRetrieveLiabilityReturn3) - await(repo.updateTimeStamp(liabilityReturn, date61DaysAgo)) - await(repo.updateTimeStamp(liabilityReturn2, date61DaysMinsAgo)) - await(repo.updateTimeStamp(liabilityReturn3, date60DaysHrsMinsAgo)) - - await(repo.collection.countDocuments().toFuture()) mustBe 3 - - val deleteCount: Int = await(deleteLiabilityReturnsService.invoke()) - val deletedDraft: WSResponse = await(updateLiabilityReturn()) - val deletedDraft2: WSResponse = await(updateLiabilityReturn2()) - val foundDraft: WSResponse = await(updateLiabilityReturn3()) - - deleteCount mustBe 2 - deletedDraft.status mustBe NOT_FOUND - deletedDraft2.status mustBe NOT_FOUND - foundDraft.status mustBe OK - } - } -} diff --git a/it/test/service/HipDeleteLiabilityReturnsServiceISpec.scala b/it/test/service/HipDeleteLiabilityReturnsServiceISpec.scala index 6b1e3f6..48e589d 100644 --- a/it/test/service/HipDeleteLiabilityReturnsServiceISpec.scala +++ b/it/test/service/HipDeleteLiabilityReturnsServiceISpec.scala @@ -27,7 +27,6 @@ import repository.{DisposeLiabilityReturnMongoRepository, DisposeLiabilityReturn import scheduler.DeleteLiabilityReturnsService import uk.gov.hmrc.crypto.{Decrypter, Encrypter} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import java.time.{LocalDate, ZoneId, ZonedDateTime} import scala.concurrent.ExecutionContext.Implicits.global @@ -58,12 +57,10 @@ class HipDeleteLiabilityReturnsServiceISpec extends IntegrationSpec with Asserti override def beforeAll(): Unit = { super.beforeAll() - FeatureSwitch.enable(FeatureSwitch("hipSwitch", true)) } override def afterAll(): Unit = { super.afterAll() - FeatureSwitch.disable(FeatureSwitch("hipSwitch", false)) } def generateFormBundleResponse(periodKey: Int): FormBundleReturn = { @@ -253,4 +250,4 @@ class HipDeleteLiabilityReturnsServiceISpec extends IntegrationSpec with Asserti foundDraft.status mustBe OK } } -} +} \ No newline at end of file diff --git a/test/connectors/EtmpDetailsConnectorSpec.scala b/test/connectors/EtmpDetailsConnectorSpec.scala index 63379c5..795a970 100644 --- a/test/connectors/EtmpDetailsConnectorSpec.scala +++ b/test/connectors/EtmpDetailsConnectorSpec.scala @@ -24,13 +24,12 @@ import org.scalatest.BeforeAndAfter import org.scalatestplus.mockito.MockitoSugar import org.scalatestplus.play.PlaySpec import org.scalatestplus.play.guice.GuiceOneServerPerSuite -import play.api.libs.json.{JsValue, Json} +import play.api.libs.json.Json import play.api.test.Helpers._ import uk.gov.hmrc.http.client.HttpClientV2 import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.audit.http.connector.AuditConnector import uk.gov.hmrc.play.audit.model.Audit -import utils.SessionUtils import scala.concurrent.{ExecutionContext, Future} @@ -101,72 +100,6 @@ class EtmpDetailsConnectorSpec extends PlaySpec with GuiceOneServerPerSuite with } } - - "get subscription data" must { - "Correctly return no data if there is none" in new Setup { - val notFoundResponse = Json.parse( """{}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(NOT_FOUND, notFoundResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getSubscriptionData("ATED-123") - val response = await(result) - response.status must be(NOT_FOUND) - response.json must be(notFoundResponse) - } - - "Correctly return data if we have some" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getSubscriptionData("ATED-123") - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - } - - "update subscription data" must { - val addressDetails = AddressDetails("Correspondence", "line1", "line2", None, None, Some("postCode"), "GB") - val addressDetailsNoPostcode = AddressDetails("Correspondence", "line1", "line2", None, None, None, "GB") - val updatedData = new UpdateEtmpSubscriptionDataRequest(SessionUtils.getUniqueAckNo, emailConsent = true, ChangeIndicators(), None, - List(Address(addressDetails = addressDetails))) - val updatedDataNoPostcode = new UpdateEtmpSubscriptionDataRequest(SessionUtils.getUniqueAckNo, emailConsent = true, ChangeIndicators(), None, - List(Address(addressDetails = addressDetailsNoPostcode))) - - "Correctly submit data if with a valid response" in new Setup { - val successResponse: JsValue = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.updateSubscriptionData("ATED-123", updatedData) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "Correctly submit data if with a valid response and no postcode" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.updateSubscriptionData("ATED-123", updatedDataNoPostcode) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "submit data with an invalid response" in new Setup { - val notFoundResponse = Json.parse( """{}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(NOT_FOUND, notFoundResponse, Map.empty[String, Seq[String]]))) - - val result = connector.updateSubscriptionData("ATED-123", updatedData) - val response = await(result) - response.status must be(NOT_FOUND) - } - } - "update registration details" must { val registeredDetails = RegisteredAddressDetails(addressLine1 = "", addressLine2 = "", countryCode = "GB") val registeredDetailsWithPostcode = RegisteredAddressDetails(addressLine1 = "", addressLine2 = "", countryCode = "GB", postalCode = Some("NE1 1EN")) diff --git a/test/connectors/EtmpReturnsConnectorSpec.scala b/test/connectors/EtmpReturnsConnectorSpec.scala deleted file mode 100644 index e0e3c33..0000000 --- a/test/connectors/EtmpReturnsConnectorSpec.scala +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright 2023 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package connectors - -import builders.TestAudit -import metrics.ServiceMetrics -import models._ - -import java.time.LocalDate -import org.mockito.Mockito._ -import org.scalatest.BeforeAndAfter -import org.scalatestplus.mockito.MockitoSugar -import org.scalatestplus.play.PlaySpec -import org.scalatestplus.play.guice.GuiceOneServerPerSuite -import play.api.libs.json.Json -import play.api.test.Helpers._ -import uk.gov.hmrc.http.client.HttpClientV2 -import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} -import uk.gov.hmrc.play.audit.http.connector.AuditConnector -import uk.gov.hmrc.play.audit.model.Audit -import utils.SessionUtils - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future - -class EtmpReturnsConnectorSpec extends PlaySpec with GuiceOneServerPerSuite with MockitoSugar with BeforeAndAfter { - - val mockAuditConnector: AuditConnector = mock[AuditConnector] - - val testFormBundleNum = "123456789012" - - implicit val hc: HeaderCarrier = HeaderCarrier() - - trait Setup extends ConnectorTest { - class TestEtmpReturnsConnector extends EtmpReturnsConnector { - val serviceUrl = "http://localhost:9020/etmp-hod" - val http: HttpClientV2 = mockHttpClient - val urlHeaderEnvironment: String = "" - val urlHeaderAuthorization: String = "" - val audit: Audit = new TestAudit(mockAuditConnector) - val appName: String = "Test" - val metrics: ServiceMetrics = app.injector.instanceOf[ServiceMetrics] - override val baseURI: String = "" - override val submitReturnsURI: String = "" - override val submitEditedLiabilityReturnsURI: String = "" - override val submitClientRelationship: String = "" - override val getSummaryReturns: String = "" - override val formBundleReturns: String = "" - } - - val connector = new TestEtmpReturnsConnector() - } - - - "EtmpReturnsConnector" must { - - "submit ated returns" must { - "Correctly Submit a return with reliefs" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(200, successResponse, Map.empty[String, Seq[String]]))) - - val reliefReturns = Seq(EtmpReliefReturns("", LocalDate.now(), LocalDate.now(), "")) - val atedReturns = SubmitEtmpReturnsRequest(acknowledgementReference = SessionUtils.getUniqueAckNo, - agentReferenceNumber = None, reliefReturns = Some(reliefReturns), liabilityReturns = None) - val result = connector.submitReturns("ATED-123", atedReturns) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "Correctly Submit a return with liabilities" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(200, successResponse, Map.empty[String, Seq[String]]))) - - val _propertyDetails = Some(EtmpPropertyDetails(address = EtmpAddress("line1", "line2", Some("line3"), Some("line4"), "", Some("")))) - val liabilityReturns = Seq(EtmpLiabilityReturns("", "", "", propertyDetails = _propertyDetails, dateOfValuation = LocalDate.now(), professionalValuation = false, ninetyDayRuleApplies = false, lineItems = Nil)) - val atedReturns = SubmitEtmpReturnsRequest(acknowledgementReference = SessionUtils.getUniqueAckNo, - agentReferenceNumber = None, reliefReturns = None, liabilityReturns = Some(liabilityReturns)) - val result = connector.submitReturns("ATED-123", atedReturns) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "check for a failure response" in new Setup { - val failureResponse = Json.parse( """{"Reason" : "Service Unavailable"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(503, failureResponse, Map.empty[String, Seq[String]]))) - - val atedReturns = SubmitEtmpReturnsRequest(acknowledgementReference = SessionUtils.getUniqueAckNo, - agentReferenceNumber = None, reliefReturns = None, liabilityReturns = None) - val result = connector.submitReturns("ATED-123", atedReturns) - val response = await(result) - response.status must be(SERVICE_UNAVAILABLE) - response.json must be(failureResponse) - } - } - - "get summary returns" must { - "Correctly return no data if there is none" in new Setup { - val notFoundResponse = Json.parse( """{}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(NOT_FOUND, notFoundResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getSummaryReturns("ATED-123", 1) - val response = await(result) - response.status must be(NOT_FOUND) - response.json must be(notFoundResponse) - } - - "Correctly return data if we have some" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getSummaryReturns("ATED-123", 1) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "not return data if we get some other status" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getSummaryReturns("ATED-123", 1) - val response = await(result) - response.status must be(BAD_REQUEST) - response.body must include(" \"processingDate\"") - } - } - - "get form bundle returns" must { - "Correctly return no data if there is none" in new Setup { - val notFoundResponse = Json.parse( """{}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(NOT_FOUND, notFoundResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getFormBundleReturns("ATED-123", testFormBundleNum) - val response = await(result) - response.status must be(NOT_FOUND) - response.json must be(notFoundResponse) - } - - "Correctly return data if we have some" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.getFormBundleReturns("ATED-123", testFormBundleNum) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - } - - "submit edited liability returns" must { - - "correctly submit a disposal return" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - - val address = EtmpAddress("address-line-1", "address-line-2", None, None, "GB") - val p = EtmpPropertyDetails(address = address) - val lineItem1 = EtmpLineItems(123456, LocalDate.of(2015, 2, 3), LocalDate.of(2015, 2, 3), "Liability") - val editLiabReturnReq = EditLiabilityReturnsRequest(oldFormBundleNumber = "form-123", - mode = "Pre-Calculation", - periodKey = "2015", - propertyDetails = p, - dateOfValuation = LocalDate.now, - professionalValuation = true, - ninetyDayRuleApplies = true, - bankDetails = Some(EtmpBankDetails(accountName = "testAccountName", ukAccount = Some(UKAccount(sortCode = "20-01-01", accountNumber = "123456789")))), - lineItem = Seq(lineItem1)) - val editLiablityReturns = EditLiabilityReturnsRequestModel(acknowledgmentReference = SessionUtils.getUniqueAckNo, liabilityReturn = Seq(editLiabReturnReq)) - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.submitEditedLiabilityReturns("ATED-123", editLiablityReturns, disposal = true) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "correctly submit an amended return" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z", "amountDueOrRefund": -1.0}""") - - val address = EtmpAddress("address-line-1", "address-line-2", None, None, "GB") - val p = EtmpPropertyDetails(address = address) - val lineItem1 = EtmpLineItems(123456, LocalDate.of(2015, 2, 3), LocalDate.of(2015, 2, 3), "Liability") - val editLiabReturnReq = EditLiabilityReturnsRequest(oldFormBundleNumber = "form-123", mode = "Pre-Calculation", periodKey = "2015", propertyDetails = p, dateOfValuation = LocalDate.now, professionalValuation = true, ninetyDayRuleApplies = true, lineItem = Seq(lineItem1)) - val editLiablityReturns = EditLiabilityReturnsRequestModel(acknowledgmentReference = SessionUtils.getUniqueAckNo, liabilityReturn = Seq(editLiabReturnReq)) - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.submitEditedLiabilityReturns("ATED-123", editLiablityReturns) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "correctly submit a further return" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z", "amountDueOrRefund": 1.0}""") - - val address = EtmpAddress("address-line-1", "address-line-2", None, None, "GB") - val p = EtmpPropertyDetails(address = address) - val lineItem1 = EtmpLineItems(123456, LocalDate.of(2015, 2, 3), LocalDate.of(2015, 2, 3), "Liability") - val editLiabReturnReq = EditLiabilityReturnsRequest(oldFormBundleNumber = "form-123", mode = "Pre-Calculation", periodKey = "2015", propertyDetails = p, dateOfValuation = LocalDate.now, professionalValuation = true, ninetyDayRuleApplies = true, lineItem = Seq(lineItem1)) - val editLiablityReturns = EditLiabilityReturnsRequestModel(acknowledgmentReference = SessionUtils.getUniqueAckNo, liabilityReturn = Seq(editLiabReturnReq)) - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.submitEditedLiabilityReturns("ATED-123", editLiablityReturns) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "correctly submit a change of details return" in new Setup { - val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z", "amountDueOrRefund": 0.0}""") - - val address = EtmpAddress("address-line-1", "address-line-2", None, None, "GB") - val p = EtmpPropertyDetails(address = address) - val lineItem1 = EtmpLineItems(123456, LocalDate.of(2015, 2, 3), LocalDate.of(2015, 2, 3), "Liability") - val editLiabReturnReq = EditLiabilityReturnsRequest(oldFormBundleNumber = "form-123", mode = "Pre-Calculation", periodKey = "2015", propertyDetails = p, dateOfValuation = LocalDate.now, professionalValuation = true, ninetyDayRuleApplies = true, lineItem = Seq(lineItem1)) - val editLiablityReturns = EditLiabilityReturnsRequestModel(acknowledgmentReference = SessionUtils.getUniqueAckNo, liabilityReturn = Seq(editLiabReturnReq)) - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result = connector.submitEditedLiabilityReturns("ATED-123", editLiablityReturns) - val response = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - - "check for a failure response" in new Setup { - - val failureResponse = Json.parse( """{"Reason" : "Service Unavailable"}""") - - when(requestBuilderExecute[HttpResponse]).thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, failureResponse, Map.empty[String, Seq[String]]))) - - val address = EtmpAddress("address-line-1", "address-line-2", None, None, "GB") - val p = EtmpPropertyDetails(address = address) - val lineItem1 = EtmpLineItems(123456, LocalDate.of(2015, 2, 3), LocalDate.of(2015, 2, 3), "Liability") - val editLiabReturnReq = EditLiabilityReturnsRequest(oldFormBundleNumber = "form-123", mode = "Pre-Calculation", periodKey = "2015", propertyDetails = p, dateOfValuation = LocalDate.now, professionalValuation = true, ninetyDayRuleApplies = true, lineItem = Seq(lineItem1)) - val editLiablityReturns = EditLiabilityReturnsRequestModel(acknowledgmentReference = SessionUtils.getUniqueAckNo, liabilityReturn = Seq(editLiabReturnReq)) - - - val result = connector.submitEditedLiabilityReturns("ATED-123", editLiablityReturns) - val response = await(result) - response.status must be(INTERNAL_SERVER_ERROR) - response.json must be(failureResponse) - } - - } - } - -} diff --git a/test/services/ChangeLiabilityServiceSpec.scala b/test/services/ChangeLiabilityServiceSpec.scala index 4715ccd..f7fea1e 100644 --- a/test/services/ChangeLiabilityServiceSpec.scala +++ b/test/services/ChangeLiabilityServiceSpec.scala @@ -18,7 +18,7 @@ package services import builders.AuthFunctionalityHelper import builders.ChangeLiabilityReturnBuilder._ -import connectors.{EmailConnector, EmailSent, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, EmailSent, HipReturnsConnector} import models._ import java.time.{ZoneId, ZonedDateTime} @@ -35,7 +35,6 @@ import repository.{PropertyDetailsCached, PropertyDetailsDeleted, PropertyDetail import uk.gov.hmrc.auth.core.{AuthConnector, Enrolment, EnrolmentIdentifier, Enrolments} import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} import scala.concurrent.ExecutionContext.Implicits.global @@ -45,7 +44,6 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi val mockPropertyDetailsCache: PropertyDetailsMongoRepository = mock[PropertyDetailsMongoRepository] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockAuthConnector: AuthConnector = mock[AuthConnector] val mockSubscriptionDataService: SubscriptionDataService = mock[SubscriptionDataService] val mockEmailConnector: EmailConnector = mock[EmailConnector] @@ -57,7 +55,6 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi override implicit val ec: ExecutionContext = app.injector.instanceOf[ExecutionContext] override implicit val sc: ServicesConfig = mockServicesConfig override val propertyDetailsCache: PropertyDetailsMongoRepository = mockPropertyDetailsCache - override val etmpConnector: EtmpReturnsConnector = mockEtmpConnector override val hipConnector: HipReturnsConnector = mockHipConnector override val authConnector: AuthConnector = mockAuthConnector override val subscriptionDataService: SubscriptionDataService = mockSubscriptionDataService @@ -80,15 +77,9 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi override def beforeEach(): Unit = { reset(mockPropertyDetailsCache) reset(mockAuthConnector) - reset(mockEtmpConnector) reset(mockHipConnector) reset(mockSubscriptionDataService) reset(mockEmailConnector) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } "ChangeLiabilityService" must { @@ -115,25 +106,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi result must be(Some(updateChangeLiabilityReturnWithBankDetails(2015, formBundle3, generateLiabilityBankDetails).copy(timeStamp = ZonedDateTime.of(2005, 3, 26, 12, 0, 0, 0, ZoneId.of("UTC"))))) } - "return Some(ChangeLiabilityReturn) if form-bundle not-found in cache, but found in ETMP - also cache it in mongo - based on previous return" in new Setup { - when(mockPropertyDetailsCache.fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq())) - when(mockEtmpConnector.getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, Json.toJson(formBundleResponse1), Map.empty[String, Seq[String]]))) - val result: Option[PropertyDetails] = await(testChangeLiabilityReturnService.convertSubmittedReturnToCachedDraft(atedRefNo, formBundle1, Some(true), Some(2016))) - - result.get.title.isDefined must be(true) - result.get.calculated.isDefined must be(false) - result.get.formBundleReturn.isDefined must be(true) - result.get.value.isDefined must be(true) - result.get.period.isDefined must be(false) - result.get.bankDetails.isDefined must be(false) - result.get.periodKey must be(2016) - result.get.id mustNot be(formBundle1) - } - "return Some(ChangeLiabilityReturn) if form-bundle not-found in cache, but found in ETMP (HIP) - also cache it in mongo - based on previous return" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockPropertyDetailsCache.fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq())) when(mockHipConnector.getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(ArgumentMatchers.any(), ArgumentMatchers.any())) @@ -150,29 +123,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi result.get.id mustNot be(formBundle1) } - - "return Some(ChangeLiabilityReturn) if form-bundle not-found in cache, but found in ETMP - also cache it in mongo" in new Setup { - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq())) - when(mockEtmpConnector - .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, Json.toJson(formBundleResponse1), Map.empty[String, Seq[String]]))) - val result: Option[PropertyDetails] = await(testChangeLiabilityReturnService.convertSubmittedReturnToCachedDraft(atedRefNo, formBundle1)) - - result.get.title.isDefined must be(true) - result.get.calculated.isDefined must be(false) - result.get.formBundleReturn.isDefined must be(true) - result.get.value.isDefined must be(true) - result.get.period.isDefined must be(true) - result.get.bankDetails.isDefined must be(false) - result.get.periodKey must be(2015) - result.get.id must be(formBundle1) - - } - "return Some(ChangeLiabilityReturn) if form-bundle not-found in cache, but found in ETMP (HIP) - also cache it in mongo" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockPropertyDetailsCache .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq())) @@ -192,19 +143,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi } - "return None if form-bundle not-found in cache as well as in ETMP" in new Setup { - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq())) - when(mockEtmpConnector - .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(NOT_FOUND, ""))) - val result: Option[PropertyDetails] = await(testChangeLiabilityReturnService.convertSubmittedReturnToCachedDraft(atedRefNo, formBundle1)) - result must be(None) - } - "return None if form-bundle not-found in cache as well as in ETMP (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockPropertyDetailsCache .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq())) @@ -217,25 +156,8 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi } "calculateDraftChangeLiability" must { - "throw an exception, when there is no calculated object" in new Setup { - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(changeLiability1))) - when(mockPropertyDetailsCache - .cachePropertyDetails(any[PropertyDetails]())) - .thenReturn(Future.successful(PropertyDetailsCached)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())( - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]])) ) - mockRetrievingNoAuthRef() - val thrown: NoLiabilityAmountException = the[NoLiabilityAmountException] thrownBy await(testChangeLiabilityReturnService.calculateDraftChangeLiability(atedRefNo, formBundle1)) - thrown.message must include("[ChangeLiabilityService][getAmountDueOrRefund] Invalid Data for the request") - } "throw an exception, when there is no calculated object (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockPropertyDetailsCache .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq(changeLiability1))) @@ -252,31 +174,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi thrown.message must include("[ChangeLiabilityService][getAmountDueOrRefund] Invalid Data for the request") } - "calculate the change liabilty details, when calculated object is present" in new Setup { - mockRetrievingNoAuthRef() - - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(changeLiability3))) - when(mockPropertyDetailsCache - .cachePropertyDetails(any[PropertyDetails]())) - .thenReturn(Future.successful(PropertyDetailsCached)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())( - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - - val result: Option[PropertyDetails] = await(testChangeLiabilityReturnService.calculateDraftChangeLiability(atedRefNo, formBundle1)) - result.isDefined must be(true) - result.get.title must be(Some(PropertyDetailsTitle("12345678"))) - result.get.calculated.isDefined must be(true) - result.get.calculated.get.liabilityAmount must be(Some(BigDecimal(2000.00))) - result.get.calculated.get.amountDueOrRefund must be(Some(-500.0)) - } - "calculate the change liabilty details, when calculated object is present (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) mockRetrievingNoAuthRef() @@ -327,37 +225,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi } "submitChangeLiability" must { - "return status OK, if return found in cache and submitted correctly and then deleted from cache" in new Setup { - val calc1: PropertyDetailsCalculated = generateCalculated - val changeLiability1Changed: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) - - val testEnrolments: Set[Enrolment] = Set(Enrolment("HMRC-ATED-ORG", Seq(EnrolmentIdentifier("AgentRefNumber", "XN1200000100001")), "activated")) - - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(Seq(changeLiability1Changed, changeLiability2))) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())).thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockPropertyDetailsCache - .cachePropertyDetails(any[PropertyDetails]())) - .thenReturn(Future.successful(PropertyDetailsCached)) - when(mockPropertyDetailsCache.deletePropertyDetailsByfieldName(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(PropertyDetailsDeleted)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector.sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - - val result: HttpResponse = await(testChangeLiabilityReturnService.submitChangeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return status OK, if return found in cache and submitted correctly and then deleted from cache (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val calc1: PropertyDetailsCalculated = generateCalculated val changeLiability1Changed: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) @@ -409,31 +277,9 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi result.status must be(NOT_FOUND) verify(mockEmailConnector, times(0)).sendTemplatedEmail(any(), any(), any())(any()) } - - "return status returned by connector, if return found in cache and but submission failed and hence draft return is not-deleted from cache" in new Setup { - val calc1: PropertyDetailsCalculated = generateCalculated - val changeLiability1Changed: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) - when(mockPropertyDetailsCache - .fetchPropertyDetails(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(changeLiability1Changed, changeLiability2))) - - mockRetrievingNoAuthRef() - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(BAD_REQUEST, respJson, Map.empty[String, Seq[String]]))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - val result: HttpResponse = await(testChangeLiabilityReturnService.submitChangeLiability(atedRefNo, formBundle1)) - result.status must be(BAD_REQUEST) - verify(mockEmailConnector, times(0)).sendTemplatedEmail(any(), any(), any())(any()) - } } "return status returned by connector, if return found in cache and but submission failed and hence draft return is not-deleted from cache (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val calc1: PropertyDetailsCalculated = generateCalculated val changeLiability1Changed: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) when(mockPropertyDetailsCache @@ -455,19 +301,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi } "getAmountDueOrRefund" must { - "throw an NoLiabilityAmountException if due to some issue, the API call returned BAD_REQUEST (invalid data)" in new Setup { - val calc1: PropertyDetailsCalculated = generateCalculated - val changeLiability1WithCalc: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(BAD_REQUEST, respJson, Map.empty[String, Seq[String]]))) - val thrown: NoLiabilityAmountException = the[NoLiabilityAmountException] thrownBy await(testChangeLiabilityReturnService.getAmountDueOrRefund(atedRefNo, "1", changeLiability1WithCalc)) - thrown.message must include("No Liability Amount Found") - } - "throw an NoLiabilityAmountException if due to some issue, the API call returned BAD_REQUEST (invalid data) (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val calc1: PropertyDetailsCalculated = generateCalculated val changeLiability1WithCalc: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) @@ -478,15 +312,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi thrown.message must include("No Liability Amount Found") } - "throw an InternalServerException if due to some issue, the API call didn't return OK as status" in new Setup { - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, respJson, Map.empty[String, Seq[String]]))) - } - "throw an InternalServerException if due to some issue, the API call didn't return OK as status (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) val respJson: JsValue = Json.toJson(respModel) when(mockHipConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())) @@ -498,19 +324,7 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi thrown.message must include("[ChangeLiabilityService][getAmountDueOrRefund] Invalid Data for the request") } - "liability and amount due or refund is returned, if ETMP returns OK but " in new Setup { - val calc1: PropertyDetailsCalculated = generateCalculated - val changeLiability1WithCalc: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: (Option[BigDecimal], Option[BigDecimal]) = await(testChangeLiabilityReturnService.getAmountDueOrRefund(atedRefNo, formBundle1, changeLiability1WithCalc)) - result must be((Some(2000.0), Some(-500.0))) - } - "liability and amount due or refund is returned, if ETMP returns OK but (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val calc1: PropertyDetailsCalculated = generateCalculated val changeLiability1WithCalc: PropertyDetails = changeLiability1.copy(calculated = Some(calc1)) val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) @@ -521,7 +335,5 @@ class ChangeLiabilityServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi result must be((Some(2000.0), Some(-500.0))) } } - } - -} +} \ No newline at end of file diff --git a/test/services/DisposeLiabilityReturnServiceSpec.scala b/test/services/DisposeLiabilityReturnServiceSpec.scala index caa4cbe..4cdb7f1 100644 --- a/test/services/DisposeLiabilityReturnServiceSpec.scala +++ b/test/services/DisposeLiabilityReturnServiceSpec.scala @@ -18,7 +18,7 @@ package services import builders.ChangeLiabilityReturnBuilder._ import builders.{AuthFunctionalityHelper, ChangeLiabilityReturnBuilder} -import connectors.{EmailConnector, EmailSent, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, EmailSent, HipReturnsConnector} import models._ import java.time.LocalDate @@ -35,7 +35,6 @@ import repository.{DisposeLiabilityReturnCached, DisposeLiabilityReturnMongoRepo import uk.gov.hmrc.auth.core.{AuthConnector, Enrolment, EnrolmentIdentifier, Enrolments} import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} @@ -43,7 +42,6 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS override val mockAuthConnector: AuthConnector = mock[AuthConnector] val mockDisposeLiabilityReturnRepository: DisposeLiabilityReturnMongoRepository = mock[DisposeLiabilityReturnMongoRepository] implicit val mockServicesConfig: ServicesConfig = mock[ServicesConfig] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] val mockSubscriptionDataService: SubscriptionDataService = mock[SubscriptionDataService] val mockEmailConnector: EmailConnector = mock[EmailConnector] @@ -93,16 +91,10 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS override def beforeEach(): Unit = { reset(mockDisposeLiabilityReturnRepository) - reset(mockEtmpConnector) reset(mockHipConnector) reset(mockAuthConnector) reset(mockEmailConnector) reset(mockSubscriptionDataService) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } trait Setup { @@ -112,7 +104,6 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS class TestDisposeLiabilityReturnService extends DisposeLiabilityReturnService { override val ec: ExecutionContext = app.injector.instanceOf[ExecutionContext] override val sc: ServicesConfig = mockServicesConfig - override val etmpReturnsConnector: EtmpReturnsConnector = mockEtmpConnector override val hipReturnsConnector: HipReturnsConnector = mockHipConnector override val disposeLiabilityReturnRepository: DisposeLiabilityReturnMongoRepository = mockDisposeLiabilityReturnRepository override val authConnector: AuthConnector = mockAuthConnector @@ -171,20 +162,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS result must be(Some(disposeLiability1.copy(bankDetails = Some(generateLiabilityBankDetails)))) } - "return DisposeLiabilityReturn, if not found in mongo, but found in ETMP call, also cache it in mongo for future calls" in new Setup { - when(mockDisposeLiabilityReturnRepository.fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(Seq())) - when(mockEtmpConnector - .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, Json.toJson(formBundleReturn1), Map.empty[String, Seq[String]]))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - val result: Option[DisposeLiabilityReturn] = await(testDisposeLiabilityReturnService.retrieveAndCacheDisposeLiabilityReturn(atedRefNo, formBundle1)) - result must be(None) - } - "return DisposeLiabilityReturn, if not found in mongo, but found in ETMP call, also cache it in mongo for future calls (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockDisposeLiabilityReturnRepository.fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(Seq())) when(mockHipConnector .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(any(), any())) @@ -196,19 +174,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS result must be(None) } - "return None, because neither dispose was found in mongo, nor there was any formBundle returned from ETMP" in new Setup { - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disposeLiability2))) - when(mockEtmpConnector - .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle1))(any(), any())) - .thenReturn(Future.successful(HttpResponse(NOT_FOUND, ""))) - val result: Option[DisposeLiabilityReturn] = await(testDisposeLiabilityReturnService.retrieveAndCacheDisposeLiabilityReturn(atedRefNo, formBundle1)) - result must be(None) - } - "return None, because neither dispose was found in mongo, nor there was any formBundle returned from ETMP (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockDisposeLiabilityReturnRepository .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq(disposeLiability2))) @@ -402,33 +368,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS } "updateDraftDisposeBankDetails" must { - "create bankDetails if we have none" in new Setup { - lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails - val dL1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some(DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), - periodKey = periodKey)), bankDetails = None) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(dL1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: Option[DisposeLiabilityReturn] = await( - testDisposeLiabilityReturnService.updateDraftDisposeBankDetails(atedRefNo, formBundle1, bankDetails.bankDetails.get)) - - result.get.bankDetails.get.hasBankDetails must be(true) - result.get.bankDetails.get.bankDetails.isDefined must be(false) - result.get.bankDetails.get.protectedBankDetails.isDefined must be(true) - } - "create bankDetails if we have none (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails val dL1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some(DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), @@ -453,34 +393,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS result.get.bankDetails.get.protectedBankDetails.isDefined must be(true) } - "update bankDetails and cache that into mongo" in new Setup { - lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails - lazy val protectedBankDetails: BankDetailsModel = generateLiabilityProtectedBankDetails - val dL1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some( - DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), periodKey = periodKey)), bankDetails = Some(protectedBankDetails)) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(dL1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: Option[DisposeLiabilityReturn] = await( - testDisposeLiabilityReturnService.updateDraftDisposeBankDetails(atedRefNo, formBundle1, bankDetails.bankDetails.get) - ) - - val expected: DisposeLiabilityReturn = dL1.copy(calculated = None) - result must be(Some(expected)) - } - "update bankDetails and cache that into mongo (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails lazy val protectedBankDetails: BankDetailsModel = generateLiabilityProtectedBankDetails val dL1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some( @@ -506,24 +419,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS result must be(Some(expected)) } - "return None, if form-bundle-no is not found in cache, in such case don't do pre-calculation call" in new Setup { - lazy val bank1: BankDetailsModel = generateLiabilityBankDetails - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - val result: Option[DisposeLiabilityReturn] = await( - testDisposeLiabilityReturnService.updateDraftDisposeBankDetails(atedRefNo, formBundle1, bank1.bankDetails.get) - ) - result must be(None) - verify(mockEtmpConnector, times(0)).submitEditedLiabilityReturns(any(), any(), any())(any(), any()) - } - "return None, if form-bundle-no is not found in cache, in such case don't do pre-calculation call (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bank1: BankDetailsModel = generateLiabilityBankDetails when(mockDisposeLiabilityReturnRepository .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) @@ -541,35 +437,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS } "calculateDraftDispose" must { - - "update the pre calculated values and cache that into mongo" in new Setup { - lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails - lazy val protectedBankDetails: BankDetailsModel = generateLiabilityProtectedBankDetails - val dL1: DisposeLiabilityReturn = disposeLiability1.copy( - disposeLiability = Some(DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), periodKey = periodKey)), - bankDetails = Some(protectedBankDetails)) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(dL1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: Option[DisposeLiabilityReturn] = await(testDisposeLiabilityReturnService.calculateDraftDispose(atedRefNo, formBundle1)) - - val expected: DisposeLiabilityReturn = dL1 - .copy(bankDetails = Some(bankDetails), calculated = Some(DisposeCalculated(BigDecimal(2000.00), BigDecimal(-500.00)))) - result must be(Some(expected)) - } - "update the pre calculated values and cache that into mongo (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bankDetails: BankDetailsModel = generateLiabilityBankDetails lazy val protectedBankDetails: BankDetailsModel = generateLiabilityProtectedBankDetails val dL1: DisposeLiabilityReturn = disposeLiability1.copy( @@ -595,27 +463,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS result must be(Some(expected)) } - "throw exception if pre-calculation call fails" in new Setup { - - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disposeLiability1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, ""))) - val thrown: RuntimeException = the[RuntimeException] thrownBy await(testDisposeLiabilityReturnService.calculateDraftDispose(atedRefNo, formBundle1)) - - thrown.getMessage must include("pre-calculation-request returned wrong status") - verify(mockEtmpConnector, times(1)).submitEditedLiabilityReturns(any(), any(), any())(any(), any()) - } - "throw exception if pre-calculation call fails (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockDisposeLiabilityReturnRepository .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq(disposeLiability1, disposeLiability2))) @@ -633,21 +481,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS verify(mockHipConnector, times(1)).submitEditedLiabilityReturns(any(), any(), any())(any(), any()) } - "return None, if form-bundle-no is not found in cache, in such case don't do pre-calculation call" in new Setup { - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - val result: Option[DisposeLiabilityReturn] = await(testDisposeLiabilityReturnService.calculateDraftDispose(atedRefNo, formBundle1)) - result must be(None) - verify(mockEtmpConnector, times(0)).submitEditedLiabilityReturns(any(), any(), any())(any(), any()) - } - "return None, if form-bundle-no is not found in cache, in such case don't do pre-calculation call (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockDisposeLiabilityReturnRepository .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) .thenReturn(Future.successful(Seq(disposeLiability2))) @@ -662,31 +496,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS } "getPreCalculationAmounts" must { - "just in case, if returned oldFornBundleReturnNo is not equal to one being passed, return amounts as 0,0" in new Setup { - val bank1: BankDetailsModel = generateLiabilityBankDetails - val dL1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some(DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), - periodKey = periodKey)), bankDetails = Some(bank1)) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(dL1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: DisposeCalculated = await(testDisposeLiabilityReturnService.getPreCalculationAmounts(atedRefNo, - formBundleReturn1, - DisposeLiability(Some(LocalDate.of(periodKey, month, date)), periodKey), - formBundle2)) - result must be(DisposeCalculated(BigDecimal(0.00), BigDecimal(0.00))) - } - "just in case, if returned oldFornBundleReturnNo is not equal to one being passed, return amounts as 0,0 (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val bank1: BankDetailsModel = generateLiabilityBankDetails val dL1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some(DisposeLiability(dateOfDisposal = Some(LocalDate.of(periodKey, month, date)), @@ -734,42 +544,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS "submitDisposeLiability" must { "return HttpResponse wit Status OK, when form-bundle is found in cache and successfully submitted to ETMP" must { "getEtmpBankDetails" must { - "return BankDetails, if valid bank-details-model is passed" in new Setup { - lazy val disp1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some( - DisposeLiability(Some(LocalDate.of(periodKey, - month, - date)), periodKey)), - bankDetails = Some(ChangeLiabilityReturnBuilder.generateLiabilityProtectedBankDetails), - calculated = Some(DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector - .sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - - lazy val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - lazy val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return BankDetails, if valid bank-details-model is passed (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val disp1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some( DisposeLiability(Some(LocalDate.of(periodKey, month, @@ -803,36 +578,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) } - - "return None, if hasBankDetails is false passed" in new Setup { - lazy val disp1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some(DisposeLiability( - Some(LocalDate.of(periodKey, month, date)), periodKey)), bankDetails = Some(ChangeLiabilityReturnBuilder - .generateLiabilityProtectedBankDetailsNoBankDetails), calculated = Some(DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector.sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return None, if hasBankDetails is false passed (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val disp1: DisposeLiabilityReturn = disposeLiability1.copy(disposeLiability = Some(DisposeLiability( Some(LocalDate.of(periodKey, month, date)), periodKey)), bankDetails = Some(ChangeLiabilityReturnBuilder .generateLiabilityProtectedBankDetailsNoBankDetails), calculated = Some(DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) @@ -859,39 +605,8 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) } - "return None, if accountNumber & accountName & sortCode is not found" in new Setup { - lazy val disp1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some( - DisposeLiability(Some(LocalDate.of(periodKey, - month, - date)), periodKey)), - bankDetails = Some(ChangeLiabilityReturnBuilder.generateLiabilityProtectedBankDetailsBlank), - calculated = Some(DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())).thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector - .sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - lazy val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - lazy val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return None, if accountNumber & accountName & sortCode is not found (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) + lazy val disp1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some( DisposeLiability(Some(LocalDate.of(periodKey, @@ -922,33 +637,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) } - "return None, if None was passed as bank-details-model" in new Setup { - lazy val disp1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some( - DisposeLiability(Some(LocalDate.of(periodKey, - month, - date)), periodKey)), calculated = Some( DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())).thenReturn(Future.successful(DisposeLiabilityReturnCached)) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())).thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())).thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector - .sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - lazy val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - lazy val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector.submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return None, if None was passed as bank-details-model (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val disp1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some( DisposeLiability(Some(LocalDate.of(periodKey, @@ -975,37 +664,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS } } - "generateEditReturnRequest - if dateOfDisposal is not found, use oldFormbundleReturn 'date from' value" in new Setup { - lazy val bank1: BankDetailsModel = generateLiabilityBankDetails - lazy val disp1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some(DisposeLiability(None, periodKey)), bankDetails = Some(bank1), calculated = Some( - DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())) - .thenReturn(Future.successful(DisposeLiabilityReturnCached)) - when(mockAuthConnector - .authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector - .sendTemplatedEmail(any(), any(), any())(any())) thenReturn Future.successful(EmailSent) - lazy val respModel: EditLiabilityReturnsResponseModel = generateEditLiabilityReturnResponse(formBundle1) - lazy val respJson: JsValue = Json.toJson(respModel) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(OK, respJson, Map.empty[String, Seq[String]]))) - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(any(), any(), any())(any()) - } - "generateEditReturnRequest - if dateOfDisposal is not found, use oldFormbundleReturn 'date from' value (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bank1: BankDetailsModel = generateLiabilityBankDetails lazy val disp1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some(DisposeLiability(None, periodKey)), bankDetails = Some(bank1), calculated = Some( @@ -1047,31 +706,7 @@ class DisposeLiabilityReturnServiceSpec extends PlaySpec with GuiceOneServerPerS verify(mockEmailConnector, times(0)).sendTemplatedEmail(any(), any(), any())(any()) } - "return the status with body, if etmp call returns any other status other than OK" in new Setup { - lazy val bank1: BankDetailsModel = generateLiabilityBankDetails - lazy val disp1: DisposeLiabilityReturn = disposeLiability1 - .copy(disposeLiability = Some(DisposeLiability(Some(LocalDate - .of(periodKey, month, date)), periodKey)), - bankDetails = Some(bank1), - calculated = Some(DisposeCalculated(BigDecimal(2500.00), BigDecimal(-500.00)))) - when(mockDisposeLiabilityReturnRepository - .fetchDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(Seq(disp1, disposeLiability2))) - when(mockDisposeLiabilityReturnRepository - .cacheDisposeLiabilityReturns(any[DisposeLiabilityReturn]())).thenReturn(Future.successful(DisposeLiabilityReturnCached)) - mockRetrievingNoAuthRef() - when(mockSubscriptionDataService - .retrieveSubscriptionData(any())(any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEtmpConnector - .submitEditedLiabilityReturns(ArgumentMatchers.eq(atedRefNo), any(), any())(any(), any())) - .thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, Json.parse("""{"reason": "Server error"}"""), Map.empty[String, Seq[String]]))) - val result: HttpResponse = await(testDisposeLiabilityReturnService.submitDisposeLiability(atedRefNo, formBundle1)) - result.status must be(INTERNAL_SERVER_ERROR) - verify(mockEmailConnector, times(0)).sendTemplatedEmail(any(), any(), any())(any()) - } - "return the status with body, if etmp call returns any other status other than OK (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val bank1: BankDetailsModel = generateLiabilityBankDetails lazy val disp1: DisposeLiabilityReturn = disposeLiability1 .copy(disposeLiability = Some(DisposeLiability(Some(LocalDate diff --git a/test/services/FormBundleServiceSpec.scala b/test/services/FormBundleServiceSpec.scala index 5ff8d68..deb6354 100644 --- a/test/services/FormBundleServiceSpec.scala +++ b/test/services/FormBundleServiceSpec.scala @@ -16,7 +16,7 @@ package services -import connectors.{EtmpReturnsConnector, HipReturnsConnector} +import connectors.HipReturnsConnector import org.mockito.ArgumentMatchers import org.mockito.Mockito._ import org.scalatest.BeforeAndAfterEach @@ -27,34 +27,25 @@ import play.api.libs.json.{JsValue, Json} import play.api.test.Helpers._ import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} class FormBundleServiceSpec extends PlaySpec with GuiceOneServerPerSuite with MockitoSugar with BeforeAndAfterEach { implicit val mockServicesConfig: ServicesConfig = mock[ServicesConfig] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] val atedRefNo = "ATED-123" val formBundle = "form-bundle-01" val successResponseJson: JsValue = Json.parse( """{"sapNumber":"1234567890", "safeId": "EX0012345678909", "agentReferenceNumber": "AARN1234567"}""") override def beforeEach(): Unit = { - reset(mockEtmpConnector) reset(mockHipConnector) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } trait Setup { class TestFormBundleService extends FormBundleService { implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global implicit val sc: ServicesConfig = mockServicesConfig - override val etmpReturnsConnector: EtmpReturnsConnector = mockEtmpConnector override val hipReturnsConnector: HipReturnsConnector = mockHipConnector } implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global @@ -63,18 +54,8 @@ class FormBundleServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mo "FormBundleService" must { "getFormBundleReturns" must { - "return response from connector" in new Setup { - implicit val hc: HeaderCarrier = HeaderCarrier() - when(mockEtmpConnector - .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - val response: Future[HttpResponse] = testFormBundleService.getFormBundleReturns(atedRefNo, formBundle) - await(response).status must be(OK) - } - "return response from connector (HIP)" in new Setup { implicit val hc: HeaderCarrier = HeaderCarrier() - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockHipConnector .getFormBundleReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(formBundle))(ArgumentMatchers.any(), ArgumentMatchers.any())) .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) @@ -83,5 +64,4 @@ class FormBundleServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mo } } } - -} +} \ No newline at end of file diff --git a/test/services/PropertyDetailsServiceSpec.scala b/test/services/PropertyDetailsServiceSpec.scala index 0cb4542..d246243 100644 --- a/test/services/PropertyDetailsServiceSpec.scala +++ b/test/services/PropertyDetailsServiceSpec.scala @@ -18,7 +18,7 @@ package services import builders.{AuthFunctionalityHelper, ChangeLiabilityReturnBuilder, PropertyDetailsBuilder} -import connectors.{EmailConnector, EmailSent, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, EmailSent, HipReturnsConnector} import models._ import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.any @@ -35,7 +35,6 @@ import uk.gov.hmrc.http.{BadRequestException, HeaderCarrier, HttpResponse, Inter import uk.gov.hmrc.play.audit.http.connector.AuditConnector import uk.gov.hmrc.play.audit.model.Audit import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import java.util.UUID import scala.concurrent.{ExecutionContext, Future} @@ -43,7 +42,6 @@ import scala.concurrent.{ExecutionContext, Future} class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with MockitoSugar with BeforeAndAfterEach with AuthFunctionalityHelper { val mockPropertyDetailsCache: PropertyDetailsMongoRepository = mock[PropertyDetailsMongoRepository] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] val mockAuthConnector: AuthConnector = mock[AuthConnector] val mockSubscriptionDataService: SubscriptionDataService = mock[SubscriptionDataService] @@ -58,7 +56,6 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global implicit val sc: ServicesConfig = mockServicesConfig override val propertyDetailsCache: PropertyDetailsMongoRepository = mockPropertyDetailsCache - override val etmpConnector: EtmpReturnsConnector = mockEtmpConnector override val hipConnector: HipReturnsConnector = mockHipConnector override val authConnector: AuthConnector = mockAuthConnector override val subscriptionDataService: SubscriptionDataService = mockSubscriptionDataService @@ -79,15 +76,9 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi override def beforeEach(): Unit = { reset(mockPropertyDetailsCache) reset(mockAuthConnector) - reset(mockEtmpConnector) reset(mockHipConnector) reset(mockSubscriptionDataService) reset(mockEmailConnector) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } val jsonEtmpResponse: String = @@ -366,7 +357,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi ).copy(calculated = None) val successResponse: JsValue = Json.parse(jsonEtmpResponse) - when(mockEtmpConnector.submitReturns( + when(mockHipConnector.submitReturns( ArgumentMatchers.eq(accountRef), ArgumentMatchers.any[SubmitEtmpReturnsRequest] )(ArgumentMatchers.any(), ArgumentMatchers.any()) @@ -894,24 +885,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi "Retrieve the Liability Amount for the PropertyDetails" must { - "Get the Liability Amount " in new Setup { - lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) - - val successResponse: JsValue = Json.parse(jsonEtmpResponse) - when(mockEtmpConnector.submitReturns( - ArgumentMatchers.eq(accountRef), - ArgumentMatchers.any[SubmitEtmpReturnsRequest] - )(ArgumentMatchers.any(), ArgumentMatchers.any()) - ).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result: Future[Option[BigDecimal]] = testPropertyDetailsService.getLiabilityAmount(accountRef, "1", propertyDetailsExample) - - val liabilityAmount: Option[BigDecimal] = await(result) - liabilityAmount must be(Some(999.99)) - } - "Get the Liability Amount (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) val successResponse: JsValue = Json.parse(jsonEtmpResponse) @@ -927,21 +901,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi liabilityAmount must be(Some(999.99)) } - "Return None if we have no Liability Amount " in new Setup { - lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) - - val successResponse: JsValue = Json.parse(jsonEtmpResponse) - when(mockEtmpConnector.submitReturns( - ArgumentMatchers.eq(accountRef), ArgumentMatchers.any[SubmitEtmpReturnsRequest])(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - val result: Future[Option[BigDecimal]] = testPropertyDetailsService.getLiabilityAmount(accountRef, "3", propertyDetailsExample) - - val liabilityAmount: Option[BigDecimal] = await(result) - liabilityAmount.isDefined must be(false) - } - "Return None if we have no Liability Amount (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) val successResponse: JsValue = Json.parse(jsonEtmpResponse) @@ -954,24 +914,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi liabilityAmount.isDefined must be(false) } - "Fail if we have BAD_REQUEST" in new Setup { - lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) - - val failureResponse: JsValue = Json.parse( """{ "reason": "Error"}""") - when(mockEtmpConnector.submitReturns( - ArgumentMatchers.eq(accountRef), - ArgumentMatchers.any[SubmitEtmpReturnsRequest] - )(ArgumentMatchers.any(), ArgumentMatchers.any()) - ).thenReturn(Future.successful(HttpResponse(BAD_REQUEST, failureResponse, Map.empty[String, Seq[String]]))) - - val result: Future[Option[BigDecimal]] = testPropertyDetailsService.getLiabilityAmount(accountRef, "3", propertyDetailsExample) - - val thrown: BadRequestException = the[BadRequestException] thrownBy await(result) - thrown.getMessage must include("Error") - } - "Fail if we have BAD_REQUEST (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) val failureResponse: JsValue = Json.parse( """{ "reason": "Error"}""") @@ -987,21 +930,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi thrown.getMessage must include("Error") } - "Fail if we have dont find Liability Amount" in new Setup { - lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) - - val failureResponse: JsValue = Json.parse( """{ "reason": "Error"}""") - when(mockEtmpConnector.submitReturns( - ArgumentMatchers.eq(accountRef), ArgumentMatchers.any[SubmitEtmpReturnsRequest])(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(INTERNAL_SERVER_ERROR, failureResponse, Map.empty[String, Seq[String]]))) - val result: Future[Option[BigDecimal]] = testPropertyDetailsService.getLiabilityAmount(accountRef, "3", propertyDetailsExample) - - val thrown: InternalServerException = the[InternalServerException] thrownBy await(result) - thrown.getMessage must include("No Liability Amount Found") - } - "Fail if we have dont find Liability Amount (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetailsExample: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) val failureResponse: JsValue = Json.parse( """{ "reason": "Error"}""") @@ -1014,22 +943,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi thrown.getMessage must include("No Liability Amount Found") } - "Fail if we have dont have valid details " in new Setup { - lazy val propertyDetailsPopulated: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) - val propertyDetailsExample: PropertyDetails = propertyDetailsPopulated.copy(period = None, calculated = None) - - val failureResponse: JsValue = Json.parse( """{ "reason": "Error"}""") - when(mockEtmpConnector.submitReturns( - ArgumentMatchers.eq(accountRef), ArgumentMatchers.any[SubmitEtmpReturnsRequest])(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(BAD_REQUEST, failureResponse, Map.empty[String, Seq[String]]))) - val thrown: InternalServerException = the[InternalServerException]thrownBy testPropertyDetailsService - .getLiabilityAmount(accountRef, "3", propertyDetailsExample) - - thrown.getMessage must include("Invalid Data for the request") - } - "Fail if we have dont have valid details (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetailsPopulated: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something better")) val propertyDetailsExample: PropertyDetails = propertyDetailsPopulated.copy(period = None, calculated = None) @@ -1045,39 +959,7 @@ class PropertyDetailsServiceSpec extends PlaySpec with GuiceOneServerPerSuite wi } "Submit the Property Details from the Cache" must { - "Submit the property details and delete the item from the cache if it's a valid id" in new Setup { - lazy val propertyDetails1: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something"), liabilityAmount = Some(BigDecimal(999.99))) - lazy val propertyDetails2: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("2", Some("something else")) - lazy val propertyDetails3: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("3", Some("something more")) - - val testEnrolments: Set[Enrolment] = Set(Enrolment("HMRC-ATED-ORG", Seq(EnrolmentIdentifier("AgentRefNumber", "XN1200000100001")), "activated")) - - val successResponse: JsValue = Json.parse(jsonEtmpResponse) - when(mockAuthConnector.authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockPropertyDetailsCache.fetchPropertyDetails(accountRef)) - .thenReturn(Future.successful(List(propertyDetails1, propertyDetails2, propertyDetails3))) - when(mockPropertyDetailsCache.deletePropertyDetailsByfieldName(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(PropertyDetailsDeleted)) - when(mockEtmpConnector.submitReturns(ArgumentMatchers.eq(accountRef), - ArgumentMatchers.any[SubmitEtmpReturnsRequest]())(ArgumentMatchers.any(), ArgumentMatchers.any())) thenReturn { - Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]])) - } - when(mockPropertyDetailsCache.cachePropertyDetails(ArgumentMatchers.any[PropertyDetails]())) - .thenReturn(Future.successful(PropertyDetailsCached)) - when(mockSubscriptionDataService.retrieveSubscriptionData( - ArgumentMatchers.any())(ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector.sendTemplatedEmail( - ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any())) thenReturn Future.successful(EmailSent) - - val result: Future[HttpResponse] = testPropertyDetailsService.submitDraftPropertyDetail(accountRef, "1") - await(result).status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any()) - } - "Submit the property details and delete the item from the cache if it's a valid id (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) lazy val propertyDetails1: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", Some("something"), liabilityAmount = Some(BigDecimal(999.99))) lazy val propertyDetails2: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("2", Some("something else")) lazy val propertyDetails3: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("3", Some("something more")) diff --git a/test/services/ReliefsServiceSpec.scala b/test/services/ReliefsServiceSpec.scala index 7b9289d..64fe0d2 100644 --- a/test/services/ReliefsServiceSpec.scala +++ b/test/services/ReliefsServiceSpec.scala @@ -17,7 +17,7 @@ package services import builders.{AuthFunctionalityHelper, ReliefBuilder} -import connectors.{EmailConnector, EmailSent, EtmpReturnsConnector, HipReturnsConnector} +import connectors.{EmailConnector, EmailSent, HipReturnsConnector} import models.{Reliefs, ReliefsTaxAvoidance, TaxAvoidance} import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.any @@ -32,7 +32,6 @@ import repository.{ReliefCached, ReliefDeleted, ReliefsMongoRepository} import uk.gov.hmrc.auth.core.{AuthConnector, Enrolment, EnrolmentIdentifier, Enrolments} import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} @@ -40,7 +39,6 @@ class ReliefsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mocki val mockReliefsCache: ReliefsMongoRepository = mock[ReliefsMongoRepository] implicit val mockServicesConfig: ServicesConfig = mock[ServicesConfig] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] val mockAuthConnector: AuthConnector = mock[AuthConnector] val mockSubscriptionDataService: SubscriptionDataService = mock[SubscriptionDataService] @@ -50,7 +48,6 @@ class ReliefsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mocki trait Setup { class TestReliefsService extends ReliefsService { override val reliefsCache: ReliefsMongoRepository = mockReliefsCache - override val etmpConnector: EtmpReturnsConnector = mockEtmpConnector override val hipConnector: HipReturnsConnector = mockHipConnector override val authConnector: AuthConnector = mockAuthConnector override val subscriptionDataService: SubscriptionDataService = mockSubscriptionDataService @@ -68,16 +65,10 @@ class ReliefsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mocki override def beforeEach(): Unit = { reset(mockReliefsCache) - reset(mockEtmpConnector) reset(mockHipConnector) reset(mockAuthConnector) reset(mockEmailConnector) reset(mockSubscriptionDataService) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } "ReliefsService" must { @@ -110,29 +101,8 @@ class ReliefsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mocki } "submit cached Reliefs" must { - - "work even if we have no reliefs found" in new Setup { - implicit val hc: HeaderCarrier = new HeaderCarrier() - - when(mockReliefsCache.fetchReliefs(ArgumentMatchers.any())).thenReturn(Future.successful(Seq())) - when(mockEtmpConnector.submitReturns(ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, ""))) - when(mockAuthConnector.authorise[Option[String]](any(), any())(any(), any())).thenReturn(Future.successful(Some("Name"))) - - when(mockReliefsCache.deleteReliefs(ArgumentMatchers.anyString())).thenReturn(Future.successful(ReliefDeleted)) - mockRetrievingNoAuthRef() - - when(mockSubscriptionDataService.retrieveSubscriptionData(ArgumentMatchers.any())(ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - - val result: Future[HttpResponse] = testReliefsService.submitAndDeleteDraftReliefs("accountRef", periodKey) - await(result).status must be(NOT_FOUND) - verify(mockEmailConnector, times(0)).sendTemplatedEmail(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any()) - } - "work even if we have no reliefs found (HIP)" in new Setup { implicit val hc: HeaderCarrier = new HeaderCarrier() - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockReliefsCache.fetchReliefs(ArgumentMatchers.any())).thenReturn(Future.successful(Seq())) when(mockHipConnector.submitReturns(ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())) .thenReturn(Future.successful(HttpResponse(OK, ""))) @@ -149,46 +119,9 @@ class ReliefsServiceSpec extends PlaySpec with GuiceOneServerPerSuite with Mocki verify(mockEmailConnector, times(0)).sendTemplatedEmail(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any()) } - "submit cached Reliefs and delete them if this submit works" in new Setup { - implicit val hc:HeaderCarrier = HeaderCarrier() - - val testEnrolments: Set[Enrolment] = Set(Enrolment("HMRC-ATED-ORG", Seq(EnrolmentIdentifier("AgentRefNumber", "XN1200000100001")), "activated")) - - val reliefs = new Reliefs(periodKey = periodKey, rentalBusiness = true, - openToPublic = true, - propertyDeveloper = true, - propertyTrading = true, - lending = true, - employeeOccupation = true, - farmHouses = true, - socialHousing = true) - - val taxAvoidance = new TaxAvoidance(rentalBusinessScheme = Some("Scheme123"), - socialHousingScheme = Some("Scheme789")) - - val reliefsTaxAvoidance: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(accountRef, periodKey, reliefs, taxAvoidance) - when(mockReliefsCache.fetchReliefs(ArgumentMatchers.any())).thenReturn(Future.successful(Seq(reliefsTaxAvoidance))) - when(mockReliefsCache.fetchReliefsByYear(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(Seq(reliefsTaxAvoidance))) - when(mockReliefsCache.cacheRelief(ArgumentMatchers.any())).thenReturn(Future.successful(ReliefCached)) - when(mockAuthConnector.authorise[Any](any(), any())(any(), any())) - .thenReturn(Future.successful(Enrolments(testEnrolments))) - when(mockSubscriptionDataService.retrieveSubscriptionData( - ArgumentMatchers.any())(ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, successResponseJson, Map.empty[String, Seq[String]]))) - when(mockEmailConnector.sendTemplatedEmail( - ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any())) thenReturn Future.successful(EmailSent) - when(mockReliefsCache.deleteDraftReliefByYear(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(Future.successful(ReliefDeleted)) - - val submitSuccess: JsValue = Json.parse( """{"status" : "OK", "processingDate" : "2014-12-17T09:30:47Z", "formBundleNumber" : "123456789012"}""") - when(mockEtmpConnector.submitReturns(ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, submitSuccess, Map.empty[String, Seq[String]]))) - val result: Future[HttpResponse] = testReliefsService.submitAndDeleteDraftReliefs("accountRef", periodKey) - await(result).status must be(OK) - verify(mockEmailConnector, times(1)).sendTemplatedEmail(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any()) - } - "submit cached Reliefs and delete them if this submit works (HIP)" in new Setup { implicit val hc:HeaderCarrier = HeaderCarrier() - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) + val testEnrolments: Set[Enrolment] = Set(Enrolment("HMRC-ATED-ORG", Seq(EnrolmentIdentifier("AgentRefNumber", "XN1200000100001")), "activated")) val reliefs = new Reliefs(periodKey = periodKey, rentalBusiness = true, diff --git a/test/services/ReturnSummaryServiceSpec.scala b/test/services/ReturnSummaryServiceSpec.scala index 7487613..04c4701 100644 --- a/test/services/ReturnSummaryServiceSpec.scala +++ b/test/services/ReturnSummaryServiceSpec.scala @@ -18,7 +18,7 @@ package services import builders.ChangeLiabilityReturnBuilder._ import builders._ -import connectors.{EtmpReturnsConnector, HipReturnsConnector} +import connectors.HipReturnsConnector import models._ import java.time.LocalDate @@ -32,14 +32,12 @@ import play.api.libs.json.{JsValue, Json} import play.api.test.Helpers._ import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with MockitoSugar with BeforeAndAfterEach { implicit val mockServicesConfig: ServicesConfig = mock[ServicesConfig] - val mockEtmpConnector: EtmpReturnsConnector = mock[EtmpReturnsConnector] val mockHipConnector: HipReturnsConnector = mock[HipReturnsConnector] val mockPropertyDetailsService: PropertyDetailsService = mock[PropertyDetailsService] val mockReliefsService: ReliefsService = mock[ReliefsService] @@ -59,21 +57,14 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with val disposeCalculated2: DisposeCalculated = DisposeCalculated(1000, 200) override def beforeEach(): Unit = { - reset(mockEtmpConnector) reset(mockHipConnector) reset(mockPropertyDetailsService) reset(mockReliefsService) reset(mockDisposeLiabilityReturnService) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } trait Setup { class TestReturnSummaryService extends ReturnSummaryService { - override val etmpConnector: EtmpReturnsConnector = mockEtmpConnector override val hipConnector: HipReturnsConnector = mockHipConnector override val propertyDetailsService: PropertyDetailsService = mockPropertyDetailsService override val reliefsService: ReliefsService = mockReliefsService @@ -128,46 +119,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with } "getFullSummaryReturn" must { - - "return SummaryReturnModel with drafts and submitted return when we only have new - from Mongo DB and ETMP" in new Setup { - - //TODO: if etmp reverts back to numeric, uncomment next line and comment next-to-next - //val etmpReturnJson = Json.toJson(etmpReturn) - val etmpReturnJson: JsValue = - Json.parse( - """ {"safeId":"123Safe","organisationName":"ACNE LTD.","periodData":[{"periodKey":"2014", - |"returnData":{"reliefReturnSummary":[{"formBundleNumber":"12345","dateOfSubmission":"2014-05-05","relief":"Farmhouses","reliefStartDate":"2014-09-05","reliefEndDate":"2014-10-05"}], - |"liabilityReturnSummary":[{"propertySummary":[{"contractObject":"abc","addressLine1":"line1","addressLine2":"line2", - |"return":[ - |{"formBundleNumber":"12345","dateOfSubmission":"2014-05-05","dateFrom":"2014-09-05","dateTo":"2014-10-05","liabilityAmount":"1000","paymentReference":"pay-123","changeAllowed":true} - |]}]}]}}],"atedBalance":"10000"} """.stripMargin) - val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) - val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) - val propDetails: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1") - val propDetailsSeq: Seq[PropertyDetails] = Seq(propDetails) - val dispLiab: Seq[DisposeLiabilityReturn] = Seq(disposeLiability1) - - val years = 6 - - val expected = SummaryReturnsModel(Some(10000), List(PeriodSummaryReturns(2015, List(DraftReturns(2015, "1", "addr1 addr2", None, "Liability")), None), - PeriodSummaryReturns(periodKey, List(DraftReturns(periodKey, "123456789012", "line1 line2", None, "Dispose_Liability")), - Some(SubmittedReturns(periodKey, List(SubmittedReliefReturns("12345", "Farmhouses", LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), LocalDate.of(2014, 5, 5), None, None)), - List(SubmittedLiabilityReturns("12345", "line1 line2", 1000, LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), LocalDate.of(2014, 5, 5), - changeAllowed = true, paymentReference = "pay-123"))))))) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, etmpReturnJson, Map.empty[String, Seq[String]]))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return SummaryReturnModel with drafts and submitted return when we only have new - from Mongo DB and ETMP (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) //TODO: if etmp reverts back to numeric, uncomment next line and comment next-to-next //val etmpReturnJson = Json.toJson(etmpReturn) val etmpReturnJson: JsValue = @@ -203,57 +155,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return SummaryReturnModel with drafts and submitted return when we have new and old returns - from Mongo DB and ETMP" in new Setup { - - //TODO: if etmp reverts back to numeric, uncomment next line and comment next-to-next - //val etmpReturnJson = Json.toJson(etmpReturn) - val etmpReturnJson: JsValue = - Json.parse( - """ {"safeId":"123Safe","organisationName":"ACNE LTD.","periodData":[{"periodKey":"2014", - |"returnData":{"reliefReturnSummary":[{"formBundleNumber":"12345","dateOfSubmission":"2014-05-05","relief":"Farmhouses","reliefStartDate":"2014-09-05","reliefEndDate":"2014-10-05"}], - |"liabilityReturnSummary":[{"propertySummary":[{"contractObject":"abc","addressLine1":"line1","addressLine2":"line2", - |"return":[ - |{"formBundleNumber":"12346","dateOfSubmission":"2014-05-05","dateFrom":"2014-09-05","dateTo":"2014-10-05","liabilityAmount":"1000","paymentReference":"pay-123","changeAllowed":true}, - |{"formBundleNumber":"12345","dateOfSubmission":"2014-01-01","dateFrom":"2014-09-05","dateTo":"2014-10-05","liabilityAmount":"1000","paymentReference":"pay-123","changeAllowed":false} - |]}]}]}}],"atedBalance":"10000"} """.stripMargin) - val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) - val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) - val propDetails: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1") - val propDetailsSeq: Seq[PropertyDetails] = Seq(propDetails) - val dispLiab: Seq[DisposeLiabilityReturn] = Seq(disposeLiability1) - - val years = 6 - - val expected = SummaryReturnsModel(Some(10000), - List( - PeriodSummaryReturns(2015, List(DraftReturns(2015, "1", "addr1 addr2", None, "Liability")), None), - PeriodSummaryReturns(periodKey, List(DraftReturns(periodKey, "123456789012", "line1 line2", None, "Dispose_Liability")), - Some(SubmittedReturns(periodKey, List(SubmittedReliefReturns("12345", "Farmhouses", LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), LocalDate.of(2014, 5, 5), None, None)), - List( - SubmittedLiabilityReturns("12346", "line1 line2", 1000, LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), LocalDate.of(2014, 5, 5), changeAllowed = true, paymentReference = "pay-123") - ), - List( - SubmittedLiabilityReturns("12345", "line1 line2", 1000, LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), LocalDate.of(2014, 1, 1), changeAllowed = false, paymentReference = "pay-123") - ) - ) - ) - ) - ) - ) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, etmpReturnJson, Map.empty[String, Seq[String]]))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return SummaryReturnModel with drafts and submitted return when we have new and old returns - from Mongo DB and ETMP (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) //TODO: if etmp reverts back to numeric, uncomment next line and comment next-to-next //val etmpReturnJson = Json.toJson(etmpReturn) val etmpReturnJson: JsValue = @@ -301,34 +203,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return SummaryReturnModel with drafts and submitted return - from Mongo DB and ETMP - no liability or draft" in new Setup { - - val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[{"periodKey":"2014","returnData":{}}],"atedBalance":"0"}""") - val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) - val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) - val propDetails: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1") - val propDetailsSeq: Seq[PropertyDetails] = Seq(propDetails) - val dispLiab: Seq[DisposeLiabilityReturn] = Seq(disposeLiability1) - - val years = 6 - - val expected: SummaryReturnsModel = SummaryReturnsModel(Some(0), List(PeriodSummaryReturns(2015, List(DraftReturns(2015, "1", "addr1 addr2", None, "Liability")), None), - PeriodSummaryReturns(periodKey, List(DraftReturns(periodKey, "123456789012", "line1 line2", None, "Dispose_Liability")), - Some(SubmittedReturns(periodKey, List(), List()))))) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, etmpReturnJson, Map.empty[String, Seq[String]]))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return SummaryReturnModel with drafts and submitted return - from Mongo DB and ETMP - no liability or draft (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[{"periodKey":"2014","returnData":{}}],"atedBalance":"0"}""") val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) @@ -353,35 +228,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return SummaryReturnModel with drafts and submitted return - from Mongo DB and ETMP - no liabliity amount in liabilty return" in new Setup { - - val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[{"periodKey":"2014","returnData":{"reliefReturnSummary":[{"formBundleNumber":"12345","dateOfSubmission":"2014-05-05","relief":"Farmhouses","reliefStartDate":"2014-09-05","reliefEndDate":"2014-10-05"}],"liabilityReturnSummary":[{}]}}],"atedBalance":"0"}""") - val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) - val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) - val propDetails: PropertyDetails = PropertyDetails(atedRefNo = "ated-ref-1", "123456789099", periodKey, addressProperty = PropertyDetailsBuilder.getPropertyDetailsAddress(None), calculated = None, formBundleReturn = Some(ChangeLiabilityReturnBuilder.generateFormBundleResponse(periodKey))) - val propDetailsSeq: Seq[PropertyDetails] = Seq(propDetails) - val dispLiab: Seq[DisposeLiabilityReturn] = Seq(disposeLiability2) - - val years = 6 - - val expected: SummaryReturnsModel = SummaryReturnsModel(Some(0), List(PeriodSummaryReturns(periodKey, List(DraftReturns(periodKey, "123456789099", "addr1 addr2", None, "Change_Liability"), - DraftReturns(periodKey, "123456789012", "line1 line2", Some(1000), "Dispose_Liability")), - Some(SubmittedReturns(periodKey, List(SubmittedReliefReturns("12345", "Farmhouses", LocalDate.of(2014, 9, 5), LocalDate.of(2014, 10, 5), - LocalDate.of(2014, 5, 5), None, None)), List()))))) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, etmpReturnJson, Map.empty[String, Seq[String]]))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return SummaryReturnModel with drafts and submitted return - from Mongo DB and ETMP - no liabliity amount in liabilty return (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[{"periodKey":"2014","returnData":{"reliefReturnSummary":[{"formBundleNumber":"12345","dateOfSubmission":"2014-05-05","relief":"Farmhouses","reliefStartDate":"2014-09-05","reliefEndDate":"2014-10-05"}],"liabilityReturnSummary":[{}]}}],"atedBalance":"0"}""") val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey) val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) @@ -407,32 +254,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return SummaryReturnModel with drafts but no ETMP data found - from Mongo DB " in new Setup { - - val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey, Reliefs(periodKey, rentalBusiness = true)) - val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) - val propDetails: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", liabilityAmount = Some(1000)) - val propDetailsSeq: Seq[PropertyDetails] = Seq(propDetails) - val dispLiab: Seq[DisposeLiabilityReturn] = Seq(disposeLiability1) - val years = 6 - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(NOT_FOUND, ""))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val expected: SummaryReturnsModel = SummaryReturnsModel(None, List(PeriodSummaryReturns(2015, List(DraftReturns(2015, "1", "addr1 addr2", Some(1000), "Liability")), None), - PeriodSummaryReturns(periodKey, List(DraftReturns(periodKey, "", "Rental businesses", None, "Relief"), - DraftReturns(periodKey, "123456789012", "line1 line2", None, "Dispose_Liability")), None))) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return SummaryReturnModel with drafts but no ETMP data found - from Mongo DB (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val relDraft: ReliefsTaxAvoidance = ReliefBuilder.reliefTaxAvoidance(atedRefNo, periodKey, Reliefs(periodKey, rentalBusiness = true)) val reliefDrafts: Seq[ReliefsTaxAvoidance] = Seq(relDraft) val propDetails: PropertyDetails = PropertyDetailsBuilder.getPropertyDetails("1", liabilityAmount = Some(1000)) @@ -455,27 +277,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return blank SummaryReturnModel no drafts and NO submitted ETMP return found, - for no matching period keys" in new Setup { - val reliefDrafts: Seq[Nothing] = Nil - val propDetailsSeq: Seq[Nothing] = Nil - val dispLiab: Seq[Nothing] = Nil - val years = 6 - - val expected: SummaryReturnsModel = SummaryReturnsModel(None, Nil) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(NOT_FOUND, ""))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return blank SummaryReturnModel no drafts and NO submitted ETMP return found, - for no matching period keys (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val reliefDrafts: Seq[Nothing] = Nil val propDetailsSeq: Seq[Nothing] = Nil val dispLiab: Seq[Nothing] = Nil @@ -494,27 +296,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return blank SummaryReturnModel no ETMP Return - internal server error" in new Setup { - val reliefDrafts: Seq[Nothing] = Nil - val propDetailsSeq: Seq[Nothing] = Nil - val dispLiab: Seq[Nothing] = Nil - val years = 6 - - val expected: SummaryReturnsModel = SummaryReturnsModel(None, Nil) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(BAD_REQUEST, ""))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return blank SummaryReturnModel no ETMP Return - internal server error (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val reliefDrafts: Seq[Nothing] = Nil val propDetailsSeq: Seq[Nothing] = Nil val dispLiab: Seq[Nothing] = Nil @@ -533,29 +315,7 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with await(result) must be(expected) } - "return blank SummaryReturnModel for no drafts but no matching period key" in new Setup { - val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[],"atedBalance":"0"}""") - val reliefDrafts: Seq[Nothing] = Nil - val propDetailsSeq: Seq[Nothing] = Nil - val dispLiab: Seq[Nothing] = Nil - val years = 6 - - val expected: SummaryReturnsModel = SummaryReturnsModel(None, Nil) - - when(mockEtmpConnector.getSummaryReturns(ArgumentMatchers.eq(atedRefNo), ArgumentMatchers.eq(years))(ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, etmpReturnJson, Map.empty[String, Seq[String]]))) - when(mockPropertyDetailsService.retrieveDraftPropertyDetails(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(propDetailsSeq)) - when(mockReliefsService.retrieveDraftReliefs(ArgumentMatchers.eq(atedRefNo))).thenReturn(Future.successful(reliefDrafts)) - - when(mockDisposeLiabilityReturnService.retrieveDraftDisposeLiabilityReturns(ArgumentMatchers.eq(atedRefNo))) - .thenReturn(Future.successful(dispLiab)) - - val result: Future[SummaryReturnsModel] = testReturnSummaryService.getFullSummaryReturns(atedRefNo) - await(result) must be(expected) - } - "return blank SummaryReturnModel for no drafts but no matching period key (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val etmpReturnJson: JsValue = Json.parse("""{"safeId":"123Safe","organisationName":"organisationName","periodData":[],"atedBalance":"0"}""") val reliefDrafts: Seq[Nothing] = Nil val propDetailsSeq: Seq[Nothing] = Nil @@ -783,4 +543,4 @@ class ReturnSummaryServiceSpec extends PlaySpec with GuiceOneServerPerSuite with returnTuple._2.find(_.formBundleNo == "2").isDefined must be (true) } } -} +} \ No newline at end of file diff --git a/test/services/SubscriptionDataServiceSpec.scala b/test/services/SubscriptionDataServiceSpec.scala index b304ca8..cc93fab 100644 --- a/test/services/SubscriptionDataServiceSpec.scala +++ b/test/services/SubscriptionDataServiceSpec.scala @@ -30,7 +30,6 @@ import play.api.test.Helpers._ import uk.gov.hmrc.auth.core.AuthConnector import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig -import utils.FeatureSwitch import scala.concurrent.{ExecutionContext, Future} @@ -60,30 +59,11 @@ class SubscriptionDataServiceSpec extends PlaySpec with GuiceOneServerPerSuite w reset(mockEtmpConnector) reset(mockHipConnector) reset(mockAuthConnector) - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) - } - - override def afterEach(): Unit = { - FeatureSwitch.disable(FeatureSwitch.apply("hipSwitch", false)) } "SubscriptionDataService" must { - - "retrieve Subscription Data" in new Setup { - implicit val hc: HeaderCarrier = HeaderCarrier() - when(mockEtmpConnector.getSubscriptionData(ArgumentMatchers.any())( - ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - - val result: Future[HttpResponse] = testSubscriptionDataService.retrieveSubscriptionData(accountRef) - - val response: HttpResponse = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - "retrieve Subscription Data (HIP)" in new Setup { implicit val hc: HeaderCarrier = HeaderCarrier() - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) when(mockHipConnector.getSubscriptionData(ArgumentMatchers.any())( ArgumentMatchers.any())).thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) @@ -97,25 +77,7 @@ class SubscriptionDataServiceSpec extends PlaySpec with GuiceOneServerPerSuite w "save account details" must { val successResponse = Json.parse( """{"processingDate": "2001-12-17T09:30:47Z"}""") - "work if we have valid data" in new Setup { - val addressDetails: AddressDetails = AddressDetails("Correspondence", "line1", "line2", None, None, Some("postCode"), "GB") - val updatedData: UpdateSubscriptionDataRequest = UpdateSubscriptionDataRequest( - emailConsent = true, ChangeIndicators(), List(Address(addressDetails = addressDetails)) - ) - implicit val hc:HeaderCarrier = HeaderCarrier() - - when(mockEtmpConnector.updateSubscriptionData( - ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any())) - .thenReturn(Future.successful(HttpResponse(OK, successResponse, Map.empty[String, Seq[String]]))) - mockRetrievingNoAuthRef() - val result: Future[HttpResponse] = testSubscriptionDataService.updateSubscriptionData(accountRef, updatedData) - val response: HttpResponse = await(result) - response.status must be(OK) - response.json must be(successResponse) - } - "work if we have valid data (HIP)" in new Setup { - FeatureSwitch.enable(FeatureSwitch.apply("hipSwitch", true)) val addressDetails: AddressDetails = AddressDetails("Correspondence", "line1", "line2", None, None, Some("postCode"), "GB") val updatedData: UpdateSubscriptionDataRequest = UpdateSubscriptionDataRequest( emailConsent = true, ChangeIndicators(), List(Address(addressDetails = addressDetails)) @@ -154,4 +116,4 @@ class SubscriptionDataServiceSpec extends PlaySpec with GuiceOneServerPerSuite w } } } -} +} \ No newline at end of file diff --git a/test/utils/FeatureSwitchSpec.scala b/test/utils/FeatureSwitchSpec.scala deleted file mode 100644 index cdf4d8f..0000000 --- a/test/utils/FeatureSwitchSpec.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2026 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package utils - -import org.scalatestplus.play.PlaySpec - -import scala.io.Source -import scala.util.Using - -class FeatureSwitchSpec extends PlaySpec { - - "HIP Switch feature flag should be true by default" in { - val applicationConfFileContents = Using.resource(Source.fromFile("conf/application.conf")) { source => source.getLines().mkString("") } - val hipSwitchFlagSetToTrue = applicationConfFileContents.contains("feature.hipSwitch = true") - - withClue("HIP Switch feature flag should be true by default in application.conf:") { - hipSwitchFlagSetToTrue mustBe true - } - } -} -