Skip to content

Commit

Permalink
TDRD-162 Allow user to re-select metadata entry method (#3823)
Browse files Browse the repository at this point in the history
  • Loading branch information
thanhz authored Apr 4, 2024
1 parent bc19da9 commit 00b23c4
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 33 deletions.
21 changes: 16 additions & 5 deletions app/controllers/AdditionalMetadataEntryMethodController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package controllers

import auth.TokenSecurity
import configuration.{ApplicationConfig, KeycloakConfiguration}
import graphql.codegen.types.ConsignmentStatusInput
import org.pac4j.play.scala.SecurityComponents
import play.api.data.Form
import play.api.data.Forms.{mapping, optional, text}
import play.api.i18n.I18nSupport
import play.api.mvc.{Action, AnyContent, Request, Result}
import services.Statuses.InProgressValue
import services.Statuses.{DraftMetadataType, InProgressValue}
import services._
import viewsapi.Caching.preventCaching

Expand Down Expand Up @@ -46,14 +47,15 @@ class AdditionalMetadataEntryMethodController @Inject() (
}

def submitAdditionalMetadataEntryMethod(consignmentId: UUID): Action[AnyContent] = standardTypeAction(consignmentId) { implicit request: Request[AnyContent] =>
val token = request.token.bearerAccessToken
if (applicationConfig.blockDraftMetadataUpload) {
Future(Ok(views.html.notFoundError(name = request.token.name, isLoggedIn = true, isJudgmentUser = false)))
} else {
val formValidationResult: Form[AdditionalMetadataEntryData] = additionalMetadataEntryForm.bindFromRequest()

val errorFunction: Form[AdditionalMetadataEntryData] => Future[Result] = { formWithErrors: Form[AdditionalMetadataEntryData] =>
for {
reference <- consignmentService.getConsignmentRef(consignmentId, request.token.bearerAccessToken)
reference <- consignmentService.getConsignmentRef(consignmentId, token)
} yield {
Ok(views.html.standard.additionalMetadataEntryMethod(consignmentId, reference, formWithErrors, request.token.name))
.uncache()
Expand All @@ -64,9 +66,18 @@ class AdditionalMetadataEntryMethodController @Inject() (
formData.metadataRoute match {
case Some("manual") => Future.successful(Redirect(routes.AdditionalMetadataController.start(consignmentId)))
case Some("csv") =>
consignmentStatusService
.addConsignmentStatus(consignmentId, "DraftMetadata", InProgressValue.value, request.token.bearerAccessToken)
.map(_ => Redirect(routes.DraftMetadataUploadController.draftMetadataUploadPage(consignmentId)))
for {
consignmentStatuses <- consignmentStatusService.getConsignmentStatuses(consignmentId, token)
statusesToValue = consignmentStatusService.getStatusValues(consignmentStatuses, DraftMetadataType).values.headOption.flatten
_ <-
if (statusesToValue.isEmpty) {
consignmentStatusService.addConsignmentStatus(consignmentId, DraftMetadataType.id, InProgressValue.value, token)
} else {
consignmentStatusService.updateConsignmentStatus(ConsignmentStatusInput(consignmentId, DraftMetadataType.id, Some(InProgressValue.value)), token)
}
} yield {
Redirect(routes.DraftMetadataUploadController.draftMetadataUploadPage(consignmentId))
}
case _ => Future.successful(Redirect(routes.DownloadMetadataController.downloadMetadataPage(consignmentId)))
}
}
Expand Down
40 changes: 38 additions & 2 deletions test/controllers/AdditionalMetadataEntryMethodControllerSpec.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package controllers

import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock.{containing, postRequestedFor, urlEqualTo}
import configuration.{ApplicationConfig, GraphQLConfiguration, KeycloakConfiguration}
import graphql.codegen.GetConsignmentStatus.getConsignmentStatus.{GetConsignment => gcs}
import org.mockito.Mockito.when
import org.pac4j.play.scala.SecurityComponents
import org.scalatest.matchers.should.Matchers._
Expand All @@ -11,13 +13,15 @@ import play.api.mvc.Result
import play.api.test.CSRFTokenHelper._
import play.api.test.FakeRequest
import play.api.test.Helpers.{status => playStatus, _}
import services.Statuses.DraftMetadataType
import services.{ConsignmentService, ConsignmentStatusService}
import testUtils.FrontEndTestHelper
import org.scalatest.concurrent.ScalaFutures._

import java.time.ZonedDateTime
import java.util.UUID
import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters.CollectionHasAsScala
import org.scalatest.concurrent.ScalaFutures._

class AdditionalMetadataEntryMethodControllerSpec extends FrontEndTestHelper {
implicit val ec: ExecutionContext = ExecutionContext.global
Expand Down Expand Up @@ -129,12 +133,14 @@ class AdditionalMetadataEntryMethodControllerSpec extends FrontEndTestHelper {
redirectLocation must include(s"/consignment/$consignmentId/additional-metadata/download-metadata")
}

"redirect to draft metadat upload page when the user chooses 'csv' option to enter metadata" in {
"redirect to draft metadata upload page when the user chooses 'csv' option to enter metadata" in {
val controller = instantiateController(blockDraftMetadataUpload = false)
val someDateTime = ZonedDateTime.now()

setConsignmentTypeResponse(wiremockServer, "standard")
setConsignmentReferenceResponse(wiremockServer)
setAddConsignmentStatusResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = Nil)

val additionalMetadataEntryMethodPage: Result = controller
.submitAdditionalMetadataEntryMethod(consignmentId)
Expand All @@ -156,6 +162,36 @@ class AdditionalMetadataEntryMethodControllerSpec extends FrontEndTestHelper {
val expectedInput = s"""{"addConsignmentStatusInput":{"consignmentId":"$consignmentId","statusType":"DraftMetadata","statusValue":"InProgress"}}"""
addConsignmentStatusEvent.getRequest.getBodyAsString must include(expectedInput)
}

"redirect to draft metadata upload page when the user chooses 'csv' option to enter metadata and 'draftMetadata' status already exists" in {
val controller = instantiateController(blockDraftMetadataUpload = false)
val someDateTime = ZonedDateTime.now()
val consignmentStatuses = List(gcs.ConsignmentStatuses(UUID.randomUUID(), UUID.randomUUID(), DraftMetadataType.id, InProgress.value, someDateTime, None))

setConsignmentTypeResponse(wiremockServer, "standard")
setConsignmentReferenceResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = consignmentStatuses)
setUpdateConsignmentStatus(wiremockServer)

val additionalMetadataEntryMethodPage: Result = controller
.submitAdditionalMetadataEntryMethod(consignmentId)
.apply(
FakeRequest(POST, "/additional-metadata/entry-method")
.withFormUrlEncodedBody(Seq(("metadataRoute", "csv")): _*)
.withCSRFToken
)
.futureValue

val redirectLocation = additionalMetadataEntryMethodPage.header.headers.getOrElse("Location", "")

additionalMetadataEntryMethodPage.header.status should equal(303)
redirectLocation must include(s"/consignment/$consignmentId/draft-metadata/upload")

wiremockServer.verify(
postRequestedFor(urlEqualTo("/graphql"))
.withRequestBody(containing(s"""{"updateConsignmentStatusInput":{"consignmentId":"$consignmentId","statusType":"DraftMetadata","statusValue":"InProgress"}}"""))
)
}
}

private def instantiateController(
Expand Down
21 changes: 4 additions & 17 deletions test/controllers/FileChecksControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import com.github.tomakehurst.wiremock.client.WireMock._
import configuration.GraphQLConfiguration
import graphql.codegen.GetConsignmentStatus.getConsignmentStatus.GetConsignment.ConsignmentStatuses
import graphql.codegen.GetFileCheckProgress.{getFileCheckProgress => fileCheck}
import graphql.codegen.UpdateConsignmentStatus.updateConsignmentStatus
import io.circe.Printer
import io.circe.generic.auto._
import io.circe.syntax._
Expand Down Expand Up @@ -188,12 +187,9 @@ class FileChecksControllerSpec extends FrontEndTestHelper with TableDrivenProper
val dataString: String = progressData(40, 40, 40, allChecksSucceeded = true)

val uploadStatus = List(ConsignmentStatuses(UUID.randomUUID(), UUID.randomUUID(), UploadType.id, InProgress.value, someDateTime, None))
val client = graphQLConfiguration.getClient[updateConsignmentStatus.Data, updateConsignmentStatus.Variables]()
val data = client.GraphqlData(Option(updateConsignmentStatus.Data(Option(1))), Nil)
val ucsDataString = data.asJson.noSpaces
when(backendChecksService.triggerBackendChecks(org.mockito.ArgumentMatchers.any(classOf[UUID]), anyString())).thenReturn(Future.successful(true))
mockGetFileCheckProgress(dataString, userType)
mockUpdateConsignmentStatus(ucsDataString, wiremockServer)
setUpdateConsignmentStatus(wiremockServer)
setConsignmentReferenceResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = uploadStatus)

Expand Down Expand Up @@ -285,11 +281,8 @@ class FileChecksControllerSpec extends FrontEndTestHelper with TableDrivenProper
val dataString: String = progressData(filesProcessedWithAntivirus, filesProcessedWithChecksum, filesProcessedWithFFID, allChecksSucceeded = false)

val uploadStatus = List(ConsignmentStatuses(UUID.randomUUID(), UUID.randomUUID(), UploadType.id, CompletedValue.value, someDateTime, None))
val client = graphQLConfiguration.getClient[updateConsignmentStatus.Data, updateConsignmentStatus.Variables]()
val data = client.GraphqlData(Option(updateConsignmentStatus.Data(Option(1))), Nil)
val ucsDataString = data.asJson.noSpaces
mockGetFileCheckProgress(dataString, userType)
mockUpdateConsignmentStatus(ucsDataString, wiremockServer)
setUpdateConsignmentStatus(wiremockServer)
setConsignmentReferenceResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = uploadStatus)

Expand Down Expand Up @@ -342,12 +335,9 @@ class FileChecksControllerSpec extends FrontEndTestHelper with TableDrivenProper
val dataString: String = progressData(filesProcessedWithAntivirus, filesProcessedWithChecksum, filesProcessedWithFFID, allChecksSucceeded = false)

val uploadStatus = List(ConsignmentStatuses(UUID.randomUUID(), UUID.randomUUID(), UploadType.id, InProgress.value, someDateTime, None))
val client = graphQLConfiguration.getClient[updateConsignmentStatus.Data, updateConsignmentStatus.Variables]()
val data = client.GraphqlData(Option(updateConsignmentStatus.Data(Option(1))), Nil)
val ucsDataString = data.asJson.noSpaces
when(backendChecksService.triggerBackendChecks(org.mockito.ArgumentMatchers.any(classOf[UUID]), anyString())).thenReturn(Future.successful(false))
mockGetFileCheckProgress(dataString, userType)
mockUpdateConsignmentStatus(ucsDataString, wiremockServer)
setUpdateConsignmentStatus(wiremockServer)
setConsignmentReferenceResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = uploadStatus)

Expand Down Expand Up @@ -400,12 +390,9 @@ class FileChecksControllerSpec extends FrontEndTestHelper with TableDrivenProper
val dataString: String = progressData(filesProcessedWithAntivirus, filesProcessedWithChecksum, filesProcessedWithFFID, allChecksSucceeded = false)

val uploadStatus = List(ConsignmentStatuses(UUID.randomUUID(), UUID.randomUUID(), UploadType.id, CompletedWithIssuesValue.value, someDateTime, None))
val client = graphQLConfiguration.getClient[updateConsignmentStatus.Data, updateConsignmentStatus.Variables]()
val data = client.GraphqlData(Option(updateConsignmentStatus.Data(Option(1))), Nil)
val ucsDataString = data.asJson.noSpaces
when(backendChecksService.triggerBackendChecks(org.mockito.ArgumentMatchers.any(classOf[UUID]), anyString())).thenReturn(Future.successful(false))
mockGetFileCheckProgress(dataString, userType)
mockUpdateConsignmentStatus(ucsDataString, wiremockServer)
setUpdateConsignmentStatus(wiremockServer)
setConsignmentReferenceResponse(wiremockServer)
setConsignmentStatusResponse(app.configuration, wiremockServer, consignmentStatuses = uploadStatus)

Expand Down
20 changes: 11 additions & 9 deletions test/testUtils/FrontEndTestHelper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@ import com.github.tomakehurst.wiremock.client.WireMock.{containing, okJson, post
import com.github.tomakehurst.wiremock.stubbing.StubMapping
import com.nimbusds.oauth2.sdk.token.BearerAccessToken
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata
import com.typesafe.config.{ConfigFactory, ConfigValue, ConfigValueFactory}
import configuration.{ApplicationConfig, GraphQLConfiguration, KeycloakConfiguration}
import graphql.codegen.AddBulkFileMetadata.addBulkFileMetadata.UpdateBulkFileMetadata
import graphql.codegen.AddBulkFileMetadata.{addBulkFileMetadata => abfm}
import graphql.codegen.AddConsignmentStatus.addConsignmentStatus.AddConsignmentStatus
import graphql.codegen.AddConsignmentStatus.{addConsignmentStatus => acs}
import graphql.codegen.DeleteFileMetadata.deleteFileMetadata.DeleteFileMetadata
import graphql.codegen.DeleteFileMetadata.{deleteFileMetadata => dfm}
import graphql.codegen.GetAllDescendants.getAllDescendantIds
import graphql.codegen.GetAllDescendants.getAllDescendantIds.AllDescendants
import graphql.codegen.GetConsignment.{getConsignment => gcd}
import graphql.codegen.GetConsignmentFiles.{getConsignmentFiles => gcf}
import graphql.codegen.GetConsignmentFilesMetadata.getConsignmentFilesMetadata.GetConsignment.Files.{FileMetadata, FileStatuses}
import graphql.codegen.GetConsignmentFilesMetadata.{getConsignmentFilesMetadata => gcfm}
import graphql.codegen.GetConsignmentFiles.{getConsignmentFiles => gcf}
import graphql.codegen.GetConsignmentStatus.getConsignmentStatus.GetConsignment
import graphql.codegen.GetConsignmentStatus.getConsignmentStatus.GetConsignment.ConsignmentStatuses
import graphql.codegen.GetConsignmentStatus.{getConsignmentStatus => gcs}
import graphql.codegen.GetConsignments.getConsignments.Consignments
Expand All @@ -29,9 +31,9 @@ import graphql.codegen.GetCustomMetadata.customMetadata.CustomMetadata.Values
import graphql.codegen.GetCustomMetadata.customMetadata.CustomMetadata.Values.Dependencies
import graphql.codegen.GetCustomMetadata.{customMetadata => cm}
import graphql.codegen.GetDisplayProperties.{displayProperties => dp}
import graphql.codegen.UpdateConsignmentStatus.{updateConsignmentStatus => ucs}
import graphql.codegen.types.DataType.{Boolean, DateTime, Integer, Text}
import graphql.codegen.types.PropertyType.{Defined, Supplied}
import graphql.codegen.AddConsignmentStatus.{addConsignmentStatus => acs}
import io.circe.Printer
import io.circe.generic.auto._
import io.circe.syntax._
Expand Down Expand Up @@ -65,11 +67,9 @@ import play.api.mvc.{BodyParsers, ControllerComponents}
import play.api.test.Helpers.stubControllerComponents
import play.api.test.Injecting
import play.api.{Application, Configuration}
import services.Statuses.{InProgressValue, SeriesType}
import uk.gov.nationalarchives.tdr.GraphQLClient
import uk.gov.nationalarchives.tdr.keycloak.Token
import graphql.codegen.GetConsignment.{getConsignment => gcd}
import graphql.codegen.GetConsignmentStatus.getConsignmentStatus.GetConsignment
import services.Statuses.{InProgressValue, SeriesType}
import viewsapi.FrontEndInfo

import java.io.File
Expand All @@ -80,7 +80,6 @@ import java.util.{Date, UUID}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.jdk.CollectionConverters._
import scala.language.existentials

trait FrontEndTestHelper extends PlaySpec with MockitoSugar with Injecting with GuiceOneAppPerTest with BeforeAndAfterEach with TableDrivenPropertyChecks {
Expand Down Expand Up @@ -258,11 +257,14 @@ trait FrontEndTestHelper extends PlaySpec with MockitoSugar with Injecting with
)
}

def mockUpdateConsignmentStatus(dataString: String, wiremockServer: WireMockServer): StubMapping = {
def setUpdateConsignmentStatus(wiremockServer: WireMockServer): StubMapping = {
val client = new GraphQLConfiguration(app.configuration).getClient[ucs.Data, ucs.Variables]()
val data = client.GraphqlData(Option(ucs.Data(Option(1))), Nil)
val ucsDataString = data.asJson.noSpaces
wiremockServer.stubFor(
post(urlEqualTo("/graphql"))
.withRequestBody(containing("updateConsignmentStatus"))
.willReturn(okJson(dataString))
.willReturn(okJson(ucsDataString))
)
}

Expand Down

0 comments on commit 00b23c4

Please sign in to comment.