Skip to content

Commit

Permalink
Merge CTUTR addition
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjwwalker authored and Thomas Stacey committed May 4, 2017
2 parents e8404f3 + 5c30569 commit 09d6c91
Show file tree
Hide file tree
Showing 10 changed files with 786 additions and 58 deletions.
8 changes: 7 additions & 1 deletion app/audit/DesSubmissionAuditEventDetail.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import uk.gov.hmrc.play.http.HeaderCarrier
case class DesSubmissionAuditEventDetail(externalId: String,
authProviderId: String,
regId: String,
ctutr: Option[String],
desSubmissionState: String,
jsSubmission: JsObject)

Expand All @@ -32,13 +33,18 @@ object DesSubmissionAuditEventDetail {
implicit val writes = new Writes[DesSubmissionAuditEventDetail] {
def writes(detail: DesSubmissionAuditEventDetail) = {
val regMetadata = Json.obj("businessType" -> "Limited company")
val ctutrTuple = detail.ctutr map( utr =>
Json.obj("ctutr" -> utr)
)

Json.obj(
val event = Json.obj(
EXTERNAL_ID -> detail.externalId,
AUTH_PROVIDER_ID -> detail.authProviderId,
JOURNEY_ID -> detail.regId,
DES_SUBMISSION_STATE -> detail.desSubmissionState
) ++ detail.jsSubmission

if(ctutrTuple.isDefined) event ++ ctutrTuple.get else event
}
}
}
Expand Down
53 changes: 53 additions & 0 deletions app/connectors/CompanyRegistrationConnector.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2017 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 javax.inject.{Inject, Singleton}

import config.WSHttp
import play.api.Logger
import uk.gov.hmrc.play.config.ServicesConfig
import uk.gov.hmrc.play.http.ws.WSHttp
import uk.gov.hmrc.play.http.{ForbiddenException, HeaderCarrier, HttpResponse, NotFoundException}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

@Singleton
class CompanyRegistrationConnector @Inject()() extends CompanyRegistrationConnect with ServicesConfig{
val compRegUrl = baseUrl("company-registration")
val http: WSHttp = WSHttp
}

trait CompanyRegistrationConnect {
val compRegUrl: String
val http: WSHttp

def fetchCompanyRegistrationDocument(regId: String)(implicit hc: HeaderCarrier): Future[HttpResponse] = {
http.GET[HttpResponse](s"$compRegUrl/company-registration/corporation-tax-registration/$regId/corporation-tax-registration") recover {
case e: NotFoundException =>
Logger.error(s"[CompanyRegistrationConnector] - [fetchCompanyRegistrationDocument] : Received a NotFound status code when expecting reg document from Company-Registration")
throw e
case e: ForbiddenException =>
Logger.error(s"[CompanyRegistrationConnector] - [fetchCompanyRegistrationDocument] : Received a Forbidden status code when expecting reg document from Company-Registration")
throw e
case e: Exception =>
Logger.error(s"[CompanyRegistrationConnector] - [fetchCompanyRegistrationDocument] : Received error when expecting reg document from Company-Registration - Error ${e.getMessage}")
throw e
}
}
}
61 changes: 39 additions & 22 deletions app/services/SubmissionService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import common.exceptions.DBExceptions.MissingRegDocument
import common.exceptions.RegistrationExceptions._
import common.exceptions.SubmissionExceptions._
import config.MicroserviceAuditConnector
import connectors.{AuthConnect, AuthConnector, BusinessRegistrationConnect, BusinessRegistrationConnector, DESConnect, DESConnector, IncorporationInformationConnect, IncorporationInformationConnector}
import connectors._
import enums.PAYEStatus
import models._
import models.incorporation.IncorpStatusUpdate
Expand All @@ -38,6 +38,7 @@ import uk.gov.hmrc.play.http.HeaderCarrier

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success, Try}
import scala.util.control.NoStackTrace

class RejectedIncorporationException(msg: String) extends NoStackTrace {
Expand All @@ -50,14 +51,16 @@ class SubmissionService @Inject()(injSequenceMongoRepository: SequenceMongo,
injDESConnector: DESConnector,
injIncorprorationInformationConnector: IncorporationInformationConnector,
injAuthConnector: AuthConnector,
injBusinessRegistrationConnector: BusinessRegistrationConnector) extends SubmissionSrv {
injBusinessRegistrationConnector: BusinessRegistrationConnector,
injCompanyRegistrationConnector: CompanyRegistrationConnector) extends SubmissionSrv {
val sequenceRepository = injSequenceMongoRepository.store
val registrationRepository = injRegistrationMongoRepository.store
val desConnector = injDESConnector
val incorporationInformationConnector = injIncorprorationInformationConnector
val authConnector = injAuthConnector
val auditConnector = MicroserviceAuditConnector
val businessRegistrationConnector = injBusinessRegistrationConnector
val companyRegistrationConnector = injCompanyRegistrationConnector
}

trait SubmissionSrv {
Expand All @@ -69,27 +72,30 @@ trait SubmissionSrv {
val authConnector: AuthConnect
val auditConnector: AuditConnector
val businessRegistrationConnector: BusinessRegistrationConnect
val companyRegistrationConnector: CompanyRegistrationConnect

private val REGIME = "paye"
private val SUBSCRIBER = "SCRS"
private val rejected = "rejected"

def submitToDes(regId: String)(implicit hc: HeaderCarrier, req: Request[AnyContent]): Future[String] = {
for {
ackRef <- assertOrGenerateAcknowledgementReference(regId)
incUpdate <- getIncorporationUpdate(regId) recover {
case ex: RejectedIncorporationException =>
updatePAYERegistrationDocument(regId, PAYEStatus.cancelled)
throw ex
}
submission <- buildADesSubmission(regId, incUpdate)
_ <- desConnector.submitToDES(submission)
_ <- auditDESSubmission(regId, incUpdate.fold("partial")(_ => "full"), Json.toJson[DESSubmission](submission).as[JsObject])
updatedStatus = incUpdate.fold(PAYEStatus.held)(_ => PAYEStatus.submitted)
_ <- updatePAYERegistrationDocument(regId, updatedStatus)
ackRef <- assertOrGenerateAcknowledgementReference(regId)
incUpdate <- getIncorporationUpdate(regId) recover {
case ex: RejectedIncorporationException =>
updatePAYERegistrationDocument(regId, PAYEStatus.cancelled)
throw ex
}
ctutr <- incUpdate.fold[Future[Option[String]]](Future.successful(None))(_ => fetchCtUtr(regId))
submission <- buildADesSubmission(regId, incUpdate, ctutr)
_ <- desConnector.submitToDES(submission)
_ <- auditDESSubmission(regId, incUpdate.fold("partial")(_ => "full"), Json.toJson[DESSubmission](submission).as[JsObject], ctutr)
updatedStatus = incUpdate.fold(PAYEStatus.held)(_ => PAYEStatus.submitted)
_ <- updatePAYERegistrationDocument(regId, updatedStatus)
} yield ackRef
}


def submitTopUpToDES(regId: String, incorpStatusUpdate: IncorpStatusUpdate)(implicit hc: HeaderCarrier): Future[PAYEStatus.Value] = {
for {
desSubmission <- buildTopUpDESSubmission(regId, incorpStatusUpdate)
Expand Down Expand Up @@ -126,15 +132,15 @@ trait SubmissionSrv {
.map(ref => f"BRPY$ref%011d")
}

private[services] def buildADesSubmission(regId: String, incorpStatusUpdate: Option[IncorpStatusUpdate])(implicit hc: HeaderCarrier): Future[DESSubmissionModel] = {
private[services] def buildADesSubmission(regId: String, incorpStatusUpdate: Option[IncorpStatusUpdate], ctutr: Option[String])(implicit hc: HeaderCarrier): Future[DESSubmissionModel] = {
registrationRepository.retrieveRegistration(regId) flatMap {
case Some(payeReg) if payeReg.status == PAYEStatus.draft => incorpStatusUpdate match {
case Some(statusUpdate) =>
Logger.info("[SubmissionService] - [buildPartialOrFullDesSubmission]: building a full DES submission")
payeReg2DESSubmission(payeReg, DateTime.now(DateTimeZone.UTC), statusUpdate.crn)
payeReg2DESSubmission(payeReg, DateTime.now(DateTimeZone.UTC), statusUpdate.crn, ctutr)
case None =>
Logger.info("[SubmissionService] - [buildPartialOrFullDesSubmission]: building a partial DES submission")
payeReg2DESSubmission(payeReg, DateTime.now(DateTimeZone.UTC), None)
payeReg2DESSubmission(payeReg, DateTime.now(DateTimeZone.UTC), None, ctutr)
}
case Some(payeReg) if payeReg.status == PAYEStatus.invalid => throw new InvalidRegistrationException(regId)
case None =>
Expand Down Expand Up @@ -165,7 +171,8 @@ trait SubmissionSrv {
}
}

private[services] def payeReg2DESSubmission(payeReg: PAYERegistration, timestamp: DateTime, incorpUpdateCrn: Option[String])(implicit hc: HeaderCarrier): Future[DESSubmissionModel] = {
private[services] def payeReg2DESSubmission(payeReg: PAYERegistration, timestamp: DateTime, incorpUpdateCrn: Option[String], ctutr: Option[String])
(implicit hc: HeaderCarrier): Future[DESSubmissionModel] = {
val companyDetails = payeReg.companyDetails.getOrElse {
throw new CompanyDetailsNotDefinedException
}
Expand All @@ -180,7 +187,7 @@ trait SubmissionSrv {
DESSubmissionModel(
acknowledgementReference = ackRef,
metaData = desMetaData,
limitedCompany = buildDESLimitedCompany(companyDetails, payeReg.sicCodes, incorpUpdateCrn, payeReg.directors, payeReg.employment),
limitedCompany = buildDESLimitedCompany(companyDetails, payeReg.sicCodes, incorpUpdateCrn, payeReg.directors, payeReg.employment, ctutr),
employingPeople = buildDESEmployingPeople(payeReg.registrationID, payeReg.employment, payeReg.payeContact)
)
}
Expand Down Expand Up @@ -232,9 +239,10 @@ trait SubmissionSrv {
sicCodes: Seq[SICCode],
incorpUpdateCrn: Option[String],
directors: Seq[Director],
employment: Option[Employment]): DESLimitedCompany = {
employment: Option[Employment],
ctutr: Option[String]): DESLimitedCompany = {
DESLimitedCompany(
companyUTR = None,
companyUTR = ctutr,
companiesHouseCompanyName = companyDetails.companyName,
nameOfBusiness = companyDetails.tradingName,
businessAddress = companyDetails.ppobAddress,
Expand All @@ -261,13 +269,13 @@ trait SubmissionSrv {
)
}

private[services] def auditDESSubmission(regId: String, desSubmissionState: String, jsSubmission: JsObject)(implicit hc: HeaderCarrier, req: Request[AnyContent]) = {
private[services] def auditDESSubmission(regId: String, desSubmissionState: String, jsSubmission: JsObject, ctutr: Option[String])(implicit hc: HeaderCarrier, req: Request[AnyContent]) = {
for {
authority <- authConnector.getCurrentAuthority
userDetails <- authConnector.getUserDetails
authProviderId = userDetails.get.authProviderId
} yield {
val event = new DesSubmissionEvent(DesSubmissionAuditEventDetail(authority.get.ids.externalId, authProviderId, regId, desSubmissionState, jsSubmission))
val event = new DesSubmissionEvent(DesSubmissionAuditEventDetail(authority.get.ids.externalId, authProviderId, regId, ctutr, desSubmissionState, jsSubmission))
auditConnector.sendEvent(event)
}
}
Expand Down Expand Up @@ -298,4 +306,13 @@ trait SubmissionSrv {
val s = hc.headers.collect{case ("X-Session-ID", x) => x}
if( s.nonEmpty ) s.head else throw new SessionIDNotExists
}

private[services] def fetchCtUtr(regId: String)(implicit hc: HeaderCarrier): Future[Option[String]] = {
companyRegistrationConnector.fetchCompanyRegistrationDocument(regId) map { response =>
Try((response.json \ "acknowledgementReferences" \ "ctUtr").as[String]) match {
case Success(ctutr) => Some(ctutr)
case Failure(_) => None
}
}
}
}
5 changes: 5 additions & 0 deletions conf/application.conf
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,11 @@ microservice {
port = 9660
}

company-registration {
host = localhost
port = 9973
}

paye-registration {
host = localhost
port = 9873
Expand Down
Loading

0 comments on commit 09d6c91

Please sign in to comment.