<commit_before>/*
 * 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 controllers

import auth.{AuthorisedForPLA, PLAUser}
import common._
import config.{FrontendAppConfig, FrontendAuthConnector}
import connectors.{KeyStoreConnector, PLAConnector}
import constructors.{AmendsGAConstructor, DisplayConstructors, ResponseConstructors}
import enums.ApplicationType
import forms.AmendCurrentPensionForm._
import forms._
import forms.AmendOverseasPensionsForm._
import forms.AmendPensionsTakenBeforeForm._
import forms.AmendPensionsTakenBetweenForm._
import forms.AmendPSODetailsForm._
import forms.AmendmentTypeForm._
import models.{AmendResponseModel, PensionDebitModel, ProtectionModel}
import models.amendModels._
import play.api.Logger
import play.api.mvc.{Action, AnyContent, Result, _}
import uk.gov.hmrc.play.frontend.controller.FrontendController
import uk.gov.hmrc.play.http.HttpResponse
import utils.Constants
import views.html.pages
import views.html.pages.result.manualCorrespondenceNeeded

import scala.concurrent.Future

object AmendsController extends AmendsController {
  val keyStoreConnector = KeyStoreConnector
  val displayConstructors = DisplayConstructors
  val responseConstructors = ResponseConstructors
  val plaConnector = PLAConnector
  override lazy val applicationConfig = FrontendAppConfig
  override lazy val authConnector = FrontendAuthConnector
  override lazy val postSignInRedirectUrl = FrontendAppConfig.ipStartUrl
}

trait AmendsController extends FrontendController with AuthorisedForPLA {

  val keyStoreConnector: KeyStoreConnector
  val displayConstructors: DisplayConstructors
  val responseConstructors: ResponseConstructors
  val plaConnector: PLAConnector

  def amendsSummary(protectionType: String, status: String): Action[AnyContent] = AuthorisedByAny.async { implicit user => implicit request =>
    val protectionKey = Strings.keyStoreAmendFetchString(protectionType, status)
    keyStoreConnector.fetchAndGetFormData[AmendProtectionModel](protectionKey).map {
      case Some(amendModel) =>
        Ok(views.html.pages.amends.amendSummary(
        displayConstructors.createAmendDisplayModel(amendModel),
        status,
        amendmentTypeForm.fill(AmendmentTypeModel(protectionType, status))

      ))
      case _ =>
        Logger.error(s"Could not retrieve amend protection model for user with nino ${user.nino} when loading the amend summary page")
        InternalServerError(views.html.pages.fallback.technicalError(ApplicationType.existingProtections.toString)).withHeaders(CACHE_CONTROL -> "no-cache")
    }
  }

  val amendProtection = AuthorisedByAny.async { implicit user => implicit request =>
    amendmentTypeForm.bindFromRequest.fold(
      errors => {
        Logger.error(s"Couldn't bind protection type or status to amend request for user with nino ${user.nino}")
        Future.successful(InternalServerError(views.html.pages.fallback.technicalError(ApplicationType.existingProtections.toString)).withHeaders(CACHE_CONTROL -> "no-cache"))
      },
      success => for {
        protectionAmendment <- keyStoreConnector.fetchAndGetFormData[AmendProtectionModel](Strings.keyStoreAmendFetchString(success.protectionType, success.status))
        saveProtection <- keyStoreConnector.saveData[ProtectionModel]("openProtection", protectionAmendment.get.updatedProtection)
        saveAmendsGA <- keyStoreConnector.saveData[AmendsGAModel]("AmendsGA",AmendsGAConstructor.identifyAmendsChanges(protectionAmendment.get.updatedProtection,protectionAmendment.get.originalProtection))
        response <- plaConnector.amendProtection(user.nino.get, protectionAmendment.get.updatedProtection)
        result <- routeViaMCNeededCheck(response)
      } yield result
    )
  }
<commit_msg>removed redundant save to keystore<commit_after>/*
 * 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 controllers

import auth.{AuthorisedForPLA, PLAUser}
import common._
import config.{FrontendAppConfig, FrontendAuthConnector}
import connectors.{KeyStoreConnector, PLAConnector}
import constructors.{AmendsGAConstructor, DisplayConstructors, ResponseConstructors}
import enums.ApplicationType
import forms.AmendCurrentPensionForm._
import forms._
import forms.AmendOverseasPensionsForm._
import forms.AmendPensionsTakenBeforeForm._
import forms.AmendPensionsTakenBetweenForm._
import forms.AmendPSODetailsForm._
import forms.AmendmentTypeForm._
import models.{AmendResponseModel, PensionDebitModel, ProtectionModel}
import models.amendModels._
import play.api.Logger
import play.api.mvc.{Action, AnyContent, Result, _}
import uk.gov.hmrc.play.frontend.controller.FrontendController
import uk.gov.hmrc.play.http.HttpResponse
import utils.Constants
import views.html.pages
import views.html.pages.result.manualCorrespondenceNeeded

import scala.concurrent.Future

object AmendsController extends AmendsController {
  val keyStoreConnector = KeyStoreConnector
  val displayConstructors = DisplayConstructors
  val responseConstructors = ResponseConstructors
  val plaConnector = PLAConnector
  override lazy val applicationConfig = FrontendAppConfig
  override lazy val authConnector = FrontendAuthConnector
  override lazy val postSignInRedirectUrl = FrontendAppConfig.ipStartUrl
}

trait AmendsController extends FrontendController with AuthorisedForPLA {

  val keyStoreConnector: KeyStoreConnector
  val displayConstructors: DisplayConstructors
  val responseConstructors: ResponseConstructors
  val plaConnector: PLAConnector

  def amendsSummary(protectionType: String, status: String): Action[AnyContent] = AuthorisedByAny.async { implicit user => implicit request =>
    val protectionKey = Strings.keyStoreAmendFetchString(protectionType, status)
    keyStoreConnector.fetchAndGetFormData[AmendProtectionModel](protectionKey).map {
      case Some(amendModel) =>
        Ok(views.html.pages.amends.amendSummary(
        displayConstructors.createAmendDisplayModel(amendModel),
        status,
        amendmentTypeForm.fill(AmendmentTypeModel(protectionType, status))

      ))
      case _ =>
        Logger.error(s"Could not retrieve amend protection model for user with nino ${user.nino} when loading the amend summary page")
        InternalServerError(views.html.pages.fallback.technicalError(ApplicationType.existingProtections.toString)).withHeaders(CACHE_CONTROL -> "no-cache")
    }
  }

  val amendProtection = AuthorisedByAny.async { implicit user => implicit request =>
    amendmentTypeForm.bindFromRequest.fold(
      errors => {
        Logger.error(s"Couldn't bind protection type or status to amend request for user with nino ${user.nino}")
        Future.successful(InternalServerError(views.html.pages.fallback.technicalError(ApplicationType.existingProtections.toString)).withHeaders(CACHE_CONTROL -> "no-cache"))
      },
      success => for {
        protectionAmendment <- keyStoreConnector.fetchAndGetFormData[AmendProtectionModel](Strings.keyStoreAmendFetchString(success.protectionType, success.status))
        saveAmendsGA <- keyStoreConnector.saveData[AmendsGAModel]("AmendsGA",AmendsGAConstructor.identifyAmendsChanges(protectionAmendment.get.updatedProtection,protectionAmendment.get.originalProtection))
        response <- plaConnector.amendProtection(user.nino.get, protectionAmendment.get.updatedProtection)
        result <- routeViaMCNeededCheck(response)
      } yield result
    )
  }

{'fraction_non_alphanumeric': 0.0737164390014131, 'fraction_numerical': 0.0018841262364578427, 'mean_word_length': 5.333333333333333, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1351809', 'n_tokens_mistral': 2274, 'n_tokens_neox': 2227, 'n_words': 551}