play.twirl.api.Html Scala Examples

The following examples show how to use play.twirl.api.Html. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: LagomMarkdownTheme.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package lagom

import com.lightbend.markdown.theme.MarkdownTheme
import play.doc.Toc
import play.doc.TocTree
import play.twirl.api.Html

object LagomMarkdownTheme extends MarkdownTheme {
  override def renderPage(
      projectName: Option[String],
      title: Option[String],
      home: String,
      content: Html,
      sidebar: Option[Html],
      breadcrumbs: Option[Html],
      apiDocs: Seq[(String, String)],
      sourceUrl: Option[String]
  ): Html =
    html.documentation(projectName, title, home, content, sidebar, breadcrumbs, apiDocs, sourceUrl)

  override def renderNextLinks(nextLinks: List[TocTree]): Html = html.nextLinks(nextLinks)

  override def renderSidebar(hierarchy: List[Toc]): Html = html.sidebar(hierarchy)

  override def renderBreadcrumbs(hierarchy: List[Toc]): Html = html.breadcrumbs(hierarchy)
} 
Example 2
Source File: PlayUtils.scala    From scalingua   with Apache License 2.0 5 votes vote down vote up
package ru.makkarpov.scalingua.play

import play.api.mvc.RequestHeader
import play.twirl.api.Html
import ru.makkarpov.scalingua._

import scala.language.experimental.macros

object PlayUtils {
  class StringInterpolator(val sc: StringContext) extends AnyVal {
    def h(args: Any*)(implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
      macro Macros.interpolate[Html]

    def lh(args: Any*)(implicit outputFormat: OutputFormat[Html]): LValue[Html] =
      macro Macros.lazyInterpolate[Html]

    def ph(args: Any*)(implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
      macro Macros.pluralInterpolate[Html]

    def lph(args: Any*)(outputFormat: OutputFormat[Html]): LValue[Html] =
      macro Macros.lazyPluralInterpolate[Html]
  }

  // Modified to match only correct doubles
  private val qPattern = ";\\s*q=((?:[0-9]+\\.)?[0-9]+)".r

  def languageFromAccept(accept: String)(implicit msg: Messages): Language = {
    val langs = (for {
      value0 <- accept.split(',')
      value = value0.trim
    } yield {
      qPattern.findFirstMatchIn(value) match {
        case Some(m) => (BigDecimal(m.group(1)), m.before.toString)
        case None => (BigDecimal(1.0), value) // “The default value is q=1.”
      }
    }).sortBy(-_._1).iterator

    while (langs.hasNext) {
      val (_, id) = langs.next()
      val lng = LanguageId.get(id)

      if (lng.isDefined && msg.contains(lng.get))
        return msg(lng.get)
    }

    Language.English
  }
} 
Example 3
Source File: I18n.scala    From scalingua   with Apache License 2.0 5 votes vote down vote up
package ru.makkarpov.scalingua.play

import play.api.http.HeaderNames
import play.api.mvc.RequestHeader
import play.twirl.api.Html
import ru.makkarpov.scalingua
import ru.makkarpov.scalingua._

import scala.language.experimental.macros
import scala.language.implicitConversions

trait I18n extends scalingua.I18n {
  type LHtml = LValue[Html]

  implicit val htmlOutputFormat = new OutputFormat[Html] {
    override def convert(s: String): Html = Html(s)

    override def escape(s: String): String = {
      val ret = new StringBuilder
      var i = 0
      ret.sizeHint(s.length)
      while (i < s.length) {
        s.charAt(i) match {
          case '<' => ret.append("&lt;")
          case '>' => ret.append("&gt;")
          case '"' => ret.append("&quot;")
          case '\'' => ret.append("&#x27;")
          case '&' => ret.append("&amp;")
          case c => ret += c
        }
        i += 1
      }
      ret.result()
    }
  }

  // The conversion from `RequestHeader` to `LanguageId` will imply information loss:
  // Suppose browser sent the following language precedence list `xx_YY`, `zz_WW`, `en_US`.
  // This conversion will have no information about available languages, so it will result in
  // `LanguageId("xx", "YY")` even if this language is absent. By supplying implicit `Messages`
  // too, we will have enough information to skip unsupported languages and return supported
  // one with respect to priority.

  implicit def requestHeader2Language(implicit rq: RequestHeader, msg: Messages): Language =
    rq.headers.get(HeaderNames.ACCEPT_LANGUAGE).map(PlayUtils.languageFromAccept).getOrElse(Language.English)

  implicit def stringContext2Interpolator1(sc: StringContext): PlayUtils.StringInterpolator =
    new PlayUtils.StringInterpolator(sc)

  def th(msg: String, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
    macro Macros.singular[Html]

  def lth(msg: String, args: (String, Any)*)(implicit outputFormat: OutputFormat[Html]): LHtml =
    macro Macros.lazySingular[Html]

  def tch(ctx: String, msg: String, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
    macro Macros.singularCtx[Html]

  def ltch(ctx: String, msg: String, args: (String, Any)*)(implicit outputFormat: OutputFormat[Html]): LHtml =
    macro Macros.lazySingularCtx[Html]

  def p(msg: String, msgPlural: String, n: Long, args: (String, Any)*)
       (implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
    macro Macros.plural[Html]

  def lp(msg: String, msgPlural: String, n: Long, args: (String, Any)*)
        (implicit outputFormat: OutputFormat[Html]): LHtml =
    macro Macros.lazyPlural[Html]

  def pc(ctx: String, msg: String, msgPlural: String, n: Long, args: (String, Any)*)
        (implicit lang: Language, outputFormat: OutputFormat[Html]): Html =
    macro Macros.pluralCtx[Html]

  def lpc(ctx: String, msg: String, msgPlural: String, n: Long, args: (String, Any)*)
         (implicit outputFormat: OutputFormat[Html]): LHtml =
    macro Macros.lazyPluralCtx[Html]
}

object I18n extends I18n 
Example 4
Source File: Mailer.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.utils

import javax.inject.Inject
import akka.Done
import akka.actor.ActorSystem
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.phata.views
import org.hatdex.hat.resourceManagement.HatServer
import play.api.i18n.{ Lang, Messages, MessagesApi }
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.RequestHeader
import play.api.{ Configuration, UsefulException }
import play.twirl.api.Html

import scala.concurrent.{ ExecutionContext, Future }

trait Mailer {
  protected val configuration: Configuration
  protected val system: ActorSystem
  protected val mailerClient: MailerClient

  import scala.language.implicitConversions

  implicit def html2String(html: Html): String = html.toString

  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done

  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done

  def sendEmail(recipients: String*)(from: String, subject: String, bodyHtml: String, bodyText: String)(implicit ec: ExecutionContext): Future[Done] = {
    Future(mailerClient.send(Email(subject, from, recipients, Some(bodyText), Some(bodyHtml))))
      .map(_ => Done)
  }
}

trait HatMailer extends Mailer {
  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done
  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done
  def passwordReset(email: String, user: HatUser, resetLink: String)(implicit m: Messages, server: HatServer): Done
  def passwordChanged(email: String, user: HatUser)(implicit m: Messages, server: HatServer): Done

  def claimHat(email: String, claimLink: String, maybePartnerDetails: Option[(String, String)])(implicit m: MessagesApi, l: Lang, server: HatServer): Done
}

class HatMailerImpl @Inject() (
    val configuration: Configuration,
    val system: ActorSystem,
    val mailerClient: MailerClient)(implicit ec: RemoteExecutionContext) extends HatMailer {
  private val emailFrom = configuration.get[String]("play.mailer.from")
  private val adminEmails = configuration.get[Seq[String]]("exchange.admin")

  def serverErrorNotify(request: RequestHeader, exception: UsefulException)(implicit m: Messages): Done = {
    sendEmail(adminEmails: _*)(
      from = emailFrom,
      subject = s"HAT server ${request.host} error #${exception.id}",
      bodyHtml = views.html.mails.emailServerError(request, exception),
      bodyText = views.html.mails.emailServerError(request, exception).toString())
    Done
  }

  def serverExceptionNotify(request: RequestHeader, exception: Throwable)(implicit m: Messages): Done = {
    sendEmail(adminEmails: _*)(
      from = emailFrom,
      subject = s"HAT server ${request.host} error: ${exception.getMessage} for ${request.path + request.rawQueryString}",
      bodyHtml = views.html.mails.emailServerThrowable(request, exception),
      bodyText = views.html.mails.emailServerThrowable(request, exception).toString())
    Done
  }

  def passwordReset(email: String, user: HatUser, resetLink: String)(implicit m: Messages, server: HatServer): Done = {
    sendEmail(email)(
      from = emailFrom,
      subject = s"HAT ${server.domain} - reset your password",
      bodyHtml = views.html.mails.emailPasswordReset(user, server.domain, resetLink),
      bodyText = views.txt.mails.emailPasswordReset(user, server.domain, resetLink).toString())
    Done
  }

  def passwordChanged(email: String, user: HatUser)(implicit m: Messages, server: HatServer): Done = {
    sendEmail(email)(
      from = emailFrom,
      subject = s"HAT ${server.domain} - password changed",
      bodyHtml = views.html.mails.emailPasswordChanged(user, server.domain),
      bodyText = views.txt.mails.emailPasswordChanged(user, server.domain).toString())
    Done
  }

  def claimHat(email: String, claimLink: String, maybePartnerDetails: Option[(String, String)])(implicit m: MessagesApi, l: Lang, server: HatServer): Done = {
    sendEmail(email)(
      from = "[email protected]",
      subject = m("email.hatclaim.subject", maybePartnerDetails.map(_._1).getOrElse("")),
      bodyHtml = views.html.mails.emailHatClaim(server.domain, claimLink, maybePartnerDetails),
      bodyText = views.txt.mails.emailHatClaim(server.domain, claimLink, maybePartnerDetails.map(_._1)).toString())
    Done
  }
} 
Example 5
Source File: RestResource.scala    From pizza-auth-3   with MIT License 5 votes vote down vote up
package moe.pizza.auth.webapp.rest

import moe.pizza.auth.config.ConfigFile.ConfigFile
import moe.pizza.auth.graphdb.EveMapDb
import moe.pizza.auth.interfaces.{PilotGrader, UserDatabase, BroadcastService}
import BroadcastService._
import moe.pizza.auth.tasks.Update
import moe.pizza.crestapi.CrestApi
import org.http4s.{HttpService, _}
import org.http4s.dsl.{Root, _}
import org.http4s.server._
import org.http4s.server.staticcontent.ResourceService
import org.http4s.server.syntax.ServiceOps
import org.joda.time.DateTime
import play.twirl.api.Html
import moe.pizza.eveapi._
import scala.concurrent.ExecutionContext.Implicits.global
import org.http4s.twirl._
import scala.concurrent.Future
import scala.util.Try
import scalaz._
import Scalaz._
import scala.util.{Success => TSuccess}
import scala.util.{Failure => TFailure}
import scala.concurrent.duration._
import scala.concurrent.Await
import moe.pizza.crestapi.character.location.Types.Location
import org.slf4j.LoggerFactory
import io.circe.generic.auto._
import io.circe.syntax._
import org.http4s.circe._
import io.circe.Json
import io.circe.generic.JsonCodec

class RestResource(fullconfig: ConfigFile,
                   graders: PilotGrader,
                   portnumber: Int = 9021,
                   ud: UserDatabase,
                   crestapi: Option[CrestApi] = None,
                   eve: Option[EVEAPI] = None,
                   mapper: Option[EveMapDb] = None,
                   updater: Option[Update] = None,
                   broadcasters: List[BroadcastService] =
                     List.empty[BroadcastService]) {

  case class ApiError(`type`: String, message: String)

  case class PingRequest(message: String, from: String, to: String)
  case class PingResponse(total: Int)

  def resource = HttpService {

    case req @ GET -> Root / "api" / "v1" / "ping" / "group" / group => {
      req.decode[Json] { p =>
        p.as[PingRequest] match {
          case Left(failure) =>
            BadRequest(ApiError(
              "bad_post_body",
              "Unable to process your post body, please format it correctly").asJson)
          case Right(pingreq) =>
            val users = ud.getUsers(s"authgroup=${group}")
            val templatedMessage = templates.txt.broadcast(pingreq.message,
                                                           pingreq.to,
                                                           pingreq.from,
                                                           DateTime.now())
            val sendreqs =
              ud.sendGroupAnnouncement(broadcasters,
                                       templatedMessage.toString(),
                                       pingreq.from,
                                       users)
            val r = Await.result(Future.sequence(sendreqs), 2 seconds).sum
            Ok(PingResponse(r).asJson)
          }
      }
    }

  }

} 
Example 6
Source File: PlantUMLRenderer.scala    From gitbucket-plantuml-plugin   with Apache License 2.0 5 votes vote down vote up
package com.yotaichino.gitbucket.plugins.plantuml

import gitbucket.core.plugin.Renderer
import gitbucket.core.plugin.RenderRequest
import gitbucket.core.util.StringUtil
import java.nio.charset.Charset
import java.util.Base64
import play.twirl.api.Html

class PlantUMLRenderer extends Renderer {

  override def render(request: RenderRequest): Html = {
    Html(imgEmbedded(request.fileContent))
  }

  def imgEmbedded(content: String): String = {
    val raw = PlantUMLUtils.generateSVGImage(content)
    raw match {
      case null => {
        val c = StringUtil.escapeHtml(content)
        s"""<pre class="prettyprint linenums blob">$c</pre>"""
      }
      case _ => {
        val src = Base64.getEncoder.encodeToString(raw)
        s"""<img src="data:image/svg+xml;charset=utf-8;base64,$src">"""
      }
    }
  }
} 
Example 7
Source File: Generator.scala    From play-soap   with Apache License 2.0 5 votes vote down vote up
package play.soap.docs

import java.io.File
import java.util.Collections

import org.apache.commons.io.FileUtils
import org.pegdown.ast.WikiLinkNode
import org.pegdown.VerbatimSerializer
import org.pegdown.LinkRenderer
import org.pegdown.Extensions
import org.pegdown.PegDownProcessor
import play.doc.PrettifyVerbatimSerializer
import play.twirl.api.Html

object Generator extends App {
  val outDir  = new File(args(0))
  val inDir   = new File(args(1))
  val inPages = args.drop(2)

  val parser = new PegDownProcessor(Extensions.ALL)
  val linkRenderer = new LinkRenderer {
    import LinkRenderer.Rendering
    override def render(node: WikiLinkNode) = {
      node.getText.split("\\|", 2) match {
        case Array(name)        => new Rendering(name + ".html", name)
        case Array(title, name) => new Rendering(name + ".html", title)
        case _                  => new Rendering(node.getText + ".html", node.getText)
      }
    }
  }
  val verbatimSerializer =
    Collections.singletonMap[String, VerbatimSerializer](VerbatimSerializer.DEFAULT, PrettifyVerbatimSerializer)

  val nav = Seq(
    "Home"                       -> "Home",
    "Using sbt WSDL"             -> "SbtWsdl",
    "Using the Play SOAP client" -> "PlaySoapClient",
    "Using JAX WS Handlers"      -> "Handlers",
    "Security"                   -> "Security"
  )
  val titleMap = nav.map(t => t._2 -> t._1).toMap

  // Ensure target directory exists
  outDir.mkdirs()

  inPages.foreach { name =>
    val inFile      = new File(inDir, name + ".md")
    val markdown    = FileUtils.readFileToString(inFile)
    val htmlSnippet = parser.markdownToHtml(markdown, linkRenderer, verbatimSerializer)
    val title       = titleMap.get(name)
    val htmlPage    = html.template(title, nav)(Html(htmlSnippet))
    FileUtils.writeStringToFile(new File(outDir, name + ".html"), htmlPage.body)
  }
} 
Example 8
Source File: FooterLinksSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.jsoup.Jsoup
import org.scalatest.{Matchers, WordSpec}
import play.api.i18n.Lang
import play.api.test.Helpers._
import play.twirl.api.Html
import uk.gov.hmrc.play.views.html.layouts.FooterLinks
import play.api.i18n.Messages.Implicits._
import play.api.inject.guice.GuiceApplicationBuilder
import java.util.{List => JavaList}
import scala.collection.JavaConverters._
import scala.collection.immutable.List


class FooterLinksSpec extends WordSpec with Matchers {

  implicit val application =
    new GuiceApplicationBuilder()
      .configure(Map("play.i18n.langs" -> List("en", "cy")))
      .build()

  val englishLinkTextEntries: JavaList[String] = List(
    "Cookies",
    "Privacy policy",
    "Terms and conditions",
    "Help using GOV.UK"
  ).asJava

  val welshLinkTextEntries: JavaList[String] = List(
    "Cwcis",
    "Polisi preifatrwydd",
    "Telerau ac Amodau",
    "Help wrth ddefnyddio GOV.UK"
  ).asJava

  "The footerLinks in English" should {

    val footerLinks = new FooterLinks()

    implicit val lang = Lang("en")
    val content  = contentAsString(footerLinks())
    val document = Jsoup.parse(content)
    val links    = document.getElementsByTag("a")

    "include visually hidden h2 text in English" in {
      implicit val lang = Lang("en")
      val content  = contentAsString(footerLinks())
      content should include("<h2 class=\"visually-hidden\">Support links</h2>")
    }

    "Have the correct link text in English" in {
      links.eachText() should be(englishLinkTextEntries)
    }

  }

  "The footerLinks in Welsh" should {

    val footerLinks = new FooterLinks()

    implicit val lang = Lang("cy")
    val content  = contentAsString(footerLinks())
    val document = Jsoup.parse(content)
    val links    = document.getElementsByTag("a")


    "include visually hidden h2 text in Welsh" in {
      content should include("<h2 class=\"visually-hidden\">Cysylltiadau cymorth</h2>")
    }

    "Have the correct link text in Welsh" in {
      links.eachText() should be(welshLinkTextEntries)
    }

  }
} 
Example 9
Source File: HeadSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.scalatest.{Matchers, WordSpec}
import play.api.test.Helpers.{contentAsString, defaultAwaitTimeout}
import play.twirl.api.Html
import uk.gov.hmrc.play.test.NoStartedPlayApp
import uk.gov.hmrc.play.views.html.layouts.{GTMSnippet, Head, OptimizelySnippet}
import uk.gov.hmrc.play.views.layouts.test.TestConfigs._

class HeadSpec extends WordSpec with Matchers with NoStartedPlayApp {
  "head" should {
    "be renderable without a started Play application" in {
      thereShouldBeNoStartedPlayApp()

      val head = new Head(
        new OptimizelySnippet(testOptimizelyConfig),
        testAssetsConfig,
        new GTMSnippet(testGTMConfig)
      )

      val rendered = contentAsString(head(linkElem = None, headScripts = Some(Html("head was rendered"))))

      rendered should include("head was rendered")
    }
  }
} 
Example 10
Source File: FooterSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.scalatest.{Matchers, WordSpec}
import play.api.test.Helpers.{contentAsString, defaultAwaitTimeout}
import play.twirl.api.Html
import uk.gov.hmrc.play.test.NoStartedPlayApp
import uk.gov.hmrc.play.views.html.layouts.Footer
import uk.gov.hmrc.play.views.layouts.test.TestConfigs._

class FooterSpec extends WordSpec with Matchers with NoStartedPlayApp {
  "footer" should {

    val footer = new Footer(testAssetsConfig)

    "be renderable without a started Play application" in {
      thereShouldBeNoStartedPlayApp()

      val rendered = contentAsString(
        footer(
          analyticsToken = None,
          analyticsHost  = "",
          ssoUrl         = None,
          scriptElem     = Some(Html("footer was rendered")),
          gaCalls        = None))

      rendered should include("footer was rendered")
    }

    "remove the query string by default from the page data item" in {
      val rendered = contentAsString(
        footer(
          analyticsToken = Some("TESTTOKEN"),
          analyticsHost  = "localhost",
          ssoUrl         = Some("localhost"),
          scriptElem     = None,
          gaCalls        = None))

      rendered should include("ga('set',  'page', location.pathname);")
    }

    "allow the query string by exception in the page data item" in {
      val rendered = contentAsString(
        footer(
          analyticsToken              = Some("TESTTOKEN"),
          analyticsHost               = "localhost",
          ssoUrl                      = Some("localhost"),
          scriptElem                  = None,
          allowQueryStringInAnalytics = true,
          gaCalls                     = None))

      rendered should not include "ga('set',  'page', location.pathname);"
    }
  }
} 
Example 11
Source File: GTMSnippetSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.jsoup.Jsoup
import org.scalatest.prop.PropertyChecks
import org.scalatest.{Matchers, WordSpec}
import play.api.Configuration
import play.api.test.Helpers._
import play.twirl.api.Html
import uk.gov.hmrc.play.config.GTMConfig
import uk.gov.hmrc.play.views.html.layouts.GTMSnippet
import scala.collection.JavaConverters._

class GTMSnippetSpec extends WordSpec with Matchers with PropertyChecks {
  "gtmSnippet" should {
    "include script tag with appropriate URL for container if gtm.container is defined" in {
      val transitionalUrl = "http://s3bucket/transitional/gtm.js"
      val mainUrl         = "http://s3bucket/main/gtm.js"
      val dataLayerUrl    = "http://s3bucket/include/gtm_dl.js"
      val containersAndUrls =
        Table(
          ("container", "url"),
          ("transitional", transitionalUrl),
          ("main", mainUrl)
        )

      forAll(containersAndUrls) { (container: String, url: String) =>
        val snippet = createSnippet(
          container       = Some(container),
          mainUrl         = Some(mainUrl),
          transitionalUrl = Some(transitionalUrl),
          dataLayerUrl    = Some(dataLayerUrl))
        script(snippet()) should contain(s"$url")
        script(snippet()) should contain(s"$dataLayerUrl")
      }
    }

    "not include script tag if gtm.container is not defined" in {
      val snippet = createSnippet(None, None, None, None)
      script(snippet()) shouldBe empty
    }
  }

  private def createSnippet(
    container: Option[String],
    mainUrl: Option[String],
    transitionalUrl: Option[String],
    dataLayerUrl: Option[String]): GTMSnippet = {
    val config = new GTMConfig(
      Configuration(
        Seq(
          container.map("gtm.container"              -> _),
          mainUrl.map("gtm.main.url"                 -> _),
          transitionalUrl.map("gtm.transitional.url" -> _),
          dataLayerUrl.map("gtm.data.layer.url"      -> _)
        ).flatten: _*))
    new GTMSnippet(config)
  }

  private def script(html: Html): List[String] = {
    val content  = contentAsString(html)
    val document = Jsoup.parse(content)
    document
      .head()
      .select("script")
      .iterator()
      .asScala
      .toList
      .map(_.attr("src"))
  }
} 
Example 12
Source File: ServiceInfoSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.layouts

import org.scalatest.{Matchers, WordSpec}
import play.twirl.api.Html
import uk.gov.hmrc.play.views.html.layouts.ServiceInfo
import play.api.test.Helpers._

class ServiceInfoSpec extends WordSpec with Matchers {

  "The serviceInfo" should {

    val serviceInfo = new ServiceInfo()

    "include hmrc branding when not specified" in {
      val content = contentAsString(serviceInfo(Html("label"), true, None))
      content should include("<div class=\"logo\">")
    }

    "include hmrc branding when specified" in {
      val content = contentAsString(serviceInfo(Html("label"), true, None, true))
      content should include("<div class=\"logo\">")
    }

    "not include hmrc branding when specified" in {
      val content = contentAsString(serviceInfo(Html("label"), true, None, false))
      content should not include ("<div class=\"logo\">")
    }

    "appear in english when no parameter is specified" in {
      val content = contentAsString(serviceInfo(Html("label"), true, None, true))
      content should include("HM Revenue &amp; Customs")
      content should not include ("Cyllid a Thollau EM")
    }

    "appear in welsh when a parameter of 'cy' is specified" in {
      val content = contentAsString(serviceInfo(Html("label"), true, None, true, "cy"))
      content should include("Cyllid a Thollau EM")
      content should not include ("HM Revenue &amp; Customs")
    }
  }
} 
Example 13
Source File: FormWithCSRFSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views
package helpers
import uk.gov.hmrc.play.MessagesSupport
import play.twirl.api.Html
import play.api.test.Helpers._
import org.scalatest.{Matchers, WordSpec}
import play.api.mvc.Call
import play.api.test.FakeRequest
import play.twirl.api.HtmlFormat
import uk.gov.hmrc.play.views.html.helpers.form

class FormWithCSRFSpec extends WordSpec with Matchers with MessagesSupport with CSRFSpec {

  "@helpers.formWithCSRF" should {
    val simpleCall = Call(method = "POST", url = "/the-post-url")

    "render with the correct action attribute" in {
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))
          .select("form")

      formElement.attr("action") shouldBe "/the-post-url"
    }

    "render with the correct action including a fragment" in {
      val formElement =
        jsoupDocument(form(action = simpleCall.withFragment("tab"))(HtmlFormat.empty))
          .select("form")

      formElement.attr("action") shouldBe "/the-post-url#tab"
    }

    "render with the correct method" in {
      val getCall = Call(method = "GET", url = "/the-post-url")

      val formElement =
        jsoupDocument(form(action = getCall)(HtmlFormat.empty))
          .select("form")

      formElement.attr("method") shouldBe "GET"
    }

    "render the passed attributes" in {
      val formElement =
        jsoupDocument(form(action = simpleCall, 'attribute1 -> "value1")(HtmlFormat.empty))
          .select("form")

      formElement.attr("attribute1") shouldBe "value1"
    }

    "render multiple attributes" in {
      val formElement =
        jsoupDocument(form(action = simpleCall, 'attribute1 -> "value1", 'attribute2 -> "value2")(HtmlFormat.empty))
          .select("form")

      formElement.attr("attribute1") shouldBe "value1"
      formElement.attr("attribute2") shouldBe "value2"
    }

    "render the contents of the form" in {
      val content = Html("<p>Content</p>")
      val formElement =
        jsoupDocument(form(action = simpleCall)(content))
          .select("p")

      formElement.outerHtml shouldBe "<p>Content</p>"
    }

    "not render the CSRF token if the request does not contain the token" in {
      implicit val request = FakeRequest()
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))

      val input = formElement.select("input")
      input.size shouldBe 0
    }

    "render the CSRF token" in {
      val formElement =
        jsoupDocument(form(action = simpleCall)(HtmlFormat.empty))

      val input = formElement.select("input")
      input.size shouldBe 1

      input.attr("type")         shouldBe "hidden"
      input.attr("name")         shouldBe "csrfToken"
      input.attr("value").length should be > 0
    }
  }
} 
Example 14
Source File: DateFieldsSpec.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views
package helpers

import org.scalatest.{Matchers, WordSpec}
import play.api.data.Form
import play.api.data.Forms.{mapping, of => fieldOf}
import play.api.data.format.Formats._
import play.api.test.Helpers._
import play.twirl.api.Html
import uk.gov.hmrc.play.MessagesSupport
import uk.gov.hmrc.play.views.html.helpers._

class DateFieldsSpec extends WordSpec with Matchers with MessagesSupport {

  val months = Seq(
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December")

  case class DummyFormData(day: Int, month: Int, year: Int)

  def dummyForm =
    Form(
      mapping(
        "dummyField.day"   -> fieldOf[Int],
        "dummyField.month" -> fieldOf[Int],
        "dummyField.year"  -> fieldOf[Int]
      )(DummyFormData.apply)(DummyFormData.unapply))

  "The Date Fields with a freeform year input box" should {
    "Display months using long nouns" in {
      val dateFieldsFreeYearInline = new DateFieldsFreeYearInline(new Input(), new Dropdown())
      val doc                      = jsoupDocument(dateFieldsFreeYearInline(dummyForm, "dummyField", Html("label")))
      months.zipWithIndex.foreach {
        case (month: String, i: Int) =>
          doc.getElementById(s"dummyField.month-${i + 1}").text shouldBe month
      }
    }
  }

  "The Date Fields with a limited year input box" should {
    "Display months using long nouns" in {
      val dateFieldsInline = new DateFieldsInline(new Dropdown())
      val doc              = jsoupDocument(dateFieldsInline(dummyForm, "dummyField", Html("label"), 1 to 2, None))
      months.zipWithIndex.foreach {
        case (month: String, i: Int) =>
          doc.getElementById(s"dummyField.month-${i + 1}").text shouldBe month
      }
    }
  }

} 
Example 15
Source File: model.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.helpers

import play.twirl.api.Html

trait FieldType

case class InputType(
  inputType: String,
  key: String,
  value: String,
  divClass: Option[String]      = None,
  labelClass: Option[String]    = None,
  inputClass: Option[String]    = None,
  dataAttribute: Option[String] = None,
  label: Option[String]         = None)
    extends FieldType

object RadioButton {
  def apply(
    key: String,
    value: String,
    divClass: Option[String]      = None,
    labelClass: Option[String]    = None,
    inputClass: Option[String]    = None,
    dataAttribute: Option[String] = None) =
    InputType("radio", key, value, divClass, labelClass, inputClass, dataAttribute)
}

object InputText {
  def apply(
    fieldLabel: String,
    divClass: Option[String]   = None,
    labelClass: Option[String] = None,
    inputClass: Option[String] = None,
    label: Option[String]      = None) =
    InputType("text", "", fieldLabel, divClass, labelClass, inputClass, label)
}

case class Select(
  values: Seq[(String, String)],
  emptyValueText: Option[String],
  label: String,
  labelClass: Option[String]          = None,
  groupClass: Option[String]          = None,
  selectClass: Option[String]         = None,
  additionalTitleText: Option[String] = None)
    extends FieldType

case class DateControl(yearRange: Range, extraClass: Option[String] = None) extends FieldType

case class FormField(field: play.api.data.Field, inputs: Seq[FieldType], explanationText: Option[Html] = None) 
Example 16
Source File: LocalErrorHandler.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package error

import akka.stream.Materializer
import config.ConfigDecorator
import controllers.auth.AuthJourney
import com.google.inject.{Inject, Singleton}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._
import play.twirl.api.Html
import uk.gov.hmrc.play.bootstrap.http.FrontendErrorHandler
import uk.gov.hmrc.renderer.TemplateRenderer
import javax.inject.Provider
import util.LocalPartialRetriever

@Singleton
class LocalErrorHandler @Inject()(
  val messagesApi: MessagesApi,
  val materializer: Materializer,
  authJourney: Provider[AuthJourney]
)(
  implicit val partialRetriever: LocalPartialRetriever,
  val configDecorator: ConfigDecorator,
  val templateRenderer: TemplateRenderer)
    extends FrontendErrorHandler with I18nSupport with RendersErrors {

  override def standardErrorTemplate(
    pageTitle: String,
    heading: String,
    message: String
  )(implicit request: Request[_]): Html =
    views.html.unauthenticatedError(pageTitle, Some(heading), Some(message))

} 
Example 17
Source File: MarkdownTheme.scala    From lightbend-markdown   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.markdown.theme

import play.doc.{TocTree, PlayDocTemplates, Toc}
import play.twirl.api.Html


  final val playDocTemplates: PlayDocTemplates = new PlayDocTemplates {
    override def nextLink(toc: TocTree): String = renderNextLink(toc).body
    override def nextLinks(toc: List[TocTree]): String = renderNextLinks(toc).body
    override def sidebar(hierarchy: List[Toc]): String = renderSidebar(hierarchy).body
    override def toc(toc: Toc): String = renderToc(toc).body
    override def breadcrumbs(hierarchy: List[Toc]): String = renderBreadcrumbs(hierarchy).body
  }
}

object MarkdownTheme {
  def load(classLoader: ClassLoader, objectName: Option[String]): MarkdownTheme = {
    objectName match {
      case Some("bare") => BareTheme
      case Some(name) => classLoader.loadClass(name + "$").getField("MODULE$").get(null).asInstanceOf[MarkdownTheme]
      case None => DefaultMarkdownTheme
    }
  }
}

object DefaultMarkdownTheme extends MarkdownTheme

trait BareTheme extends MarkdownTheme {
  override def renderPage(projectName: Option[String], title: Option[String], home: String, content: Html,
                          sidebar: Option[Html], breadcrumbs: Option[Html], apiDocs: Seq[(String, String)], sourceUrl: Option[String]): Html = content
  override def renderSidebar(hierarchy: List[Toc]): Html = Html("")
  override def renderNextLink(toc: TocTree): Html = Html("")
  override def renderNextLinks(toc: List[TocTree]): Html = Html("")
  override def renderBreadcrumbs(hierarchy: List[Toc]): Html = Html("")
}

object BareTheme extends BareTheme 
Example 18
Source File: GenerateSite.scala    From lightbend-markdown   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.markdown.generator

import java.io.File
import java.nio.file.Files

import com.lightbend.markdown.server.{AggregateFileRepository, PrefixedRepository, SourceFinder}
import com.lightbend.markdown.theme.MarkdownTheme
import com.lightbend.docs.TOC
import com.lightbend.markdown.{DocPath, Documentation, GenerateDocumentationConfig}
import play.api.libs.json.Json
import play.core.PlayVersion
import play.doc._
import play.twirl.api.{Content, Html}

object GenerateSite extends App {

  val jsonPath = new File(args.head)
  val configJson = Json.parse(Files.readAllBytes(jsonPath.toPath))
  val generateConfig = configJson.as[GenerateDocumentationConfig]

  import generateConfig._
  import config._

  val markdownTheme = MarkdownTheme.load(this.getClass.getClassLoader, theme)

  case class Docs(
    documentation: Documentation,
    repo: FileRepository
  )

  documentation.foreach { docs =>
    val repo = new AggregateFileRepository(docs.docsPaths.map {
      case DocPath(path, "." | "") => new FilesystemRepository(path)
      case DocPath(path, prefix) => new PrefixedRepository(prefix + "/", new FilesystemRepository(path))
    })

    val playDoc = new PlayDoc(repo, repo, "resources", PlayVersion.current, PageIndex.parseFrom(repo, docs.homePageTitle, None),
        markdownTheme.playDocTemplates, Some("html"))

    val index = playDoc.pageIndex.getOrElse(throw new IllegalStateException("Generating documentation only works for indexed documentation"))

    val outputPath = new File(outputDir, docs.name)

    def render(toc: Toc): Seq[String] = {
      toc.nodes.flatMap {
        case (_, childToc: Toc) => render(childToc)
        case (_, page: TocPage) =>
          println("Generating " + page.page + "...")
          playDoc.renderPage(page.page).map { rendered =>
            val sourcePath = for {
              url <- sourceUrl
              path <- SourceFinder.findPathFor(documentationRoot, docs.docsPaths, rendered.path)
            } yield s"$url$path"

            val renderedHtml: Content = markdownTheme.renderPage(projectName, None, docs.homePage, Html(rendered.html),
              rendered.sidebarHtml.map(Html.apply), rendered.breadcrumbsHtml.map(Html.apply), docs.apiDocs.toSeq, sourcePath)
            val pageName = page.page + ".html"
            Files.write(new File(outputPath, pageName).toPath, renderedHtml.body.getBytes("utf-8"))
            pageName
          }.toSeq
      }
    }

    // Ensure parent directory exists
    Files.createDirectories(outputPath.toPath)

    // Render all pages
    val allPages = render(index.toc).toSet

    // Delete all pages that don't exist
    outputPath.list().filterNot(allPages).foreach(new File(outputPath, _).delete())

    if (generateIndex) {
      def convertToc(toc: TocTree): TOC = {
        toc match {
          case childToc: Toc =>
            TOC(childToc.title, None, None, nostyle = false, None, childToc.nodes.map(_._2).map(convertToc), None)
          case page: TocPage =>
            val sourcePath = for {
              url <- sourceUrl
              indexPage <- index.get(page.page)
              path <- SourceFinder.findPathFor(documentationRoot, docs.docsPaths, indexPage.fullPath + ".md")
            } yield {
              s"$url$path"
            }

            TOC(page.title, Some(page.page + ".html"), sourcePath, nostyle = false, None, Nil, page.next.map(_.map(_ + ".html")))
        }
      }

      val tocJson = Json.toJson(convertToc(index.toc))
      val indexFile = new File(outputPath, "index.json")
      Files.write(indexFile.toPath, Json.prettyPrint(tocJson).getBytes("utf-8"))
    }
  }

  println("Done!")
} 
Example 19
Source File: BootstrapEndpoints.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package cqrs.publicserver

import endpoints4s.openapi.model.OpenApi
import endpoints4s.play.server.{
  Assets,
  Endpoints,
  JsonEntitiesFromEncodersAndDecoders,
  PlayComponents
}
import play.api.routing.{Router => PlayRouter}
import play.twirl.api.{Html, StringInterpolation}

 ))
    )

  lazy val digests = BootstrapDigests.digests

  lazy val indexHtml =
    html"""<!DOCTYPE html>
          <html>
            <head>
              <script src="${assets
      .call(asset("example-cqrs-web-client-fastopt.js"))
      .url}" defer></script>
              <title>Meters</title>
            </head>
            <body></body>
          </html>
        """

} 
Example 20
Source File: MockTemplateRenderer.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import org.scalatest.mock.MockitoSugar
import play.api.Mode.Mode
import play.api.i18n.Messages
import play.api.{Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.nisp.config.{LocalTemplateRenderer, WsAllMethods}

import scala.concurrent.duration._

object MockTemplateRenderer extends LocalTemplateRenderer {
  override lazy val templateServiceBaseUrl = "http://example.com/template/mustache"
  override val refreshAfter = 10 minutes
  override val wsHttp = MockitoSugar.mock[WsAllMethods]

  override def renderDefaultTemplate(path:String, content: Html, extraArgs: Map[String, Any])(implicit messages: Messages) = {
    Html(
      "<title>" + extraArgs("pageTitle") + "</title>"
        + "<sidebar>"+extraArgs("sidebar")+"</sidebar>"
        + "<navLinks>"+extraArgs("navLinks")+"</navLinks>"
        + displayUrBanner(extraArgs) +
        "<mainContentHeader>" +extraArgs("mainContentHeader")+ "</mainContentHeader>"
        + content)
  }

    def displayUrBanner(extraArgs: Map[String, Any]): String ={
      if(extraArgs.contains("fullWidthBannerTitle")){
        "<div id=full-width-banner>" + "<div class = \"full-width-banner__title\">" + extraArgs("fullWidthBannerTitle") + "</div>" + "<div id = fullWidthBannerLink>" + extraArgs("fullWidthBannerLink") +  "</div>"+ "<div>" + extraArgs("fullWidthBannerText")+ "</div>"+ "<div id = fullWidthBannerDismissText>"+extraArgs("fullWidthBannerDismissText")+"</div>"
      }
      else ""
    }

  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
} 
Example 21
Source File: ApplicationGlobal.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.config

import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode.Mode
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.nisp.config.wiring.NispAuditConnector
import uk.gov.hmrc.nisp.controllers.NispFrontendController
import uk.gov.hmrc.nisp.controllers.partial.PartialRetriever
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.frontend.filters.{FrontendAuditFilter, FrontendLoggingFilter, MicroserviceFilterSupport}

object ApplicationGlobal extends ApplicationGlobalTrait {
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override def messagesApi = Play.current.injector.instanceOf[MessagesApi]
}

trait ApplicationGlobalTrait extends DefaultFrontendGlobal with RunMode with PartialRetriever with NispFrontendController with I18nSupport {

  implicit lazy val app:Application = Play.current

  override val auditConnector = NispAuditConnector
  override val loggingFilter = NispLoggingFilter
  override val frontendAuditFilter = NispFrontendAuditFilter

  override def onStart(app: Application) {
    super.onStart(app)
    new ApplicationCrypto(Play.current.configuration.underlying).verifyConfiguration()
  }

  override def internalServerErrorTemplate(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.service_error_500()

  override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit request: Request[_]): Html =
    uk.gov.hmrc.nisp.views.html.global_error(pageTitle, heading, message)

  override def notFoundTemplate(implicit request: Request[_]): Html = {
    uk.gov.hmrc.nisp.views.html.page_not_found_template()
  }

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}

object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object NispLoggingFilter extends FrontendLoggingFilter with MicroserviceFilterSupport {
  override def controllerNeedsLogging(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object NispFrontendAuditFilter extends FrontendAuditFilter with RunMode with AppName with MicroserviceFilterSupport {
  override lazy val maskedFormFields = Seq.empty
  override lazy val applicationPort = None
  override lazy val auditConnector = NispAuditConnector
  override def controllerNeedsAuditing(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuditing
  override protected def mode: Mode = Play.current.mode
  override protected def runModeConfiguration: Configuration = Play.current.configuration
  override protected def appNameConfiguration: Configuration = Play.current.configuration
} 
Example 22
Source File: MainTemplateParams.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.views.viewParams

import play.twirl.api.Html
import uk.gov.hmrc.nisp.config.ApplicationConfig

case class MainTemplateParams(
  browserTitle: Option[String] = None,
  pageInfo: Option[String] = None,
  pageTitle: Option[String] = None,
  h1Class: Option[String] = None,
  printableDocument: Boolean = false,
  sidebarLinks: Option[Html] = None,
  sidebarClasses: Option[String] = None,
  userLoggedIn: Boolean = false,
  applicationConfig: ApplicationConfig = ApplicationConfig,
  showTitleHeaderNav: Boolean = true,
  showBetaBanner: Boolean = false,
  pageScripts: Option[Html] = None,
  articleClasses: Option[String] = None,
  gaDimensions: Option[Map[String, Any]] = None,
  analyticsAdditionalJs: Option[Html] = None,
  articleEnabled: Boolean = true,
  hideBreadcrumb: Boolean = false,
  showUrBanner: Boolean = false,
  hideNavBar: Boolean = false
) 
Example 23
Source File: PaperlessPreferencesControllerSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import controllers.auth.{AuthJourney, WithActiveTabAction, WithBreadcrumbAction}
import models.{ActivatedOnlineFilerSelfAssessmentUser, NonFilerSelfAssessmentUser}
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.MessagesApi
import play.api.mvc.{ActionBuilder, MessagesControllerComponents, Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.twirl.api.Html
import services.partials.PreferencesFrontendPartialService
import uk.gov.hmrc.auth.core.ConfidenceLevel
import uk.gov.hmrc.auth.core.retrieve.Credentials
import uk.gov.hmrc.domain.SaUtr
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import util.{ActionBuilderFixture, BaseSpec, BetterOptionValues, LocalPartialRetriever, Tools}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class PaperlessPreferencesControllerSpec extends BaseSpec with MockitoSugar {
  import BetterOptionValues._

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  val mockPreferencesFrontendPartialService = mock[PreferencesFrontendPartialService]
  val mockAuthJourney = mock[AuthJourney]

  def controller: PaperlessPreferencesController =
    new PaperlessPreferencesController(
      mockPreferencesFrontendPartialService,
      mockAuthJourney,
      injected[WithActiveTabAction],
      injected[WithBreadcrumbAction],
      injected[MessagesControllerComponents],
      injected[Tools]
    )(mock[LocalPartialRetriever], injected[ConfigDecorator], injected[TemplateRenderer], injected[ExecutionContext]) {}

  "Calling PaperlessPreferencesController.managePreferences" should {
    "Redirect to  preferences-frontend manage paperless url when a user is logged in using GG" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(request = request)
          )
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe SEE_OTHER

      val redirectUrl = redirectLocation(r).getValue
      val configDecorator = app.injector.instanceOf[ConfigDecorator]
      redirectUrl should include regex s"${configDecorator.preferencesFrontendService}/paperless/check-settings\\?returnUrl=.*\\&returnLinkText=.*"
    }

    "Return 400 for Verify users" in {

      when(mockAuthJourney.authWithPersonalDetails).thenReturn(new ActionBuilderFixture {
        override def invokeBlock[A](request: Request[A], block: UserRequest[A] => Future[Result]): Future[Result] =
          block(
            buildUserRequest(
              credentials = Credentials("", "Verify"),
              confidenceLevel = ConfidenceLevel.L500,
              request = request
            ))
      })

      val r = controller.managePreferences(FakeRequest())
      status(r) shouldBe BAD_REQUEST
    }
  }
} 
Example 24
Source File: FormPartialServiceSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package services

import com.codahale.metrics.Timer
import com.kenshoo.play.metrics.Metrics
import config.ConfigDecorator
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.{Configuration, Environment}
import play.twirl.api.Html
import services.partials.FormPartialService
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import uk.gov.hmrc.play.bootstrap.filters.frontend.crypto.SessionCookieCrypto
import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient
import uk.gov.hmrc.play.partials.HtmlPartial
import util.BaseSpec
import util.Fixtures._

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

class FormPartialServiceSpec extends BaseSpec {

  trait LocalSetup {
    val servicesConfig = app.injector.instanceOf[ServicesConfig]
    val timer = MockitoSugar.mock[Timer.Context]
    val formPartialService: FormPartialService = new FormPartialService(
      injected[Environment],
      injected[Configuration],
      MockitoSugar.mock[DefaultHttpClient],
      MockitoSugar.mock[Metrics],
      MockitoSugar.mock[ConfigDecorator],
      injected[SessionCookieCrypto],
      servicesConfig
    ) {
      override val metricsOperator: MetricsOperator = MockitoSugar.mock[MetricsOperator]
      when(metricsOperator.startTimer(any())) thenReturn timer
    }
  }

  "Calling FormPartialServiceSpec" should {

    "return form list for National insurance" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getNationalInsurancePartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

    "return form list for Self-assessment" in new LocalSetup {

      when(formPartialService.http.GET[HtmlPartial](any())(any(), any(), any())) thenReturn
        Future.successful[HtmlPartial](HtmlPartial.Success(Some("Title"), Html("<title/>")))

      formPartialService.getSelfAssessmentPartial(buildFakeRequestWithAuth("GET")).map(p => p shouldBe "<title/>")
      verify(formPartialService.http, times(1)).GET[Html](any())(any(), any(), any())
    }

  }

} 
Example 25
Source File: ViewNationalInsuranceInterstitialHomeViewSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package views.html.interstitial

import config.ConfigDecorator
import org.scalatestplus.mockito.MockitoSugar
import play.api.test.FakeRequest
import play.twirl.api.Html
import uk.gov.hmrc.renderer.TemplateRenderer
import util.UserRequestFixture.buildUserRequest
import views.html.ViewSpec

class ViewNationalInsuranceInterstitialHomeViewSpec extends ViewSpec with MockitoSugar {

  override implicit lazy val app = localGuiceApplicationBuilder().build()

  lazy val view = injected[ViewNationalInsuranceInterstitialHomeView]

  implicit val templateRenderer = app.injector.instanceOf[TemplateRenderer]
  implicit val configDecorator: ConfigDecorator = injected[ConfigDecorator]
  implicit val userRequest = buildUserRequest(request = FakeRequest())

  "Rendering ViewNationalInsuranceInterstitialHomeView.scala.html" should {

    "show NINO section when a nino is present" in {
      val document = asDocument(view(Html(""), "asfa", userRequest.nino).toString)
      Option(document.select(".nino").first).isDefined shouldBe true
    }

    "show incomplete when there is no NINO" in {
      val document = asDocument(view(Html(""), "http://google.com", None).toString)
      Option(document.select(".nino").first).isDefined shouldBe false
      document.body().toString should include(messages("label.you_can_see_this_part_of_your_account_if_you_complete"))
    }

  }
} 
Example 26
Source File: HomeViewModel.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package viewmodels

import models.{SelfAssessmentUser, SelfAssessmentUserType}
import play.twirl.api.Html

final case class HomeViewModel(
  incomeCards: Seq[Html],
  benefitCards: Seq[Html],
  pensionCards: Seq[Html],
  showUserResearchBanner: Boolean,
  saUtr: Option[String])

object HomeViewModel {
  def apply(
    incomeCards: Seq[Html],
    benefitCards: Seq[Html],
    pensionCards: Seq[Html],
    showUserResearchBanner: Boolean,
    selfAssessmentUserType: SelfAssessmentUserType): HomeViewModel = {

    val utr: Option[String] = selfAssessmentUserType match {
      case saUser: SelfAssessmentUser => Some(saUser.saUtr.toString())
      case _                          => None
    }

    HomeViewModel(incomeCards, benefitCards, pensionCards, showUserResearchBanner, utr)
  }
} 
Example 27
Source File: PersonalDetailsController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.controllershelpers.{AddressJourneyCachingHelper, PersonalDetailsCardGenerator}
import models.{AddressJourneyTTLModel, AddressPageVisitedDtoId, PersonDetails}
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import play.twirl.api.Html
import repositories.EditAddressLockRepository
import services.NinoDisplayService
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.renderer.TemplateRenderer
import util.AuditServiceTools.buildPersonDetailsEvent
import util.LocalPartialRetriever
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.PersonalDetailsView

import scala.concurrent.{ExecutionContext, Future}

class PersonalDetailsController @Inject()(
  val personalDetailsCardGenerator: PersonalDetailsCardGenerator,
  val editAddressLockRepository: EditAddressLockRepository,
  ninoDisplayService: NinoDisplayService,
  authJourney: AuthJourney,
  cachingHelper: AddressJourneyCachingHelper,
  withActiveTabAction: WithActiveTabAction,
  auditConnector: AuditConnector,
  cc: MessagesControllerComponents,
  displayAddressInterstitialView: DisplayAddressInterstitialView,
  personalDetailsView: PersonalDetailsView
)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends AddressController(authJourney, withActiveTabAction, cc, displayAddressInterstitialView) {

  def onPageLoad: Action[AnyContent] = authenticate.async { implicit request =>
    import models.dto.AddressPageVisitedDto

    for {
      addressModel <- request.nino
                       .map { nino =>
                         editAddressLockRepository.get(nino.withoutSuffix)
                       }
                       .getOrElse(Future.successful(List[AddressJourneyTTLModel]()))
      ninoToDisplay <- ninoDisplayService.getNino
      personalDetailsCards: Seq[Html] = personalDetailsCardGenerator
        .getPersonalDetailsCards(addressModel, ninoToDisplay)
      personDetails: Option[PersonDetails] = request.personDetails

      _ <- personDetails
            .map { details =>
              auditConnector.sendEvent(buildPersonDetailsEvent("personalDetailsPageLinkClicked", details))
            }
            .getOrElse(Future.successful(Unit))
      _ <- cachingHelper.addToCache(AddressPageVisitedDtoId, AddressPageVisitedDto(true))

    } yield Ok(personalDetailsView(personalDetailsCards))
  }
} 
Example 28
Source File: HomeCardGenerator.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import models._
import play.api.i18n.Messages
import play.api.mvc.AnyContent
import play.twirl.api.{Html, HtmlFormat}
import util.DateTimeTools.previousAndCurrentTaxYear
import viewmodels.TaxCalculationViewModel
import views.html.cards.home._

@Singleton
class HomeCardGenerator @Inject()(
  payAsYouEarnView: PayAsYouEarnView,
  taxCalculationView: TaxCalculationView,
  selfAssessmentView: SelfAssessmentView,
  nationalInsuranceView: NationalInsuranceView,
  taxCreditsView: TaxCreditsView,
  childBenefitView: ChildBenefitView,
  marriageAllowanceView: MarriageAllowanceView,
  statePensionView: StatePensionView
)(implicit configDecorator: ConfigDecorator) {

  def getIncomeCards(
    taxComponentsState: TaxComponentsState,
    taxCalculationStateCyMinusOne: Option[TaxYearReconciliation],
    taxCalculationStateCyMinusTwo: Option[TaxYearReconciliation],
    saActionNeeded: SelfAssessmentUserType,
    currentTaxYear: Int)(implicit request: UserRequest[AnyContent], messages: Messages): Seq[Html] =
    List(
      getPayAsYouEarnCard(taxComponentsState),
      getTaxCalculationCard(taxCalculationStateCyMinusOne),
      getTaxCalculationCard(taxCalculationStateCyMinusTwo),
      getSelfAssessmentCard(saActionNeeded, currentTaxYear + 1),
      getNationalInsuranceCard()
    ).flatten

  def getBenefitCards(taxComponents: Option[TaxComponents])(implicit messages: Messages): Seq[Html] =
    List(
      getTaxCreditsCard(configDecorator.taxCreditsPaymentLinkEnabled),
      getChildBenefitCard(),
      getMarriageAllowanceCard(taxComponents)
    ).flatten

  def getPensionCards()(implicit messages: Messages): Seq[Html] =
    List(
      getStatePensionCard()
    ).flatten

  def getPayAsYouEarnCard(taxComponentsState: TaxComponentsState)(
    implicit request: UserRequest[_],
    messages: Messages): Option[HtmlFormat.Appendable] =
    request.nino.flatMap { _ =>
      taxComponentsState match {
        case TaxComponentsNotAvailableState => None
        case _                              => Some(payAsYouEarnView(configDecorator))
      }
    }

  def getTaxCalculationCard(taxYearReconciliations: Option[TaxYearReconciliation])(
    implicit messages: Messages): Option[HtmlFormat.Appendable] =
    taxYearReconciliations
      .flatMap(TaxCalculationViewModel.fromTaxYearReconciliation)
      .map(taxCalculationView(_))

  def getSelfAssessmentCard(saActionNeeded: SelfAssessmentUserType, nextDeadlineTaxYear: Int)(
    implicit request: UserRequest[AnyContent],
    messages: Messages): Option[HtmlFormat.Appendable] =
    if (!request.isVerify) {
      saActionNeeded match {
        case NonFilerSelfAssessmentUser => None
        case saWithActionNeeded =>
          Some(selfAssessmentView(saWithActionNeeded, previousAndCurrentTaxYear, nextDeadlineTaxYear.toString))
      }
    } else {
      None
    }

  def getNationalInsuranceCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(nationalInsuranceView())

  def getTaxCreditsCard(showTaxCreditsPaymentLink: Boolean)(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(taxCreditsView(showTaxCreditsPaymentLink))

  def getChildBenefitCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(childBenefitView())

  def getMarriageAllowanceCard(taxComponents: Option[TaxComponents])(
    implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(marriageAllowanceView(taxComponents))

  def getStatePensionCard()(implicit messages: Messages): Some[HtmlFormat.Appendable] =
    Some(statePensionView())
} 
Example 29
Source File: PersonalDetailsCardGenerator.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.controllershelpers

import config.ConfigDecorator
import controllers.auth.requests.UserRequest
import com.google.inject.{Inject, Singleton}
import models.{AddressJourneyTTLModel, EditCorrespondenceAddress, EditPrimaryAddress, EditSoleAddress}
import play.twirl.api.{Html, HtmlFormat}
import uk.gov.hmrc.domain.Nino
import views.html.cards.personaldetails._

@Singleton
class PersonalDetailsCardGenerator @Inject()(
  val configDecorator: ConfigDecorator,
  val countryHelper: CountryHelper,
  mainAddress: MainAddressView,
  postalAddress: PostalAddressView,
  nationalInsurance: NationalInsuranceView,
  changeName: ChangeNameView
) {

  def getPersonalDetailsCards(changedAddressIndicator: List[AddressJourneyTTLModel], ninoToDisplay: Option[Nino])(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    messages: play.api.i18n.Messages): Seq[Html] = {

    val optionalEditAddress = changedAddressIndicator.map(y => y.editedAddress)

    val mainAddressChangeIndicator = optionalEditAddress.exists(_.isInstanceOf[EditSoleAddress]) || optionalEditAddress
      .exists(_.isInstanceOf[EditPrimaryAddress])
    val correspondenceAddressChangeIndicator =
      optionalEditAddress.exists(_.isInstanceOf[EditCorrespondenceAddress])

    List(
      getChangeNameCard(),
      getMainAddressCard(mainAddressChangeIndicator),
      getPostalAddressCard(correspondenceAddressChangeIndicator),
      getNationalInsuranceCard(ninoToDisplay)
    ).flatten
  }

  private def getPersonDetails()(implicit request: UserRequest[_]) =
    request.personDetails

  def hasCorrespondenceAddress()(implicit request: UserRequest[_]): Boolean = {
    val cAdd = getPersonDetails.flatMap(_.correspondenceAddress)
    cAdd.isDefined
  }

  def getMainAddressCard(isLocked: Boolean)(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    getPersonDetails match {
      case Some(personDetails) =>
        Some(
          mainAddress(
            personDetails = personDetails,
            taxCreditsEnabled = configDecorator.taxCreditsEnabled,
            hasCorrespondenceAddress = hasCorrespondenceAddress,
            isLocked = isLocked,
            countryHelper.excludedCountries
          ))
      case _ => None
    }

  def getPostalAddressCard(isLocked: Boolean)(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    getPersonDetails match {
      case Some(personDetails) =>
        hasCorrespondenceAddress match {
          case true if !personDetails.correspondenceAddress.exists(_.isWelshLanguageUnit) =>
            Some(
              postalAddress(
                personDetails = personDetails,
                isLocked = isLocked,
                countryHelper.excludedCountries,
                configDecorator.closePostalAddressEnabled))
          case _ => None
        }
      case _ => None
    }

  def getNationalInsuranceCard(ninoToDisplay: Option[Nino])(
    implicit request: UserRequest[_],
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    ninoToDisplay.map(n => nationalInsurance(n))

  def getChangeNameCard()(
    implicit request: UserRequest[_],
    configDecorator: ConfigDecorator,
    messages: play.api.i18n.Messages): Option[HtmlFormat.Appendable] =
    request.name.map(_ => changeName())
} 
Example 30
Source File: MessageController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth._
import error.RendersErrors
import models.Breadcrumb
import play.api.i18n.Messages
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents}
import play.twirl.api.Html
import services.partials.MessageFrontendService
import uk.gov.hmrc.play.partials.HtmlPartial
import uk.gov.hmrc.renderer.{ActiveTabMessages, TemplateRenderer}
import util.LocalPartialRetriever
import views.html.message.{MessageDetailView, MessageInboxView}

import scala.concurrent.ExecutionContext

class MessageController @Inject()(
  val messageFrontendService: MessageFrontendService,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  withBreadcrumbAction: WithBreadcrumbAction,
  cc: MessagesControllerComponents,
  messageInboxView: MessageInboxView,
  messageDetailView: MessageDetailView)(
  implicit val partialRetriever: LocalPartialRetriever,
  val configDecorator: ConfigDecorator,
  val templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends PertaxBaseController(cc) with RendersErrors {

  def messageBreadcrumb: Breadcrumb =
    "label.all_messages" -> routes.MessageController.messageList().url ::
      baseBreadcrumb

  def messageList: Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction.addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction
      .addBreadcrumb(baseBreadcrumb)).async { implicit request =>
      messageFrontendService.getMessageListPartial map { p =>
        Ok(
          messageInboxView(
            messageListPartial = p successfulContentOrElse Html(
              Messages("label.sorry_theres_been_a_technical_problem_retrieving_your_messages")))
        )
      }
    }

  def messageDetail(messageToken: String): Action[AnyContent] =
    (authJourney.authWithPersonalDetails andThen withActiveTabAction.addActiveTab(ActiveTabMessages) andThen withBreadcrumbAction
      .addBreadcrumb(messageBreadcrumb)).async { implicit request =>
      messageFrontendService.getMessageDetailPartial(messageToken).map {
        case HtmlPartial.Success(Some(title), content) =>
          Ok(messageDetailView(message = content, title = title))
        case HtmlPartial.Success(None, content) =>
          Ok(messageDetailView(message = content, title = Messages("label.message")))
        case HtmlPartial.Failure(_, _) =>
          Ok(
            messageDetailView(
              message = Html(Messages("label.sorry_theres_been_a_techinal_problem_retrieving_your_message")),
              title = Messages("label.message")
            )
          )
      }
    }
}