Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GFORMS-3083 - Improve on the feature draftRetrievalMethod so that it … #1270

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions app/uk/gov/hmrc/gform/form/FormService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import uk.gov.hmrc.gform.formtemplate.FormTemplateAlgebra
import uk.gov.hmrc.gform.logging.Loggers
import uk.gov.hmrc.gform.objectstore.ObjectStoreAlgebra
import uk.gov.hmrc.gform.save4later.FormPersistenceAlgebra
import uk.gov.hmrc.gform.sharedmodel.form.{ FormStatus, _ }
import uk.gov.hmrc.gform.sharedmodel.formtemplate.{ BySubmissionReference, FormAccessCodeForAgents, FormComponentId, FormTemplate, FormTemplateId }
import uk.gov.hmrc.gform.sharedmodel.form._
import uk.gov.hmrc.gform.sharedmodel.formtemplate.{ BySubmissionReference, DraftRetrievalMethod, FormAccessCode, FormAccessCodeForAgents, FormComponentId, FormTemplate, FormTemplateId }
import uk.gov.hmrc.gform.sharedmodel.{ AccessCode, SubmissionRef, UserId }
import uk.gov.hmrc.gform.time.TimeProvider
import uk.gov.hmrc.http.HeaderCarrier
Expand Down Expand Up @@ -85,18 +85,24 @@ class FormService[F[_]: Monad](
affinityGroup: Option[AffinityGroup]
): FormIdData = {
val formTemplateId = formTemplate._id
(formTemplate.draftRetrievalMethod, affinityGroup) match {

case (BySubmissionReference, _) =>
val submissionRef = SubmissionRef(envelopeId)
FormIdData.WithAccessCode(userId, formTemplateId, AccessCode(submissionRef.value))
def checkDraftRetrievalMethod(draftRetrievalMethod: DraftRetrievalMethod) =
(draftRetrievalMethod, affinityGroup) match {
case (BySubmissionReference, _) =>
val submissionRef = SubmissionRef(envelopeId)
FormIdData.WithAccessCode(userId, formTemplateId, AccessCode(submissionRef.value))

case (FormAccessCodeForAgents(_), Some(AffinityGroup.Agent)) =>
val ac = AccessCode.random
FormIdData.WithAccessCode(userId, formTemplateId, ac)
case (FormAccessCodeForAgents(_), Some(AffinityGroup.Agent)) | (FormAccessCode(_), _) =>
val ac = AccessCode.random
FormIdData.WithAccessCode(userId, formTemplateId, ac)

case _ => FormIdData.Plain(userId, formTemplateId)
}
case _ => FormIdData.Plain(userId, formTemplateId)
}

formTemplate.draftRetrieval
.flatMap(dr => affinityGroup.flatMap(ag => dr.mapping.get(ag)))
.collect { case drm => checkDraftRetrievalMethod(drm) }
.getOrElse(checkDraftRetrievalMethod(formTemplate.draftRetrievalMethod))
}

def create(
Expand Down
18 changes: 17 additions & 1 deletion app/uk/gov/hmrc/gform/formtemplate/FormTemplateValidator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import uk.gov.hmrc.gform.sharedmodel.DataRetrieve.Attribute
import uk.gov.hmrc.gform.sharedmodel._
import uk.gov.hmrc.gform.sharedmodel.formtemplate.Dynamic.DataRetrieveBased
import uk.gov.hmrc.gform.sharedmodel.formtemplate.InternalLink.PageLink
import uk.gov.hmrc.gform.sharedmodel.formtemplate._
import uk.gov.hmrc.gform.sharedmodel.formtemplate.{ BySubmissionReference, _ }
import uk.gov.hmrc.gform.sharedmodel.graph.DependencyGraph._

import java.time.LocalDate
Expand Down Expand Up @@ -1401,6 +1401,22 @@ object FormTemplateValidator {
isATLChoiceOptionsValid.combineAll
}

def validateDraftRetrieval(formTemplate: FormTemplate): ValidationResult =
formTemplate.draftRetrieval
.flatMap { dr =>
dr.mapping
.get(AffinityGroup.Agent)
.collect { case BySubmissionReference =>
Invalid("The draft retrieve method 'submissionReference' is invalid for the user type 'agent'")
}
.orElse {
dr.mapping.get(AffinityGroup.Individual).collect { case FormAccessCode(_) =>
Invalid("The draft retrieve method 'accessCode' is invalid for the user type 'individual'")
}
}
}
.getOrElse(Valid)

def validateIncludeIfForTaskStatus(sections: List[Section]): ValidationResult = {
val allTaskStatus = uk.gov.hmrc.gform.sharedmodel.form.TaskStatus.statuses.map(_.asString)
def validateTaskStatus(booleanExpr: BooleanExpr, location: String): ValidationResult = {
Expand Down
1 change: 1 addition & 0 deletions app/uk/gov/hmrc/gform/formtemplate/Verifier.scala
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ trait Verifier {
_ <- fromOptA(FormTemplateValidator.validateChoiceFormCtxOptionValues(pages, formTemplate).toEither)
_ <- fromOptA(FormTemplateValidator.validateUniqueTaskIds(formTemplate).toEither)
_ <- fromOptA(FormTemplateValidator.validateIncludeIfForTaskStatus(sections).toEither)
_ <- fromOptA(FormTemplateValidator.validateDraftRetrieval(formTemplate).toEither)
_ <- fromOptA(DestinationsValidator.validateUniqueDestinationIds(formTemplate.destinations).toEither)
_ <- fromOptA(DestinationsValidator.validateNoGroupInDeclaration(formTemplate.destinations).toEither)
_ <- fromOptA(DestinationsValidator.validateDestinationIncludeIfs(formTemplate.destinations).toEither)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* 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 uk.gov.hmrc.gform.sharedmodel.formtemplate

import cats.implicits.catsSyntaxEq
import play.api.libs.json._
import uk.gov.hmrc.gform.sharedmodel.AffinityGroup

case class DraftRetrieval(mapping: Map[AffinityGroup, DraftRetrievalMethod])

object DraftRetrieval {
val readsDraftRetrievalMethod: Reads[DraftRetrievalMethod] = Reads { json =>
(json \ "method", json \ "showContinueOrDeletePage") match {
case (JsDefined(JsString(field)), JsDefined(JsBoolean(bool))) =>
DraftRetrievalMethod.Helper(field, bool).toDraftRetrieval
case (JsDefined(JsString(field)), _) =>
if (field === "submissionReference") {
DraftRetrievalMethod.Helper(field, true).toDraftRetrieval
} else {
DraftRetrievalMethod.Helper(field, false).toDraftRetrieval
}
case (method, showContinueOrDeletePage) =>
JsError(
s"Failure, $method and $showContinueOrDeletePage are invalid in combination with DraftRetrieval"
)
}
}

implicit val formatDraftRetrievalMethod: OFormat[DraftRetrievalMethod] = OFormatWithTemplateReadFallback(
readsDraftRetrievalMethod
)

def reads: Reads[DraftRetrieval] = Reads { json =>
for {
a <- (json \ "agent").validateOpt[DraftRetrievalMethod].map(_.map(AffinityGroup.Agent -> _))
i <- (json \ "individual").validateOpt[DraftRetrievalMethod].map(_.map(AffinityGroup.Individual -> _))
o <- (json \ "organisation").validateOpt[DraftRetrievalMethod].map(_.map(AffinityGroup.Organisation -> _))
} yield DraftRetrieval(mapping = (a ++ i ++ o).toMap)
}

val writes: Writes[DraftRetrieval] = Writes { draftRetrieval =>
Json
.obj(
"agent" -> draftRetrieval.mapping.get(AffinityGroup.Agent),
"individual" -> draftRetrieval.mapping.get(AffinityGroup.Individual),
"organisation" -> draftRetrieval.mapping.get(AffinityGroup.Organisation)
)
.fields
.filterNot { case (_, value) => value == JsNull }
.foldLeft(Json.obj()) { case (acc, (key, value)) =>
acc + (key -> value)
}
}

implicit val format: Format[DraftRetrieval] = Format[DraftRetrieval](reads, writes)
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,26 @@

package uk.gov.hmrc.gform.sharedmodel.formtemplate

import cats.Eq
import play.api.libs.json._

sealed trait DraftRetrievalMethod

case class OnePerUser(continueOrDeletePage: ContinueOrDeletePage) extends DraftRetrievalMethod
case class FormAccessCodeForAgents(continueOrDeletePage: ContinueOrDeletePage) extends DraftRetrievalMethod
case object BySubmissionReference extends DraftRetrievalMethod
case class FormAccessCode(continueOrDeletePage: ContinueOrDeletePage) extends DraftRetrievalMethod

case object NotPermitted extends DraftRetrievalMethod

object DraftRetrievalMethod {
private case class Helper(value: String, showContinueOrDeletePage: Boolean) {
private[formtemplate] case class Helper(value: String, showContinueOrDeletePage: Boolean) {
def toDraftRetrievalMethod: JsResult[DraftRetrievalMethod] = (value, showContinueOrDeletePage) match {
case ("onePerUser", conOrDel) => JsSuccess(OnePerUser(ContinueOrDeletePage.fromBoolean(conOrDel)))
case ("formAccessCodeForAgents", conOrDel) =>
JsSuccess(FormAccessCodeForAgents(ContinueOrDeletePage.fromBoolean(conOrDel)))
case ("accessCode", conOrDel) =>
JsSuccess(FormAccessCode(ContinueOrDeletePage.fromBoolean(conOrDel)))
case ("notPermitted", _) => JsSuccess(NotPermitted)
case ("submissionReference", true) => JsSuccess(BySubmissionReference)
case ("submissionReference", false) =>
Expand All @@ -43,8 +47,24 @@ object DraftRetrievalMethod {
s"only three values are allowed for draftRetrievalMethod: either onePerUser, submissionReference or formAccessCodeForAgents; $err is not valid"
)
}

def toDraftRetrieval: JsResult[DraftRetrievalMethod] = (value, showContinueOrDeletePage) match {
case ("onePerUser", conOrDel) => JsSuccess(OnePerUser(ContinueOrDeletePage.fromBoolean(conOrDel)))
case ("accessCode", conOrDel) =>
JsSuccess(FormAccessCode(ContinueOrDeletePage.fromBoolean(conOrDel)))
case ("notPermitted", _) => JsSuccess(NotPermitted)
case ("submissionReference", true) => JsSuccess(BySubmissionReference)
case ("submissionReference", false) =>
JsError(
"Failure, showContinueOrDeletePage is invalid in combination with 'draftRetrieval: submissionReference'"
)
case (err, _) =>
JsError(
s"only three values are allowed for draftRetrieval: either onePerUser, submissionReference or accessCode; $err is not valid"
)
}
}
private object Helper {
private[formtemplate] object Helper {
val reads = Json.reads[Helper]
}

Expand All @@ -53,4 +73,5 @@ object DraftRetrievalMethod {
}

implicit val format: OFormat[DraftRetrievalMethod] = OFormatWithTemplateReadFallback(templateReads)
implicit val equal: Eq[DraftRetrievalMethod] = Eq.fromUniversalEquals
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ case class FormTemplate(
developmentPhase: Option[DevelopmentPhase],
formCategory: FormCategory,
draftRetrievalMethod: DraftRetrievalMethod,
draftRetrieval: Option[DraftRetrieval],
destinations: Destinations,
authConfig: formtemplate.AuthConfig,
emailTemplateId: Option[LocalisedEmailTemplateId],
Expand Down
51 changes: 51 additions & 0 deletions conf/formTemplateSchema.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@
"type": "string",
"pattern": "^(formAccessCodeForAgents|notPermitted|onePerUser)$"
},
"draftRetrieval": {
"$ref": "#/$defs/draftRetrievalObject"
},
"showContinueOrDeletePage": {
"type": "boolean"
},
Expand Down Expand Up @@ -1660,6 +1663,54 @@
}
]
}
},
"draftRetrievalObject": {
"type": "object",
"additionalProperties": false,
"properties": {
"agent": {
"type": "object",
"properties": {
"method": {
"type": "string",
"pattern": "^(accessCode|notPermitted|onePerUser|submissionReference)$"
},
"showContinueOrDeletePage": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": ["method"]
},
"individual": {
"type": "object",
"properties": {
"method": {
"type": "string",
"pattern": "^(accessCode|notPermitted|onePerUser|submissionReference)$"
},
"showContinueOrDeletePage": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": ["method"]
},
"organisation": {
"type": "object",
"properties": {
"method": {
"type": "string",
"pattern": "^(accessCode|notPermitted|onePerUser|submissionReference)$"
},
"showContinueOrDeletePage": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": ["method"]
}
}
}
}
}
1 change: 1 addition & 0 deletions test/uk/gov/hmrc/gform/core/parsers/ValueParserSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ class ValueParserSpec extends Spec with TableDrivenPropertyChecks {
Some(ResearchBanner),
Default,
OnePerUser(ContinueOrDeletePage.Show),
None,
Destinations
.DestinationList(
NonEmptyList.of(
Expand Down
1 change: 1 addition & 0 deletions test/uk/gov/hmrc/gform/sharedmodel/ExampleData.scala
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ trait ExampleFormTemplate {
Some(ResearchBanner),
Default,
OnePerUser(ContinueOrDeletePage.Show),
None,
destinationList,
authConfig,
emailTemplateId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import cats.data.NonEmptyList
import org.scalacheck.Gen
import uk.gov.hmrc.gform.config.FileInfoConfig
import uk.gov.hmrc.gform.sharedmodel.email.LocalisedEmailTemplateId
import uk.gov.hmrc.gform.sharedmodel.{ AvailableLanguages, LocalisedString }
import uk.gov.hmrc.gform.sharedmodel.{ AffinityGroup, AvailableLanguages, LocalisedString }
import uk.gov.hmrc.gform.sharedmodel.formtemplate._

trait FormTemplateGen {
Expand All @@ -43,6 +43,20 @@ trait FormTemplateGen {
)
} yield draftRetrievalMethod

def draftRetrievalGen: Gen[DraftRetrieval] =
for {
affinityGroup <- Gen.oneOf(List(AffinityGroup.Individual, AffinityGroup.Agent, AffinityGroup.Organisation))
continueOrDeletePage <- ContinueOrDeletePageGen.continueOrDeletePageGen
draftRetrievalMethod <-
Gen
.oneOf(
OnePerUser(continueOrDeletePage),
FormAccessCode(continueOrDeletePage),
BySubmissionReference,
NotPermitted
)
} yield DraftRetrieval(mapping = Map(affinityGroup -> draftRetrievalMethod))

def emailTemplateIdGen: Gen[Option[LocalisedEmailTemplateId]] =
Gen.option(LocalisedEmailTemplateIdGen.localisedEmailTemplateIdGen)

Expand Down Expand Up @@ -93,6 +107,7 @@ trait FormTemplateGen {
developmentPhase <- Gen.option(developmentPhaseGen)
category <- formCategoryGen
draftRetrievalMethod <- draftRetrievalMethodGen
draftRetrieval <- Gen.option(draftRetrievalGen)
destinations <- DestinationsGen.destinationsGen
authConfig <- AuthConfigGen.authConfigGen
emailTemplateId <- emailTemplateIdGen
Expand All @@ -118,6 +133,7 @@ trait FormTemplateGen {
developmentPhase,
category,
draftRetrievalMethod,
draftRetrieval,
destinations,
authConfig,
emailTemplateId,
Expand Down