repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchedController.scala | <reponame>hmrc/organisations-matching-api
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.controllers
import play.api.hal.Hal.state
import play.api.hal.HalLink
import play.api.libs.json.Json
import play.api.libs.json.Json.toJson
import play.api.mvc.{Action, AnyContent, ControllerComponents, MessagesControllerComponents}
import uk.gov.hmrc.auth.core.AuthConnector
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
import uk.gov.hmrc.organisationsmatchingapi.play.RequestHeaderUtils.{maybeCorrelationId, validateCorrelationId}
import uk.gov.hmrc.organisationsmatchingapi.services.{MatchedService, ScopesHelper, ScopesService}
import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext
@Singleton
class MatchedController @Inject()(val authConnector: AuthConnector,
cc: ControllerComponents,
mcc: MessagesControllerComponents,
scopeService: ScopesService,
scopesHelper: ScopesHelper,
matchedService: MatchedService)
(implicit auditHelper: AuditHelper,
ec: ExecutionContext) extends BaseApiController(mcc, cc)
with PrivilegedAuthentication {
def matchedOrganisationCt(matchId: String): Action[AnyContent] = Action.async { implicit request =>
val self = s"/organisations/matching/corporation-tax/$matchId"
authenticate(scopeService.getAllScopes, matchId) { authScopes =>
val correlationId = validateCorrelationId(request)
withValidUuid(matchId, "matchId") { matchIdUuuid =>
matchedService.fetchCt(matchIdUuuid) map { cacheData =>
val exclude = Some(List("getSelfAssessmentDetails"))
val selfLink = HalLink("self", self)
val links = scopesHelper.getHalLinks(matchIdUuuid, exclude, authScopes, None, true) ++ selfLink
val response = Json.toJson(state(CtMatch.convert(cacheData)) ++ links)
auditHelper.auditApiResponse(
correlationId.toString, matchId.toString, authScopes.mkString(","), request, selfLink.toString, Some(response)
)
Ok(response)
}
}
} recover recoveryWithAudit(maybeCorrelationId(request), request.body.toString, self)
}
def matchedOrganisationSa(matchId: String) : Action[AnyContent] = Action.async { implicit request =>
val self = s"/organisations/matching/self-assessment/$matchId"
authenticate(scopeService.getAllScopes, matchId) { authScopes =>
val correlationId = validateCorrelationId(request)
withValidUuid(matchId, "matchId") { matchIdUuuid =>
matchedService.fetchSa(matchIdUuuid) map { cacheData =>
val exclude = Some(List("getCorporationTaxDetails"))
val selfLink = HalLink("self", self)
val links = scopesHelper.getHalLinks(matchIdUuuid, exclude, authScopes, None, true) ++ selfLink
val response = Json.toJson(state(SaMatch.convert(cacheData)) ++ links)
auditHelper.auditApiResponse(
correlationId.toString, matchId.toString, authScopes.mkString(","), request, selfLink.toString, Some(response)
)
Ok(response)
}
}
} recover recoveryWithAudit(maybeCorrelationId(request), request.body.toString, self)
}
def matchedOrganisation(matchId: String) = Action.async { implicit request =>
withValidUuid(matchId, "matchId") { matchIdUuuid =>
matchedService.fetchMatchedOrganisationRecord(matchIdUuuid) map { matchedOrganisation =>
Ok(toJson(matchedOrganisation))
}
} recover recoveryWithAudit(maybeCorrelationId(request), matchId.toString, s"/match-record/$matchId")
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/connectors/OrganisationsMatchingConnector.scala | <reponame>hmrc/organisations-matching-api
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.connectors
import play.api.Logger
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.RequestHeader
import uk.gov.hmrc.http.{HeaderCarrier, HttpClient, InternalServerException, JsValidationException, NotFoundException, Upstream4xxResponse, Upstream5xxResponse}
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.{CtOrganisationsMatchingRequest, SaOrganisationsMatchingRequest}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import javax.inject.Inject
import uk.gov.hmrc.organisationsmatchingapi.domain.models.MatchingException
import scala.concurrent.{ExecutionContext, Future}
class OrganisationsMatchingConnector @Inject()(servicesConfig: ServicesConfig,
http: HttpClient,
val auditHelper: AuditHelper) {
val logger : Logger = Logger(this.getClass)
private val baseUrl = servicesConfig.baseUrl("organisations-matching")
val requiredHeaders: Seq[String] = Seq("X-Application-ID", "CorrelationId")
def matchCycleCotax(matchId: String, correlationId: String, postData: CtOrganisationsMatchingRequest)
(implicit hc: HeaderCarrier, request: RequestHeader, ec: ExecutionContext): Future[JsValue] = {
val url = s"$baseUrl/organisations-matching/perform-match/cotax?matchId=$matchId&correlationId=$correlationId"
recover(http.POST[CtOrganisationsMatchingRequest, JsValue](url, postData, hc.headers(requiredHeaders)) map {
response =>
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, url, response)
response
}, correlationId, matchId, request, url)
}
def matchCycleSelfAssessment(matchId: String, correlationId: String, postData: SaOrganisationsMatchingRequest)
(implicit hc: HeaderCarrier, request: RequestHeader, ec: ExecutionContext): Future[JsValue] = {
val url = s"$baseUrl/organisations-matching/perform-match/self-assessment?matchId=$matchId&correlationId=$correlationId"
recover(http.POST[SaOrganisationsMatchingRequest, JsValue](url, postData, hc.headers(requiredHeaders)) map {
response =>
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, url, response)
response
}, correlationId, matchId, request, url)
}
private def recover(x: Future[JsValue],
correlationId: String,
matchId: String,
request: RequestHeader,
requestUrl: String)
(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[JsValue] = x.recoverWith {
case notFound: NotFoundException => {
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, requestUrl, Json.toJson(notFound.getMessage))
// No Kibana for security reasons. Splunk only.
throw new MatchingException
}
case validationError: JsValidationException => {
logger.warn("Organisations Matching JsValidationException encountered")
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, requestUrl, s"Error parsing organisations matching response: ${validationError.errors}")
Future.failed(new InternalServerException("Something went wrong."))
}
case Upstream5xxResponse(msg, code, _, _) => {
logger.warn(s"Organisations Matching Upstream5xxResponse encountered: $code")
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, requestUrl, s"Internal Server error: $msg")
Future.failed(new InternalServerException("Something went wrong."))
}
case Upstream4xxResponse(msg, code, _, _) => {
logger.warn(s"Organisations Matching Upstream4xxResponse encountered: $code")
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, requestUrl, msg)
Future.failed(new InternalServerException("Something went wrong."))
}
case e: Exception => {
logger.warn(s"Organisations Matching Exception encountered")
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, requestUrl, e.getMessage)
Future.failed(new InternalServerException("Something went wrong."))
}
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchingController.scala | <gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.controllers
import play.api.hal.Hal.state
import play.api.hal.HalLink
import play.api.libs.json.Json.toJson
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.{Action, ControllerComponents, MessagesControllerComponents, PlayBodyParsers}
import uk.gov.hmrc.auth.core.AuthConnector
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, MatchIdResponse, SaMatchingRequest}
import uk.gov.hmrc.organisationsmatchingapi.play.RequestHeaderUtils._
import uk.gov.hmrc.organisationsmatchingapi.services.{CacheService, MatchingService, ScopesHelper, ScopesService}
import java.util.UUID
import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext
@Singleton
class MatchingController @Inject()(val authConnector: AuthConnector,
cc: ControllerComponents,
mcc: MessagesControllerComponents,
scopeService: ScopesService,
scopesHelper: ScopesHelper,
bodyParsers: PlayBodyParsers,
cacheService: CacheService,
matchingService: MatchingService)
(implicit auditHelper: AuditHelper,
ec: ExecutionContext) extends BaseApiController(mcc, cc)
with PrivilegedAuthentication {
def matchOrganisationCt() : Action[JsValue] = Action.async(bodyParsers.json) { implicit request =>
val matchId = UUID.randomUUID()
val self = "/organisations/matching/corporation-tax"
authenticate(scopeService.getAllScopes, matchId.toString) { authScopes =>
withValidJson[CtMatchingRequest] { matchRequest => {
val correlationId = validateCorrelationId(request)
matchingService.matchCoTax(matchId, correlationId.toString, matchRequest).map { _ => {
val selfLink = HalLink("self", self)
val data = toJson(MatchIdResponse(matchId))
val response = Json.toJson(state(data) ++ scopesHelper.getHalLinks(matchId, None, authScopes, Some(List("getCorporationTaxMatch"))) ++ selfLink)
auditHelper.auditApiResponse(
correlationId.toString,
matchId.toString,
authScopes.mkString(","),
request,
selfLink.toString,
Some(response))
Ok(response)
}
}
}}
} recover recoveryWithAudit(maybeCorrelationId(request), request.body.toString, self)
}
def matchOrganisationSa() : Action[JsValue] = Action.async(bodyParsers.json) { implicit request =>
val matchId = UUID.randomUUID()
val self = "/organisations/matching/self-assessment"
authenticate(scopeService.getAllScopes, matchId.toString) { authScopes =>
withValidJson[SaMatchingRequest] { matchRequest => {
val correlationId = validateCorrelationId(request)
matchingService.matchSaTax(matchId, correlationId.toString, matchRequest).map { _ => {
val selfLink = HalLink("self", self)
val data = toJson(MatchIdResponse(matchId))
val response = Json.toJson(state(data) ++ scopesHelper.getHalLinks(matchId, None, authScopes, Some(List("getSelfAssessmentMatch"))) ++ selfLink)
auditHelper.auditApiResponse(
correlationId.toString,
matchId.toString,
authScopes.mkString(","),
request,
selfLink.toString,
Some(response))
Ok(response)
}
}
}}
} recover recoveryWithAudit(maybeCorrelationId(request), request.body.toString, self)
}
} |
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/domain/integrationframework/IfCorpTaxCompanyDetails.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework
import play.api.libs.functional.syntax.unlift
import play.api.libs.json.{Format, JsPath}
import play.api.libs.json.Reads.{pattern, _}
import play.api.libs.functional.syntax._
case class IfNameDetails( name1: Option[String],
name2: Option[String] )
object IfNameDetails {
implicit val format: Format[IfNameDetails] = Format(
(
(JsPath \ "name1").readNullable[String](maxLength(100)) and
(JsPath \ "name2").readNullable[String](maxLength(100))
)(IfNameDetails.apply _),
(
(JsPath \ "name1").writeNullable[String] and
(JsPath \ "name2").writeNullable[String]
)(unlift(IfNameDetails.unapply))
)
}
case class IfNameAndAddressDetails( name: Option[IfNameDetails],
address: Option[IfAddress] )
object IfNameAndAddressDetails {
implicit val format: Format[IfNameAndAddressDetails] = Format(
(
(JsPath \ "name").readNullable[IfNameDetails] and
(JsPath \ "address").readNullable[IfAddress]
)(IfNameAndAddressDetails.apply _),
(
(JsPath \ "name").writeNullable[IfNameDetails] and
(JsPath \ "address").writeNullable[IfAddress]
)(unlift(IfNameAndAddressDetails.unapply))
)
}
case class IfCorpTaxCompanyDetails( utr: Option[String],
crn: Option[String],
registeredDetails: Option[IfNameAndAddressDetails],
communicationDetails: Option[IfNameAndAddressDetails])
object IfCorpTaxCompanyDetails {
val utrPattern = "^[0-9]{10}$".r
val crnPattern = "^[A-Z0-9]{1,10}$".r
implicit val format: Format[IfCorpTaxCompanyDetails] = Format(
(
(JsPath \ "utr").readNullable[String](pattern(utrPattern, "UTR is in invalid format")) and
(JsPath \ "crn").readNullable[String](pattern(crnPattern, "CRN is in invalid format")) and
(JsPath \ "registeredDetails").readNullable[IfNameAndAddressDetails] and
(JsPath \ "communicationDetails").readNullable[IfNameAndAddressDetails]
)(IfCorpTaxCompanyDetails.apply _),
(
(JsPath \ "utr").writeNullable[String] and
(JsPath \ "crn").writeNullable[String] and
(JsPath \ "registeredDetails").writeNullable[IfNameAndAddressDetails] and
(JsPath \ "communicationDetails").writeNullable[IfNameAndAddressDetails]
)(unlift(IfCorpTaxCompanyDetails.unapply))
)
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/cache/CacheConfiguration.scala | <reponame>hmrc/organisations-matching-api<gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.cache
import javax.inject.{Inject, Singleton}
import play.api.Configuration
@Singleton
class CacheConfiguration @Inject()(configuration: Configuration) {
lazy val cacheEnabled: Boolean = configuration.getOptional[Boolean]("cache.enabled")
.getOrElse(true)
lazy val cacheTtl: Int = configuration.getOptional[Int]("cache.ttlInSeconds")
.getOrElse(60 * 60 * 5)
lazy val colName: String = configuration.getOptional[String]("cache.colName")
.getOrElse("matching-cache")
lazy val key: String = configuration.getOptional[String]("cache.key")
.getOrElse("organisations-matching")
} |
hmrc/organisations-matching-api | test/it/uk/gov/hmrc/organisationsmatchingapi/repository/ShortLivedCacheSpec.scala | /*
* Copyright 2021 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 it.uk.gov.hmrc.organisationsmatchingapi.repository
import org.mongodb.scala.model.Filters
import org.scalatest.BeforeAndAfterEach
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsString, Json, OFormat}
import play.api.{Application, Configuration, Mode}
import uk.gov.hmrc.mongo.MongoComponent
import uk.gov.hmrc.mongo.play.json.Codecs.toBson
import uk.gov.hmrc.organisationsmatchingapi.cache.{CacheConfiguration, ShortLivedCache}
import util.UnitSpec
import java.util.UUID
import scala.concurrent.ExecutionContext
class ShortLivedCacheSpec extends UnitSpec with Matchers with GuiceOneAppPerSuite with MockitoSugar with ScalaFutures with BeforeAndAfterEach {
val cacheTtl = 60
val id: String = UUID.randomUUID().toString
val cachekey: String = "test-class-key"
val testValue: TestClass = TestClass("one", "two")
override def fakeApplication: Application =
GuiceApplicationBuilder()
.configure("run.mode" -> "Stub")
.configure(Map(
"metrics.enabled" -> false,
"auditing.enabled" -> false,
"microservice.services.metrics.graphite.enabled" -> false
))
.in(Mode.Test)
.build()
implicit val ec: ExecutionContext = fakeApplication.injector.instanceOf[ExecutionContext]
val cacheConfig: CacheConfiguration = fakeApplication.injector.instanceOf[CacheConfiguration]
val configuration: Configuration = fakeApplication.injector.instanceOf[Configuration]
val mongoComponent: MongoComponent = fakeApplication.injector.instanceOf[MongoComponent]
val shortLivedCache = new ShortLivedCache(cacheConfig, configuration, mongoComponent)
override def beforeEach(): Unit = {
super.beforeEach()
await(shortLivedCache.collection.drop().toFuture())
}
override def afterEach(): Unit = {
super.afterEach()
await(shortLivedCache.collection.drop().toFuture())
}
"cache" should {
"store the encrypted version of a value" in {
await(shortLivedCache.cache(id, testValue)(TestClass.format))
retrieveRawCachedValue(id) shouldBe JsString(
"I9gl6p5GRucOfXOFmhtiYfePGl5Nnksdk/aJFXf0iVQ=")
}
}
"fetch" should {
"retrieve the unencrypted cached value for a given id and key" in {
await(shortLivedCache.cache(id, testValue)(TestClass.format))
await(
shortLivedCache.fetchAndGetEntry(id)(
TestClass.format)) shouldBe Some(testValue)
}
"return None if no cached value exists for a given id and key" in {
await(
shortLivedCache.fetchAndGetEntry(id)(
TestClass.format)) shouldBe None
}
}
private def retrieveRawCachedValue(id: String) = {
await(shortLivedCache.collection.find(Filters.equal("id", toBson(id)))
.headOption
.map {
case Some(entry) => entry.data.value
case None => None
})
}
case class TestClass(one: String, two: String)
object TestClass {
implicit val format: OFormat[TestClass] = Json.format[TestClass]
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/controllers/BaseApiController.scala | <gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.controllers
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import uk.gov.hmrc.auth.core.authorise.Predicate
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals
import uk.gov.hmrc.auth.core.{AuthorisationException, AuthorisedFunctions, Enrolment, InsufficientEnrolments}
import uk.gov.hmrc.http.{BadRequestException, HeaderCarrier, InternalServerException, TooManyRequestException}
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.domain.models._
import uk.gov.hmrc.organisationsmatchingapi.utils.UuidValidator
import uk.gov.hmrc.play.bootstrap.backend.controller.BackendController
import uk.gov.hmrc.play.http.HeaderCarrierConverter
import java.util.UUID
import javax.inject.Inject
import scala.concurrent.Future.successful
import scala.concurrent.{ExecutionContext, Future}
abstract class BaseApiController @Inject()(mcc: MessagesControllerComponents, cc: ControllerComponents) extends BackendController(cc) with AuthorisedFunctions {
protected val logger: Logger = play.api.Logger(this.getClass)
protected implicit val lang = mcc.langs.availables.head
protected override implicit def hc(implicit rh: RequestHeader): HeaderCarrier =
HeaderCarrierConverter.fromRequest(rh)
protected def withValidUuid(uuidString: String, uuidName: String)(f: UUID => Future[Result]): Future[Result] =
if (UuidValidator.validate(uuidString)) {
f(UUID.fromString(uuidString))
} else {
successful(ErrorInvalidRequest(s"$uuidName format is invalid").toHttpResponse)
}
def withValidJson[T](f: T => Future[Result])(implicit request: Request[JsValue],
r: Reads[T]): Future[Result] =
request.body.validate[T] match {
case JsSuccess(t, _) => f(t)
case JsError(errors) =>
val firstError = errors.head
Future.failed(new BadRequestException(mcc.messagesApi(firstError._2.head.message, firstError._1)))
}
private[controllers] def recoveryWithAudit(correlationId: Option[String], matchId: String, url: String)(
implicit request: RequestHeader,
auditHelper: AuditHelper): PartialFunction[Throwable, Result] = {
case _: MatchNotFoundException => {
auditHelper.auditApiResponse(correlationId.getOrElse("-"), matchId, "", request, url, Some(Json.toJson("Not Found")))
ErrorNotFound.toHttpResponse
}
case e: InvalidBodyException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorInvalidRequest(e.getMessage).toHttpResponse
}
case _: MatchingException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, "Not Found")
ErrorMatchingFailed.toHttpResponse
}
case e: InsufficientEnrolments => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorUnauthorized("Insufficient Enrolments").toHttpResponse
}
case e: AuthorisationException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorUnauthorized(e.getMessage).toHttpResponse
}
case tmr: TooManyRequestException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, tmr.getMessage)
ErrorTooManyRequests.toHttpResponse
}
case br: BadRequestException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, br.getMessage)
ErrorInvalidRequest(br.getMessage).toHttpResponse
}
case e: IllegalArgumentException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorInvalidRequest(e.getMessage).toHttpResponse
}
case e: InternalServerException => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorInternalServer("Something went wrong").toHttpResponse
}
case e => {
auditHelper.auditApiFailure(correlationId, matchId, request, url, e.getMessage)
ErrorInternalServer("Something went wrong").toHttpResponse
}
}
}
trait PrivilegedAuthentication extends AuthorisedFunctions {
def authPredicate(scopes: Iterable[String]): Predicate =
scopes.map(Enrolment(_): Predicate).reduce(_ or _)
def authenticate(endpointScopes: Iterable[String], matchId: String)(f: Iterable[String] => Future[Result])(
implicit hc: HeaderCarrier,
request: RequestHeader,
auditHelper: AuditHelper,
ec: ExecutionContext): Future[Result] = {
if (endpointScopes.isEmpty) throw new Exception("No scopes defined")
authorised(authPredicate(endpointScopes)).retrieve(Retrievals.allEnrolments) {
scopes => {
auditHelper.auditAuthScopes(matchId, scopes.enrolments.map(e => e.key).mkString(","), request)
f(scopes.enrolments.map(e => e.key))
}
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/integrationframework/IfCorpTaxCompanyDetailsSpec.scala | <filename>test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/integrationframework/IfCorpTaxCompanyDetailsSpec.scala
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import util.IfHelpers
class IfCorpTaxCompanyDetailsSpec extends AnyWordSpec with Matchers with IfHelpers {
"Writes " in {
val expected = Json.parse("""{
| "utr": "1234567890",
| "crn": "12345678",
| "registeredDetails": {
| "name": {
| "name1": "Waitrose",
| "name2": "<NAME>"
| },
| "address": {
| "line1": "Alfie House",
| "line2": "Main Street",
| "line3": "Manchester",
| "line4": "Londonberry",
| "postcode": "LN1 1AG"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "Waitrose",
| "name2": "<NAME>"
| },
| "address": {
| "line1": "Orange House",
| "line2": "Corporation Street",
| "line3": "London",
| "line4": "Londonberry",
| "postcode": "LN1 1AG"
| }
| }
|}""".stripMargin)
val parsed = Json.toJson(ifCorpTaxCompanyDetails)
parsed shouldBe expected
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/util/MatchUuidPathBinderSpec.scala | <gh_stars>0
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.util
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import uk.gov.hmrc.organisationsmatchingapi.utils.MatchUuidPathBinder
import java.util.UUID
class MatchUuidPathBinderSpec
extends AnyWordSpec
with Matchers {
private val queryStringParameterName = "matchId"
private val matchUuidQueryStringBinder = new MatchUuidPathBinder
"Match UUID query string binder" should {
"fail to bind missing or malformed uuid parameter" in {
val fixtures = Seq(
("", s"$queryStringParameterName is required"),
("Not-A-Uuid", s"$queryStringParameterName format is invalid")
)
fixtures foreach {
case (parameters, response) =>
matchUuidQueryStringBinder.bind("", parameters) shouldBe Left(response)
}
}
}
"bind well formed uuid strings" in {
val fixtures = Seq(
("a7b7945e-3ba8-4334-a9cd-2348f98d6867", UUID.fromString("a7b7945e-3ba8-4334-a9cd-2348f98d6867")),
("b5a9afcb-c7ec-4343-b275-9a3ca0a8f362", UUID.fromString("b5a9afcb-c7ec-4343-b275-9a3ca0a8f362")),
("c44ca64d-2451-4449-9a9a-70e099efe279", UUID.fromString("c44ca64d-2451-4449-9a9a-70e099efe279"))
)
fixtures foreach {
case (parameters, response) =>
matchUuidQueryStringBinder.bind("", parameters) shouldBe Right(response)
}
}
"unbind uuid strings to query parameters" in {
val fixtures = Seq(
(UUID.fromString("a7b7945e-3ba8-4334-a9cd-2348f98d6867"), s"$queryStringParameterName=a7b7945e-3ba8-4334-a9cd-2348f98d6867"),
(UUID.fromString("b5a9afcb-c7ec-4343-b275-9a3ca0a8f362"), s"$queryStringParameterName=b5a9afcb-c7ec-4343-b275-9a3ca0a8f362"),
(UUID.fromString("c44ca64d-2451-4449-9a9a-70e099efe279"), s"$queryStringParameterName=c44ca64d-2451-4449-9a9a-70e099efe279")
)
fixtures foreach {
case (parameters, response) =>
matchUuidQueryStringBinder.unbind(queryStringParameterName, parameters) shouldBe response
}
}
}
|
hmrc/organisations-matching-api | test/it/uk/gov/hmrc/organisationsmatchingapi/connectors/OrganisationsMatchingConnectorSpec.scala | /*
* Copyright 2021 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 it.uk.gov.hmrc.organisationsmatchingapi.connectors
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito
import org.mockito.Mockito.{times, verify}
import org.scalatest.BeforeAndAfterEach
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsValue, Json}
import play.api.test.FakeRequest
import uk.gov.hmrc.http.{HeaderCarrier, HttpClient, InternalServerException}
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.connectors.OrganisationsMatchingConnector
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfCorpTaxCompanyDetails, IfNameAndAddressDetails, IfNameDetails, IfSaTaxPayerNameAddress, IfSaTaxpayerDetails}
import uk.gov.hmrc.organisationsmatchingapi.domain.models.MatchingException
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.{CtKnownFacts, CtOrganisationsMatchingRequest, SaKnownFacts, SaOrganisationsMatchingRequest}
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util.UnitSpec
import scala.concurrent.ExecutionContext
class OrganisationsMatchingConnectorSpec
extends AnyWordSpec
with BeforeAndAfterEach
with UnitSpec
with MockitoSugar
with Matchers
with GuiceOneAppPerSuite {
val stubPort: Int = sys.env.getOrElse("WIREMOCK", "11122").toInt
val stubHost = "127.0.0.1"
val wireMockServer = new WireMockServer(wireMockConfig().port(stubPort))
def externalServices: Seq[String] = Seq.empty
override lazy val fakeApplication = new GuiceApplicationBuilder()
.bindings(bindModules: _*)
.configure(
"auditing.enabled" -> false,
"cache.enabled" -> false,
"microservice.services.organisations-matching.host" -> "127.0.0.1",
"microservice.services.organisations-matching.port" -> "11122",
)
.build()
implicit val ec: ExecutionContext =
fakeApplication.injector.instanceOf[ExecutionContext]
trait Setup {
val matchId = "80a6bb14-d888-436e-a541-4000674c60aa"
val correlationId = "188e9400-b636-4a3b-80ba-230a8c72b92a"
val applicationId = "12345"
val correlationIdHeader: (String, String) = ("CorrelationId" -> correlationId)
val applicationIdHeader: (String, String) = ("X-Application-ID" -> "12345")
val ctKnownFacts: CtKnownFacts = CtKnownFacts("test", "test", "test", "test")
val name: IfNameDetails = IfNameDetails(Some("test"), Some("test"))
val address: IfAddress = IfAddress(Some("test"), None, None, None, Some("test"))
val details: IfNameAndAddressDetails = IfNameAndAddressDetails(Some(name), Some(address))
val ctIfData: IfCorpTaxCompanyDetails = IfCorpTaxCompanyDetails(Some("test"), Some("test"), Some(details), Some(details))
val ctPostData: CtOrganisationsMatchingRequest = CtOrganisationsMatchingRequest(ctKnownFacts, ctIfData)
val saKnownFacts: SaKnownFacts = SaKnownFacts("test", "Individual", "test", "test", "test")
val saDetails: IfSaTaxPayerNameAddress = IfSaTaxPayerNameAddress(Some("test"), None, Some(address))
val taxpayerDetails: Option[Seq[IfSaTaxPayerNameAddress]] = Some(Seq(saDetails))
val saIfData: IfSaTaxpayerDetails = IfSaTaxpayerDetails(Some("test"), Some("Individual"), taxpayerDetails)
val saPostData: SaOrganisationsMatchingRequest = SaOrganisationsMatchingRequest(saKnownFacts, saIfData)
implicit val hc: HeaderCarrier = HeaderCarrier(otherHeaders = Seq(correlationIdHeader, applicationIdHeader))
val config: ServicesConfig = fakeApplication.injector.instanceOf[ServicesConfig]
val httpClient: HttpClient = fakeApplication.injector.instanceOf[HttpClient]
val auditHelper: AuditHelper = mock[AuditHelper]
val underTest = new OrganisationsMatchingConnector(config, httpClient, auditHelper)
}
override def beforeEach(): Unit = {
wireMockServer.start()
configureFor(stubHost, stubPort)
}
override def afterEach(): Unit = {
wireMockServer.stop()
}
"matchCycleCotax" should {
"Fail when organisations matching returns an error CT" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "crn": "test",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "crn": "test",
| "registeredDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }
| }
|}
""".stripMargin
))
.willReturn(aResponse().withStatus(500)))
intercept[InternalServerException] {
await(
underTest.matchCycleCotax(matchId, correlationId, ctPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingFailure(any(), any(), any(), any(), any())(any())
}
"Fail when organisations matching returns a bad request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=${matchId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "crn": "test",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "crn": "test",
| "registeredDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }
| }
|}
""".stripMargin
))
.willReturn(aResponse().withStatus(400).withBody("BAD_REQUEST")))
intercept[InternalServerException] {
await(
underTest.matchCycleCotax(matchId, correlationId, ctPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingFailure(any(), any(), any(), any(), any())(any())
}
"return a match for a matched request CT" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "crn": "test",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "crn": "test",
| "registeredDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }
| }
|}
""".stripMargin
))
.willReturn(aResponse()
.withStatus(200)
.withBody(Json.toJson("match").toString())))
val result: JsValue = await(
underTest.matchCycleCotax(matchId, correlationId, ctPostData)(
hc,
FakeRequest(),
ec
)
)
result shouldBe Json.toJson("match")
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingResponse(any(), any(), any(), any(), any())(any())
}
"return NOT_FOUND for a non matched request CT" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "crn": "test",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "crn": "test",
| "registeredDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }
| }
|}
""".stripMargin
))
.willReturn(aResponse()
.withStatus(404).withBody("{ \"code\" : \"NOT_FOUND\"}")))
intercept[MatchingException] {
await(
underTest.matchCycleCotax(matchId, correlationId, ctPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingResponse(any(), any(), any(), any(), any())(any())
}
}
"matchCycleSelfAssessment" should {
"Fail when organisations matching returns an error SA" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "utr": "test",
| "taxpayerType": "Individual",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "taxpayerType": "Individual",
| "taxpayerDetails": [{
| "name": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }]
| }
|}
""".stripMargin
))
.willReturn(aResponse().withStatus(500)))
intercept[InternalServerException] {
await(
underTest.matchCycleSelfAssessment(matchId, correlationId, saPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingFailure(any(), any(), any(), any(), any())(any())
}
"Fail when organisations matching returns a bad request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=${matchId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "utr": "test",
| "taxpayerType": "Individual",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "taxpayerType": "Individual",
| "taxpayerDetails": [{
| "name": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }]
| }
|}
""".stripMargin
))
.willReturn(aResponse().withStatus(400).withBody("BAD_REQUEST")))
intercept[InternalServerException] {
await(
underTest.matchCycleSelfAssessment(matchId, correlationId, saPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingFailure(any(), any(), any(), any(), any())(any())
}
"return a match for a matched request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "utr": "test",
| "taxpayerType": "Individual",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "taxpayerType": "Individual",
| "taxpayerDetails": [{
| "name": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }]
| }
|}
""".stripMargin
))
.willReturn(aResponse()
.withStatus(200)
.withBody(Json.toJson("match").toString())))
val result = await(
underTest.matchCycleSelfAssessment(matchId, correlationId, saPostData)(
hc,
FakeRequest(),
ec
)
)
result shouldBe Json.toJson("match")
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingResponse(any(), any(), any(), any(), any())(any())
}
"return NOT_FOUND for a non matched request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=${matchId}&correlationId=${correlationId}"))
.withRequestBody(equalToJson(
"""
|{
| "knownFacts": {
| "utr": "test",
| "taxpayerType": "Individual",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "taxpayerType": "Individual",
| "taxpayerDetails": [{
| "name": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }]
| }
|}
""".stripMargin
))
.willReturn(aResponse()
.withStatus(404).withBody("{ \"code\" : \"NOT_FOUND\"}")))
intercept[MatchingException] {
await(
underTest.matchCycleCotax(matchId, correlationId, ctPostData)(
hc,
FakeRequest(),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditOrganisationsMatchingResponse(any(), any(), any(), any(), any())(any())
}
"return appropriate header carrier" in new Setup {
hc.headers(underTest.requiredHeaders) shouldBe(Seq("CorrelationId" -> correlationId, "X-Application-ID" -> "12345"))
}
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/connectors/IfConnector.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.connectors
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc.RequestHeader
import uk.gov.hmrc.http._
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfCorpTaxCompanyDetails, IfSaTaxpayerDetails}
import uk.gov.hmrc.organisationsmatchingapi.play.RequestHeaderUtils.validateCorrelationId
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import javax.inject.Inject
import uk.gov.hmrc.organisationsmatchingapi.domain.models.MatchingException
import uk.gov.hmrc.http.HttpReads.Implicits._
import scala.concurrent.{ExecutionContext, Future}
class IfConnector @Inject()(
servicesConfig: ServicesConfig,
http: HttpClient,
val auditHelper: AuditHelper) {
private val logger = Logger(classOf[IfConnector].getName)
private val baseUrl = servicesConfig.baseUrl("integration-framework")
private val integrationFrameworkBearerToken =
servicesConfig.getString(
"microservice.services.integration-framework.authorization-token"
)
private val integrationFrameworkEnvironment = servicesConfig.getString(
"microservice.services.integration-framework.environment"
)
def fetchSelfAssessment(matchId: String, utr: String)(
implicit hc: HeaderCarrier,
request: RequestHeader,
ec: ExecutionContext): Future[IfSaTaxpayerDetails] = {
val SAUrl =
s"$baseUrl/organisations/self-assessment/$utr/taxpayer/details"
callSa(SAUrl, matchId)
}
def fetchCorporationTax(matchId: String, crn: String)(
implicit hc: HeaderCarrier,
request: RequestHeader,
ec: ExecutionContext): Future[IfCorpTaxCompanyDetails] = {
val CTUrl =
s"$baseUrl/organisations/corporation-tax/$crn/company/details"
callCt(CTUrl, matchId)
}
private def extractCorrelationId(requestHeader: RequestHeader) = validateCorrelationId(requestHeader).toString
def setHeaders(requestHeader: RequestHeader) = Seq(
HeaderNames.authorisation -> s"Bearer $integrationFrameworkBearerToken",
"Environment" -> integrationFrameworkEnvironment,
"CorrelationId" -> extractCorrelationId(requestHeader)
)
private def callSa(url: String, matchId: String)
(implicit hc: HeaderCarrier, request: RequestHeader, ec: ExecutionContext) =
recover[IfSaTaxpayerDetails](http.GET[IfSaTaxpayerDetails](url, headers = setHeaders(request)) map { response =>
auditHelper.auditIfApiResponse(extractCorrelationId(request), matchId, request, url, Json.toJson(response).toString)
response
}, extractCorrelationId(request), matchId, request, url)
private def callCt(url: String, matchId: String)
(implicit hc: HeaderCarrier, request: RequestHeader, ec: ExecutionContext) =
recover[IfCorpTaxCompanyDetails](http.GET[IfCorpTaxCompanyDetails](url, headers = setHeaders(request))map { response =>
auditHelper.auditIfApiResponse(extractCorrelationId(request), matchId, request, url, Json.toJson(response).toString)
response
}, extractCorrelationId(request), matchId, request, url)
private def recover[T](x: Future[T],
correlationId: String,
matchId: String,
request: RequestHeader,
requestUrl: String)
(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[T] = x.recoverWith {
case validationError: JsValidationException => {
logger.warn("Integration Framework JsValidationException encountered")
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, s"Error parsing IF response: ${validationError.errors}")
Future.failed(new InternalServerException("Something went wrong."))
}
case Upstream4xxResponse(msg, 404, _, _) => {
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, msg)
logger.warn("Integration Framework NotFoundException encountered")
Future.failed(new MatchingException)
}
case Upstream5xxResponse(msg, code, _, _) => {
logger.warn(s"Integration Framework Upstream5xxResponse encountered: $code")
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, s"Internal Server error: $msg")
Future.failed(new InternalServerException("Something went wrong."))
}
case Upstream4xxResponse(msg, 429, _, _) => {
logger.warn(s"Integration Framework Rate limited: $msg")
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, s"IF Rate limited: $msg")
Future.failed(new TooManyRequestException(msg))
}
case Upstream4xxResponse(msg, code, _, _) => {
logger.warn(s"Integration Framework Upstream4xxResponse encountered: $code")
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, msg)
Future.failed(new InternalServerException("Something went wrong."))
}
case e: Exception => {
logger.warn(s"Integration Framework Exception encountered")
auditHelper.auditIfApiFailure(correlationId, matchId, request, requestUrl, e.getMessage)
Future.failed(new InternalServerException("Something went wrong."))
}
}
} |
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/domain/ogd/CtMatchingRequest.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.domain.ogd
import play.api.libs.json.{Format, JsPath}
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads.pattern
case class CtMatchingRequest(companyRegistrationNumber: String,
employerName: String,
addressLine1: String,
postcode: String)
object CtMatchingRequest {
val crnPattern = "^[A-Z0-9]{1,10}$".r
implicit val ctMatchingformat: Format[CtMatchingRequest] = Format(
(
(JsPath \ "companyRegistrationNumber").read[String](pattern(crnPattern, "error.crn")) and
(JsPath \ "employerName").read[String] and
(JsPath \ "address" \ "addressLine1").read[String] and
(JsPath \ "address" \ "postcode").read[String]
)(CtMatchingRequest.apply _),
(
(JsPath \ "companyRegistrationNumber").write[String] and
(JsPath \ "employerName").write[String] and
(JsPath \ "address" \ "addressLine1").write[String] and
(JsPath \ "address" \ "postcode").write[String]
)(unlift(CtMatchingRequest.unapply))
)
} |
hmrc/organisations-matching-api | test/component/uk/gov/hmrc/organisationsmatchingapi/controllers/stubs/BaseSpec.scala | <reponame>hmrc/organisations-matching-api
/*
* Copyright 2021 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 component.uk.gov.hmrc.organisationsmatchingapi.controllers.stubs
import java.util.concurrent.TimeUnit
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.core.WireMockConfiguration
import org.scalatest._
import org.scalatest.featurespec.AnyFeatureSpec
import org.scalatest.matchers.must.Matchers
import org.scalatestplus.play.guice.GuiceOneServerPerSuite
import play.api.Application
import play.api.http.HeaderNames.{ACCEPT, AUTHORIZATION, CONTENT_TYPE}
import play.api.inject.guice.GuiceApplicationBuilder
import play.mvc.Http.MimeTypes.JSON
import uk.gov.hmrc.organisationsmatchingapi.repository.MatchRepository
import scala.concurrent.Await.result
import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.concurrent.ExecutionContext.Implicits.global
trait BaseSpec
extends AnyFeatureSpec with BeforeAndAfterAll with BeforeAndAfterEach with Matchers with GuiceOneServerPerSuite
with GivenWhenThen {
implicit override lazy val app: Application = GuiceApplicationBuilder()
.configure(
"cache.enabled" -> true,
"auditing.enabled" -> false,
"auditing.traceRequests" -> false,
"mongodb.uri" -> "mongodb://localhost:27017/organisations-matching-api",
"microservice.services.auth.port" -> AuthStub.port,
"microservice.services.organisations-matching.port" -> MatchingStub.port,
"microservice.services.ifstub.port" -> IfStub.port,
"run.mode" -> "It",
"versioning.unversionedContexts" -> List("/match-record")
)
.build()
val timeout: FiniteDuration = Duration(5, TimeUnit.SECONDS)
val serviceUrl = s"http://127.0.0.1:$port"
val mocks = Seq(AuthStub, IfStub, MatchingStub)
val authToken = "<PASSWORD>"
val clientId = "CLIENT_ID"
val acceptHeaderP1: (String, String) = ACCEPT -> "application/vnd.hmrc.1.0+json"
val correlationIdHeader: (String, String) = "CorrelationId" -> "188e9400-b636-4a3b-80ba-230a8c72b92a"
val correlationIdHeaderMalformed: (String, String) = "CorrelationId" -> "foo"
val mongoRepository: MatchRepository = app.injector.instanceOf[MatchRepository]
protected def requestHeaders(acceptHeader: (String, String) = acceptHeaderP1) =
Map(CONTENT_TYPE -> JSON, AUTHORIZATION -> authToken, acceptHeader, correlationIdHeader)
protected def requestHeadersInvalid(acceptHeader: (String, String) = acceptHeaderP1) =
Map(CONTENT_TYPE -> JSON, AUTHORIZATION -> authToken, acceptHeader)
protected def requestHeadersMalformed(acceptHeader: (String, String) = acceptHeaderP1) =
Map(CONTENT_TYPE -> JSON, AUTHORIZATION -> authToken, acceptHeader, correlationIdHeaderMalformed)
protected def invalidRequest(message: String) =
s"""{"code":"INVALID_REQUEST","message":"$message"}"""
override protected def beforeEach(): Unit = {
mocks.foreach(m => if (!m.server.isRunning) m.server.start())
result(mongoRepository.collection.drop().toFuture(), timeout)
result(mongoRepository.ensureIndexes, timeout)
}
override protected def afterEach(): Unit =
mocks.foreach(_.mock.resetMappings())
override def afterAll(): Unit = {
mocks.foreach(_.server.stop())
result(mongoRepository.collection.drop().toFuture(), timeout)
}
}
case class MockHost(port: Int) {
val server = new WireMockServer(WireMockConfiguration.wireMockConfig().port(port))
val mock = new WireMock("127.0.0.1", port)
val url = s"http://127.0.0.1:9000"
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/audit/AuditHelperSpec.scala | /*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.audit
import org.mockito.Mockito.{times, verify}
import org.mockito.ArgumentMatchers.{any, eq => eqTo}
import org.mockito.{ArgumentCaptor, Mockito}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AsyncWordSpec
import org.scalatestplus.mockito.MockitoSugar
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.AnyContentAsEmpty
import play.api.test.FakeRequest
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.audit.models._
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
class AuditHelperSpec extends AsyncWordSpec with Matchers with MockitoSugar {
implicit val hc: HeaderCarrier = HeaderCarrier()
val auditConnector: AuditConnector = mock[AuditConnector]
val auditHelper = new AuditHelper(auditConnector)
val correlationId = "test"
val matchId = "80a6bb14-d888-436e-a541-4000674c60aa"
val applicationId = "80a6bb14-d888-436e-a541-4000674c60bb"
val request: FakeRequest[AnyContentAsEmpty.type] = FakeRequest().withHeaders("X-Application-Id" -> applicationId)
val endpoint = "/test"
val ifResponse = "bar"
val crn = "12345678"
val scopes = "test"
val ifUrl = s"host/organisations/corporation-tax/$crn/company/details"
val matchingUrlCt = s"/organisations-matching/perform-match/cotax?matchId=${matchId}&correlationId=${correlationId}"
val matchingUrlSa = s"/organisations-matching/perform-match/self-assessment?matchId=${matchId}&correlationId=${correlationId}"
val matchingResponse: JsValue = Json.toJson("match")
val matchingNonMatchResponse = "Not Found"
"auditAuthScopes" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[ScopesAuditEventModel])
auditHelper.auditAuthScopes(matchId, scopes, request)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("AuthScopesAuditEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[ScopesAuditEventModel]
capturedEvent.apiVersion shouldEqual "1.0"
capturedEvent.matchId shouldEqual matchId
capturedEvent.scopes shouldBe scopes
capturedEvent.applicationId shouldBe applicationId
}
"auditApiFailure" in {
Mockito.reset(auditConnector)
val msg = "Something went wrong"
val captor = ArgumentCaptor.forClass(classOf[ApiFailureResponseEventModel])
auditHelper.auditApiFailure(Some(correlationId), matchId, request, "/test", msg)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("ApiFailureEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[ApiFailureResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual Some(correlationId)
capturedEvent.requestUrl shouldEqual endpoint
capturedEvent.response shouldEqual msg
capturedEvent.applicationId shouldBe applicationId
}
"auditIfApiResponse" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[IfApiResponseEventModel])
auditHelper.auditIfApiResponse(correlationId, matchId, request, ifUrl, ifResponse)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("IntegrationFrameworkApiResponseEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[IfApiResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual correlationId
capturedEvent.requestUrl shouldBe ifUrl
capturedEvent.ifResponse shouldBe ifResponse
capturedEvent.applicationId shouldBe applicationId
}
"auditIfApiFailure" in {
Mockito.reset(auditConnector)
val msg = "Something went wrong"
val captor = ArgumentCaptor.forClass(classOf[ApiFailureResponseEventModel])
auditHelper.auditIfApiFailure(correlationId, matchId, request, ifUrl, msg)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("IntegrationFrameworkApiFailureEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[ApiFailureResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual Some(correlationId)
capturedEvent.requestUrl shouldEqual ifUrl
capturedEvent.response shouldEqual msg
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingResponse match CT" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingResponseEventModel])
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, matchingUrlCt, matchingResponse)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingResponseEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual correlationId
capturedEvent.requestUrl shouldBe matchingUrlCt
capturedEvent.matchingResponse shouldBe matchingResponse
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingResponse match SA" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingResponseEventModel])
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, matchingUrlSa, matchingResponse)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingResponseEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual correlationId
capturedEvent.requestUrl shouldBe matchingUrlSa
capturedEvent.matchingResponse shouldBe matchingResponse
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingResponse non match CT" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingResponseEventModel])
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, matchingUrlCt, Json.toJson(matchingNonMatchResponse))
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingResponseEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual correlationId
capturedEvent.requestUrl shouldBe matchingUrlCt
capturedEvent.matchingResponse shouldBe Json.toJson(matchingNonMatchResponse)
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingResponse non match SA" in {
Mockito.reset(auditConnector)
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingResponseEventModel])
auditHelper.auditOrganisationsMatchingResponse(correlationId, matchId, request, matchingUrlSa, Json.toJson(matchingNonMatchResponse))
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingResponseEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual correlationId
capturedEvent.requestUrl shouldBe matchingUrlSa
capturedEvent.matchingResponse shouldBe Json.toJson(matchingNonMatchResponse)
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingFailure CT" in {
Mockito.reset(auditConnector)
val msg = "Something went wrong"
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingFailureResponseEventModel])
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, matchingUrlCt, msg)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingFailureEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingFailureResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual Some(correlationId)
capturedEvent.requestUrl shouldEqual matchingUrlCt
capturedEvent.response shouldEqual msg
capturedEvent.applicationId shouldBe applicationId
}
"auditOrganisationsMatchingFailure SA" in {
Mockito.reset(auditConnector)
val msg = "Something went wrong"
val captor = ArgumentCaptor.forClass(classOf[OrganisationsMatchingFailureResponseEventModel])
auditHelper.auditOrganisationsMatchingFailure(correlationId, matchId, request, matchingUrlSa, msg)
verify(auditConnector, times(1)).sendExplicitAudit(eqTo("OrganisationsMatchingFailureEvent"),
captor.capture())(any(), any(), any())
val capturedEvent = captor.getValue.asInstanceOf[OrganisationsMatchingFailureResponseEventModel]
capturedEvent.matchId shouldEqual matchId
capturedEvent.correlationId shouldEqual Some(correlationId)
capturedEvent.requestUrl shouldEqual matchingUrlSa
capturedEvent.response shouldEqual msg
capturedEvent.applicationId shouldBe applicationId
}
} |
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/CtKnownFactsSpec.scala | /*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.CtKnownFacts
import util.IfHelpers
class CtKnownFactsSpec extends AnyWordSpec with Matchers with IfHelpers {
"CtKnownFacts" should {
"Read and write" in {
val knownFacts = CtKnownFacts("crn", "name", "line1", "postcode")
val asJson = Json.toJson(knownFacts)
asJson shouldBe Json.parse("""
|{
| "crn" : "crn",
| "name" : "name",
| "line1" : "line1",
| "postcode" : "postcode"
|}
|""".stripMargin)
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchedControllerSpec.scala | /*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.controllers
import akka.stream.Materializer
import org.mockito.ArgumentMatchers.{any, refEq}
import org.mockito.BDDMockito.`given`
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status._
import play.api.libs.json.Json
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.{FakeRequest, Helpers}
import uk.gov.hmrc.auth.core.authorise.Predicate
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals
import uk.gov.hmrc.auth.core.{AuthConnector, Enrolment, Enrolments}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.controllers.MatchedController
import uk.gov.hmrc.organisationsmatchingapi.domain.models._
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import uk.gov.hmrc.organisationsmatchingapi.services.{MatchedService, ScopesHelper, ScopesService}
import unit.uk.gov.hmrc.organisationsmatchingapi.services.ScopesConfig
import util.SpecBase
import java.util.UUID
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class MatchedControllerSpec extends AnyWordSpec with Matchers with MockitoSugar with SpecBase {
implicit lazy val materializer: Materializer = fakeApplication.materializer
trait Setup extends ScopesConfig {
val sampleCorrelationId = "188e9400-b636-4a3b-80ba-230a8c72b92a"
val sampleCorrelationIdHeader: (String, String) = "CorrelationId" -> sampleCorrelationId
val badCorrelationIdHeader: (String, String) = "CorrelationId" -> "foo"
val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest("GET", "/").withHeaders(sampleCorrelationIdHeader)
val fakeRequestMalformed: FakeRequest[AnyContentAsEmpty.type] = FakeRequest("GET", "/").withHeaders(badCorrelationIdHeader)
val mockAuthConnector: AuthConnector = mock[AuthConnector]
lazy val scopeService: ScopesService = new ScopesService(mockConfig)
lazy val scopesHelper: ScopesHelper = new ScopesHelper(scopeService)
implicit val auditHelper: AuditHelper = mock[AuditHelper]
val matchedService: MatchedService = mock[MatchedService]
val matchId: UUID = UUID.fromString("57072660-1df9-4aeb-b4ea-cd2d7f96e430")
implicit val hc: HeaderCarrier = HeaderCarrier()
val matchRequestCt = new CtMatchingRequest(
"crn",
"test",
"test",
"test"
)
val matchRequestSa = new SaMatchingRequest(
"utr",
"individual",
"test",
"test",
"test"
)
val ctMatch = new CtMatch(matchRequestCt, utr = Some("test"))
val saMatch = new SaMatch(matchRequestSa, utr = Some("test"))
val utrMatch = new UtrMatch(matchId, "test")
val controller = new MatchedController(
mockAuthConnector,
Helpers.stubControllerComponents(),
Helpers.stubMessagesControllerComponents(),
scopeService,
scopesHelper,
matchedService
)
given(mockAuthConnector.authorise(any(), refEq(Retrievals.allEnrolments))(any(), any()))
.willReturn(Future.successful(Enrolments(Set(Enrolment(mockScopeOne), Enrolment(mockScopeTwo)))))
}
"GET matchedOrganisationCt" when {
"given a valid matchId" should {
"return 200" in new Setup {
given(matchedService.fetchCt(matchId)).willReturn(Future.successful(ctMatch))
val result: Result = await(controller.matchedOrganisationCt(matchId.toString)(fakeRequest))
status(result) shouldBe OK
print(jsonBodyOf(result))
jsonBodyOf(result) shouldBe Json.parse(
s"""{
| "companyRegistrationNumber" : "crn",
| "employerName": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| },
| "_links": {
| "self": {
| "href": "/organisations/matching/corporation-tax/$matchId"
| },
| "sampleEndpointThree": {
| "href": "/external/3",
| "title": "Get the third endpoint"
| },
| "sampleEndpointTwo": {
| "href": "/external/2",
| "title": "Get the second endpoint"
| },
| "sampleEndpointOne": {
| "href": "/external/1",
| "title": "Get the first endpoint"
| }
| }
|}""".stripMargin
)
}
}
"when the match has expired" should {
"return NOT_FOUND 404" in new Setup {
given(matchedService.fetchCt(matchId)).willThrow(new MatchNotFoundException)
val result: Result = await(controller.matchedOrganisationCt(matchId.toString)(fakeRequest))
status(result) shouldBe NOT_FOUND
jsonBodyOf(result) shouldBe Json.parse(s"""{"code":"NOT_FOUND", "message":"The resource can not be found"}""")
}
}
"with a malformed correlation id" should {
"return BAD_REQUEST" in new Setup {
given(matchedService.fetchCt(matchId)).willReturn(Future.successful(ctMatch))
val result: Result = await(controller.matchedOrganisationCt(matchId.toString)(fakeRequestMalformed))
status(result) shouldBe BAD_REQUEST
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INVALID_REQUEST",
| "message": "Malformed CorrelationId"
|}
|""".stripMargin
)
}
}
"with a missing correlation id" should {
"return BAD_REQUEST" in new Setup {
given(matchedService.fetchCt(matchId)).willReturn(Future.successful(ctMatch))
val result: Result = await(controller.matchedOrganisationCt(matchId.toString)(FakeRequest()))
status(result) shouldBe BAD_REQUEST
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INVALID_REQUEST",
| "message": "CorrelationId is required"
|}
|""".stripMargin
)
}
}
"when an exception is thrown" should {
"return INTERNAL_SERVER_ERROR 500" in new Setup {
given(matchedService.fetchCt(matchId)).willThrow(new RuntimeException)
val result: Result = await(controller.matchedOrganisationCt(matchId.toString)(fakeRequest))
status(result) shouldBe INTERNAL_SERVER_ERROR
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INTERNAL_SERVER_ERROR",
| "message": "Something went wrong"
|}
|""".stripMargin
)
}
}
}
"GET matchedOrganisationSa" should {
"given a valid matchId" should {
"return 200" in new Setup {
given(matchedService.fetchSa(matchId)).willReturn(Future.successful(saMatch))
val result: Result = await(controller.matchedOrganisationSa(matchId.toString)(fakeRequest))
status(result) shouldBe OK
jsonBodyOf(result) shouldBe Json.parse(
s"""{
|"selfAssessmentUniqueTaxPayerRef": "utr",
| "taxPayerType": "individual",
| "taxPayerName": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| },
| "_links": {
| "self": {
| "href": "/organisations/matching/self-assessment/$matchId"
| },
| "sampleEndpointThree": {
| "href": "/external/3",
| "title": "Get the third endpoint"
| },
| "sampleEndpointTwo": {
| "href": "/external/2",
| "title": "Get the second endpoint"
| },
| "sampleEndpointOne": {
| "href": "/external/1",
| "title": "Get the first endpoint"
| }
| }
|}""".stripMargin
)
}
}
"when the match has expired" should {
"return NOT_FOUND 404" in new Setup {
given(matchedService.fetchSa(matchId)).willThrow(new MatchNotFoundException)
val result: Result = await(controller.matchedOrganisationSa(matchId.toString)(fakeRequest))
status(result) shouldBe NOT_FOUND
jsonBodyOf(result) shouldBe Json.parse(s"""{"code":"NOT_FOUND", "message":"The resource can not be found"}""")
}
}
"with a malformed correlation id" should {
"return BAD_REQUEST" in new Setup {
given(matchedService.fetchSa(matchId)).willReturn(Future.successful(saMatch))
val result: Result = await(controller.matchedOrganisationSa(matchId.toString)(fakeRequestMalformed))
status(result) shouldBe BAD_REQUEST
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INVALID_REQUEST",
| "message": "Malformed CorrelationId"
|}
|""".stripMargin
)
}
}
"with a missing correlation id" should {
"return BAD_REQUEST" in new Setup {
given(matchedService.fetchSa(matchId)).willReturn(Future.successful(saMatch))
val result: Result = await(controller.matchedOrganisationSa(matchId.toString)(FakeRequest()))
status(result) shouldBe BAD_REQUEST
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INVALID_REQUEST",
| "message": "CorrelationId is required"
|}
|""".stripMargin
)
}
}
"when an exception is thrown" should {
"return INTERNAL_SERVER_ERROR 500" in new Setup {
given(matchedService.fetchSa(matchId)).willThrow(new RuntimeException)
val result: Result = await(controller.matchedOrganisationSa(matchId.toString)(fakeRequest))
status(result) shouldBe INTERNAL_SERVER_ERROR
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INTERNAL_SERVER_ERROR",
| "message": "Something went wrong"
|}
|""".stripMargin
)
}
}
}
"verify matchedOrganisation record" when {
"given a valid matchId" should {
"return 200" in new Setup {
given(matchedService.fetchMatchedOrganisationRecord(matchId)).willReturn(Future.successful(utrMatch))
val result: Result = await(controller.matchedOrganisation(matchId.toString)(fakeRequest))
status(result) shouldBe OK
jsonBodyOf(result) shouldBe Json.parse(
s"""{
| "matchId": "57072660-1df9-4aeb-b4ea-cd2d7f96e430",
| "utr": "test"
|}""".stripMargin
)
}
}
"runtime exception is encountered through no match for information provided" should {
"return MATCHING_FAILED 404" in new Setup {
given(matchedService.fetchMatchedOrganisationRecord(matchId))
.willReturn(Future.failed(new MatchingException))
val result: Result = await(controller.matchedOrganisation(matchId.toString)(fakeRequest))
status(result) shouldBe NOT_FOUND
jsonBodyOf(result) shouldBe Json.parse(
s"""{"code":"MATCHING_FAILED","message":"There is no match for the information provided"}"""
)
}
}
"match is not present in cache" should {
"return NOT_FOUND 404" in new Setup {
given(matchedService.fetchMatchedOrganisationRecord(matchId))
.willReturn(Future.failed(new MatchNotFoundException))
val result: Result = await(controller.matchedOrganisation(matchId.toString)(fakeRequest))
status(result) shouldBe NOT_FOUND
jsonBodyOf(result) shouldBe Json.parse(
s"""{"code":"NOT_FOUND","message":"The resource can not be found"}"""
)
}
}
"when an exception is thrown" should {
"return INTERNAL_SERVER_ERROR 500" in new Setup {
given(matchedService.fetchMatchedOrganisationRecord(matchId))
.willReturn(Future.failed(new RuntimeException))
val result: Result = await(controller.matchedOrganisation(matchId.toString)(fakeRequest))
status(result) shouldBe INTERNAL_SERVER_ERROR
jsonBodyOf(result) shouldBe Json.parse(
"""
|{
| "code": "INTERNAL_SERVER_ERROR",
| "message": "Something went wrong"
|}
|""".stripMargin
)
}
}
}
def authPredicate(scopes: Iterable[String]): Predicate =
scopes.map(Enrolment(_): Predicate).reduce(_ or _)
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/domain/models/CtMatch.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.domain.models
import java.time.LocalDateTime
import java.util.UUID
import java.util.UUID.randomUUID
import play.api.libs.json.Json
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{Address, CtMatchingRequest, CtMatchingResponse}
case class CtMatch(
request: CtMatchingRequest,
matchId: UUID = randomUUID(),
createdAt: LocalDateTime = LocalDateTime.now(),
utr: Option[String] = None
)
object CtMatch {
implicit val formats = Json.format[CtMatch]
def convert(cacheData: CtMatch) = {
Json.toJson(
CtMatchingResponse(
cacheData.request.companyRegistrationNumber,
cacheData.request.employerName,
Address(
Some(cacheData.request.addressLine1),
Some(cacheData.request.postcode)
)
)
)
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/play/RequestHeaderUtils.scala | <gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.play
import play.api.http.HeaderNames.ACCEPT
import play.api.mvc.RequestHeader
import uk.gov.hmrc.http.BadRequestException
import uk.gov.hmrc.organisationsmatchingapi.utils.UuidValidator
import java.util.UUID
object RequestHeaderUtils {
val CLIENT_ID_HEADER = "X-Client-ID"
private val acceptHeaderRegex = "application/vnd\\.hmrc\\.(.*)\\+json".r
private val uriRegex = "(/[a-zA-Z0-9-_]*)/?.*$".r
def extractUriContext(requestHeader: RequestHeader): String =
(uriRegex.findFirstMatchIn(requestHeader.uri) map (_.group(1))).get
def validateCorrelationId(requestHeader: RequestHeader): UUID =
withCorrelationId(
requestHeader,
getUuidFromString,
() => throw new BadRequestException("CorrelationId is required")
)
def maybeCorrelationId(requestHeader: RequestHeader): Option[String] =
withCorrelationId(
requestHeader,
getUuidStringOption,
() => None
)
private def withCorrelationId[A](requestHeader: RequestHeader, onSome: String => A, onNone: () => A) =
requestHeader.headers.get("CorrelationId") match {
case Some(uuidString) => onSome(uuidString)
case None => onNone()
}
private def getUuidFromString(uuidString: String) =
UuidValidator.validate(uuidString) match {
case true => UUID.fromString(uuidString)
case false => throw new BadRequestException("Malformed CorrelationId")
}
private def getUuidStringOption(uuidString : String) =
UuidValidator.validate(uuidString) match {
case true => Some(uuidString)
case false => None
}
def getVersionedRequest(originalRequest: RequestHeader): RequestHeader = {
val version = getVersion(originalRequest)
originalRequest.withTarget(
originalRequest.target
.withUriString(versionedUri(originalRequest.uri, version))
.withPath(versionedUri(originalRequest.path, version))
)
}
def getClientIdHeader(requestHeader: RequestHeader): (String, String) =
CLIENT_ID_HEADER -> requestHeader.headers
.get(CLIENT_ID_HEADER)
.getOrElse("-")
private def getVersion(originalRequest: RequestHeader) =
originalRequest.headers.get(ACCEPT) flatMap { acceptHeaderValue =>
acceptHeaderRegex.findFirstMatchIn(acceptHeaderValue) map (_.group(1))
} getOrElse "1.0"
private def versionedUri(urlPath: String, version: String) = {
urlPath match {
case "/" => s"/v$version"
case uri => s"/v$version$urlPath"
}
}
} |
hmrc/organisations-matching-api | build.sbt | <reponame>hmrc/organisations-matching-api<gh_stars>0
import play.sbt.routes.RoutesKeys
import sbt.Tests.{Group, SubProcess}
import uk.gov.hmrc.sbtdistributables.SbtDistributablesPlugin.publishingSettings
val appName = "organisations-matching-api"
val silencerVersion = "1.7.1"
lazy val scoverageSettings = {
import scoverage.ScoverageKeys
Seq(
// Semicolon-separated list of regexs matching classes to exclude
ScoverageKeys.coverageExcludedPackages := "<empty>;Reverse.*;" +
".*BuildInfo.;uk.gov.hmrc.BuildInfo;.*Routes;.*RoutesPrefix*;" +
//All after this is due to Early project and getting pipelines up and running. May be removed later.
"uk.gov.hmrc.organisationsmatchingapi.views;" +
".*DocumentationController*;" +
"uk.gov.hmrc.organisationsmatchingapi.handlers;" +
".*definition*;",
ScoverageKeys.coverageMinimum := 80,
ScoverageKeys.coverageFailOnMinimum := true,
ScoverageKeys.coverageHighlighting := true
)
}
lazy val ComponentTest = config("component") extend Test
def intTestFilter(name: String): Boolean = name startsWith "it"
def unitFilter(name: String): Boolean = name startsWith "unit"
def componentFilter(name: String): Boolean = name startsWith "component"
def oneForkedJvmPerTest(tests: Seq[TestDefinition]) =
tests.map { test =>
new Group(test.name, Seq(test), SubProcess(ForkOptions().withRunJVMOptions(Vector(s"-Dtest.name=${test.name}"))))
}
TwirlKeys.templateImports := Seq.empty
RoutesKeys.routesImport := Seq(
"uk.gov.hmrc.organisationsmatchingapi.Binders._"
)
lazy val microservice = Project(appName, file("."))
.enablePlugins(play.sbt.PlayScala, SbtAutoBuildPlugin, SbtGitVersioning, SbtDistributablesPlugin)
.settings(
majorVersion := 0,
scalaVersion := "2.12.12",
libraryDependencies ++= AppDependencies.compile ++ AppDependencies.test(),
// ***************
// Use the silencer plugin to suppress warnings
scalacOptions += "-P:silencer:pathFilters=routes",
libraryDependencies ++= Seq(
compilerPlugin("com.github.ghik" % "silencer-plugin" % silencerVersion cross CrossVersion.full),
"com.github.ghik" % "silencer-lib" % silencerVersion % Provided cross CrossVersion.full
),
testOptions in Test := Seq(Tests.Filter(unitFilter))
// ***************
)
.configs(IntegrationTest)
.settings(inConfig(IntegrationTest)(Defaults.itSettings): _*)
.settings(
Keys.fork in IntegrationTest := true,
unmanagedSourceDirectories in IntegrationTest := (baseDirectory in IntegrationTest)(
base => Seq(base / "test")).value,
testOptions in IntegrationTest := Seq(Tests.Filter(intTestFilter))
)
.configs(ComponentTest)
.settings(inConfig(ComponentTest)(Defaults.testSettings): _*)
.settings(
testOptions in ComponentTest := Seq(Tests.Filter(componentFilter)),
unmanagedSourceDirectories in ComponentTest := (baseDirectory in ComponentTest)(base => Seq(base / "test")).value,
testGrouping in ComponentTest := oneForkedJvmPerTest((definedTests in ComponentTest).value),
parallelExecution in ComponentTest := false
)
.settings(publishingSettings: _*)
.settings(scoverageSettings: _*)
.settings(resolvers ++= Seq(
Resolver.jcenterRepo
))
.settings(unmanagedResourceDirectories in Compile += baseDirectory.value / "resources")
.settings(PlayKeys.playDefaultPort := 9657) |
hmrc/organisations-matching-api | test/component/uk/gov/hmrc/organisationsmatchingapi/services/IfQueriesSpec.scala | /*
* Copyright 2021 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 component.uk.gov.hmrc.organisationsmatchingapi.services
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import uk.gov.hmrc.organisationsmatchingapi.services.ScopesHelper
import util.ComponentSpec
class IfQueriesSpec extends AnyWordSpec with Matchers with ComponentSpec {
val helper: ScopesHelper = app.injector.instanceOf[ScopesHelper]
val res1 = "communicationsDetails(address(line1,postcode),name(name1,name2)),crn,registeredDetails(address(line1,postcode),name(name1,name2))"
val res2 = "taxPayerDetails(address(line1,postcode),name),taxPayerType,utr"
"read:organisations-matching-ho-ssp" should {
"have correct IF query string for corporation-tax" in {
val queryString = helper.getQueryStringFor(Seq("read:organisations-matching-ho-ssp"), List("getCorporationTax"))
queryString shouldBe res1
}
"have correct IF query string for corporation-tax-match" in {
val queryString = helper.getQueryStringFor(Seq("read:organisations-matching-ho-ssp"), List("getCorporationTaxMatch"))
queryString shouldBe res1
}
"have correct IF query string for self-assessment" in {
val queryString = helper.getQueryStringFor(Seq("read:organisations-matching-ho-ssp"), List("getSelfAssessment"))
queryString shouldBe res2
}
"have correct IF query string for self-assessment-match" in {
val queryString = helper.getQueryStringFor(Seq("read:organisations-matching-ho-ssp"), List("getSelfAssessmentMatch"))
queryString shouldBe res2
}
}
}
|
hmrc/organisations-matching-api | test/component/uk/gov/hmrc/organisationsmatchingapi/controllers/stubs/MatchingStub.scala | <reponame>hmrc/organisations-matching-api<gh_stars>0
/*
* Copyright 2021 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 component.uk.gov.hmrc.organisationsmatchingapi.controllers.stubs
import com.github.tomakehurst.wiremock.client.WireMock._
import play.api.http.Status
object MatchingStub extends MockHost(9658) {
def willReturnCtMatch(
correlationId: String): Unit =
mock.register(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=[a-z0-9-]*&correlationId=${correlationId}"))
.willReturn(aResponse()
.withStatus(Status.OK)
.withBody(s""""match"""")))
def willReturnCtMatchNotFound(
correlationId: String): Unit =
mock.register(
post(urlMatching(s"/organisations-matching/perform-match/cotax\\?matchId=[a-z0-9-]*&correlationId=${correlationId}"))
.willReturn(aResponse()
.withStatus(Status.NOT_FOUND)))
def willReturnSaMatch(
correlationId: String): Unit =
mock.register(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=[a-z0-9-]*&correlationId=${correlationId}"))
.willReturn(aResponse()
.withStatus(Status.OK)
.withBody(s""""match"""")))
def willReturnSaMatchNotFound(
correlationId: String): Unit =
mock.register(
post(urlMatching(s"/organisations-matching/perform-match/self-assessment\\?matchId=[a-z0-9-]*&correlationId=${correlationId}"))
.willReturn(aResponse()
.withStatus(Status.NOT_FOUND)))
}
|
hmrc/organisations-matching-api | test/util/IfHelpers.scala | <filename>test/util/IfHelpers.scala<gh_stars>0
/*
* Copyright 2021 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 util
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfCorpTaxCompanyDetails, IfNameAndAddressDetails, IfNameDetails, IfSaTaxPayerNameAddress, IfSaTaxpayerDetails}
trait IfHelpers {
val ifCorpTaxCompanyDetails: IfCorpTaxCompanyDetails = IfCorpTaxCompanyDetails(
utr = Some("1234567890"),
crn = Some("12345678"),
registeredDetails = Some(IfNameAndAddressDetails(
name = Some(IfNameDetails(
name1 = Some("Waitrose"),
name2 = Some("And Partners")
)),
address = Some(IfAddress(
line1 = Some("Alfie House"),
line2 = Some("Main Street"),
line3 = Some("Manchester"),
line4 = Some("Londonberry"),
postcode = Some("LN1 1AG")
))
)),
communicationDetails = Some(IfNameAndAddressDetails(
name = Some(IfNameDetails(
name1 = Some("Waitrose"),
name2 = Some("And Partners")
)),
address = Some(IfAddress(
line1 = Some("Orange House"),
line2 = Some("Corporation Street"),
line3 = Some("London"),
line4 = Some("Londonberry"),
postcode = Some("LN1 1AG")
))
))
)
val saTaxpayerDetails: IfSaTaxpayerDetails = IfSaTaxpayerDetails(
utr = Some( "1234567890"),
taxpayerType = Some( "Individual"),
taxpayerDetails = Some( Seq (
IfSaTaxPayerNameAddress (
name = Some( "<NAME>" ),
addressType = Some( "Base" ),
address = Some( IfAddress (
line1 = Some( "Alfie House" ),
line2 = Some( "Main Street" ),
line3 = Some( "Birmingham" ),
line4 = Some( "West midlands" ),
postcode = Some( "B14 6JH" )
))),
IfSaTaxPayerNameAddress (
name = Some( "<NAME>" ),
addressType = Some( "Correspondence"),
address = Some( IfAddress (
line1 = Some( "Alice House" ),
line2 = Some( "Main Street" ),
line3 = Some( "Manchester" ),
line4 = None,
postcode = Some( "MC1 4AA" )
))),
IfSaTaxPayerNameAddress (
name = Some( "<NAME>" ),
addressType = Some( "Correspondence"),
address = Some( IfAddress (
line1 = Some( "1 Main Street" ),
line2 = Some( "Disneyland" ),
line3 = Some( "Liverpool" ),
line4 = None,
postcode = Some( "MC1 4AA" )
)))
))
)
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/ogd/CtMatchingResponseSpec.scala | /*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.ogd
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{Address, CtMatchingResponse}
import util.IfHelpers
class CtMatchingResponseSpec extends AnyWordSpec with Matchers with IfHelpers {
"PayeMatchingResponse" should {
"Read and write" in {
val payeMatchingResponse = CtMatchingResponse(
companyRegistrationNumber = "12345",
employerName = "1234567890",
address = Address(
line1 = Some("line1"),
postcode = Some("postcode")))
val asJson = Json.toJson(payeMatchingResponse)
asJson shouldBe Json.parse("""{
| "companyRegistrationNumber": "12345",
| "employerName" : "12<PASSWORD>0",
| "address" : {
| "line1" : "line1",
| "postcode" : "postcode"
| }
|}""".stripMargin)
}
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/services/MatchingService.scala | <reponame>hmrc/organisations-matching-api
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.services
import play.api.libs.json.JsValue
import java.time.LocalDateTime
import java.util.UUID
import javax.inject.Inject
import play.api.mvc.RequestHeader
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.organisationsmatchingapi.connectors.{IfConnector, OrganisationsMatchingConnector}
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.{CtKnownFacts, CtOrganisationsMatchingRequest, SaKnownFacts, SaOrganisationsMatchingRequest}
import scala.concurrent.{ExecutionContext, Future}
class MatchingService @Inject()( ifConnector: IfConnector,
matchingConnector: OrganisationsMatchingConnector,
cacheService: CacheService)
( implicit val ec: ExecutionContext ) {
def matchCoTax(matchId: UUID, correlationId: String, ctMatchingRequest: CtMatchingRequest)(implicit hc: HeaderCarrier, header: RequestHeader): Future[JsValue] = {
for {
ifData <- ifConnector.fetchCorporationTax(matchId.toString, ctMatchingRequest.companyRegistrationNumber)
matched <- matchingConnector.matchCycleCotax(matchId.toString, correlationId, CtOrganisationsMatchingRequest(
CtKnownFacts(
ctMatchingRequest.companyRegistrationNumber,
ctMatchingRequest.employerName,
ctMatchingRequest.addressLine1,
ctMatchingRequest.postcode
), ifData
))
_ <- cacheService.cacheCtUtr(CtMatch(ctMatchingRequest, matchId, LocalDateTime.now(), ifData.utr), ifData.utr.getOrElse(""))
} yield matched
}
def matchSaTax(matchId: UUID, correlationId: String, saMatchingRequest: SaMatchingRequest)(implicit hc: HeaderCarrier, header: RequestHeader): Future[JsValue] = {
for {
ifData <- ifConnector.fetchSelfAssessment(matchId.toString, saMatchingRequest.selfAssessmentUniqueTaxPayerRef)
matched <- matchingConnector.matchCycleSelfAssessment(matchId.toString, correlationId, SaOrganisationsMatchingRequest(
SaKnownFacts(
saMatchingRequest.selfAssessmentUniqueTaxPayerRef,
saMatchingRequest.taxPayerType,
saMatchingRequest.taxPayerName,
saMatchingRequest.addressLine1,
saMatchingRequest.postcode
), ifData
))
_ <- cacheService.cacheSaUtr(SaMatch(saMatchingRequest, matchId, LocalDateTime.now(), ifData.utr), ifData.utr.getOrElse(""))
} yield matched
}
}
|
hmrc/organisations-matching-api | test/component/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchingControllerSpec.scala | <gh_stars>0
/*
* Copyright 2021 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 component.uk.gov.hmrc.organisationsmatchingapi.controllers
import component.uk.gov.hmrc.organisationsmatchingapi.controllers.stubs.{AuthStub, BaseSpec, IfStub, MatchingStub}
import play.api.http.Status
import play.api.libs.json.Json
import scalaj.http.{Http, HttpResponse}
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfCorpTaxCompanyDetails, IfSaTaxPayerNameAddress, IfSaTaxpayerDetails}
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import java.util.concurrent.TimeUnit
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
class MatchingControllerSpec extends BaseSpec {
val scopes = List("read:organisations-matching-ho-ssp")
val ctRequest: CtMatchingRequest = CtMatchingRequest("0213456789", "name", "line1", "NE11NE")
val ctRequestString: String = Json.prettyPrint(Json.toJson(ctRequest))
val saRequest: SaMatchingRequest = SaMatchingRequest("0213456789", "A", "name", "line1", "NE11NE")
val saRequestString: String = Json.prettyPrint(Json.toJson(saRequest))
val ifCorpTax: IfCorpTaxCompanyDetails = IfCorpTaxCompanyDetails(
utr = Some("0123456789"),
crn = Some("0123456789"),
registeredDetails = None,
communicationDetails = None
)
val ifSa: IfSaTaxpayerDetails = IfSaTaxpayerDetails(
utr = Some("0123456789"),
taxpayerType = Some("Individual"),
taxpayerDetails = Some(Seq(IfSaTaxPayerNameAddress(
name = Some("<NAME>"),
addressType = Some("Base"),
address = Some(IfAddress(
line1 = Some("line 1"),
line2 = None,
line3 = None,
line4 = None,
postcode = Some("ABC DEF")
)))
)))
Feature("corporation-tax endpoint") {
Scenario("Valid POST request") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data found in IF")
IfStub.searchCorpTaxCompanyDetails(ctRequest.companyRegistrationNumber, ifCorpTax)
Given("A successful match")
MatchingStub.willReturnCtMatch(correlationIdHeader._2)
val response: HttpResponse[String] = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(ctRequestString)
.asString
Then("The response status should be 200 (Ok)")
response.code mustBe Status.OK
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
val matchId = (responseJson \ "matchId").get.as[String]
responseJson mustBe Json.parse(
s"""{
| "_links" : {
| "getCorporationTaxMatch" : {
| "href" : "/organisations/matching/corporation-tax/$matchId",
| "title" : "Get links to Corporation Tax and number of employees details for a matched organisation"
| },
| "self" : {
| "href" : "/organisations/matching/corporation-tax"
| }
| },
| "matchId" : "$matchId"
|}""".stripMargin)
val cachedData: Option[CtMatch] = Await.result(mongoRepository.fetchAndGetEntry[CtMatch](matchId), Duration(5, TimeUnit.SECONDS))
cachedData.isEmpty mustBe false
}
Scenario("Bad request with missing fields") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
val requestWithMissingFields =
"""{
| "companyRegistrationNumber": "0213456789",
| "employerName": "name",
| "address": {
| "postcode": "NE11NE"}
| }""".stripMargin
val response: HttpResponse[String] = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(requestWithMissingFields)
.asString
Then("The response status should be 400 (Bad request)")
response.code mustBe Status.BAD_REQUEST
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(
s"""{ "code": "INVALID_REQUEST",
| "message" : "/address/addressLine1 is required" }""".stripMargin)
}
Scenario("Bad request with malformed CRN") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
val requestWithMalformedCrn =
"""{
| "companyRegistrationNumber": "021xxx6789",
| "employerName": "name",
| "address": {
| "addressLine1": "line1",
| "postcode": "NE11NE"}
| }""".stripMargin
val response: HttpResponse[String] = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(requestWithMalformedCrn)
.asString
Then("The response status should be 400 (Bad request)")
response.code mustBe Status.BAD_REQUEST
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(
s"""{ "code": "INVALID_REQUEST",
| "message" : "Malformed CRN submitted" }""".stripMargin)
}
Scenario("Valid POST request but IF data not found") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data not found in IF")
IfStub.searchCorpTaxCompanyDetailsNotFound(ctRequest.companyRegistrationNumber, ifCorpTax)
val response: HttpResponse[String] = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(ctRequestString)
.asString
Then("The response status should be 404 (Not Found)")
response.code mustBe Status.NOT_FOUND
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(s"""{"code":"MATCHING_FAILED","message":"There is no match for the information provided"}""".stripMargin)
}
Scenario("Valid POST request but match not found") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data found in IF")
IfStub.searchCorpTaxCompanyDetails(ctRequest.companyRegistrationNumber, ifCorpTax)
Given("An unsuccessful match")
MatchingStub.willReturnCtMatchNotFound(correlationIdHeader._2)
val response: HttpResponse[String] = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(ctRequestString)
.asString
Then("The response status should be 404 (Not Found)")
response.code mustBe Status.NOT_FOUND
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(s"""{"code":"MATCHING_FAILED","message":"There is no match for the information provided"}""".stripMargin)
}
Scenario("A missing correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeadersInvalid(acceptHeaderP1))
.postData(ctRequestString)
.asString
response.code mustBe Status.BAD_REQUEST
Json.parse(response.body) mustBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "CorrelationId is required"
)
}
Scenario("a request is made with a malformed correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeadersMalformed(acceptHeaderP1))
.postData(ctRequestString)
.asString
response.code mustBe Status.BAD_REQUEST
Json.parse(response.body) mustBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "Malformed CorrelationId"
)
}
Scenario("not authorized") {
val requestString: String = Json.prettyPrint(Json.toJson(ctRequest))
Given("an invalid privileged Auth bearer token")
AuthStub.willNotAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeaders(acceptHeaderP1))
.postData(requestString)
.asString
Then("the response status should be 401 (unauthorized)")
response.code mustBe Status.UNAUTHORIZED
Json.parse(response.body) mustBe Json.obj(
"code" -> "UNAUTHORIZED",
"message" -> "Bearer token is missing or not authorized"
)
}
}
Feature("self-assessment endpoint") {
Scenario("Valid POST request") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data found in IF")
IfStub.searchSaCompanyDetails(saRequest.selfAssessmentUniqueTaxPayerRef, ifSa)
Given("A successful match")
MatchingStub.willReturnSaMatch(correlationIdHeader._2)
val response: HttpResponse[String] = Http(s"$serviceUrl/self-assessment")
.headers(requestHeaders(acceptHeaderP1))
.postData(saRequestString)
.asString
Then("The response status should be 200 (Ok)")
response.code mustBe Status.OK
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
val matchId = (responseJson \ "matchId").get.as[String]
responseJson mustBe Json.parse(
s"""{
| "_links" : {
| "getSelfAssessmentMatch" : {
| "href" : "/organisations/matching/self-assessment/$matchId",
| "title" : "Get links to Self Assessment and number of employees details for a matched organisation"
| },
| "self" : {
| "href" : "/organisations/matching/self-assessment"
| }
| },
| "matchId" : "$matchId"
|}""".stripMargin)
val cachedData: Option[SaMatch] = Await.result(mongoRepository.fetchAndGetEntry[SaMatch](matchId), Duration(5, TimeUnit.SECONDS))
cachedData.isEmpty mustBe false
}
Scenario("Valid POST request but IF data not found") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data not found in IF")
IfStub.searchSaCompanyDetailsNotFound(saRequest.selfAssessmentUniqueTaxPayerRef, ifSa)
val response: HttpResponse[String] = Http(s"$serviceUrl/self-assessment")
.headers(requestHeaders(acceptHeaderP1))
.postData(saRequestString)
.asString
Then("The response status should be 404 (Not Found)")
response.code mustBe Status.NOT_FOUND
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(s"""{"code":"MATCHING_FAILED","message":"There is no match for the information provided"}""".stripMargin)
}
Scenario("Valid POST request but match not found") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
Given("Data found in IF")
IfStub.searchSaCompanyDetails(saRequest.selfAssessmentUniqueTaxPayerRef, ifSa)
Given("An unsuccessful match")
MatchingStub.willReturnSaMatchNotFound(correlationIdHeader._2)
val response: HttpResponse[String] = Http(s"$serviceUrl/self-assessment")
.headers(requestHeaders(acceptHeaderP1))
.postData(saRequestString)
.asString
Then("The response status should be 404 (Not Found)")
response.code mustBe Status.NOT_FOUND
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(s"""{"code":"MATCHING_FAILED","message":"There is no match for the information provided"}""".stripMargin)
}
Scenario("Bad request with missing fields") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
val requestWithMissingFields =
"""{
| "selfAssessmentUniqueTaxPayerRef": "0213456789",
| "taxPayerType": "A",
| "taxPayerName": "name",
| "address": {
| "postcode": "NE11NE"
| }
| }""".stripMargin
val response: HttpResponse[String] = Http(s"$serviceUrl/self-assessment")
.headers(requestHeaders(acceptHeaderP1))
.postData(requestWithMissingFields)
.asString
Then("The response status should be 400 (Bad request)")
response.code mustBe Status.BAD_REQUEST
And("The response should have a valid payload")
val responseJson = Json.parse(response.body)
responseJson mustBe Json.parse(
s"""{ "code": "INVALID_REQUEST",
| "message" : "/address/addressLine1 is required" }""".stripMargin)
}
Scenario("A missing correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax")
.headers(requestHeadersInvalid(acceptHeaderP1))
.postData(ctRequestString)
.asString
response.code mustBe Status.BAD_REQUEST
Json.parse(response.body) mustBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "CorrelationId is required"
)
}
Scenario("a request is made with a malformed correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment")
.headers(requestHeadersMalformed(acceptHeaderP1))
.postData(saRequestString)
.asString
response.code mustBe Status.BAD_REQUEST
Json.parse(response.body) mustBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "Malformed CorrelationId"
)
}
Scenario("not authorized") {
Given("an invalid privileged Auth bearer token")
AuthStub.willNotAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment")
.headers(requestHeaders(acceptHeaderP1))
.postData(saRequestString)
.asString
Then("the response status should be 401 (unauthorized)")
response.code mustBe Status.UNAUTHORIZED
Json.parse(response.body) mustBe Json.obj(
"code" -> "UNAUTHORIZED",
"message" -> "Bearer token is missing or not authorized"
)
}
}
} |
hmrc/organisations-matching-api | test/it/uk/gov/hmrc/organisationsmatchingapi/services/CacheServiceSpec.scala | <filename>test/it/uk/gov/hmrc/organisationsmatchingapi/services/CacheServiceSpec.scala
/*
* Copyright 2021 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 it.uk.gov.hmrc.organisationsmatchingapi.services
import org.mockito.BDDMockito.`given`
import org.mockito.Mockito.{times, verify}
import java.util.UUID
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import org.mockito.ArgumentMatchers.{any, eq => eqTo}
import org.mockito.Mockito
import uk.gov.hmrc.organisationsmatchingapi.cache.{CacheConfiguration, InsertResult}
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import uk.gov.hmrc.organisationsmatchingapi.repository.MatchRepository
import uk.gov.hmrc.organisationsmatchingapi.services.CacheService
import util.UnitSpec
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class CacheServiceSpec extends UnitSpec with Matchers with GuiceOneAppPerSuite with MockitoSugar with ScalaFutures {
val mockCacheConfig: CacheConfiguration = mock[CacheConfiguration]
val mockMatchRepo: MatchRepository = mock[MatchRepository]
val matchId: UUID = UUID.fromString("69f0da0d-4e50-4161-badc-fa39f769bed3")
val cacheService = new CacheService(mockMatchRepo, mockCacheConfig)
val ctRequest: CtMatchingRequest = CtMatchingRequest("crn", "name", "line1", "postcode")
val ctMatch: CtMatch = CtMatch(ctRequest, matchId)
val saRequest: SaMatchingRequest = SaMatchingRequest("utr", "Individual", "name", "line1", "postcode")
val saMatch: SaMatch = SaMatch(saRequest, matchId)
"getByMatchId" should {
"Retrieve CT match details from cache service" in {
Mockito.reset(mockMatchRepo)
given(mockMatchRepo.fetchAndGetEntry[CtMatch](any())(any()))
.willReturn(Future.successful(Some(ctMatch)))
val result = cacheService.fetch[CtMatch](matchId)
await(result) shouldBe Some(ctMatch)
}
"CT return none where no details found in cache" in {
Mockito.reset(mockMatchRepo)
given(mockMatchRepo.fetchAndGetEntry[CtMatch](any())(any()))
.willReturn(Future.successful(None))
val result = cacheService.fetch[CtMatch](matchId)
await(result) shouldBe None
}
"Retrieve SA match details from cache service" in {
Mockito.reset(mockMatchRepo)
given(mockMatchRepo.fetchAndGetEntry[SaMatch](any())(any()))
.willReturn(Future.successful(Some(saMatch)))
val result = cacheService.fetch[SaMatch](matchId)
await(result) shouldBe Some(saMatch)
}
"SA return none where no details found in cache" in {
Mockito.reset(mockMatchRepo)
given(mockMatchRepo.fetchAndGetEntry[SaMatch](any())(any()))
.willReturn(Future.successful(None))
val result = cacheService.fetch[SaMatch](matchId)
await(result) shouldBe None
}
}
"cacheCtUtr" should {
"save a CTUTR to the cache" in {
Mockito.reset(mockMatchRepo)
val ctUtr = "SOMECTUTR"
val expected = ctMatch.copy(utr = Some(ctUtr))
given(mockMatchRepo.cache(any(), any())(any()))
.willReturn(Future.successful(InsertResult.InsertSucceeded))
await {
cacheService.cacheCtUtr(ctMatch, ctUtr)
}
verify(mockMatchRepo, times(1)).cache(any(), eqTo(expected))(any())
}
}
"cacheSaUtr" should {
"save an SAUTR to the cache" in {
Mockito.reset(mockMatchRepo)
val saUtr = "SOMESAUTR"
val expected = saMatch.copy(utr = Some(saUtr))
given(mockMatchRepo.cache(any(), any())(any()))
.willReturn(Future.successful(InsertResult.InsertSucceeded))
await {
cacheService.cacheSaUtr(saMatch, saUtr)
}
verify(mockMatchRepo, times(1)).cache(any(), eqTo(expected))(any())
}
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/domain/integrationframework/IfSaTaxpayerDetails.scala | <reponame>hmrc/organisations-matching-api<gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework
import play.api.libs.functional.syntax.unlift
import play.api.libs.json.{Format, JsPath}
import play.api.libs.json.Reads.{pattern, _}
import play.api.libs.functional.syntax._
import scala.util.matching.Regex
case class IfAddress( line1: Option[String],
line2: Option[String],
line3: Option[String],
line4: Option[String],
postcode: Option[String] )
object IfAddress {
implicit val format: Format[IfAddress] = Format(
(
(JsPath \ "line1").readNullable[String](maxLength(100)) and
(JsPath \ "line2").readNullable[String](maxLength(100)) and
(JsPath \ "line3").readNullable[String](maxLength(100)) and
(JsPath \ "line4").readNullable[String](maxLength(100)) and
(JsPath \ "postcode").readNullable[String](maxLength(10))
)(IfAddress.apply _),
(
(JsPath \ "line1").writeNullable[String] and
(JsPath \ "line2").writeNullable[String] and
(JsPath \ "line3").writeNullable[String] and
(JsPath \ "line4").writeNullable[String] and
(JsPath \ "postcode").writeNullable[String]
)(unlift(IfAddress.unapply))
)
}
case class IfSaTaxPayerNameAddress( name: Option[String],
addressType: Option[String],
address: Option[IfAddress] )
object IfSaTaxPayerNameAddress {
val addressTypePattern = "^[A-Za-z0-9\\s -]{1,24}$".r
implicit val format: Format[IfSaTaxPayerNameAddress] = Format(
(
(JsPath \ "name").readNullable[String](maxLength(100)) and
(JsPath \ "addressType").readNullable[String](pattern(addressTypePattern, "Address type is not valid")) and
(JsPath \ "address").readNullable[IfAddress]
)(IfSaTaxPayerNameAddress.apply _),
(
(JsPath \ "name").writeNullable[String] and
(JsPath \ "addressType").writeNullable[String] and
(JsPath \ "address").writeNullable[IfAddress]
)(unlift(IfSaTaxPayerNameAddress.unapply))
)
}
case class IfSaTaxpayerDetails( utr: Option[String],
taxpayerType: Option[String],
taxpayerDetails: Option[Seq[IfSaTaxPayerNameAddress]])
object IfSaTaxpayerDetails {
val utrPattern: Regex = "^[0-9]{10}$".r
val taxpayerTypePattern: Regex = "^[A-Za-z0-9\\s -]{1,24}$".r
implicit val format: Format[IfSaTaxpayerDetails] = Format(
(
(JsPath \ "utr").readNullable[String](pattern(utrPattern, "UTR is in the incorrect Format")) and
(JsPath \ "taxpayerType").readNullable[String](pattern(taxpayerTypePattern, "Taxpayer type is not valid")) and
(JsPath \ "taxpayerDetails").readNullable[Seq[IfSaTaxPayerNameAddress]]
)(IfSaTaxpayerDetails.apply _),
(
(JsPath \ "utr").writeNullable[String] and
(JsPath \ "taxpayerType").writeNullable[String] and
(JsPath \ "taxpayerDetails").writeNullable[Seq[IfSaTaxPayerNameAddress]]
)(unlift(IfSaTaxpayerDetails.unapply))
)
}
|
hmrc/organisations-matching-api | test/it/uk/gov/hmrc/organisationsmatchingapi/connectors/IfConnectorSpec.scala | /*
* Copyright 2021 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 it.uk.gov.hmrc.organisationsmatchingapi.connectors
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito
import org.mockito.Mockito.{times, verify}
import org.scalatest.BeforeAndAfterEach
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.Json
import play.api.test.FakeRequest
import uk.gov.hmrc.http.{HeaderCarrier, HeaderNames, HttpClient, InternalServerException}
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.connectors.IfConnector
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework._
import uk.gov.hmrc.organisationsmatchingapi.domain.models.MatchingException
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig
import util.UnitSpec
import java.util.UUID
import scala.concurrent.ExecutionContext
class IfConnectorSpec
extends AnyWordSpec
with BeforeAndAfterEach
with UnitSpec
with MockitoSugar
with Matchers
with GuiceOneAppPerSuite {
val stubPort: Int = sys.env.getOrElse("WIREMOCK", "11122").toInt
val stubHost = "127.0.0.1"
val wireMockServer = new WireMockServer(wireMockConfig().port(stubPort))
val integrationFrameworkAuthorizationToken = "IF_TOKEN"
val integrationFrameworkEnvironment = "IF_ENVIRONMENT"
def externalServices: Seq[String] = Seq.empty
override lazy val fakeApplication = new GuiceApplicationBuilder()
.bindings(bindModules: _*)
.configure(
"auditing.enabled" -> false,
"cache.enabled" -> false,
"microservice.services.integration-framework.host" -> "127.0.0.1",
"microservice.services.integration-framework.port" -> "11122",
"microservice.services.integration-framework.authorization-token" -> integrationFrameworkAuthorizationToken,
"microservice.services.integration-framework.environment" -> integrationFrameworkEnvironment
)
.build()
implicit val ec: ExecutionContext =
fakeApplication.injector.instanceOf[ExecutionContext]
trait Setup {
val matchId = "80a6bb14-d888-436e-a541-4000674c60aa"
val sampleCorrelationId = "188e9400-b636-4a3b-80ba-230a8c72b92a"
val sampleCorrelationIdHeader: (String, String) = ("CorrelationId" -> sampleCorrelationId)
implicit val hc: HeaderCarrier = HeaderCarrier()
val config: ServicesConfig = fakeApplication.injector.instanceOf[ServicesConfig]
val httpClient: HttpClient = fakeApplication.injector.instanceOf[HttpClient]
val auditHelper: AuditHelper = mock[AuditHelper]
val underTest = new IfConnector(config, httpClient, auditHelper)
}
override def beforeEach(): Unit = {
wireMockServer.start()
configureFor(stubHost, stubPort)
}
override def afterEach(): Unit = {
wireMockServer.stop()
}
"fetch Corporation Tax" should {
val crn = "12345678"
val utr = "1234567890"
"return data on successful call" in new Setup {
val registeredDetails: IfNameAndAddressDetails = IfNameAndAddressDetails(
Some(IfNameDetails(
Some("Waitrose"),
Some("<NAME>")
)),
Some(IfAddress(
Some("Alfie House"),
Some("Main Street"),
Some("Manchester"),
Some("Londonberry"),
Some("LN1 1AG")
))
)
val communicationDetails: IfNameAndAddressDetails = IfNameAndAddressDetails(
Some(IfNameDetails(
Some("Waitrose"),
Some("<NAME>")
)),
Some(IfAddress(
Some("Orange House"),
Some("Corporation Street"),
Some("London"),
Some("Londonberry"),
Some("LN1 1AG")
))
)
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/corporation-tax/$crn/company/details"))
.withHeader(HeaderNames.authorisation, equalTo(s"Bearer $integrationFrameworkAuthorizationToken"))
.withHeader("Environment", equalTo(integrationFrameworkEnvironment))
.withHeader("CorrelationId", equalTo(sampleCorrelationId))
.willReturn(
aResponse()
.withStatus(200)
.withBody(
Json.toJson(
IfCorpTaxCompanyDetails(
Some(utr),
Some(crn),
Some(registeredDetails),
Some(communicationDetails)
)).toString()
)
)
)
val result: IfCorpTaxCompanyDetails = await(
underTest
.fetchCorporationTax(matchId, crn)(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec))
verify(underTest.auditHelper, times(1))
.auditIfApiResponse(any(), any(), any(), any(), any())(any())
result shouldBe IfCorpTaxCompanyDetails(
Some(utr),
Some(crn),
Some(registeredDetails),
Some(communicationDetails)
)
}
"Fail when IF returns an error" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/corporation-tax/$crn/company/details"))
.willReturn(aResponse().withStatus(500)))
intercept[InternalServerException] {
await(
underTest.fetchCorporationTax(UUID.randomUUID().toString, "12345678")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
"Fail when IF returns a bad request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/corporation-tax/$crn/company/details"))
.willReturn(aResponse().withStatus(400).withBody("BAD_REQUEST")))
intercept[InternalServerException] {
await(
underTest.fetchCorporationTax(UUID.randomUUID().toString, "12345678")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
"Fail when IF returns a NOT_FOUND" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/corporation-tax/$crn/company/details"))
.willReturn(aResponse().withStatus(404).withBody("NOT_FOUND")))
intercept[MatchingException] {
await(
underTest.fetchCorporationTax(UUID.randomUUID().toString, "12345678")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
}
"fetch Self Assessment" should {
val utr = "1234567890"
"return data on successful request" in new Setup {
val taxpayerJohnNameAddress: IfSaTaxPayerNameAddress = IfSaTaxPayerNameAddress(
Some("<NAME>"),
Some("Base"),
Some(IfAddress(
Some("Alfie House"),
Some("Main Street"),
Some("Birmingham"),
Some("West Midlands"),
Some("B14 6JH"),
))
)
val taxpayerJoanneNameAddress: IfSaTaxPayerNameAddress = IfSaTaxPayerNameAddress(
Some("<NAME>"),
Some("Correspondence"),
Some(IfAddress(
Some("Alfie House"),
Some("Main Street"),
Some("Birmingham"),
Some("West Midlands"),
Some("MC1 4AA"),
))
)
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/self-assessment/$utr/taxpayer/details"))
.withHeader(
HeaderNames.authorisation,
equalTo(s"Bearer $integrationFrameworkAuthorizationToken"))
.withHeader("Environment", equalTo(integrationFrameworkEnvironment))
.withHeader("CorrelationId", equalTo(sampleCorrelationId))
.willReturn(aResponse()
.withStatus(200)
.withBody(Json.toJson(IfSaTaxpayerDetails(
Some(utr),
Some("Individual"),
Some(Seq(taxpayerJohnNameAddress, taxpayerJoanneNameAddress))
)).toString())))
val result: IfSaTaxpayerDetails = await(
underTest.fetchSelfAssessment(UUID.randomUUID().toString, "1234567890")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
verify(underTest.auditHelper,
times(1)).auditIfApiResponse(any(), any(), any(), any(), any())(any())
result shouldBe IfSaTaxpayerDetails(
Some(utr),
Some("Individual"),
Some(Seq(taxpayerJohnNameAddress, taxpayerJoanneNameAddress))
)
}
"Fail when IF returns an error" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/self-assessment/$utr/taxpayer/details"))
.willReturn(aResponse().withStatus(500)))
intercept[InternalServerException] {
await(
underTest.fetchSelfAssessment(UUID.randomUUID().toString, "1234567890")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
"Fail when IF returns a bad request" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/self-assessment/$utr/taxpayer/details"))
.willReturn(aResponse().withStatus(400).withBody("BAD_REQUEST")))
intercept[InternalServerException] {
await(
underTest.fetchSelfAssessment(UUID.randomUUID().toString, "1234567890")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
"Fail when IF returns a NOT_FOUND" in new Setup {
Mockito.reset(underTest.auditHelper)
stubFor(
get(urlPathMatching(s"/organisations/self-assessment/$utr/taxpayer/details"))
.willReturn(aResponse().withStatus(404).withBody("NOT_FOUND")))
intercept[MatchingException] {
await(
underTest.fetchSelfAssessment(UUID.randomUUID().toString, "1234567890")(
hc,
FakeRequest().withHeaders(sampleCorrelationIdHeader),
ec
)
)
}
verify(underTest.auditHelper,
times(1)).auditIfApiFailure(any(), any(), any(), any(), any())(any())
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/play/RequestHeaderUtilsSpec.scala | <reponame>hmrc/organisations-matching-api
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.play
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.typedmap.TypedMap
import play.api.mvc.request.{RemoteConnection, RequestTarget}
import play.api.mvc.{Headers, RequestHeader}
import play.api.test.FakeRequest
import play.api.test.Helpers.{ACCEPT, GET}
import uk.gov.hmrc.http.BadRequestException
import uk.gov.hmrc.organisationsmatchingapi.play.RequestHeaderUtils._
import java.util.UUID
class RequestHeaderUtilsSpec extends AnyWordSpec with Matchers {
"getVersionedUri" should {
"return the versioned request when the Accept header is set" in {
val fooRequest = FakeRequest(GET, "/foo")
getVersionedRequest(fooRequest.withHeaders(ACCEPT -> "application/vnd.hmrc.2.0+json")).uri shouldBe "/v2.0/foo"
getVersionedRequest(fooRequest.withHeaders(ACCEPT -> "application/vnd.hmrc.2.0+json")).path shouldBe "/v2.0/foo"
}
"return the versioned request for the root endpoint when the Accept header is set" in {
val fooRequest = FakeRequest(GET, "/")
getVersionedRequest(fooRequest.withHeaders(ACCEPT -> "application/vnd.hmrc.2.0+json")).uri shouldBe "/v2.0"
getVersionedRequest(fooRequest.withHeaders(ACCEPT -> "application/vnd.hmrc.2.0+json")).path shouldBe "/v2.0"
}
"Default to v1.0 when the Accept header is not set" in {
val fooRequest = FakeRequest(GET, "/foo")
getVersionedRequest(fooRequest).uri shouldBe "/v1.0/foo"
getVersionedRequest(fooRequest).path shouldBe "/v1.0/foo"
}
}
"extractUriContext" should {
"extract uri contexts" in {
extractUriContext(FakeRequest(GET, "/")) shouldBe "/"
extractUriContext(FakeRequest(GET, "/foo")) shouldBe "/foo"
extractUriContext(FakeRequest(GET, "/foo/bar")) shouldBe "/foo"
}
}
"getClientIdHeader" should {
"extract the client id header from the request if present" in {
val clientId = UUID.randomUUID().toString
val fooRequest = FakeRequest(GET, "/")
getClientIdHeader(fooRequest.withHeaders(CLIENT_ID_HEADER -> clientId)) shouldBe (CLIENT_ID_HEADER -> clientId)
}
"generate a new header with the default value dash (-) if the header is not present" in {
getClientIdHeader(FakeRequest(GET, "/")) shouldBe (CLIENT_ID_HEADER -> "-")
}
"validate correlationId successfully when CorrelationId header exists in correct format" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq(("CorrelationId", "1ed32c2b-7f45-4b30-b15e-64166dd97e9b")))
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val result = validateCorrelationId(requestHeader)
result shouldBe UUID.fromString("1ed32c2b-7f45-4b30-b15e-64166dd97e9b")
}
"validateCorrelationId throws exception when CorrelationId header exists in incorrect format" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq(("CorrelationId", "IncorrectFormat")))
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val exception = intercept[BadRequestException] { validateCorrelationId(requestHeader) }
exception.message shouldBe "Malformed CorrelationId"
}
"validateCorrelationId throws exception when CorrelationId header is missing" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq())
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val exception = intercept[BadRequestException] { validateCorrelationId(requestHeader) }
exception.message shouldBe "CorrelationId is required"
}
"maybeCorrelationId successfully when CorrelationId header exists in correct format" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq(("CorrelationId", "1ed32c2b-7f45-4b30-b15e-64166dd97e9b")))
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val result = maybeCorrelationId(requestHeader)
result shouldBe Some("1ed32c2b-7f45-4b30-b15e-64166dd97e9b")
}
"maybeCorrelationId returns None when CorrelationId header is missing" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq())
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val result = maybeCorrelationId(requestHeader)
result shouldBe None
}
"maybeCorrelationId returns None when CorrelationId header is malformed" in {
val requestHeader: RequestHeader = new RequestHeader {
override def headers: Headers = new Headers(Seq(("CorrelationId", "IncorrectFormat")))
override def connection: RemoteConnection = ???
override def method: String = ???
override def target: RequestTarget = ???
override def version: String = ???
override def attrs: TypedMap = ???
}
val result = maybeCorrelationId(requestHeader)
result shouldBe None
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/services/MatchedServiceSpec.scala | <gh_stars>0
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.services
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import org.mockito.ArgumentMatchers.{any, eq => eqTo}
import org.mockito.BDDMockito.`given`
import play.api.test.Helpers.{await, defaultAwaitTimeout}
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, MatchNotFoundException, SaMatch, UtrMatch}
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import uk.gov.hmrc.organisationsmatchingapi.services.{CacheService, MatchedService}
import java.util.UUID
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future.successful
class MatchedServiceSpec extends AnyWordSpec with Matchers with MockitoSugar {
private val cacheService = mock[CacheService]
private val matchedService = new MatchedService(cacheService)
private val matchId = UUID.fromString("57072660-1df9-4aeb-b4ea-cd2d7f96e430")
private val matchRequestCt = new CtMatchingRequest(
"crn",
"test",
"test",
"test"
)
private val matchRequestSa = new SaMatchingRequest(
"utr",
"individual",
"test",
"test",
"test"
)
private val ctMatch = new CtMatch(matchRequestCt, utr = Some("test"))
private val saMatch = new SaMatch(matchRequestSa, utr = Some("test"))
private val utrMatch = new UtrMatch(matchId, "test")
"fetchCt" should {
"return cache entry" in {
given(cacheService.fetch[CtMatch](eqTo(matchId))(any())).willReturn(successful(Some(ctMatch)))
val res = await(matchedService.fetchCt(matchId))
res shouldBe ctMatch
}
"return not found" in {
given(cacheService.fetch[CtMatch](eqTo(matchId))(any())).willReturn(successful(None))
intercept[MatchNotFoundException] {
await(matchedService.fetchCt(matchId))
}
}
}
"fetchSa" should {
"return cache entry" in {
given(cacheService.fetch[SaMatch](eqTo(matchId))(any())).willReturn(successful(Some(saMatch)))
val res = await(matchedService.fetchSa(matchId))
res shouldBe saMatch
}
"return not found" in {
given(cacheService.fetch[SaMatch](eqTo(matchId))(any())).willReturn(successful(None))
intercept[MatchNotFoundException] {
await(matchedService.fetchSa(matchId))
}
}
}
"fetch any" should {
"return cache entry" in {
given(cacheService.fetch[UtrMatch](eqTo(matchId))(any())).willReturn(successful(Some(utrMatch)))
val res = await(matchedService.fetchMatchedOrganisationRecord(matchId))
res shouldBe utrMatch
}
"return not found" in {
given(cacheService.fetch[UtrMatch](eqTo(matchId))(any())).willReturn(successful(None))
intercept[MatchNotFoundException] {
await(matchedService.fetchMatchedOrganisationRecord(matchId))
}
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/CtOrganisationsMatchingRequestSpec.scala | <filename>test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/CtOrganisationsMatchingRequestSpec.scala<gh_stars>0
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfCorpTaxCompanyDetails, IfNameAndAddressDetails, IfNameDetails}
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.{CtKnownFacts, CtOrganisationsMatchingRequest}
import util.IfHelpers
class CtOrganisationsMatchingRequestSpec extends AnyWordSpec with Matchers with IfHelpers {
"CtOrganisationsMatchingRequest" should {
"Read and write" in {
val ctKnownFacts = CtKnownFacts("test", "test", "test", "test")
val name = IfNameDetails(Some("test"), Some("test"))
val address = IfAddress(Some("test"), None, None, None, Some("test"))
val details = IfNameAndAddressDetails(Some(name), Some(address))
val ctIfData = IfCorpTaxCompanyDetails(Some("test"), Some("test"), Some(details), Some(details))
val request = CtOrganisationsMatchingRequest(ctKnownFacts, ctIfData)
val asJson = Json.toJson(request)
asJson shouldBe Json.parse("""
|{
| "knownFacts": {
| "crn": "test",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "crn": "test",
| "registeredDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| },
| "communicationDetails": {
| "name": {
| "name1": "test",
| "name2": "test"
| },
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }
| }
|}
|""".stripMargin
)
}
}
}
|
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/services/CacheService.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.services
import play.api.libs.json.Format
import java.util.UUID
import javax.inject.Inject
import uk.gov.hmrc.organisationsmatchingapi.cache.{CacheConfiguration, InsertResult}
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
import uk.gov.hmrc.organisationsmatchingapi.repository.MatchRepository
import scala.concurrent.{ExecutionContext, Future}
class CacheService @Inject()(
matchRepository: MatchRepository,
val conf: CacheConfiguration)(implicit ec: ExecutionContext) {
lazy val cacheEnabled: Boolean = conf.cacheEnabled
def cacheCtUtr(ctMatch: CtMatch, utr: String): Future[InsertResult] = {
matchRepository.cache(ctMatch.matchId.toString, ctMatch.copy(utr = Some(utr)))
}
def cacheSaUtr(saMatch: SaMatch, utr: String): Future[InsertResult] = {
matchRepository.cache(saMatch.matchId.toString, saMatch.copy(utr = Some(utr)))
}
def fetch[T: Format](matchId: UUID): Future[Option[T]] = {
matchRepository.fetchAndGetEntry(matchId.toString) flatMap {
result =>
Future.successful(result)
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/SaOrganisationsMatchingRequestSpec.scala | <filename>test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/organisationsmatching/SaOrganisationsMatchingRequestSpec.scala<gh_stars>0
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework.{IfAddress, IfSaTaxPayerNameAddress, IfSaTaxpayerDetails}
import uk.gov.hmrc.organisationsmatchingapi.domain.organisationsmatching.{SaKnownFacts, SaOrganisationsMatchingRequest}
import util.IfHelpers
class SaOrganisationsMatchingRequestSpec extends AnyWordSpec with Matchers with IfHelpers {
"SaOrganisationsMatchingRequest" should {
"Read and write" in {
val saKnownFacts = SaKnownFacts("test", "Individual", "test", "test", "test")
val address = IfAddress(Some("test"), None, None, None, Some("test"))
val saDetails = IfSaTaxPayerNameAddress(Some("test"), None, Some(address))
val taxpayerDetails = Some(Seq(saDetails))
val saIfData = IfSaTaxpayerDetails(Some("test"), Some("Individual"), taxpayerDetails)
val request = SaOrganisationsMatchingRequest(saKnownFacts, saIfData)
val asJson = Json.toJson(request)
asJson shouldBe Json.parse("""
|{
| "knownFacts": {
| "utr": "test",
| "taxpayerType": "Individual",
| "name": "test",
| "line1": "test",
| "postcode": "test"
| },
| "ifData": {
| "utr": "test",
| "taxpayerType": "Individual",
| "taxpayerDetails": [{
| "name": "test",
| "address": {
| "line1": "test",
| "postcode": "test"
| }
| }]
| }
|}
""".stripMargin
)
}
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchingControllerSpec.scala | <gh_stars>0
/*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.controllers
import org.mockito.ArgumentMatchers.{any, refEq}
import org.mockito.BDDMockito.`given`
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import play.api.http.Status
import play.api.libs.json.Json
import play.api.mvc.PlayBodyParsers
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers}
import uk.gov.hmrc.auth.core.retrieve.v2.Retrievals
import uk.gov.hmrc.auth.core.{AuthConnector, Enrolment, Enrolments}
import uk.gov.hmrc.organisationsmatchingapi.audit.AuditHelper
import uk.gov.hmrc.organisationsmatchingapi.controllers.MatchingController
import uk.gov.hmrc.organisationsmatchingapi.domain.models.MatchingException
import uk.gov.hmrc.organisationsmatchingapi.services.{CacheService, MatchingService, ScopesHelper, ScopesService}
import util.SpecBase
import java.util.UUID
import scala.concurrent.{ExecutionContext, Future}
class MatchingControllerSpec extends AnyWordSpec with SpecBase with Matchers with MockitoSugar {
private implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
private val mockAuthConnector = mock[AuthConnector]
private val mockCacheService = mock[CacheService]
private val mockAuditHelper = mock[AuditHelper]
private val mockScopesService = mock[ScopesService]
private val scopesHelper = new ScopesHelper(mockScopesService)
private val mockMatchingService = mock[MatchingService]
private val mockBodyParser = mock[PlayBodyParsers]
private val controller = new MatchingController(
mockAuthConnector,
Helpers.stubControllerComponents(),
Helpers.stubMessagesControllerComponents(),
mockScopesService,
scopesHelper,
mockBodyParser,
mockCacheService,
mockMatchingService
)(mockAuditHelper, ec)
given(mockAuthConnector.authorise(any(), refEq(Retrievals.allEnrolments))(any(), any()))
.willReturn(Future.successful(Enrolments(Set(Enrolment("test-scope"), Enrolment("test-scope-1")))))
given(mockScopesService.getAllScopes).willReturn(List("test-scope", "test-scope-1"))
given(mockMatchingService.matchSaTax(any(), any(), any())(any(), any())).willReturn(Future.successful(Json.toJson("match")))
given(mockMatchingService.matchCoTax(any(), any(), any())(any(), any())).willReturn(Future.successful(Json.toJson("match")))
given(mockScopesService.getInternalEndpoints(any())).willReturn(Seq())
given(mockScopesService.getExternalEndpoints(any())).willReturn(Seq())
"POST matchOrganisationCt" should {
val fakeRequest = FakeRequest("POST", "/")
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse(
"""
|{
| "companyRegistrationNumber":"1234567890",
| "employerName":"name",
| "address": {
| "postcode":"postcode",
| "addressLine1":"line1"
| }
|}""".stripMargin))
"return 200" in {
val result = controller.matchOrganisationCt()(fakeRequest)
status(result) shouldBe Status.OK
}
"return 404 when request does not match" in {
given(mockMatchingService.matchCoTax(any(), any(), any())(any(), any())).willReturn(Future.failed(new MatchingException))
val result = controller.matchOrganisationCt()(
FakeRequest()
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse(
"""
|{
| "companyRegistrationNumber":"999999999",
| "employerName":"notAname",
| "address": {
| "postcode":"notApostcode",
| "addressLine1":"notAline1"
| }
|}""".stripMargin))
)
status(result) shouldBe Status.NOT_FOUND
contentAsJson(result) shouldBe Json.parse(
"""
|{
| "code":"MATCHING_FAILED",
| "message":"There is no match for the information provided"
|}""".stripMargin)
}
"return 400 when request is invalid" in {
val result = controller.matchOrganisationCt()(
FakeRequest()
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse("{}")))
status(result) shouldBe Status.BAD_REQUEST
}
}
"POST matchOrganisationSa" should {
val fakeRequest = FakeRequest("POST", "/")
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse(
"""
|{
| "selfAssessmentUniqueTaxPayerRef":"1234567890",
| "taxPayerType":"A",
| "taxPayerName":"name",
| "address":{
| "postcode":"postcode",
| "addressLine1":"line1"
| }
| }""".stripMargin))
"return 200" in {
val result = controller.matchOrganisationSa()(fakeRequest)
status(result) shouldBe Status.OK
}
"return 404 when request does not match" in {
given(mockMatchingService.matchSaTax(any(), any(), any())(any(), any())).willReturn(Future.failed(new MatchingException))
val result = controller.matchOrganisationSa()(
FakeRequest()
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse(
"""
|{
| "selfAssessmentUniqueTaxPayerRef":"999999999",
| "taxPayerType":"A",
| "taxPayerName":"notAname",
| "address":{
| "postcode":"notApostcode",
| "addressLine1":"notAline1"
| }
| }""".stripMargin))
)
status(result) shouldBe Status.NOT_FOUND
contentAsJson(result) shouldBe Json.parse(
"""
|{
| "code":"MATCHING_FAILED",
| "message":"There is no match for the information provided"
|}""".stripMargin)
}
"return 400 when request is invalid" in {
val result = controller.matchOrganisationSa()(
FakeRequest()
.withHeaders(("CorrelationId", UUID.randomUUID().toString))
.withBody(Json.parse("{}"))
)
status(result) shouldBe Status.BAD_REQUEST
}
}
} |
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/services/MatchedService.scala | <filename>app/uk/gov/hmrc/organisationsmatchingapi/services/MatchedService.scala
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.services
import com.google.inject.Inject
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, MatchNotFoundException, SaMatch, UtrMatch}
import java.util.UUID
import scala.concurrent.{ExecutionContext, Future}
class MatchedService @Inject()(cacheService: CacheService) {
def fetchCt(matchId: UUID)(implicit ec: ExecutionContext): Future[CtMatch] =
cacheService.fetch[CtMatch](matchId) flatMap {
case Some(entry) => Future.successful(entry)
case _ => Future.failed(new MatchNotFoundException)
}
def fetchSa(matchId: UUID)(implicit ec: ExecutionContext): Future[SaMatch] =
cacheService.fetch[SaMatch](matchId) flatMap {
case Some(entry) => Future.successful(entry)
case _ => Future.failed(new MatchNotFoundException)
}
def fetchMatchedOrganisationRecord(matchId: UUID)
(implicit ec: ExecutionContext): Future[UtrMatch] =
cacheService.fetch[UtrMatch](matchId) flatMap {
case Some(utrMatch) => Future.successful(UtrMatch(utrMatch.matchId, utrMatch.utr))
case _ => Future.failed(new MatchNotFoundException)
}
}
|
hmrc/organisations-matching-api | test/unit/uk/gov/hmrc/organisationsmatchingapi/domain/integrationframework/IfSaTaxpayerDetailsSpec.scala | /*
* Copyright 2021 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 unit.uk.gov.hmrc.organisationsmatchingapi.domain.integrationframework
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import play.api.libs.json.Json
import util.IfHelpers
class IfSaTaxpayerDetailsSpec extends AnyWordSpec with Matchers with IfHelpers {
val saTaxPayerDetailsString: String = """{
| "utr": "1234567890",
| "taxpayerType": "Individual",
| "taxpayerDetails": [
| {
| "name": "<NAME>",
| "addressType": "Base",
| "address": {
| "line1": "Alfie House",
| "line2": "Main Street",
| "line3": "Birmingham",
| "line4": "West midlands",
| "postcode": "B14 6JH"
| }
| },
| {
| "name": "<NAME>",
| "addressType": "Correspondence",
| "address": {
| "line1": "Alice House",
| "line2": "Main Street",
| "line3": "Manchester",
| "postcode": "MC1 4AA"
| }
| },
| {
| "name": "<NAME>",
| "addressType": "Correspondence",
| "address": {
| "line1": "1 Main Street",
| "line2": "Disneyland",
| "line3": "Liverpool",
| "postcode": "MC1 4AA"
| }
| }
| ]
|}""".stripMargin
"IfSaTaxpayerDetails" should {
"Read and write" in {
val parsed = Json.toJson(saTaxpayerDetails)
parsed shouldBe Json.parse(saTaxPayerDetailsString)
}
}
}
|
hmrc/organisations-matching-api | project/AppDependencies.scala | import play.core.PlayVersion
import play.sbt.PlayImport._
import sbt._
object AppDependencies {
val hmrc = "uk.gov.hmrc"
val hmrcMongo = "uk.gov.hmrc.mongo"
val compile: Seq[ModuleID] = Seq(
ws,
hmrcMongo %% "hmrc-mongo-play-28" % "0.53.0",
hmrc %% "bootstrap-backend-play-28" % "5.12.0",
hmrc %% "play-hmrc-api" % "6.4.0-play-28",
hmrc %% "play-hal" % "2.1.0-play-27",
hmrc %% "json-encryption" % "4.10.0-play-28"
)
def test(scope: String = "test, it, component") = Seq(
hmrc %% "bootstrap-test-play-28" % "5.12.0" % scope,
hmrcMongo %% "hmrc-mongo-test-play-28" % "0.53.0" % scope,
"org.scalatestplus" %% "mockito-3-4" % "3.2.7.0" % scope,
"org.scalatest" %% "scalatest" % "3.2.9" % scope,
"com.typesafe.play" %% "play-test" % PlayVersion.current % scope,
"com.vladsch.flexmark" % "flexmark-all" % "0.36.8" % scope,
"org.scalatestplus.play" %% "scalatestplus-play" % "4.0.3" % scope,
"org.pegdown" % "pegdown" % "1.6.0" % scope,
"com.github.tomakehurst" % "wiremock-jre8" % "2.27.2" % scope,
"org.mockito" % "mockito-core" % "3.8.0" % scope,
hmrc %% "service-integration-test" % "1.1.0-play-28" % scope,
"org.scalaj" %% "scalaj-http" % "2.4.2" % scope,
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.12.2" % scope
)
} |
hmrc/organisations-matching-api | app/uk/gov/hmrc/organisationsmatchingapi/utils/MatchUuidPathBinder.scala | <filename>app/uk/gov/hmrc/organisationsmatchingapi/utils/MatchUuidPathBinder.scala<gh_stars>0
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.organisationsmatchingapi.utils
import play.api.mvc.PathBindable
import java.util.UUID
import scala.util.Try
class MatchUuidPathBinder extends PathBindable[UUID] {
private val parameterName = "matchId"
override def bind(key: String, value:String): Either[String, UUID] = {
if(value.isEmpty)
Left(s"$parameterName is required")
else {
Try(
Right(UUID.fromString(value))
).getOrElse(
Left(s"$parameterName format is invalid")
)
}
}
override def unbind(key: String, uuid: UUID) = s"$key=${uuid.toString}"
}
|
hmrc/organisations-matching-api | test/component/uk/gov/hmrc/organisationsmatchingapi/controllers/MatchedControllerSpec.scala | /*
* Copyright 2021 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 component.uk.gov.hmrc.organisationsmatchingapi.controllers
import scalaj.http.Http
import component.uk.gov.hmrc.organisationsmatchingapi.controllers.stubs.{AuthStub, BaseSpec}
import play.api.libs.json.Json
import play.api.test.Helpers._
import org.scalatest.matchers.should.Matchers.convertToAnyShouldWrapper
import uk.gov.hmrc.organisationsmatchingapi.domain.models.{CtMatch, SaMatch}
import uk.gov.hmrc.organisationsmatchingapi.domain.ogd.{CtMatchingRequest, SaMatchingRequest}
import java.util.UUID
import scala.concurrent.Await.result
class MatchedControllerSpec extends BaseSpec {
val matchId: UUID = UUID.randomUUID()
val scopes = List("read:organisations-matching-ho-ssp")
val ctRequest: CtMatchingRequest = CtMatchingRequest("0123456789", "name", "line1", "postcode")
val ctMatch: CtMatch = CtMatch(ctRequest, matchId, utr = Some("testutr"))
val saRequest: SaMatchingRequest = SaMatchingRequest("utr", "Individual", "name", "line1", "postcode")
val saMatch: SaMatch = SaMatch(saRequest, matchId, utr = Some("testutr"))
Feature("cotax") {
Scenario("a valid request is made for an existing match") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
And("A valid match exist")
result(mongoRepository.cache(matchId.toString, ctMatch), timeout)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe OK
Json.parse(response.body) shouldBe Json.parse(
s"""{
| "address": {
| "line1": "line1",
| "postcode": "postcode"
| },
| "_links": {
| "getEmployeeCount": {
| "href": "/organisations/details/number-of-employees?matchId=$matchId",
| "title": "Find the number of employees for an organisation"
| },
| "self": {
| "href": "/organisations/matching/corporation-tax/$matchId"
| },
| "getCorporationTaxDetails": {
| "href": "/organisations/details/corporation-tax?matchId=$matchId",
| "title": "Get an organisation's Corporation Tax details"
| }
| },
| "companyRegistrationNumber": "${ctRequest.companyRegistrationNumber}",
| "employerName": "name"
|}""".stripMargin
)
}
Scenario("a request is made with a missing match id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe NOT_FOUND
Json.parse(response.body) shouldBe Json.obj(
"code" -> "NOT_FOUND",
"message" -> "The resource can not be found"
)
}
Scenario("a valid request is made for an expired match") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe NOT_FOUND
Json.parse(response.body) shouldBe Json.obj(
"code" -> "NOT_FOUND",
"message" -> "The resource can not be found"
)
}
Scenario("a request is made with a missing correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/$matchId")
.headers(requestHeadersInvalid(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "CorrelationId is required"
)
}
Scenario("a request is made with a malformed correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/$matchId")
.headers(requestHeadersMalformed(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "Malformed CorrelationId"
)
}
Scenario("not authorized") {
Given("an invalid privileged Auth bearer token")
AuthStub.willNotAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
Then("the response status should be 401 (unauthorized)")
response.code shouldBe UNAUTHORIZED
Json.parse(response.body) shouldBe Json.obj(
"code" -> "UNAUTHORIZED",
"message" -> "Bearer token is missing or not authorized"
)
}
Scenario("a request is made with a malformed match id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/corporation-tax/foo")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "matchId format is invalid"
)
}
}
Feature("self-assessment") {
Scenario("a valid request is made for an existing match") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
And("A valid match exist")
result(mongoRepository.cache(matchId.toString, saMatch), timeout)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe OK
Json.parse(response.body) shouldBe Json.parse(
s"""{
| "address": {
| "line1": "line1",
| "postcode": "postcode"
| },
| "_links": {
| "getEmployeeCount": {
| "href": "/organisations/details/number-of-employees?matchId=$matchId",
| "title": "Find the number of employees for an organisation"
| },
| "getSelfAssessmentDetails": {
| "href": "/organisations/details/self-assessment?matchId=$matchId",
| "title": "Get an organisation's Self Assessment details"
| },
| "self": {
| "href": "/organisations/matching/self-assessment/$matchId"
| }
| },
| "selfAssessmentUniqueTaxPayerRef": "utr",
| "taxPayerType": "Individual",
| "taxPayerName": "name"
|}""".stripMargin
)
}
Scenario("a request is made with a missing match id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe NOT_FOUND
Json.parse(response.body) shouldBe Json.obj(
"code" -> "NOT_FOUND",
"message" -> "The resource can not be found"
)
}
Scenario("a valid request is made for an expired match") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe NOT_FOUND
Json.parse(response.body) shouldBe Json.obj(
"code" -> "NOT_FOUND",
"message" -> "The resource can not be found"
)
}
Scenario("a request is made with a missing correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/$matchId")
.headers(requestHeadersInvalid(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "CorrelationId is required"
)
}
Scenario("a request is made with a malformed correlation id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/$matchId")
.headers(requestHeadersMalformed(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "Malformed CorrelationId"
)
}
Scenario("not authorized") {
Given("an invalid privileged Auth bearer token")
AuthStub.willNotAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/$matchId")
.headers(requestHeaders(acceptHeaderP1))
.asString
Then("the response status should be 401 (unauthorized)")
response.code shouldBe UNAUTHORIZED
Json.parse(response.body) shouldBe Json.obj(
"code" -> "UNAUTHORIZED",
"message" -> "Bearer token is missing or not authorized"
)
}
Scenario("a request is made with a malformed match id") {
Given("A valid privileged Auth bearer token")
AuthStub.willAuthorizePrivilegedAuthToken(authToken, scopes)
When("the API is invoked")
val response = Http(s"$serviceUrl/self-assessment/foo")
.headers(requestHeaders(acceptHeaderP1))
.asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" ->"INVALID_REQUEST",
"message" ->"matchId format is invalid"
)
}
}
Feature("matched organisation") {
Scenario("a valid request is made for an existing match id") {
Given("A valid privileged Auth bearer token")
And("A valid match exist")
result(mongoRepository.cache(matchId.toString, saMatch), timeout)
When("the API is invoked")
val response = Http(s"$serviceUrl/match-record/$matchId").asString
response.code shouldBe OK
Json.parse(response.body) shouldBe Json.parse(
s"""{
| "matchId": "$matchId",
| "utr": "testutr"
|}""".stripMargin
)
}
Scenario("a valid request is made for an match id that does not exist") {
Given("A valid privileged Auth bearer token")
And("A valid match does not exist")
When("the API is invoked")
val response = Http(s"$serviceUrl/match-record/$matchId").asString
response.code shouldBe NOT_FOUND
Json.parse(response.body) shouldBe Json.obj(
"code" -> "NOT_FOUND",
"message" -> "The resource can not be found"
)
}
Scenario("a valid request is made for an invalid match id") {
Given("A valid privileged Auth bearer token")
And("A valid match exist")
result(mongoRepository.cache(matchId.toString, saMatch), timeout)
When("the API is invoked")
val response = Http(s"$serviceUrl/match-record/foo").asString
response.code shouldBe BAD_REQUEST
Json.parse(response.body) shouldBe Json.obj(
"code" -> "INVALID_REQUEST",
"message" -> "matchId format is invalid"
)
}
}
}
|
brharrington/akka-http | project/Publish.scala | <reponame>brharrington/akka-http<gh_stars>1000+
/*
* Copyright (C) 2016-2020 Lightbend Inc. <https://www.lightbend.com>
*/
package akka
import scala.language.postfixOps
import sbt.{Def, _}
import Keys._
import xerial.sbt.Sonatype.autoImport.sonatypeProfileName
/**
* For projects that are not published.
*/
object NoPublish extends AutoPlugin {
override def requires = plugins.JvmPlugin
override def projectSettings = Seq(
skip in publish := true,
publishArtifact := false,
publish := {},
publishLocal := {},
)
}
object Publish extends AutoPlugin {
override def requires = plugins.JvmPlugin
override def trigger = AllRequirements
override def projectSettings: Seq[Def.Setting[_]] = Seq(
sonatypeProfileName := "com.typesafe",
)
} |
rene-ffs/gatling-amqp-plugin | src/main/scala/ru/tinkoff/gatling/amqp/checks/AmqpJsonPathCheckMaterializer.scala | package ru.tinkoff.gatling.amqp.checks
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import io.gatling.core.check.extractor.jsonpath.JsonPathCheckType
import io.gatling.core.check.{CheckMaterializer, Preparer, Specializer}
import io.gatling.core.json.JsonParsers
import ru.tinkoff.gatling.amqp.AmqpCheck
import ru.tinkoff.gatling.amqp.request.AmqpProtocolMessage
import scala.util.Try
class AmqpJsonPathCheckMaterializer(jsonParsers: JsonParsers)
extends CheckMaterializer[JsonPathCheckType, AmqpCheck, AmqpProtocolMessage, Any] {
override protected def preparer: Preparer[AmqpProtocolMessage, Any] =
AmqpJsonPathCheckMaterializer.jsonPathPreparer(jsonParsers)
override protected def specializer: Specializer[AmqpCheck, AmqpProtocolMessage] = identity
}
object AmqpJsonPathCheckMaterializer {
private val CharsParsingThreshold = 200 * 1000
private def jsonPathPreparer(jsonParsers: JsonParsers): Preparer[AmqpProtocolMessage, Any] =
replyMessage => {
val bodyCharset = Try(Charset.forName(replyMessage.amqpProperties.getContentEncoding))
.getOrElse(Charset.defaultCharset())
if (replyMessage.payload.length > CharsParsingThreshold || jsonParsers.preferJackson)
jsonParsers.safeParseJackson(new ByteArrayInputStream(replyMessage.payload), bodyCharset)
else
jsonParsers.safeParse(new String(replyMessage.payload, bodyCharset))
}
}
|
rene-ffs/gatling-amqp-plugin | src/main/scala/ru/tinkoff/gatling/amqp/request/PublishDslBuilderExchange.scala | package ru.tinkoff.gatling.amqp.request
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.session.Expression
case class PublishDslBuilderExchange(
requestName: Expression[String],
configuration: GatlingConfiguration
) {
def directExchange(name: Expression[String], routingKey: Expression[String]): PublishDslBuilderMessage =
destination(AmqpDirectExchange(name, routingKey))
def queueExchange(name: Expression[String]): PublishDslBuilderMessage = destination(AmqpQueueExchange(name))
protected def destination(dest: AmqpExchange) = PublishDslBuilderMessage(requestName, dest, configuration)
}
|
rene-ffs/gatling-amqp-plugin | src/main/scala/ru/tinkoff/gatling/amqp/checks/AmqpXPathCheckMaterializer.scala | package ru.tinkoff.gatling.amqp.checks
import java.io.{ByteArrayInputStream, InputStreamReader}
import io.gatling.commons.validation.{safely, _}
import io.gatling.core.check.extractor.xpath.{Dom, XPathCheckType, XmlParsers}
import io.gatling.core.check.{CheckMaterializer, Preparer, Specializer}
import org.xml.sax.InputSource
import ru.tinkoff.gatling.amqp.AmqpCheck
import ru.tinkoff.gatling.amqp.request.AmqpProtocolMessage
class AmqpXPathCheckMaterializer(xmlParsers: XmlParsers)
extends CheckMaterializer[XPathCheckType, AmqpCheck, AmqpProtocolMessage, Option[Dom]] {
private val ErrorMapper = "Could not parse response into a DOM Document: " + _
override protected def preparer: Preparer[AmqpProtocolMessage, Option[Dom]] =
message =>
safely(ErrorMapper) {
message match {
case AmqpProtocolMessage(_, payload, _) =>
val in = new ByteArrayInputStream(payload)
Some(xmlParsers.parse(new InputSource(new InputStreamReader(in)))).success
case _ => "Unsupported message type".failure
}
}
override protected def specializer: Specializer[AmqpCheck, AmqpProtocolMessage] = identity
}
|
rene-ffs/gatling-amqp-plugin | src/main/scala/ru/tinkoff/gatling/amqp/checks/AmqpCheckSupport.scala | <filename>src/main/scala/ru/tinkoff/gatling/amqp/checks/AmqpCheckSupport.scala
package ru.tinkoff.gatling.amqp.checks
import java.nio.charset.Charset
import io.gatling.commons.validation._
import io.gatling.core.check._
import io.gatling.core.check.extractor.bytes.BodyBytesCheckType
import io.gatling.core.check.extractor.string.BodyStringCheckType
import io.gatling.core.check.extractor.xpath.XmlParsers
import io.gatling.core.json.JsonParsers
import ru.tinkoff.gatling.amqp.AmqpCheck
import ru.tinkoff.gatling.amqp.checks.AmqpResponseCodeCheckBuilder.{AmqpMessageCheckType, ExtendedDefaultFindCheckBuilder, _}
import ru.tinkoff.gatling.amqp.request.AmqpProtocolMessage
import scala.annotation.implicitNotFound
import scala.util.Try
trait AmqpCheckSupport {
def messageCheck: AmqpMessageCheck.type = AmqpMessageCheck
val responseCode: ExtendedDefaultFindCheckBuilder[AmqpMessageCheckType, AmqpProtocolMessage, String] = ResponseCode
@implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
implicit def checkBuilder2AmqpCheck[A, P, X](checkBuilder: CheckBuilder[A, P, X])(
implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
checkBuilder.build(materializer)
@implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
implicit def validatorCheckBuilder2AmqpCheck[A, P, X](validatorCheckBuilder: ValidatorCheckBuilder[A, P, X])(
implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
validatorCheckBuilder.exists
@implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
implicit def findCheckBuilder2AmqpCheck[A, P, X](findCheckBuilder: FindCheckBuilder[A, P, X])(
implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
findCheckBuilder.find.exists
implicit def amqpXPathMaterializer(implicit xmlParsers: XmlParsers): AmqpXPathCheckMaterializer =
new AmqpXPathCheckMaterializer(xmlParsers)
implicit def amqpJsonPathMaterializer(implicit jsonParsers: JsonParsers): AmqpJsonPathCheckMaterializer =
new AmqpJsonPathCheckMaterializer(jsonParsers)
implicit def amqpBodyStringMaterializer: AmqpCheckMaterializer[BodyStringCheckType, String] =
new CheckMaterializer[BodyStringCheckType, AmqpCheck, AmqpProtocolMessage, String] {
override protected def preparer: Preparer[AmqpProtocolMessage, String] = replyMessage => {
val bodyCharset = Try(Charset.forName(replyMessage.amqpProperties.getContentEncoding))
.getOrElse(Charset.defaultCharset())
if (replyMessage.payload.length > 0) {
new String(replyMessage.payload, bodyCharset).success
} else "".success
}
override protected def specializer: Specializer[AmqpCheck, AmqpProtocolMessage] = identity
}
implicit def amqpBodyByteMaterializer: AmqpCheckMaterializer[BodyBytesCheckType, Array[Byte]] =
new CheckMaterializer[BodyBytesCheckType, AmqpCheck, AmqpProtocolMessage, Array[Byte]] {
override protected def preparer: Preparer[AmqpProtocolMessage, Array[Byte]] = replyMessage => {
if (replyMessage.payload.length > 0) {
replyMessage.payload.success
} else Array.emptyByteArray.success
}
override protected def specializer: Specializer[AmqpCheck, AmqpProtocolMessage] = identity
}
implicit val httpStatusCheckMaterializer: AmqpCheckMaterializer[AmqpMessageCheckType, AmqpProtocolMessage] =
new AmqpCheckMaterializer[AmqpMessageCheckType, AmqpProtocolMessage] {
override val specializer: Specializer[AmqpCheck, AmqpProtocolMessage] = identity
override val preparer: Preparer[AmqpProtocolMessage, AmqpProtocolMessage] = _.success
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/common/component/traits/VideoRamRasterizer.scala | <filename>src/main/scala/li/cil/oc/common/component/traits/VideoRamRasterizer.scala
package li.cil.oc.common.component.traits
import li.cil.oc.common.component
import li.cil.oc.common.component.GpuTextBuffer
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.village.VillageDoorInfo
import scala.collection.mutable
trait VideoRamRasterizer {
class VirtualRamDevice(val owner: String) extends VideoRamDevice {}
private val internalBuffers = new mutable.HashMap[String, VideoRamDevice]
def onBufferRamInit(ram: component.GpuTextBuffer): Unit
def onBufferBitBlt(col: Int, row: Int, w: Int, h: Int, ram: component.GpuTextBuffer, fromCol: Int, fromRow: Int): Unit
def onBufferRamDestroy(ram: component.GpuTextBuffer): Unit
def addBuffer(ram: GpuTextBuffer): Boolean = {
var gpu = internalBuffers.get(ram.owner)
if (gpu.isEmpty) {
gpu = Option(new VirtualRamDevice(ram.owner))
internalBuffers += ram.owner -> gpu.get
}
val preexists: Boolean = gpu.get.addBuffer(ram)
if (!preexists || ram.dirty) {
onBufferRamInit(ram)
}
preexists
}
def removeBuffer(owner: String, id: Int): Boolean = {
internalBuffers.get(owner) match {
case Some(gpu: VideoRamDevice) => {
gpu.getBuffer(id) match {
case Some(ram: component.GpuTextBuffer) => {
onBufferRamDestroy(ram)
gpu.removeBuffers(Array(id)) == 1
}
case _ => false
}
}
case _ => false
}
}
def removeAllBuffers(owner: String): Int = {
var count = 0
internalBuffers.get(owner) match {
case Some(gpu: VideoRamDevice) => {
val ids = gpu.bufferIndexes()
for (id <- ids) {
if (removeBuffer(owner, id)) {
count += 1
}
}
}
case _ => Unit
}
count
}
def removeAllBuffers(): Int = {
var count = 0
for ((owner: String, _: Any) <- internalBuffers) {
count += removeAllBuffers(owner)
}
count
}
def loadBuffer(owner: String, id: Int, nbt: NBTTagCompound): Boolean = {
val src = new li.cil.oc.util.TextBuffer(width = 1, height = 1, li.cil.oc.util.PackedColor.SingleBitFormat)
src.load(nbt)
addBuffer(component.GpuTextBuffer.wrap(owner, id, src))
}
def getBuffer(owner: String, id: Int): Option[component.GpuTextBuffer] = {
internalBuffers.get(owner) match {
case Some(gpu: VideoRamDevice) => gpu.getBuffer(id)
case _ => None
}
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/common/component/traits/VideoRamDevice.scala | <filename>src/main/scala/li/cil/oc/common/component/traits/VideoRamDevice.scala
package li.cil.oc.common.component.traits
import li.cil.oc.common.component
import net.minecraft.nbt.NBTTagCompound
import scala.collection.mutable
trait VideoRamDevice {
private val internalBuffers = new mutable.HashMap[Int, component.GpuTextBuffer]
val RESERVED_SCREEN_INDEX: Int = 0
def isEmpty: Boolean = internalBuffers.isEmpty
def onBufferRamDestroy(id: Int): Unit = {}
def bufferIndexes(): Array[Int] = internalBuffers.collect {
case (index: Int, _: Any) => index
}.toArray
def addBuffer(ram: component.GpuTextBuffer): Boolean = {
val preexists = internalBuffers.contains(ram.id)
internalBuffers += ram.id -> ram
preexists
}
def removeBuffers(ids: Array[Int]): Int = {
var count = 0
if (ids.nonEmpty) {
for (id <- ids) {
if (internalBuffers.remove(id).nonEmpty) {
onBufferRamDestroy(id)
count += 1
}
}
}
count
}
def removeAllBuffers(): Int = removeBuffers(bufferIndexes())
def loadBuffer(address: String, id: Int, nbt: NBTTagCompound): Unit = {
val src = new li.cil.oc.util.TextBuffer(width = 1, height = 1, li.cil.oc.util.PackedColor.SingleBitFormat)
src.load(nbt)
addBuffer(component.GpuTextBuffer.wrap(address, id, src))
}
def getBuffer(id: Int): Option[component.GpuTextBuffer] = {
if (internalBuffers.contains(id))
Option(internalBuffers(id))
else
None
}
def nextAvailableBufferIndex: Int = {
var index = RESERVED_SCREEN_INDEX + 1
while (internalBuffers.contains(index)) {
index += 1;
}
index
}
def calculateUsedMemory(): Int = {
var sum: Int = 0
for ((_, buffer: component.GpuTextBuffer) <- internalBuffers) {
sum += buffer.data.width * buffer.data.height
}
sum
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/integration/thaumicenergistics/ConvertAspectCraftable.scala | package li.cil.oc.integration.thaumicenergistics
import java.util
import cpw.mods.fml.common.registry.GameRegistry
import li.cil.oc.api.driver.Converter
import net.minecraft.item.ItemStack
import scala.collection.convert.WrapAsScala._
object ConvertAspectCraftable extends Converter {
private val DistillationPattern = GameRegistry.findItem("thaumicenergistics", "crafting.aspect")
override def convert(value: scala.Any, output: util.Map[AnyRef, AnyRef]): Unit = value match {
case stack: ItemStack if stack.getItem == DistillationPattern && stack.hasTagCompound =>
output += "aspect" -> stack.getTagCompound.getString("Aspect")
case _ =>
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/server/component/GraphicsCard.scala | <filename>src/main/scala/li/cil/oc/server/component/GraphicsCard.scala
package li.cil.oc.server.component
import java.util
import li.cil.oc.{Constants, Localization, Settings, api}
import li.cil.oc.api.Network
import li.cil.oc.api.driver.DeviceInfo
import li.cil.oc.api.driver.DeviceInfo.DeviceAttribute
import li.cil.oc.api.driver.DeviceInfo.DeviceClass
import li.cil.oc.api.machine.{Arguments, Callback, Context, LimitReachedException}
import li.cil.oc.api.network._
import li.cil.oc.api.prefab
import li.cil.oc.util.PackedColor
import net.minecraft.nbt.{NBTTagCompound, NBTTagList}
import li.cil.oc.common.component
import li.cil.oc.common.component.GpuTextBuffer
import scala.collection.convert.WrapAsJava._
import scala.util.matching.Regex
// IMPORTANT: usually methods with side effects should *not* be direct
// callbacks to avoid the massive headache synchronizing them ensues, in
// particular when it comes to world saving. I'm making an exception for
// screens, though since they'd be painfully sluggish otherwise. This also
// means we have to use a somewhat nasty trick in common.component.Buffer's
// save function: we wait for all computers in the same network to finish
// their current execution and then pause them, to ensure the state of the
// buffer is "clean", meaning the computer has the correct state when it is
// saved in turn. If we didn't, a computer might change a screen after it was
// saved, but before the computer was saved, leading to mismatching states in
// the save file - a Bad Thing (TM).
class GraphicsCard(val tier: Int) extends prefab.ManagedEnvironment with DeviceInfo with component.traits.VideoRamDevice {
override val node: Connector = Network.newNode(this, Visibility.Neighbors).
withComponent("gpu").
withConnector().
create()
private val maxResolution = Settings.screenResolutionsByTier(tier)
private val maxDepth = Settings.screenDepthsByTier(tier)
private var screenAddress: Option[String] = None
private var screenInstance: Option[api.internal.TextBuffer] = None
private var bufferIndex: Int = RESERVED_SCREEN_INDEX // screen is index zero
private def screen(index: Int, f: (api.internal.TextBuffer) => Array[AnyRef]): Array[AnyRef] = {
if (index == RESERVED_SCREEN_INDEX) {
screenInstance match {
case Some(screen) => screen.synchronized(f(screen))
case _ => Array(Unit, "no screen")
}
} else {
getBuffer(index) match {
case Some(buffer: api.internal.TextBuffer) => f(buffer)
case _ => Array(Unit, "invalid buffer index")
}
}
}
private def screen(f: (api.internal.TextBuffer) => Array[AnyRef]): Array[AnyRef] = screen(bufferIndex, f)
final val setBackgroundCosts = Array(1.0 / 32, 1.0 / 64, 1.0 / 128)
final val setForegroundCosts = Array(1.0 / 32, 1.0 / 64, 1.0 / 128)
final val setPaletteColorCosts = Array(1.0 / 2, 1.0 / 8, 1.0 / 16)
final val setCosts = Array(1.0 / 64, 1.0 / 128, 1.0 / 256)
final val copyCosts = Array(1.0 / 16, 1.0 / 32, 1.0 / 64)
final val fillCosts = Array(1.0 / 32, 1.0 / 64, 1.0 / 128)
// These are dirty page bitblt budget costs
// a single bitblt can send a screen of data, which is n*set calls where set is writing an entire line
// So for each tier, we multiple the set cost with the number of lines the screen may have
final val bitbltCost: Double = Settings.get.bitbltCost * scala.math.pow(2, tier)
final val totalVRAM: Double = (maxResolution._1 * maxResolution._2) * Settings.get.vramSizes(0 max tier min 2)
var budgetExhausted: Boolean = false // for especially expensive calls, bitblt
// ----------------------------------------------------------------------- //
private final lazy val deviceInfo = Map(
DeviceAttribute.Class -> DeviceClass.Display,
DeviceAttribute.Description -> "Graphics controller",
DeviceAttribute.Vendor -> Constants.DeviceInfo.DefaultVendor,
DeviceAttribute.Product -> ("MPG" + ((tier + 1) * 1000).toString + " GTZ"),
DeviceAttribute.Capacity -> capacityInfo,
DeviceAttribute.Width -> widthInfo,
DeviceAttribute.Clock -> clockInfo
)
def capacityInfo: String = (maxResolution._1 * maxResolution._2).toString
def widthInfo: String = Array("1", "4", "8").apply(maxDepth.ordinal())
def clockInfo: String = ((2000 / setBackgroundCosts(tier)).toInt / 100).toString + "/" + ((2000 / setForegroundCosts(tier)).toInt / 100).toString + "/" + ((2000 / setPaletteColorCosts(tier)).toInt / 100).toString + "/" + ((2000 / setCosts(tier)).toInt / 100).toString + "/" + ((2000 / copyCosts(tier)).toInt / 100).toString + "/" + ((2000 / fillCosts(tier)).toInt / 100).toString
override def getDeviceInfo: util.Map[String, String] = deviceInfo
// ----------------------------------------------------------------------- //
private def resolveInvokeCosts(idx: Int, context: Context, budgetCost: Double, units: Int, factor: Double): Boolean = {
idx match {
case RESERVED_SCREEN_INDEX =>
context.consumeCallBudget(budgetCost)
consumePower(units, factor)
case _ => true
}
}
@Callback(direct = true, doc = """function(): number -- returns the index of the currently selected buffer. 0 is reserved for the screen. Can return 0 even when there is no screen""")
def getActiveBuffer(context: Context, args: Arguments): Array[AnyRef] = {
result(bufferIndex)
}
@Callback(direct = true, doc = """function(index: number): number -- Sets the active buffer to `index`. 1 is the first vram buffer and 0 is reserved for the screen. returns nil for invalid index (0 is always valid)""")
def setActiveBuffer(context: Context, args: Arguments): Array[AnyRef] = {
val previousIndex: Int = bufferIndex
val newIndex: Int = args.checkInteger(0)
if (newIndex != RESERVED_SCREEN_INDEX && getBuffer(newIndex).isEmpty) {
result(Unit, "invalid buffer index")
} else {
bufferIndex = newIndex
if (bufferIndex == RESERVED_SCREEN_INDEX) {
screen(s => result(true))
}
result(previousIndex)
}
}
@Callback(direct = true, doc = """function(): number -- Returns an array of indexes of the allocated buffers""")
def buffers(context: Context, args: Arguments): Array[AnyRef] = {
result(bufferIndexes())
}
@Callback(direct = true, doc = """function([width: number, height: number]): number -- allocates a new buffer with dimensions width*height (defaults to max resolution) and appends it to the buffer list. Returns the index of the new buffer and returns nil with an error message on failure. A buffer can be allocated even when there is no screen bound to this gpu. Index 0 is always reserved for the screen and thus the lowest index of an allocated buffer is always 1.""")
def allocateBuffer(context: Context, args: Arguments): Array[AnyRef] = {
val width: Int = args.optInteger(0, maxResolution._1)
val height: Int = args.optInteger(1, maxResolution._2)
val size: Int = width * height
if (width <= 0 || height <= 0) {
result(Unit, "invalid page dimensions: must be greater than zero")
}
else if (size > (totalVRAM - calculateUsedMemory)) {
result(Unit, "not enough video memory")
} else if (node == null) {
result(Unit, "graphics card appears disconnected")
} else {
val format: PackedColor.ColorFormat = PackedColor.Depth.format(Settings.screenDepthsByTier(tier))
val buffer = new li.cil.oc.util.TextBuffer(width, height, format)
val page = component.GpuTextBuffer.wrap(node.address, nextAvailableBufferIndex, buffer)
addBuffer(page)
result(page.id)
}
}
// this event occurs when the gpu is told a page was removed - we need to notify the screen of this
// we do this because the VideoRamDevice trait only notifies itself, it doesn't assume there is a screen
override def onBufferRamDestroy(id: Int): Unit = {
// first protect our buffer index - it needs to fall back to the screen if its buffer was removed
if (id != RESERVED_SCREEN_INDEX) {
screen(RESERVED_SCREEN_INDEX, s => s match {
case oc: component.traits.VideoRamRasterizer => result(oc.removeBuffer(node.address, id))
case _ => result(true)// addon mod screen type that is not video ram aware
})
}
if (id == bufferIndex) {
bufferIndex = RESERVED_SCREEN_INDEX
}
}
@Callback(direct = true, doc = """function(index: number): boolean -- Closes buffer at `index`. Returns true if a buffer closed. If the current buffer is closed, index moves to 0""")
def freeBuffer(context: Context, args: Arguments): Array[AnyRef] = {
val index: Int = args.optInteger(0, bufferIndex)
if (removeBuffers(Array(index)) == 1) result(true)
else result(Unit, "no buffer at index")
}
@Callback(direct = true, doc = """function(): number -- Closes all buffers and returns the count. If the active buffer is closed, index moves to 0""")
def freeAllBuffers(context: Context, args: Arguments): Array[AnyRef] = result(removeAllBuffers())
@Callback(direct = true, doc = """function(): number -- returns the total memory size of the gpu vram. This does not include the screen.""")
def totalMemory(context: Context, args: Arguments): Array[AnyRef] = {
result(totalVRAM)
}
@Callback(direct = true, doc = """function(): number -- returns the total free memory not allocated to buffers. This does not include the screen.""")
def freeMemory(context: Context, args: Arguments): Array[AnyRef] = {
result(totalVRAM - calculateUsedMemory)
}
@Callback(direct = true, doc = """function(index: number): number, number -- returns the buffer size at index. Returns the screen resolution for index 0. returns nil for invalid indexes""")
def getBufferSize(context: Context, args: Arguments): Array[AnyRef] = {
val idx = args.optInteger(0, bufferIndex)
screen(idx, s => result(s.getWidth, s.getHeight))
}
private def determineBitbltBudgetCost(dst: api.internal.TextBuffer, src: api.internal.TextBuffer): Double = {
// large dirty buffers need throttling so their budget cost is more
// clean buffers have no budget cost.
src match {
case page: GpuTextBuffer => dst match {
case _: GpuTextBuffer => 0.0 // no cost to write to ram
case _ if page.dirty => // screen target will need the new buffer
// small buffers are cheap, so increase with size of buffer source
bitbltCost * (src.getWidth * src.getHeight) / (maxResolution._1 * maxResolution._2)
case _ => .001 // bitblt a clean page to screen has a minimal cost
}
case _ => 0.0 // from screen is free
}
}
private def determineBitbltEnergyCost(dst: api.internal.TextBuffer): Double = {
// memory to memory copies are extremely energy efficient
// rasterizing to the screen has the same cost as copy (in fact, screen-to-screen blt _is_ a copy
dst match {
case _: GpuTextBuffer => 0
case _ => Settings.get.gpuCopyCost / 15
}
}
@Callback(direct = true, doc = """function([dst: number, col: number, row: number, width: number, height: number, src: number, fromCol: number, fromRow: number]):boolean -- bitblt from buffer to screen. All parameters are optional. Writes to `dst` page in rectangle `x, y, width, height`, defaults to the bound screen and its viewport. Reads data from `src` page at `fx, fy`, default is the active page from position 1, 1""")
def bitblt(context: Context, args: Arguments): Array[AnyRef] = {
val dstIdx = args.optInteger(0, RESERVED_SCREEN_INDEX)
screen(dstIdx, dst => {
val col = args.optInteger(1, 1)
val row = args.optInteger(2, 1)
val w = args.optInteger(3, dst.getWidth)
val h = args.optInteger(4, dst.getHeight)
val srcIdx = args.optInteger(5, bufferIndex)
screen(srcIdx, src => {
val fromCol = args.optInteger(6, 1)
val fromRow = args.optInteger(7, 1)
var budgetCost: Double = determineBitbltBudgetCost(dst, src)
val energyCost: Double = determineBitbltEnergyCost(dst)
val tierCredit: Double = ((tier + 1) * .5)
val overBudget: Double = budgetCost - tierCredit
if (overBudget > 0) {
if (budgetExhausted) { // we've thrown once before
if (overBudget > tierCredit) { // we need even more pause than just a single tierCredit
val pauseNeeded = overBudget - tierCredit
val seconds: Double = (pauseNeeded / tierCredit) / 20
context.pause(seconds)
}
budgetCost = 0 // remove the rest of the budget cost at this point
} else {
budgetExhausted = true
throw new LimitReachedException()
}
}
budgetExhausted = false
if (resolveInvokeCosts(dstIdx, context, budgetCost, w * h, energyCost)) {
if (dstIdx == srcIdx) {
val tx = col - fromCol
val ty = row - fromRow
dst.copy(fromCol - 1, fromRow - 1, w, h, tx, ty)
result(true)
} else {
// at least one of the two buffers is a gpu buffer
component.GpuTextBuffer.bitblt(dst, col, row, w, h, src, fromRow, fromCol)
result(true)
}
} else result(Unit, "not enough energy")
})
})
}
@Callback(doc = """function(address:string[, reset:boolean=true]):boolean -- Binds the GPU to the screen with the specified address and resets screen settings if `reset` is true.""")
def bind(context: Context, args: Arguments): Array[AnyRef] = {
val address = args.checkString(0)
val reset = args.optBoolean(1, true)
node.network.node(address) match {
case null => result(Unit, "invalid address")
case node: Node if node.host.isInstanceOf[api.internal.TextBuffer] =>
screenAddress = Option(address)
screenInstance = Some(node.host.asInstanceOf[api.internal.TextBuffer])
screen(s => {
if (reset) {
val (gmw, gmh) = maxResolution
val smw = s.getMaximumWidth
val smh = s.getMaximumHeight
s.setResolution(math.min(gmw, smw), math.min(gmh, smh))
s.setColorDepth(api.internal.TextBuffer.ColorDepth.values.apply(math.min(maxDepth.ordinal, s.getMaximumColorDepth.ordinal)))
s.setForegroundColor(0xFFFFFF)
s.setBackgroundColor(0x000000)
s match {
case oc: component.traits.VideoRamRasterizer => oc.removeAllBuffers()
case _ =>
}
}
else context.pause(0) // To discourage outputting "in realtime" to multiple screens using one GPU.
result(true)
})
case _ => result(Unit, "not a screen")
}
}
@Callback(direct = true, doc = """function():string -- Get the address of the screen the GPU is currently bound to.""")
def getScreen(context: Context, args: Arguments): Array[AnyRef] = screen(RESERVED_SCREEN_INDEX, s => result(s.node.address))
@Callback(direct = true, doc = """function():number, boolean -- Get the current background color and whether it's from the palette or not.""")
def getBackground(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(s.getBackgroundColor, s.isBackgroundFromPalette))
@Callback(direct = true, doc = """function(value:number[, palette:boolean]):number, number or nil -- Sets the background color to the specified value. Optionally takes an explicit palette index. Returns the old value and if it was from the palette its palette index.""")
def setBackground(context: Context, args: Arguments): Array[AnyRef] = {
val color = args.checkInteger(0)
if (bufferIndex == RESERVED_SCREEN_INDEX) {
context.consumeCallBudget(setBackgroundCosts(tier))
}
screen(s => {
val oldValue = s.getBackgroundColor
val (oldColor, oldIndex) =
if (s.isBackgroundFromPalette) {
(s.getPaletteColor(oldValue), oldValue)
}
else {
(oldValue, Unit)
}
s.setBackgroundColor(color, args.optBoolean(1, false))
result(oldColor, oldIndex)
})
}
@Callback(direct = true, doc = """function():number, boolean -- Get the current foreground color and whether it's from the palette or not.""")
def getForeground(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(s.getForegroundColor, s.isForegroundFromPalette))
@Callback(direct = true, doc = """function(value:number[, palette:boolean]):number, number or nil -- Sets the foreground color to the specified value. Optionally takes an explicit palette index. Returns the old value and if it was from the palette its palette index.""")
def setForeground(context: Context, args: Arguments): Array[AnyRef] = {
val color = args.checkInteger(0)
if (bufferIndex == RESERVED_SCREEN_INDEX) {
context.consumeCallBudget(setForegroundCosts(tier))
}
screen(s => {
val oldValue = s.getForegroundColor
val (oldColor, oldIndex) =
if (s.isForegroundFromPalette) {
(s.getPaletteColor(oldValue), oldValue)
}
else {
(oldValue, Unit)
}
s.setForegroundColor(color, args.optBoolean(1, false))
result(oldColor, oldIndex)
})
}
@Callback(direct = true, doc = """function(index:number):number -- Get the palette color at the specified palette index.""")
def getPaletteColor(context: Context, args: Arguments): Array[AnyRef] = {
val index = args.checkInteger(0)
screen(s => try result(s.getPaletteColor(index)) catch {
case _: ArrayIndexOutOfBoundsException => throw new IllegalArgumentException("invalid palette index")
})
}
@Callback(direct = true, doc = """function(index:number, color:number):number -- Set the palette color at the specified palette index. Returns the previous value.""")
def setPaletteColor(context: Context, args: Arguments): Array[AnyRef] = {
val index = args.checkInteger(0)
val color = args.checkInteger(1)
if (bufferIndex == RESERVED_SCREEN_INDEX) {
context.consumeCallBudget(setPaletteColorCosts(tier))
context.pause(0.1)
}
screen(s => try {
val oldColor = s.getPaletteColor(index)
s.setPaletteColor(index, color)
result(oldColor)
}
catch {
case _: ArrayIndexOutOfBoundsException => throw new IllegalArgumentException("invalid palette index")
})
}
@Callback(direct = true, doc = """function():number -- Returns the currently set color depth.""")
def getDepth(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(PackedColor.Depth.bits(s.getColorDepth)))
@Callback(doc = """function(depth:number):number -- Set the color depth. Returns the previous value.""")
def setDepth(context: Context, args: Arguments): Array[AnyRef] = {
val depth = args.checkInteger(0)
screen(s => {
val oldDepth = s.getColorDepth
depth match {
case 1 => s.setColorDepth(api.internal.TextBuffer.ColorDepth.OneBit)
case 4 if maxDepth.ordinal >= api.internal.TextBuffer.ColorDepth.FourBit.ordinal => s.setColorDepth(api.internal.TextBuffer.ColorDepth.FourBit)
case 8 if maxDepth.ordinal >= api.internal.TextBuffer.ColorDepth.EightBit.ordinal => s.setColorDepth(api.internal.TextBuffer.ColorDepth.EightBit)
case _ => throw new IllegalArgumentException("unsupported depth")
}
result(oldDepth)
})
}
@Callback(direct = true, doc = """function():number -- Get the maximum supported color depth.""")
def maxDepth(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(PackedColor.Depth.bits(api.internal.TextBuffer.ColorDepth.values.apply(math.min(maxDepth.ordinal, s.getMaximumColorDepth.ordinal)))))
@Callback(direct = true, doc = """function():number, number -- Get the current screen resolution.""")
def getResolution(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(s.getWidth, s.getHeight))
@Callback(doc = """function(width:number, height:number):boolean -- Set the screen resolution. Returns true if the resolution changed.""")
def setResolution(context: Context, args: Arguments): Array[AnyRef] = {
val w = args.checkInteger(0)
val h = args.checkInteger(1)
val (mw, mh) = maxResolution
// Even though the buffer itself checks this again, we need this here for
// the minimum of screen and GPU resolution.
if (w < 1 || h < 1 || w > mw || h > mw || h * w > mw * mh)
throw new IllegalArgumentException("unsupported resolution")
screen(s => result(s.setResolution(w, h)))
}
@Callback(direct = true, doc = """function():number, number -- Get the maximum screen resolution.""")
def maxResolution(context: Context, args: Arguments): Array[AnyRef] =
screen(s => {
val (gmw, gmh) = maxResolution
val smw = s.getMaximumWidth
val smh = s.getMaximumHeight
result(math.min(gmw, smw), math.min(gmh, smh))
})
@Callback(direct = true, doc = """function():number, number -- Get the current viewport resolution.""")
def getViewport(context: Context, args: Arguments): Array[AnyRef] =
screen(s => result(s.getViewportWidth, s.getViewportHeight))
@Callback(doc = """function(width:number, height:number):boolean -- Set the viewport resolution. Cannot exceed the screen resolution. Returns true if the resolution changed.""")
def setViewport(context: Context, args: Arguments): Array[AnyRef] = {
val w = args.checkInteger(0)
val h = args.checkInteger(1)
val (mw, mh) = maxResolution
// Even though the buffer itself checks this again, we need this here for
// the minimum of screen and GPU resolution.
if (w < 1 || h < 1 || w > mw || h > mw || h * w > mw * mh)
throw new IllegalArgumentException("unsupported viewport size")
screen(s => {
if (w > s.getWidth || h > s.getHeight)
throw new IllegalArgumentException("unsupported viewport size")
result(s.setViewport(w, h))
})
}
@Callback(direct = true, doc = """function(x:number, y:number):string, number, number, number or nil, number or nil -- Get the value displayed on the screen at the specified index, as well as the foreground and background color. If the foreground or background is from the palette, returns the palette indices as fourth and fifth results, else nil, respectively.""")
def get(context: Context, args: Arguments): Array[AnyRef] = {
// maybe one day:
// if (bufferIndex != RESERVED_SCREEN_INDEX && args.count() == 0) {
// return screen {
// case ram: GpuTextBuffer => {
// val nbt = new NBTTagCompound
// ram.data.save(nbt)
// result(nbt)
// }
// }
// }
val x = args.checkInteger(0) - 1
val y = args.checkInteger(1) - 1
screen(s => {
val fgValue = s.getForegroundColor(x, y)
val (fgColor, fgIndex) =
if (s.isForegroundFromPalette(x, y)) {
(s.getPaletteColor(fgValue), fgValue)
}
else {
(fgValue, Unit)
}
val bgValue = s.getBackgroundColor(x, y)
val (bgColor, bgIndex) =
if (s.isBackgroundFromPalette(x, y)) {
(s.getPaletteColor(bgValue), bgValue)
}
else {
(bgValue, Unit)
}
result(s.get(x, y), fgColor, bgColor, fgIndex, bgIndex)
})
}
@Callback(direct = true, doc = """function(x:number, y:number, value:string[, vertical:boolean]):boolean -- Plots a string value to the screen at the specified position. Optionally writes the string vertically.""")
def set(context: Context, args: Arguments): Array[AnyRef] = {
val x = args.checkInteger(0) - 1
val y = args.checkInteger(1) - 1
val value = args.checkString(2)
val vertical = args.optBoolean(3, false)
screen(s => {
if (resolveInvokeCosts(bufferIndex, context, setCosts(tier), value.length, Settings.get.gpuSetCost)) {
s.set(x, y, value, vertical)
result(true)
} else result(Unit, "not enough energy")
})
}
@Callback(direct = true, doc = """function(x:number, y:number, width:number, height:number, tx:number, ty:number):boolean -- Copies a portion of the screen from the specified location with the specified size by the specified translation.""")
def copy(context: Context, args: Arguments): Array[AnyRef] = {
val x = args.checkInteger(0) - 1
val y = args.checkInteger(1) - 1
val w = math.max(0, args.checkInteger(2))
val h = math.max(0, args.checkInteger(3))
val tx = args.checkInteger(4)
val ty = args.checkInteger(5)
screen(s => {
if (resolveInvokeCosts(bufferIndex, context, copyCosts(tier), w * h, Settings.get.gpuCopyCost)) {
s.copy(x, y, w, h, tx, ty)
result(true)
}
else result(Unit, "not enough energy")
})
}
@Callback(direct = true, doc = """function(x:number, y:number, width:number, height:number, char:string):boolean -- Fills a portion of the screen at the specified position with the specified size with the specified character.""")
def fill(context: Context, args: Arguments): Array[AnyRef] = {
val x = args.checkInteger(0) - 1
val y = args.checkInteger(1) - 1
val w = math.max(0, args.checkInteger(2))
val h = math.max(0, args.checkInteger(3))
val value = args.checkString(4)
if (value.length == 1) screen(s => {
val c = value.charAt(0)
val cost = if (c == ' ') Settings.get.gpuClearCost else Settings.get.gpuFillCost
if (resolveInvokeCosts(bufferIndex, context, fillCosts(tier), w * h, cost)) {
s.fill(x, y, w, h, value.charAt(0))
result(true)
}
else {
result(Unit, "not enough energy")
}
})
else throw new Exception("invalid fill value")
}
private def consumePower(n: Double, cost: Double) = node.tryChangeBuffer(-n * cost)
// ----------------------------------------------------------------------- //
override def onMessage(message: Message) {
super.onMessage(message)
if (node.isNeighborOf(message.source)) {
if (message.name == "computer.stopped" || message.name == "computer.started") {
bufferIndex = RESERVED_SCREEN_INDEX
removeAllBuffers()
}
}
if (message.name == "computer.stopped" && node.isNeighborOf(message.source)) {
screen(s => {
val (gmw, gmh) = maxResolution
val smw = s.getMaximumWidth
val smh = s.getMaximumHeight
s.setResolution(math.min(gmw, smw), math.min(gmh, smh))
s.setColorDepth(api.internal.TextBuffer.ColorDepth.values.apply(math.min(maxDepth.ordinal, s.getMaximumColorDepth.ordinal)))
s.setForegroundColor(0xFFFFFF)
val w = s.getWidth
val h = s.getHeight
message.source.host match {
case machine: li.cil.oc.server.machine.Machine if machine.lastError != null =>
if (s.getColorDepth.ordinal > api.internal.TextBuffer.ColorDepth.OneBit.ordinal) s.setBackgroundColor(0x0000FF)
else s.setBackgroundColor(0x000000)
s.fill(0, 0, w, h, ' ')
try {
val wrapRegEx = s"(.{1,${math.max(1, w - 2)}})\\s".r
val lines = wrapRegEx.replaceAllIn(Localization.localizeImmediately(machine.lastError).replace("\t", " ") + "\n", m => Regex.quoteReplacement(m.group(1) + "\n")).lines.toArray
val firstRow = ((h - lines.length) / 2) max 2
val message = "Unrecoverable Error"
s.set((w - message.length) / 2, firstRow - 2, message, false)
val maxLineLength = lines.map(_.length).max
val col = ((w - maxLineLength) / 2) max 0
for ((line, idx) <- lines.zipWithIndex) {
val row = firstRow + idx
s.set(col, row, line, false)
}
}
catch {
case t: Throwable => t.printStackTrace()
}
case _ =>
s.setBackgroundColor(0x000000)
s.fill(0, 0, w, h, ' ')
}
null // For screen()
})
}
}
override def onConnect(node: Node): Unit = {
super.onConnect(node)
if (screenInstance.isEmpty && screenAddress.fold(false)(_ == node.address)) {
node.host match {
case buffer: api.internal.TextBuffer =>
screenInstance = Some(buffer)
case _ => // Not the screen node we're looking for.
}
}
}
override def onDisconnect(node: Node) {
super.onDisconnect(node)
if (node == this.node || screenAddress.contains(node.address)) {
screenAddress = None
screenInstance = None
}
}
// ----------------------------------------------------------------------- //
private val SCREEN_KEY: String = "screen"
private val BUFFER_INDEX_KEY: String = "bufferIndex"
private val VIDEO_RAM_KEY: String = "videoRam"
private final val NBT_PAGES: String = "pages"
private final val NBT_PAGE_IDX: String = "page_idx"
private final val NBT_PAGE_DATA: String = "page_data"
private val COMPOUND_ID = (new NBTTagCompound).getId
override def load(nbt: NBTTagCompound) {
super.load(nbt)
if (nbt.hasKey(SCREEN_KEY)) {
nbt.getString(SCREEN_KEY) match {
case screen: String if !screen.isEmpty => screenAddress = Some(screen)
case _ => screenAddress = None
}
screenInstance = None
}
if (nbt.hasKey(BUFFER_INDEX_KEY)) {
bufferIndex = nbt.getInteger(BUFFER_INDEX_KEY)
}
removeAllBuffers() // JUST in case
if (nbt.hasKey(VIDEO_RAM_KEY)) {
val videoRamNbt = nbt.getCompoundTag(VIDEO_RAM_KEY)
val nbtPages = videoRamNbt.getTagList(NBT_PAGES, COMPOUND_ID)
for (i <- 0 until nbtPages.tagCount) {
val nbtPage = nbtPages.getCompoundTagAt(i)
val idx: Int = nbtPage.getInteger(NBT_PAGE_IDX)
val data = nbtPage.getCompoundTag(NBT_PAGE_DATA)
loadBuffer(node.address, idx, data)
}
}
}
override def save(nbt: NBTTagCompound) {
super.save(nbt)
if (screenAddress.isDefined) {
nbt.setString(SCREEN_KEY, screenAddress.get)
}
nbt.setInteger(BUFFER_INDEX_KEY, bufferIndex)
val videoRamNbt = new NBTTagCompound
val nbtPages = new NBTTagList
val indexes = bufferIndexes()
for (idx: Int <- indexes) {
getBuffer(idx) match {
case Some(page) => {
val nbtPage = new NBTTagCompound
nbtPage.setInteger(NBT_PAGE_IDX, idx)
val data = new NBTTagCompound
page.data.save(data)
nbtPage.setTag(NBT_PAGE_DATA, data)
nbtPages.appendTag(nbtPage)
}
case _ => // ignore
}
}
videoRamNbt.setTag(NBT_PAGES, nbtPages)
nbt.setTag(VIDEO_RAM_KEY, videoRamNbt)
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/common/component/GpuTextBuffer.scala | <reponame>kmecpp/OpenComputers
package li.cil.oc.common.component
import java.io.InvalidObjectException
import java.security.InvalidParameterException
import li.cil.oc.api.network.{Environment, Message, Node}
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.nbt.NBTTagCompound
import li.cil.oc.api.internal.TextBuffer.ColorDepth
import li.cil.oc.api
import li.cil.oc.common.component.traits.{TextBufferProxy, VideoRamDevice, VideoRamRasterizer}
class GpuTextBuffer(val owner: String, val id: Int, val data: li.cil.oc.util.TextBuffer) extends traits.TextBufferProxy {
// the gpu ram does not join nor is searchable to the network
// this field is required because the api TextBuffer is an Environment
override def node(): Node = {
throw new InvalidObjectException("GpuTextBuffers do not have nodes")
}
override def getMaximumWidth: Int = data.width
override def getMaximumHeight: Int = data.height
override def getViewportWidth: Int = data.height
override def getViewportHeight: Int = data.width
var dirty: Boolean = true
override def onBufferSet(col: Int, row: Int, s: String, vertical: Boolean): Unit = dirty = true
override def onBufferColorChange(): Unit = dirty = true
override def onBufferCopy(col: Int, row: Int, w: Int, h: Int, tx: Int, ty: Int): Unit = dirty = true
override def onBufferFill(col: Int, row: Int, w: Int, h: Int, c: Char): Unit = dirty = true
override def load(nbt: NBTTagCompound): Unit = {
// the data is initially dirty because other devices don't know about it yet
data.load(nbt)
dirty = true
}
override def save(nbt: NBTTagCompound): Unit = {
data.save(nbt)
dirty = false
}
override def setEnergyCostPerTick(value: Double): Unit = {}
override def getEnergyCostPerTick: Double = 0
override def setPowerState(value: Boolean): Unit = {}
override def getPowerState: Boolean = false
override def setMaximumResolution(width: Int, height: Int): Unit = {}
override def setAspectRatio(width: Double, height: Double): Unit = {}
override def getAspectRatio: Double = 1
override def setResolution(width: Int, height: Int): Boolean = false
override def setViewport(width: Int, height: Int): Boolean = false
override def setMaximumColorDepth(depth: ColorDepth): Unit = {}
override def getMaximumColorDepth: ColorDepth = data.format.depth
override def renderText: Boolean = false
override def renderWidth: Int = 0
override def renderHeight: Int = 0
override def setRenderingEnabled(enabled: Boolean): Unit = {}
override def isRenderingEnabled: Boolean = false
override def keyDown(character: Char, code: Int, player: EntityPlayer): Unit = {}
override def keyUp(character: Char, code: Int, player: EntityPlayer): Unit = {}
override def clipboard(value: String, player: EntityPlayer): Unit = {}
override def mouseDown(x: Double, y: Double, button: Int, player: EntityPlayer): Unit = {}
override def mouseDrag(x: Double, y: Double, button: Int, player: EntityPlayer): Unit = {}
override def mouseUp(x: Double, y: Double, button: Int, player: EntityPlayer): Unit = {}
override def mouseScroll(x: Double, y: Double, delta: Int, player: EntityPlayer): Unit = {}
override def canUpdate: Boolean = false
override def update(): Unit = {}
override def onConnect(node: Node): Unit = {}
override def onDisconnect(node: Node): Unit = {}
override def onMessage(message: Message): Unit = {}
}
object ClientGpuTextBufferHandler {
def bitblt(dst: api.internal.TextBuffer, col: Int, row: Int, w: Int, h: Int, owner: String, srcId: Int, fromCol: Int, fromRow: Int): Unit = {
dst match {
case videoDevice: VideoRamRasterizer => videoDevice.getBuffer(owner, srcId) match {
case Some(buffer: GpuTextBuffer) => {
GpuTextBuffer.bitblt(dst, col, row, w, h, buffer, fromCol, fromRow)
}
case _ => // ignore - got a bitblt for a missing buffer
}
case _ => // ignore - weird packet handler called this, should only happen for video ram aware devices
}
}
def removeBuffer(buffer: api.internal.TextBuffer, owner: String, id: Int): Boolean = {
buffer match {
case screen: VideoRamRasterizer => screen.removeBuffer(owner, id)
case _ => false // ignore, not compatible with bitblts
}
}
def loadBuffer(buffer: api.internal.TextBuffer, owner: String, id: Int, nbt: NBTTagCompound): Boolean = {
buffer match {
case screen: VideoRamRasterizer => screen.loadBuffer(owner, id, nbt)
case _ => false // ignore, not compatible with bitblts
}
}
}
object GpuTextBuffer {
def wrap(owner: String, id: Int, data: li.cil.oc.util.TextBuffer): GpuTextBuffer = new GpuTextBuffer(owner, id, data)
def bitblt(dst: api.internal.TextBuffer, col: Int, row: Int, w: Int, h: Int, src: api.internal.TextBuffer, fromCol: Int, fromRow: Int): Unit = {
val x = col - 1
val y = row - 1
val fx = fromCol - 1
val fy = fromRow - 1
var adjustedDstX = x
var adjustedDstY = y
var adjustedWidth = w
var adjustedHeight = h
var adjustedSourceX = fx
var adjustedSourceY = fy
if (x < 0) {
adjustedWidth += x
adjustedSourceX -= x
adjustedDstX = 0
}
if (y < 0) {
adjustedHeight += y
adjustedSourceY -= y
adjustedDstY = 0
}
if (adjustedSourceX < 0) {
adjustedWidth += adjustedSourceX
adjustedDstX -= adjustedSourceX
adjustedSourceX = 0
}
if (adjustedSourceY < 0) {
adjustedHeight += adjustedSourceY
adjustedDstY -= adjustedSourceY
adjustedSourceY = 0
}
adjustedWidth -= ((adjustedDstX + adjustedWidth) - dst.getWidth) max 0
adjustedWidth -= ((adjustedSourceX + adjustedWidth) - src.getWidth) max 0
adjustedHeight -= ((adjustedDstY + adjustedHeight) - dst.getHeight) max 0
adjustedHeight -= ((adjustedSourceY + adjustedHeight) - src.getHeight) max 0
// anything left?
if (adjustedWidth <= 0 || adjustedHeight <= 0) {
return
}
dst match {
case dstScreen: TextBuffer => src match {
case srcGpu: GpuTextBuffer => write_vram_to_screen(dstScreen, adjustedDstX, adjustedDstY, adjustedWidth, adjustedHeight, srcGpu, adjustedSourceX, adjustedSourceY)
case _ => throw new UnsupportedOperationException("Source buffer does not support bitblt operations to a screen")
}
case dstGpu: GpuTextBuffer => src match {
case srcProxy: TextBufferProxy => write_to_vram(dstGpu, adjustedDstX, adjustedDstY, adjustedWidth, adjustedHeight, srcProxy, adjustedSourceX, adjustedSourceY)
case _ => throw new UnsupportedOperationException("Source buffer does not support bitblt operations")
}
case _ => throw new UnsupportedOperationException("Destination buffer does not support bitblt operations")
}
}
def write_vram_to_screen(dstScreen: TextBuffer, x: Int, y: Int, w: Int, h: Int, srcRam: GpuTextBuffer, fx: Int, fy: Int): Boolean = {
if (dstScreen.data.rawcopy(x + 1, y + 1, w, h, srcRam.data, fx + 1, fy + 1)) {
// rawcopy returns true only if data was modified
dstScreen.addBuffer(srcRam)
dstScreen.onBufferBitBlt(x + 1, y + 1, w, h, srcRam, fx + 1, fy + 1)
true
} else false
}
def write_to_vram(dstRam: GpuTextBuffer, x: Int, y: Int, w: Int, h: Int, src: TextBufferProxy, fx: Int, fy: Int): Boolean = {
dstRam.data.rawcopy(x + 1, y + 1, w, h, src.data, fx + 1, fy + 1)
}
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/integration/gregtech/ConverterDataStick.scala | package li.cil.oc.integration.gregtech
import java.util
import li.cil.oc.api.driver.Converter
import net.minecraft.item.ItemStack
import net.minecraft.nbt.{NBTTagCompound, NBTTagList, NBTTagString}
import li.cil.oc.util.ExtendedNBT._
import net.minecraftforge.common.util.Constants.NBT
import scala.collection.convert.WrapAsScala._
class ConverterDataStick extends Converter {
override def convert(value: Any, output: util.Map[AnyRef, AnyRef]): Unit = if (value.isInstanceOf[ItemStack]) {
val stack = value.asInstanceOf[ItemStack]
val nbt = stack.stackTagCompound
if (nbt.hasKey("prospection_tier"))
nbt.getString("title") match {
case "Raw Prospection Data" => getRawProspectionData(output, nbt)
case "Analyzed Prospection Data" => {
getRawProspectionData(output, nbt)
output += "Analyzed Prospection Data" ->
nbt.getTagList("pages", NBT.TAG_STRING)
.toArray[NBTTagString].map( (tag: NBTTagString) => tag.func_150285_a_().split('\n'))
}
case _ =>
}
}
def getRawProspectionData(output: util.Map[AnyRef, AnyRef], nbt: NBTTagCompound) =
output += "Raw Prospection Data" -> Map(
"prospection_tier" -> nbt.getByte("prospection_tier"),
"prospection_pos" -> nbt.getString("prospection_pos"),
"prospection_ores" -> nbt.getString("prospection_ores").split('|'),
"prospection_oils" -> nbt.getString("prospection_oils").split('|'),
"prospection_oils_pos" -> nbt.getString("prospection_oils_pos"),
"prospection_radius" -> Integer.parseInt(nbt.getString("prospection_radius"))
)
}
|
kmecpp/OpenComputers | src/main/scala/li/cil/oc/integration/opencomputers/DriverFileSystem.scala | <gh_stars>1000+
package li.cil.oc.integration.opencomputers
import li.cil.oc
import li.cil.oc.Constants
import li.cil.oc.OpenComputers
import li.cil.oc.Settings
import li.cil.oc.api
import li.cil.oc.api.network.EnvironmentHost
import li.cil.oc.common.Loot
import li.cil.oc.common.Slot
import li.cil.oc.common.item.Delegator
import li.cil.oc.common.item.FloppyDisk
import li.cil.oc.common.item.HardDiskDrive
import li.cil.oc.common.item.data.DriveData
import li.cil.oc.server.component.Drive
import li.cil.oc.server.fs.FileSystem.{ItemLabel, ReadOnlyLabel}
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
object DriverFileSystem extends Item {
val UUIDVerifier = """^([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$""".r
override def worksWith(stack: ItemStack) = isOneOf(stack,
api.Items.get(Constants.ItemName.HDDTier1),
api.Items.get(Constants.ItemName.HDDTier2),
api.Items.get(Constants.ItemName.HDDTier3),
api.Items.get(Constants.ItemName.Floppy))
override def createEnvironment(stack: ItemStack, host: EnvironmentHost) =
if (host.world != null && host.world.isRemote) null
else Delegator.subItem(stack) match {
case Some(hdd: HardDiskDrive) => createEnvironment(stack, hdd.kiloBytes * 1024, hdd.platterCount, host, hdd.tier + 2)
case Some(disk: FloppyDisk) => createEnvironment(stack, Settings.get.floppySize * 1024, 1, host, 1)
case _ => null
}
override def slot(stack: ItemStack) =
Delegator.subItem(stack) match {
case Some(hdd: HardDiskDrive) => Slot.HDD
case Some(disk: FloppyDisk) => Slot.Floppy
case _ => throw new IllegalArgumentException()
}
override def tier(stack: ItemStack) =
Delegator.subItem(stack) match {
case Some(hdd: HardDiskDrive) => hdd.tier
case _ => 0
}
private def createEnvironment(stack: ItemStack, capacity: Int, platterCount: Int, host: EnvironmentHost, speed: Int) = {
if (stack.hasTagCompound && stack.getTagCompound.hasKey(Settings.namespace + "lootFactory")) {
// Loot disk, create file system using factory callback.
Loot.factories.get(stack.getTagCompound.getString(Settings.namespace + "lootFactory")) match {
case Some(factory) =>
val label =
if (dataTag(stack).hasKey(Settings.namespace + "fs.label"))
dataTag(stack).getString(Settings.namespace + "fs.label")
else null
api.FileSystem.asManagedEnvironment(factory.call(), label, host, Settings.resourceDomain + ":floppy_access")
case _ => null // Invalid loot disk.
}
}
else {
// We have a bit of a chicken-egg problem here, because we want to use the
// node's address as the folder name... so we generate the address here,
// if necessary. No one will know, right? Right!?
val address = addressFromTag(dataTag(stack))
var label: api.fs.Label = new ReadWriteItemLabel(stack)
val isFloppy = api.Items.get(stack) == api.Items.get(Constants.ItemName.Floppy)
val sound = Settings.resourceDomain + ":" + (if (isFloppy) "floppy_access" else "hdd_access")
val drive = new DriveData(stack)
val environment = if (drive.isUnmanaged) {
new Drive(capacity max 0, platterCount, label, Option(host), Option(sound), speed, drive.isLocked)
}
else {
var fs = oc.api.FileSystem.fromSaveDirectory(address, capacity max 0, Settings.get.bufferChanges)
if (drive.isLocked) {
fs = oc.api.FileSystem.asReadOnly(fs)
label = new ReadOnlyLabel(label.getLabel)
}
oc.api.FileSystem.asManagedEnvironment(fs, label, host, sound, speed)
}
if (environment != null && environment.node != null) {
environment.node.asInstanceOf[oc.server.network.Node].address = address
}
environment
}
}
private def addressFromTag(tag: NBTTagCompound) =
if (tag.hasKey("node") && tag.getCompoundTag("node").hasKey("address")) {
tag.getCompoundTag("node").getString("address") match {
case UUIDVerifier(address) => address
case _ => // Invalid disk address.
val newAddress = java.util.UUID.randomUUID().toString
tag.getCompoundTag("node").setString("address", newAddress)
OpenComputers.log.warn(s"Generated new address for disk '${newAddress}'.")
newAddress
}
}
else java.util.UUID.randomUUID().toString
private class ReadWriteItemLabel(stack: ItemStack) extends ItemLabel(stack) {
var label: Option[String] = None
override def getLabel = label.orNull
override def setLabel(value: String) {
label = Option(value).map(_.take(16))
}
override def load(nbt: NBTTagCompound) {
if (nbt.hasKey(Settings.namespace + "fs.label")) {
label = Option(nbt.getString(Settings.namespace + "fs.label"))
}
}
override def save(nbt: NBTTagCompound) {
label match {
case Some(value) => nbt.setString(Settings.namespace + "fs.label", value)
case _ =>
}
}
}
} |
kmecpp/OpenComputers | src/main/scala/li/cil/oc/server/component/UpgradeBarcodeReader.scala | package li.cil.oc.server.component
import java.util
import li.cil.oc.{Constants, OpenComputers, api}
import li.cil.oc.api.driver.DeviceInfo
import li.cil.oc.api.driver.DeviceInfo.DeviceAttribute
import li.cil.oc.api.driver.DeviceInfo.DeviceClass
import li.cil.oc.api.internal
import li.cil.oc.api.network._
import li.cil.oc.api.prefab
import li.cil.oc.util.BlockPosition
import li.cil.oc.util.ExtendedWorld._
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.nbt.NBTTagList
import net.minecraft.util.EnumFacing
import net.minecraft.world.WorldServer
import net.minecraftforge.common.util.ForgeDirection
import scala.collection.convert.WrapAsJava._
class UpgradeBarcodeReader(val host: EnvironmentHost) extends prefab.ManagedEnvironment with DeviceInfo {
override val node = api.Network.newNode(this, Visibility.Network).
withComponent("barcode_reader").
withConnector().
create()
private final lazy val deviceInfo = Map(
DeviceAttribute.Class -> DeviceClass.Generic,
DeviceAttribute.Description -> "Barcode reader upgrade",
DeviceAttribute.Vendor -> Constants.DeviceInfo.DefaultVendor,
DeviceAttribute.Product -> "Readerizer Deluxe"
)
override def getDeviceInfo: util.Map[String, String] = deviceInfo
override def onMessage(message: Message): Unit = {
super.onMessage(message)
if (message.name == "tablet.use") message.source.host match {
case machine: api.machine.Machine => (machine.host, message.data) match {
case (tablet: internal.Tablet, Array(nbt: NBTTagCompound, stack: ItemStack, player: EntityPlayer, blockPos: BlockPosition, side: ForgeDirection, hitX: java.lang.Float, hitY: java.lang.Float, hitZ: java.lang.Float)) =>
host.world.getTileEntity(blockPos) match {
case analyzable: Analyzable =>
processNodes(analyzable.onAnalyze(player, side.ordinal(), hitX.toFloat, hitY.toFloat, hitZ.toFloat), nbt)
case host: SidedEnvironment =>
processNodes(Array(host.sidedNode(side)), nbt)
case host: Environment =>
processNodes(Array(host.node), nbt)
case _ => // Ignore
}
case _ => // Ignore
}
case _ => // Ignore
}
}
private def processNodes(nodes: Array[Node], nbt: NBTTagCompound): Unit = if (nodes != null) {
val readerNBT = new NBTTagList()
for (node <- nodes if node != null) {
val nodeNBT = new NBTTagCompound()
node match {
case component: Component =>
nodeNBT.setString("type", component.name)
case _ =>
}
val address = node.address()
if (address != null && !address.isEmpty) {
nodeNBT.setString("address", node.address())
}
readerNBT.appendTag(nodeNBT)
}
nbt.setTag("analyzed", readerNBT)
}
}
|
sullivan-/six-ways | listBuilder.scala | object listBuilder extends App {
// 1: direct translation from Java to Scala:
import scala.collection.mutable
def seqFromRangeVersion1: Seq[Int] = {
val result = mutable.ArrayBuffer[Int]()
(0 until 100).foreach { i =>
result += i * i
}
result
}
// 2: getting rid of mutable collection:
def seqFromRangeVersion2: Seq[Int] = {
var result = Vector[Int]()
(0 until 100).foreach { i =>
result = result :+ i * i
}
result
}
// 3: removing local var using recursion:
import scala.annotation.tailrec
def seqFromRangeVersion3: Seq[Int] = {
@tailrec
def recurse(range: Range, accumulator: Seq[Int]): Seq[Int] = {
if (range.isEmpty) {
accumulator
} else {
val i = range.head
recurse(range.tail, accumulator :+ i * i)
}
}
recurse(0 until 100, Vector())
}
// 4: removing local var using foldLeft:
def seqFromRangeVersion4: Seq[Int] = {
(0 until 100).foldLeft(Vector[Int]()) {
(accumulator, i) => accumulator :+ i * i
}
}
// 5: shorthand version of foldLeft:
def seqFromRangeVersion5: Seq[Int] = {
(Vector[Int]() /: (0 until 100)) {
(accumulator, i) => accumulator :+ i * i
}
}
// 6: using map:
def seqFromRangeVersion6: Seq[Int] = (0 until 100) map { i => i * i }
// -----
// println(s"version 1: $seqFromRangeVersion1")
// println(s"version 2: $seqFromRangeVersion2")
// println(s"version 3: $seqFromRangeVersion3")
// println(s"version 4: $seqFromRangeVersion4")
// println(s"version 5: $seqFromRangeVersion5")
// println(s"version 6: $seqFromRangeVersion6")
assert(seqFromRangeVersion1 == seqFromRangeVersion2)
assert(seqFromRangeVersion1 == seqFromRangeVersion3)
assert(seqFromRangeVersion1 == seqFromRangeVersion4)
assert(seqFromRangeVersion1 == seqFromRangeVersion5)
assert(seqFromRangeVersion1 == seqFromRangeVersion6)
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Smooth.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Smooth extends StObject {
/**
* The style of visual guide line in emphasis status.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.emphasis
*/
var emphasis: js.UndefOr[Show] = js.native
/**
* The length of the first segment of visual guide line.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.length
*/
var length: js.UndefOr[Double] = js.native
/**
* The length of the second segment of visual guide line.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.length2
*/
var length2: js.UndefOr[Double] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
/**
* Whether to show the visual guide ine.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.show
*/
var show: js.UndefOr[Boolean] = js.native
/**
* Whether to smooth the visual guide line.
* It defaults to be `false` and can be set as `true` or
* the values from 0 to 1 which indicating the smoothness.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.data.labelLine.smooth
*/
var smooth: js.UndefOr[Boolean | Double] = js.native
}
object Smooth {
@scala.inline
def apply(): Smooth = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Smooth]
}
@scala.inline
implicit class SmoothMutableBuilder[Self <: Smooth] (val x: Self) extends AnyVal {
@scala.inline
def setEmphasis(value: Show): Self = StObject.set(x, "emphasis", value.asInstanceOf[js.Any])
@scala.inline
def setEmphasisUndefined: Self = StObject.set(x, "emphasis", js.undefined)
@scala.inline
def setLength(value: Double): Self = StObject.set(x, "length", value.asInstanceOf[js.Any])
@scala.inline
def setLength2(value: Double): Self = StObject.set(x, "length2", value.asInstanceOf[js.Any])
@scala.inline
def setLength2Undefined: Self = StObject.set(x, "length2", js.undefined)
@scala.inline
def setLengthUndefined: Self = StObject.set(x, "length", js.undefined)
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setSmooth(value: Boolean | Double): Self = StObject.set(x, "smooth", value.asInstanceOf[js.Any])
@scala.inline
def setSmoothUndefined: Self = StObject.set(x, "smooth", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/DictunknownPropertyBorderColor.scala | <gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StringDictionary
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait DictunknownPropertyBorderColor
extends /**
* Some properties like "normal" or "emphasis" are not documented.
* Please, write description for them
*/
/* unknownProperty */ StringDictionary[js.Any] {
/**
* border color, whose format is similar to that of `color`.
*
*
* @default
* "#000"
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.borderColor
*/
var borderColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Border type, which can be `'solid'`, `'dashed'`, or `'dotted'`.
* `'solid'` by default.
*
*
* @default
* "solid"
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.borderType
*/
var borderType: js.UndefOr[String] = js.native
/**
* border width. No border when it is set to be 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.borderWidth
*/
var borderWidth: js.UndefOr[Double] = js.native
/**
* color. Color is taken from
* [option.color Palette](https://echarts.apache.org/en/option.html#color)
* by default.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for example
* `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example `'#ccc'`.
* Gradient color and texture are also supported besides single
* colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-pie.pie.itemStyle)
*
* Supports callback functions, in the form of:
*
* ```
* (params: Object) => Color
*
* ```
*
* Input parameters are `seriesIndex`, `dataIndex`, `data`,
* `value`, and etc. of data item.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color | js.Function] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will not be
* drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pie.pie.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.itemStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object DictunknownPropertyBorderColor {
@scala.inline
def apply(): DictunknownPropertyBorderColor = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[DictunknownPropertyBorderColor]
}
@scala.inline
implicit class DictunknownPropertyBorderColorMutableBuilder[Self <: DictunknownPropertyBorderColor] (val x: Self) extends AnyVal {
@scala.inline
def setBorderColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderType(value: String): Self = StObject.set(x, "borderType", value.asInstanceOf[js.Any])
@scala.inline
def setBorderTypeUndefined: Self = StObject.set(x, "borderType", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color | js.Function): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Origin.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Origin extends StObject {
/**
* Fill color.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for example
* `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example `'#ccc'`.
* Gradient color and texture are also supported besides single
* colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-line.line.areaStyle)
*
*
* @default
* "#000"
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will not be
* drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Origin position of area.
*
* By default, the area between axis line and data will be the
* area to be filled.
* This config enables you to fill data to the max or min of
* the axis data.
*
* Valid values include: `'auto'` (default), `'start'`, `'end'`.
*
* + `'auto'` to fill between axis line to data;
* + `'start'` to fill between min axis value (when not `inverse`)
* to data;
* + `'end'` to fill between max axis value (when not `inverse`)
* to data;
*
*
* @default
* "auto"
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.origin
*/
var origin: js.UndefOr[String] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-line.line.areaStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-line.areaStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object Origin {
@scala.inline
def apply(): Origin = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Origin]
}
@scala.inline
implicit class OriginMutableBuilder[Self <: Origin] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setOrigin(value: String): Self = StObject.set(x, "origin", value.asInstanceOf[js.Any])
@scala.inline
def setOriginUndefined: Self = StObject.set(x, "origin", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/BarBorderWidth.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BarBorderWidth extends StObject {
/**
* The bodrder color of bar.
*
*
* @default
* '#000'
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.barBorderColor
*/
var barBorderColor: js.UndefOr[String] = js.native
/**
* The bodrder width of bar.
* defaults to have no border.
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.barBorderWidth
*/
var barBorderWidth: js.UndefOr[Double] = js.native
/**
* Bar color..
*
*
* @default
* "auto"
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.color
*/
var color: js.UndefOr[String] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will
* not be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-radar.radar.data.emphasis.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.shadowColor
*/
var shadowColor: js.UndefOr[String] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-radar.data.emphasis.itemStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object BarBorderWidth {
@scala.inline
def apply(): BarBorderWidth = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[BarBorderWidth]
}
@scala.inline
implicit class BarBorderWidthMutableBuilder[Self <: BarBorderWidth] (val x: Self) extends AnyVal {
@scala.inline
def setBarBorderColor(value: String): Self = StObject.set(x, "barBorderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBarBorderColorUndefined: Self = StObject.set(x, "barBorderColor", js.undefined)
@scala.inline
def setBarBorderWidth(value: Double): Self = StObject.set(x, "barBorderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBarBorderWidthUndefined: Self = StObject.set(x, "barBorderWidth", js.undefined)
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: String): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/BrushType.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BrushType extends StObject {
/**
* The brush type for ripples.
* options: `'stroke'` and `'fill'`.
*
*
* @default
* "fill"
* @see https://echarts.apache.org/en/option.html#series-effectScatter.rippleEffect.brushType
*/
var brushType: js.UndefOr[String] = js.native
/**
* The period duration of animation, in seconds.
*
*
* @default
* 4
* @see https://echarts.apache.org/en/option.html#series-effectScatter.rippleEffect.period
*/
var period: js.UndefOr[Double] = js.native
/**
* The maximum zooming scale of ripples in animation.
*
*
* @default
* 2.5
* @see https://echarts.apache.org/en/option.html#series-effectScatter.rippleEffect.scale
*/
var scale: js.UndefOr[Double] = js.native
}
object BrushType {
@scala.inline
def apply(): BrushType = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[BrushType]
}
@scala.inline
implicit class BrushTypeMutableBuilder[Self <: BrushType] (val x: Self) extends AnyVal {
@scala.inline
def setBrushType(value: String): Self = StObject.set(x, "brushType", value.asInstanceOf[js.Any])
@scala.inline
def setBrushTypeUndefined: Self = StObject.set(x, "brushType", js.undefined)
@scala.inline
def setPeriod(value: Double): Self = StObject.set(x, "period", value.asInstanceOf[js.Any])
@scala.inline
def setPeriodUndefined: Self = StObject.set(x, "period", js.undefined)
@scala.inline
def setScale(value: Double): Self = StObject.set(x, "scale", value.asInstanceOf[js.Any])
@scala.inline
def setScaleUndefined: Self = StObject.set(x, "scale", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/AreaColor.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/AreaColor.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait AreaColor extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.areaColor
*/
var areaColor: js.UndefOr[String] = js.native
/**
* border color, whose format is similar to that of
* `color`.
*
*
* @default
* "#000"
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.borderColor
*/
var borderColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Border type, which can be `'solid'`, `'dashed'`,
* or `'dotted'`. `'solid'` by default.
*
*
* @default
* "solid"
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.borderType
*/
var borderType: js.UndefOr[String] = js.native
/**
* border width. No border when it is set to be 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.borderWidth
*/
var borderWidth: js.UndefOr[Double] = js.native
/**
* color.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-map.map.data.emphasis.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will
* not be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.data.emphasis.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.data.emphasis.itemStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object AreaColor {
@scala.inline
def apply(): AreaColor = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[AreaColor]
}
@scala.inline
implicit class AreaColorMutableBuilder[Self <: AreaColor] (val x: Self) extends AnyVal {
@scala.inline
def setAreaColor(value: String): Self = StObject.set(x, "areaColor", value.asInstanceOf[js.Any])
@scala.inline
def setAreaColorUndefined: Self = StObject.set(x, "areaColor", js.undefined)
@scala.inline
def setBorderColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderType(value: String): Self = StObject.set(x, "borderType", value.asInstanceOf[js.Any])
@scala.inline
def setBorderTypeUndefined: Self = StObject.set(x, "borderType", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Width.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Width extends StObject {
/**
* The axis line of gauge chart can be divided to several
* segments in different colors.
* The end position and color of each segment can be expressed
* by an array.
*
* Default value:
*
* ```
* [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']]
*
* ```
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.color
*/
var color: js.UndefOr[js.Array[_]] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will not
* be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-gauge.gauge.axisLine.lineStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.shadowColor
*/
var shadowColor: js.UndefOr[String] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
/**
* The width of axis line.
*
*
* @default
* 30
* @see https://echarts.apache.org/en/option.html#series-gauge.axisLine.lineStyle.width
*/
var width: js.UndefOr[Double] = js.native
}
object Width {
@scala.inline
def apply(): Width = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Width]
}
@scala.inline
implicit class WidthMutableBuilder[Self <: Width] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: js.Array[_]): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setColorVarargs(value: js.Any*): Self = StObject.set(x, "color", js.Array(value :_*))
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: String): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
@scala.inline
def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ExcludeComponents.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/ExcludeComponents.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ExcludeComponents extends StObject {
// Background color of exporting image, use backgroundColor in
// option by default.
var backgroundColor: String = js.native
// Excluded components list. e.g. ['toolbox']
var excludeComponents: js.UndefOr[js.Array[String]] = js.native
// Resolution ratio of exporting image, 1 by default.
var pixelRatio: Double = js.native
// Exporting format, can be either png, or jpeg
var `type`: String = js.native
}
object ExcludeComponents {
@scala.inline
def apply(backgroundColor: String, pixelRatio: Double, `type`: String): ExcludeComponents = {
val __obj = js.Dynamic.literal(backgroundColor = backgroundColor.asInstanceOf[js.Any], pixelRatio = pixelRatio.asInstanceOf[js.Any])
__obj.updateDynamic("type")(`type`.asInstanceOf[js.Any])
__obj.asInstanceOf[ExcludeComponents]
}
@scala.inline
implicit class ExcludeComponentsMutableBuilder[Self <: ExcludeComponents] (val x: Self) extends AnyVal {
@scala.inline
def setBackgroundColor(value: String): Self = StObject.set(x, "backgroundColor", value.asInstanceOf[js.Any])
@scala.inline
def setExcludeComponents(value: js.Array[String]): Self = StObject.set(x, "excludeComponents", value.asInstanceOf[js.Any])
@scala.inline
def setExcludeComponentsUndefined: Self = StObject.set(x, "excludeComponents", js.undefined)
@scala.inline
def setExcludeComponentsVarargs(value: String*): Self = StObject.set(x, "excludeComponents", js.Array(value :_*))
@scala.inline
def setPixelRatio(value: Double): Self = StObject.set(x, "pixelRatio", value.asInstanceOf[js.Any])
@scala.inline
def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/VisualMap.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/echarts/VisualMap.scala
package anduin.facades.echarts.echarts
import anduin.facades.echarts.anon.InRange
import anduin.facades.echarts.echarts.EChartOption.BaseTextStyleWithRich
import anduin.facades.echarts.echarts.EChartOption.TextStyle
import anduin.facades.echarts.echartsStrings.auto
import anduin.facades.echarts.echartsStrings.bottom
import anduin.facades.echarts.echartsStrings.continuous
import anduin.facades.echarts.echartsStrings.horizontal
import anduin.facades.echarts.echartsStrings.left
import anduin.facades.echarts.echartsStrings.multiple
import anduin.facades.echarts.echartsStrings.piecewise
import anduin.facades.echarts.echartsStrings.right
import anduin.facades.echarts.echartsStrings.single
import anduin.facades.echarts.echartsStrings.top
import anduin.facades.echarts.echartsStrings.vertical
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object VisualMap {
@js.native
trait Continuous
extends anduin.facades.echarts.echarts.EChartOption.VisualMap {
var align: js.UndefOr[auto | left | right | top | bottom] = js.native
var backgroundColor: js.UndefOr[String] = js.native
var borderColor: js.UndefOr[String] = js.native
var borderWidth: js.UndefOr[Double] = js.native
var bottom: js.UndefOr[Double | String] = js.native
var calculable: js.UndefOr[Boolean] = js.native
var color: js.UndefOr[js.Array[String]] = js.native
var controller: js.UndefOr[InRange] = js.native
var dimension: js.UndefOr[String | Double] = js.native
var formatter: js.UndefOr[String | js.Function] = js.native
var hoverLink: js.UndefOr[Boolean] = js.native
var id: js.UndefOr[String] = js.native
var inRange: js.UndefOr[RangeObject] = js.native
var inverse: js.UndefOr[Boolean] = js.native
var itemHeight: js.UndefOr[Double] = js.native
var itemWidth: js.UndefOr[Double] = js.native
var left: js.UndefOr[Double | String] = js.native
var max: js.UndefOr[Double] = js.native
var min: js.UndefOr[Double] = js.native
var orient: js.UndefOr[vertical | horizontal] = js.native
var outOfRange: js.UndefOr[RangeObject] = js.native
var padding: js.UndefOr[Double | js.Array[Double]] = js.native
var precision: js.UndefOr[Double] = js.native
var range: js.UndefOr[js.Array[Double]] = js.native
var realtime: js.UndefOr[Boolean] = js.native
var right: js.UndefOr[Double | String] = js.native
var seriesIndex: js.UndefOr[Double | js.Array[Double]] = js.native
var show: js.UndefOr[Boolean] = js.native
var text: js.UndefOr[js.Array[String]] = js.native
var textGap: js.UndefOr[Double] = js.native
var textStyle: js.UndefOr[BaseTextStyleWithRich] = js.native
var top: js.UndefOr[Double | String] = js.native
var `type`: js.UndefOr[continuous] = js.native
var z: js.UndefOr[Double] = js.native
var zlevel: js.UndefOr[Double] = js.native
}
object Continuous {
@scala.inline
def apply(): Continuous = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Continuous]
}
@scala.inline
implicit class ContinuousMutableBuilder[Self <: Continuous] (val x: Self) extends AnyVal {
@scala.inline
def setAlign(value: auto | left | right | top | bottom): Self = StObject.set(x, "align", value.asInstanceOf[js.Any])
@scala.inline
def setAlignUndefined: Self = StObject.set(x, "align", js.undefined)
@scala.inline
def setBackgroundColor(value: String): Self = StObject.set(x, "backgroundColor", value.asInstanceOf[js.Any])
@scala.inline
def setBackgroundColorUndefined: Self = StObject.set(x, "backgroundColor", js.undefined)
@scala.inline
def setBorderColor(value: String): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setBottom(value: Double | String): Self = StObject.set(x, "bottom", value.asInstanceOf[js.Any])
@scala.inline
def setBottomUndefined: Self = StObject.set(x, "bottom", js.undefined)
@scala.inline
def setCalculable(value: Boolean): Self = StObject.set(x, "calculable", value.asInstanceOf[js.Any])
@scala.inline
def setCalculableUndefined: Self = StObject.set(x, "calculable", js.undefined)
@scala.inline
def setColor(value: js.Array[String]): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setColorVarargs(value: String*): Self = StObject.set(x, "color", js.Array(value :_*))
@scala.inline
def setController(value: InRange): Self = StObject.set(x, "controller", value.asInstanceOf[js.Any])
@scala.inline
def setControllerUndefined: Self = StObject.set(x, "controller", js.undefined)
@scala.inline
def setDimension(value: String | Double): Self = StObject.set(x, "dimension", value.asInstanceOf[js.Any])
@scala.inline
def setDimensionUndefined: Self = StObject.set(x, "dimension", js.undefined)
@scala.inline
def setFormatter(value: String | js.Function): Self = StObject.set(x, "formatter", value.asInstanceOf[js.Any])
@scala.inline
def setFormatterUndefined: Self = StObject.set(x, "formatter", js.undefined)
@scala.inline
def setHoverLink(value: Boolean): Self = StObject.set(x, "hoverLink", value.asInstanceOf[js.Any])
@scala.inline
def setHoverLinkUndefined: Self = StObject.set(x, "hoverLink", js.undefined)
@scala.inline
def setId(value: String): Self = StObject.set(x, "id", value.asInstanceOf[js.Any])
@scala.inline
def setIdUndefined: Self = StObject.set(x, "id", js.undefined)
@scala.inline
def setInRange(value: RangeObject): Self = StObject.set(x, "inRange", value.asInstanceOf[js.Any])
@scala.inline
def setInRangeUndefined: Self = StObject.set(x, "inRange", js.undefined)
@scala.inline
def setInverse(value: Boolean): Self = StObject.set(x, "inverse", value.asInstanceOf[js.Any])
@scala.inline
def setInverseUndefined: Self = StObject.set(x, "inverse", js.undefined)
@scala.inline
def setItemHeight(value: Double): Self = StObject.set(x, "itemHeight", value.asInstanceOf[js.Any])
@scala.inline
def setItemHeightUndefined: Self = StObject.set(x, "itemHeight", js.undefined)
@scala.inline
def setItemWidth(value: Double): Self = StObject.set(x, "itemWidth", value.asInstanceOf[js.Any])
@scala.inline
def setItemWidthUndefined: Self = StObject.set(x, "itemWidth", js.undefined)
@scala.inline
def setLeft(value: Double | String): Self = StObject.set(x, "left", value.asInstanceOf[js.Any])
@scala.inline
def setLeftUndefined: Self = StObject.set(x, "left", js.undefined)
@scala.inline
def setMax(value: Double): Self = StObject.set(x, "max", value.asInstanceOf[js.Any])
@scala.inline
def setMaxUndefined: Self = StObject.set(x, "max", js.undefined)
@scala.inline
def setMin(value: Double): Self = StObject.set(x, "min", value.asInstanceOf[js.Any])
@scala.inline
def setMinUndefined: Self = StObject.set(x, "min", js.undefined)
@scala.inline
def setOrient(value: vertical | horizontal): Self = StObject.set(x, "orient", value.asInstanceOf[js.Any])
@scala.inline
def setOrientUndefined: Self = StObject.set(x, "orient", js.undefined)
@scala.inline
def setOutOfRange(value: RangeObject): Self = StObject.set(x, "outOfRange", value.asInstanceOf[js.Any])
@scala.inline
def setOutOfRangeUndefined: Self = StObject.set(x, "outOfRange", js.undefined)
@scala.inline
def setPadding(value: Double | js.Array[Double]): Self = StObject.set(x, "padding", value.asInstanceOf[js.Any])
@scala.inline
def setPaddingUndefined: Self = StObject.set(x, "padding", js.undefined)
@scala.inline
def setPaddingVarargs(value: Double*): Self = StObject.set(x, "padding", js.Array(value :_*))
@scala.inline
def setPrecision(value: Double): Self = StObject.set(x, "precision", value.asInstanceOf[js.Any])
@scala.inline
def setPrecisionUndefined: Self = StObject.set(x, "precision", js.undefined)
@scala.inline
def setRange(value: js.Array[Double]): Self = StObject.set(x, "range", value.asInstanceOf[js.Any])
@scala.inline
def setRangeUndefined: Self = StObject.set(x, "range", js.undefined)
@scala.inline
def setRangeVarargs(value: Double*): Self = StObject.set(x, "range", js.Array(value :_*))
@scala.inline
def setRealtime(value: Boolean): Self = StObject.set(x, "realtime", value.asInstanceOf[js.Any])
@scala.inline
def setRealtimeUndefined: Self = StObject.set(x, "realtime", js.undefined)
@scala.inline
def setRight(value: Double | String): Self = StObject.set(x, "right", value.asInstanceOf[js.Any])
@scala.inline
def setRightUndefined: Self = StObject.set(x, "right", js.undefined)
@scala.inline
def setSeriesIndex(value: Double | js.Array[Double]): Self = StObject.set(x, "seriesIndex", value.asInstanceOf[js.Any])
@scala.inline
def setSeriesIndexUndefined: Self = StObject.set(x, "seriesIndex", js.undefined)
@scala.inline
def setSeriesIndexVarargs(value: Double*): Self = StObject.set(x, "seriesIndex", js.Array(value :_*))
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setText(value: js.Array[String]): Self = StObject.set(x, "text", value.asInstanceOf[js.Any])
@scala.inline
def setTextGap(value: Double): Self = StObject.set(x, "textGap", value.asInstanceOf[js.Any])
@scala.inline
def setTextGapUndefined: Self = StObject.set(x, "textGap", js.undefined)
@scala.inline
def setTextStyle(value: BaseTextStyleWithRich): Self = StObject.set(x, "textStyle", value.asInstanceOf[js.Any])
@scala.inline
def setTextStyleUndefined: Self = StObject.set(x, "textStyle", js.undefined)
@scala.inline
def setTextUndefined: Self = StObject.set(x, "text", js.undefined)
@scala.inline
def setTextVarargs(value: String*): Self = StObject.set(x, "text", js.Array(value :_*))
@scala.inline
def setTop(value: Double | String): Self = StObject.set(x, "top", value.asInstanceOf[js.Any])
@scala.inline
def setTopUndefined: Self = StObject.set(x, "top", js.undefined)
@scala.inline
def setType(value: continuous): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setTypeUndefined: Self = StObject.set(x, "type", js.undefined)
@scala.inline
def setZ(value: Double): Self = StObject.set(x, "z", value.asInstanceOf[js.Any])
@scala.inline
def setZUndefined: Self = StObject.set(x, "z", js.undefined)
@scala.inline
def setZlevel(value: Double): Self = StObject.set(x, "zlevel", value.asInstanceOf[js.Any])
@scala.inline
def setZlevelUndefined: Self = StObject.set(x, "zlevel", js.undefined)
}
}
@js.native
trait PiecesObject extends StObject {
var color: js.UndefOr[String] = js.native
var label: js.UndefOr[String] = js.native
var max: js.UndefOr[Double] = js.native
var min: js.UndefOr[Double] = js.native
var value: js.UndefOr[Double] = js.native
}
object PiecesObject {
@scala.inline
def apply(): PiecesObject = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[PiecesObject]
}
@scala.inline
implicit class PiecesObjectMutableBuilder[Self <: PiecesObject] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setLabel(value: String): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setMax(value: Double): Self = StObject.set(x, "max", value.asInstanceOf[js.Any])
@scala.inline
def setMaxUndefined: Self = StObject.set(x, "max", js.undefined)
@scala.inline
def setMin(value: Double): Self = StObject.set(x, "min", value.asInstanceOf[js.Any])
@scala.inline
def setMinUndefined: Self = StObject.set(x, "min", js.undefined)
@scala.inline
def setValue(value: Double): Self = StObject.set(x, "value", value.asInstanceOf[js.Any])
@scala.inline
def setValueUndefined: Self = StObject.set(x, "value", js.undefined)
}
}
@js.native
trait Piecewise
extends anduin.facades.echarts.echarts.EChartOption.VisualMap {
var align: js.UndefOr[auto | left | right] = js.native
var backgroundColor: js.UndefOr[String] = js.native
var borderColor: js.UndefOr[String] = js.native
var borderWidth: js.UndefOr[Double] = js.native
var bottom: js.UndefOr[Double | String] = js.native
var categories: js.UndefOr[js.Array[String]] = js.native
var color: js.UndefOr[js.Array[String]] = js.native
var controller: js.UndefOr[InRange] = js.native
var dimension: js.UndefOr[String | Double] = js.native
var formatter: js.UndefOr[String | js.Function] = js.native
var hoverLink: js.UndefOr[Boolean] = js.native
var id: js.UndefOr[String] = js.native
var inRange: js.UndefOr[RangeObject] = js.native
var inverse: js.UndefOr[Boolean] = js.native
var itemGap: js.UndefOr[Double] = js.native
var itemHeight: js.UndefOr[Double] = js.native
var itemSymbol: js.UndefOr[String] = js.native
var itemWidth: js.UndefOr[Double] = js.native
var left: js.UndefOr[Double | String] = js.native
var max: js.UndefOr[Double] = js.native
var maxOpen: js.UndefOr[Boolean] = js.native
var min: js.UndefOr[Double] = js.native
var minOpen: js.UndefOr[Boolean] = js.native
var orient: js.UndefOr[vertical | horizontal] = js.native
var outOfRange: js.UndefOr[RangeObject] = js.native
var padding: js.UndefOr[Double | js.Array[Double]] = js.native
var pieces: js.UndefOr[js.Array[PiecesObject]] = js.native
var precision: js.UndefOr[Double] = js.native
var right: js.UndefOr[Double | String] = js.native
var selectedMode: js.UndefOr[multiple | single] = js.native
var seriesIndex: js.UndefOr[Double | js.Array[Double]] = js.native
var show: js.UndefOr[Boolean] = js.native
var showLabel: js.UndefOr[Boolean] = js.native
var splitNumber: js.UndefOr[Double] = js.native
var text: js.UndefOr[js.Array[String]] = js.native
var textGap: js.UndefOr[Double | js.Array[Double]] = js.native
var textStyle: js.UndefOr[TextStyle] = js.native
var top: js.UndefOr[Double | String] = js.native
var `type`: js.UndefOr[piecewise] = js.native
var z: js.UndefOr[Double] = js.native
var zlevel: js.UndefOr[Double] = js.native
}
object Piecewise {
@scala.inline
def apply(): Piecewise = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Piecewise]
}
@scala.inline
implicit class PiecewiseMutableBuilder[Self <: Piecewise] (val x: Self) extends AnyVal {
@scala.inline
def setAlign(value: auto | left | right): Self = StObject.set(x, "align", value.asInstanceOf[js.Any])
@scala.inline
def setAlignUndefined: Self = StObject.set(x, "align", js.undefined)
@scala.inline
def setBackgroundColor(value: String): Self = StObject.set(x, "backgroundColor", value.asInstanceOf[js.Any])
@scala.inline
def setBackgroundColorUndefined: Self = StObject.set(x, "backgroundColor", js.undefined)
@scala.inline
def setBorderColor(value: String): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setBottom(value: Double | String): Self = StObject.set(x, "bottom", value.asInstanceOf[js.Any])
@scala.inline
def setBottomUndefined: Self = StObject.set(x, "bottom", js.undefined)
@scala.inline
def setCategories(value: js.Array[String]): Self = StObject.set(x, "categories", value.asInstanceOf[js.Any])
@scala.inline
def setCategoriesUndefined: Self = StObject.set(x, "categories", js.undefined)
@scala.inline
def setCategoriesVarargs(value: String*): Self = StObject.set(x, "categories", js.Array(value :_*))
@scala.inline
def setColor(value: js.Array[String]): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setColorVarargs(value: String*): Self = StObject.set(x, "color", js.Array(value :_*))
@scala.inline
def setController(value: InRange): Self = StObject.set(x, "controller", value.asInstanceOf[js.Any])
@scala.inline
def setControllerUndefined: Self = StObject.set(x, "controller", js.undefined)
@scala.inline
def setDimension(value: String | Double): Self = StObject.set(x, "dimension", value.asInstanceOf[js.Any])
@scala.inline
def setDimensionUndefined: Self = StObject.set(x, "dimension", js.undefined)
@scala.inline
def setFormatter(value: String | js.Function): Self = StObject.set(x, "formatter", value.asInstanceOf[js.Any])
@scala.inline
def setFormatterUndefined: Self = StObject.set(x, "formatter", js.undefined)
@scala.inline
def setHoverLink(value: Boolean): Self = StObject.set(x, "hoverLink", value.asInstanceOf[js.Any])
@scala.inline
def setHoverLinkUndefined: Self = StObject.set(x, "hoverLink", js.undefined)
@scala.inline
def setId(value: String): Self = StObject.set(x, "id", value.asInstanceOf[js.Any])
@scala.inline
def setIdUndefined: Self = StObject.set(x, "id", js.undefined)
@scala.inline
def setInRange(value: RangeObject): Self = StObject.set(x, "inRange", value.asInstanceOf[js.Any])
@scala.inline
def setInRangeUndefined: Self = StObject.set(x, "inRange", js.undefined)
@scala.inline
def setInverse(value: Boolean): Self = StObject.set(x, "inverse", value.asInstanceOf[js.Any])
@scala.inline
def setInverseUndefined: Self = StObject.set(x, "inverse", js.undefined)
@scala.inline
def setItemGap(value: Double): Self = StObject.set(x, "itemGap", value.asInstanceOf[js.Any])
@scala.inline
def setItemGapUndefined: Self = StObject.set(x, "itemGap", js.undefined)
@scala.inline
def setItemHeight(value: Double): Self = StObject.set(x, "itemHeight", value.asInstanceOf[js.Any])
@scala.inline
def setItemHeightUndefined: Self = StObject.set(x, "itemHeight", js.undefined)
@scala.inline
def setItemSymbol(value: String): Self = StObject.set(x, "itemSymbol", value.asInstanceOf[js.Any])
@scala.inline
def setItemSymbolUndefined: Self = StObject.set(x, "itemSymbol", js.undefined)
@scala.inline
def setItemWidth(value: Double): Self = StObject.set(x, "itemWidth", value.asInstanceOf[js.Any])
@scala.inline
def setItemWidthUndefined: Self = StObject.set(x, "itemWidth", js.undefined)
@scala.inline
def setLeft(value: Double | String): Self = StObject.set(x, "left", value.asInstanceOf[js.Any])
@scala.inline
def setLeftUndefined: Self = StObject.set(x, "left", js.undefined)
@scala.inline
def setMax(value: Double): Self = StObject.set(x, "max", value.asInstanceOf[js.Any])
@scala.inline
def setMaxOpen(value: Boolean): Self = StObject.set(x, "maxOpen", value.asInstanceOf[js.Any])
@scala.inline
def setMaxOpenUndefined: Self = StObject.set(x, "maxOpen", js.undefined)
@scala.inline
def setMaxUndefined: Self = StObject.set(x, "max", js.undefined)
@scala.inline
def setMin(value: Double): Self = StObject.set(x, "min", value.asInstanceOf[js.Any])
@scala.inline
def setMinOpen(value: Boolean): Self = StObject.set(x, "minOpen", value.asInstanceOf[js.Any])
@scala.inline
def setMinOpenUndefined: Self = StObject.set(x, "minOpen", js.undefined)
@scala.inline
def setMinUndefined: Self = StObject.set(x, "min", js.undefined)
@scala.inline
def setOrient(value: vertical | horizontal): Self = StObject.set(x, "orient", value.asInstanceOf[js.Any])
@scala.inline
def setOrientUndefined: Self = StObject.set(x, "orient", js.undefined)
@scala.inline
def setOutOfRange(value: RangeObject): Self = StObject.set(x, "outOfRange", value.asInstanceOf[js.Any])
@scala.inline
def setOutOfRangeUndefined: Self = StObject.set(x, "outOfRange", js.undefined)
@scala.inline
def setPadding(value: Double | js.Array[Double]): Self = StObject.set(x, "padding", value.asInstanceOf[js.Any])
@scala.inline
def setPaddingUndefined: Self = StObject.set(x, "padding", js.undefined)
@scala.inline
def setPaddingVarargs(value: Double*): Self = StObject.set(x, "padding", js.Array(value :_*))
@scala.inline
def setPieces(value: js.Array[PiecesObject]): Self = StObject.set(x, "pieces", value.asInstanceOf[js.Any])
@scala.inline
def setPiecesUndefined: Self = StObject.set(x, "pieces", js.undefined)
@scala.inline
def setPiecesVarargs(value: PiecesObject*): Self = StObject.set(x, "pieces", js.Array(value :_*))
@scala.inline
def setPrecision(value: Double): Self = StObject.set(x, "precision", value.asInstanceOf[js.Any])
@scala.inline
def setPrecisionUndefined: Self = StObject.set(x, "precision", js.undefined)
@scala.inline
def setRight(value: Double | String): Self = StObject.set(x, "right", value.asInstanceOf[js.Any])
@scala.inline
def setRightUndefined: Self = StObject.set(x, "right", js.undefined)
@scala.inline
def setSelectedMode(value: multiple | single): Self = StObject.set(x, "selectedMode", value.asInstanceOf[js.Any])
@scala.inline
def setSelectedModeUndefined: Self = StObject.set(x, "selectedMode", js.undefined)
@scala.inline
def setSeriesIndex(value: Double | js.Array[Double]): Self = StObject.set(x, "seriesIndex", value.asInstanceOf[js.Any])
@scala.inline
def setSeriesIndexUndefined: Self = StObject.set(x, "seriesIndex", js.undefined)
@scala.inline
def setSeriesIndexVarargs(value: Double*): Self = StObject.set(x, "seriesIndex", js.Array(value :_*))
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowLabel(value: Boolean): Self = StObject.set(x, "showLabel", value.asInstanceOf[js.Any])
@scala.inline
def setShowLabelUndefined: Self = StObject.set(x, "showLabel", js.undefined)
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setSplitNumber(value: Double): Self = StObject.set(x, "splitNumber", value.asInstanceOf[js.Any])
@scala.inline
def setSplitNumberUndefined: Self = StObject.set(x, "splitNumber", js.undefined)
@scala.inline
def setText(value: js.Array[String]): Self = StObject.set(x, "text", value.asInstanceOf[js.Any])
@scala.inline
def setTextGap(value: Double | js.Array[Double]): Self = StObject.set(x, "textGap", value.asInstanceOf[js.Any])
@scala.inline
def setTextGapUndefined: Self = StObject.set(x, "textGap", js.undefined)
@scala.inline
def setTextGapVarargs(value: Double*): Self = StObject.set(x, "textGap", js.Array(value :_*))
@scala.inline
def setTextStyle(value: TextStyle): Self = StObject.set(x, "textStyle", value.asInstanceOf[js.Any])
@scala.inline
def setTextStyleUndefined: Self = StObject.set(x, "textStyle", js.undefined)
@scala.inline
def setTextUndefined: Self = StObject.set(x, "text", js.undefined)
@scala.inline
def setTextVarargs(value: String*): Self = StObject.set(x, "text", js.Array(value :_*))
@scala.inline
def setTop(value: Double | String): Self = StObject.set(x, "top", value.asInstanceOf[js.Any])
@scala.inline
def setTopUndefined: Self = StObject.set(x, "top", js.undefined)
@scala.inline
def setType(value: piecewise): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setTypeUndefined: Self = StObject.set(x, "type", js.undefined)
@scala.inline
def setZ(value: Double): Self = StObject.set(x, "z", value.asInstanceOf[js.Any])
@scala.inline
def setZUndefined: Self = StObject.set(x, "z", js.undefined)
@scala.inline
def setZlevel(value: Double): Self = StObject.set(x, "zlevel", value.asInstanceOf[js.Any])
@scala.inline
def setZlevelUndefined: Self = StObject.set(x, "zlevel", js.undefined)
}
}
@js.native
trait RangeObject extends StObject {
var color: js.UndefOr[String | js.Array[String]] = js.native
var colorAlpha: js.UndefOr[Double | js.Array[Double]] = js.native
var colorHue: js.UndefOr[Double | js.Array[Double]] = js.native
var colorLightness: js.UndefOr[Double | js.Array[Double]] = js.native
var colorSaturation: js.UndefOr[Double | js.Array[Double]] = js.native
var opacity: js.UndefOr[Double | js.Array[Double]] = js.native
var symbol: js.UndefOr[String | js.Array[String]] = js.native
var symbolSize: js.UndefOr[Double | js.Array[Double]] = js.native
}
object RangeObject {
@scala.inline
def apply(): RangeObject = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[RangeObject]
}
@scala.inline
implicit class RangeObjectMutableBuilder[Self <: RangeObject] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: String | js.Array[String]): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorAlpha(value: Double | js.Array[Double]): Self = StObject.set(x, "colorAlpha", value.asInstanceOf[js.Any])
@scala.inline
def setColorAlphaUndefined: Self = StObject.set(x, "colorAlpha", js.undefined)
@scala.inline
def setColorAlphaVarargs(value: Double*): Self = StObject.set(x, "colorAlpha", js.Array(value :_*))
@scala.inline
def setColorHue(value: Double | js.Array[Double]): Self = StObject.set(x, "colorHue", value.asInstanceOf[js.Any])
@scala.inline
def setColorHueUndefined: Self = StObject.set(x, "colorHue", js.undefined)
@scala.inline
def setColorHueVarargs(value: Double*): Self = StObject.set(x, "colorHue", js.Array(value :_*))
@scala.inline
def setColorLightness(value: Double | js.Array[Double]): Self = StObject.set(x, "colorLightness", value.asInstanceOf[js.Any])
@scala.inline
def setColorLightnessUndefined: Self = StObject.set(x, "colorLightness", js.undefined)
@scala.inline
def setColorLightnessVarargs(value: Double*): Self = StObject.set(x, "colorLightness", js.Array(value :_*))
@scala.inline
def setColorSaturation(value: Double | js.Array[Double]): Self = StObject.set(x, "colorSaturation", value.asInstanceOf[js.Any])
@scala.inline
def setColorSaturationUndefined: Self = StObject.set(x, "colorSaturation", js.undefined)
@scala.inline
def setColorSaturationVarargs(value: Double*): Self = StObject.set(x, "colorSaturation", js.Array(value :_*))
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setColorVarargs(value: String*): Self = StObject.set(x, "color", js.Array(value :_*))
@scala.inline
def setOpacity(value: Double | js.Array[Double]): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setOpacityVarargs(value: Double*): Self = StObject.set(x, "opacity", js.Array(value :_*))
@scala.inline
def setSymbol(value: String | js.Array[String]): Self = StObject.set(x, "symbol", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolSize(value: Double | js.Array[Double]): Self = StObject.set(x, "symbolSize", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolSizeUndefined: Self = StObject.set(x, "symbolSize", js.undefined)
@scala.inline
def setSymbolSizeVarargs(value: Double*): Self = StObject.set(x, "symbolSize", js.Array(value :_*))
@scala.inline
def setSymbolUndefined: Self = StObject.set(x, "symbol", js.undefined)
@scala.inline
def setSymbolVarargs(value: String*): Self = StObject.set(x, "symbol", js.Array(value :_*))
}
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/EChartsResizeOption.scala | package anduin.facades.echarts.echarts
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait EChartsResizeOption extends StObject {
/**
* Chart height.
*/
var height: js.UndefOr[Double | String] = js.native
/**
* Specify whether or not to prevent triggering events.
*/
var silent: js.UndefOr[Boolean] = js.native
/**
* Chart width.
*/
var width: js.UndefOr[Double | String] = js.native
}
object EChartsResizeOption {
@scala.inline
def apply(): EChartsResizeOption = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[EChartsResizeOption]
}
@scala.inline
implicit class EChartsResizeOptionMutableBuilder[Self <: EChartsResizeOption] (val x: Self) extends AnyVal {
@scala.inline
def setHeight(value: Double | String): Self = StObject.set(x, "height", value.asInstanceOf[js.Any])
@scala.inline
def setHeightUndefined: Self = StObject.set(x, "height", js.undefined)
@scala.inline
def setSilent(value: Boolean): Self = StObject.set(x, "silent", value.asInstanceOf[js.Any])
@scala.inline
def setSilentUndefined: Self = StObject.set(x, "silent", js.undefined)
@scala.inline
def setWidth(value: Double | String): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/LabelLineStyle.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait LabelLineStyle extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-graph.links.emphasis.label
*/
var label: js.UndefOr[FontSize] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-graph.links.emphasis.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
}
object LabelLineStyle {
@scala.inline
def apply(): LabelLineStyle = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[LabelLineStyle]
}
@scala.inline
implicit class LabelLineStyleMutableBuilder[Self <: LabelLineStyle] (val x: Self) extends AnyVal {
@scala.inline
def setLabel(value: FontSize): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ShadowBlur.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ShadowBlur extends StObject {
/**
* Line color.
*
* > Color can be represented in RGB, for example `'rgb(128,
* 128, 128)'`.
* RGBA can be used when you need alpha channel, for
* example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported besides
* single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-scatter.scatter.markLine.lineStyle.emphasis)
*
*
* @default
* "#000"
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component will
* not be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-scatter.scatter.markLine.lineStyle.emphasis)
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
/**
* line type.
*
* Options are:
*
* + `'solid'`
* + `'dashed'`
* + `'dotted'`
*
*
* @default
* "solid"
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.type
*/
var `type`: js.UndefOr[String] = js.native
/**
* line width.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markLine.lineStyle.emphasis.width
*/
var width: js.UndefOr[Double] = js.native
}
object ShadowBlur {
@scala.inline
def apply(): ShadowBlur = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ShadowBlur]
}
@scala.inline
implicit class ShadowBlurMutableBuilder[Self <: ShadowBlur] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
@scala.inline
def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setTypeUndefined: Self = StObject.set(x, "type", js.undefined)
@scala.inline
def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/RotateLabel.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait RotateLabel extends StObject {
/**
* Whether to rotate the label automatically.
*
*
* @see https://echarts.apache.org/en/option.html#series-graph.circular.rotateLabel
*/
var rotateLabel: js.UndefOr[Boolean] = js.native
}
object RotateLabel {
@scala.inline
def apply(): RotateLabel = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[RotateLabel]
}
@scala.inline
implicit class RotateLabelMutableBuilder[Self <: RotateLabel] (val x: Self) extends AnyVal {
@scala.inline
def setRotateLabel(value: Boolean): Self = StObject.set(x, "rotateLabel", value.asInstanceOf[js.Any])
@scala.inline
def setRotateLabelUndefined: Self = StObject.set(x, "rotateLabel", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Height.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/Height.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Height extends StObject {
/**
* Color filled in this element.
*
*
* @default
* '#000'
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.fill
*/
var fill: js.UndefOr[String] = js.native
/**
* The height of the shape of the element.
*
* More attributes in `style` (for example,
* [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text)
* ), see the `style` related attributes in
* [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable)
* .
*
* Notice, the attribute names of the `style` of graphic
* elements is derived from `zrender`, which may be
* different from the attribute names in `echarts label`,
* `echarts itemStyle`, etc.,
* although they have the same meaning. For example:
*
* + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color)
* => `style.fill`
* + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color)
* => `style.stroke`
* + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color)
* => `style.textFill`
* + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor)
* => `style.textStroke`
* + ...
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.height
*/
var height: js.UndefOr[Double] = js.native
/**
* Specify contant of the image, can be a URL, or
* [dataURI](https://tools.ietf.org/html/rfc2397)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.image
*/
var image: js.UndefOr[String] = js.native
/**
* Width of stroke.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.lineWidth
*/
var lineWidth: js.UndefOr[Double] = js.native
/**
* Width of shadow.
*
*
* @default
* "undefined"
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* color of shadow.
*
*
* @default
* "undefined"
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowColor
*/
var shadowColor: js.UndefOr[Double] = js.native
/**
* X offset of shadow.
*
*
* @default
* "undefined"
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Y offset of shadow.
*
*
* @default
* "undefined"
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
/**
* Color of stroke.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.stroke
*/
var stroke: js.UndefOr[String] = js.native
/**
* The width of the shape of the element.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.width
*/
var width: js.UndefOr[Double] = js.native
/**
* The x value of the left-top corner of the element
* in the coordinate system of its parent.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.x
*/
var x: js.UndefOr[Double] = js.native
/**
* The y value of the left-top corner of the element
* in the coordinate system of its parent.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.y
*/
var y: js.UndefOr[Double] = js.native
}
object Height {
@scala.inline
def apply(): Height = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Height]
}
@scala.inline
implicit class HeightMutableBuilder[Self <: Height] (val x: Self) extends AnyVal {
@scala.inline
def setFill(value: String): Self = StObject.set(x, "fill", value.asInstanceOf[js.Any])
@scala.inline
def setFillUndefined: Self = StObject.set(x, "fill", js.undefined)
@scala.inline
def setHeight(value: Double): Self = StObject.set(x, "height", value.asInstanceOf[js.Any])
@scala.inline
def setHeightUndefined: Self = StObject.set(x, "height", js.undefined)
@scala.inline
def setImage(value: String): Self = StObject.set(x, "image", value.asInstanceOf[js.Any])
@scala.inline
def setImageUndefined: Self = StObject.set(x, "image", js.undefined)
@scala.inline
def setLineWidth(value: Double): Self = StObject.set(x, "lineWidth", value.asInstanceOf[js.Any])
@scala.inline
def setLineWidthUndefined: Self = StObject.set(x, "lineWidth", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: Double): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
@scala.inline
def setStroke(value: String): Self = StObject.set(x, "stroke", value.asInstanceOf[js.Any])
@scala.inline
def setStrokeUndefined: Self = StObject.set(x, "stroke", js.undefined)
@scala.inline
def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
@scala.inline
def setX(value: Double): Self = StObject.set(x, "x", value.asInstanceOf[js.Any])
@scala.inline
def setXUndefined: Self = StObject.set(x, "x", js.undefined)
@scala.inline
def setY(value: Double): Self = StObject.set(x, "y", value.asInstanceOf[js.Any])
@scala.inline
def setYUndefined: Self = StObject.set(x, "y", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/8.scala | <gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait `8` extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-tree.leaves.emphasis.itemStyle
*/
var itemStyle: js.UndefOr[BorderType] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-tree.leaves.emphasis.label
*/
var label: js.UndefOr[BorderRadius] = js.native
}
object `8` {
@scala.inline
def apply(): `8` = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[`8`]
}
@scala.inline
implicit class `8MutableBuilder`[Self <: `8`] (val x: Self) extends AnyVal {
@scala.inline
def setItemStyle(value: BorderType): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: BorderRadius): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/EChartsMediaOption.scala | package anduin.facades.echarts.echarts
import anduin.facades.echarts.anon.AspectRatio
import anduin.facades.echarts.echarts.EChartOption.Series
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait EChartsMediaOption extends StObject {
var option: EChartOption[Series] = js.native
var query: AspectRatio = js.native
}
object EChartsMediaOption {
@scala.inline
def apply(option: EChartOption[Series], query: AspectRatio): EChartsMediaOption = {
val __obj = js.Dynamic.literal(option = option.asInstanceOf[js.Any], query = query.asInstanceOf[js.Any])
__obj.asInstanceOf[EChartsMediaOption]
}
@scala.inline
implicit class EChartsMediaOptionMutableBuilder[Self <: EChartsMediaOption] (val x: Self) extends AnyVal {
@scala.inline
def setOption(value: EChartOption[Series]): Self = StObject.set(x, "option", value.asInstanceOf[js.Any])
@scala.inline
def setQuery(value: AspectRatio): Self = StObject.set(x, "query", value.asInstanceOf[js.Any])
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/EChartsSeriesType.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.echarts
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/* Rewritten from type alias, can be one of:
- `anduin.facades`.echarts.echartsStrings.line
- `anduin.facades`.echarts.echartsStrings.bar
- `anduin.facades`.echarts.echartsStrings.pie
- `anduin.facades`.echarts.echartsStrings.scatter
- `anduin.facades`.echarts.echartsStrings.effectScatter
- `anduin.facades`.echarts.echartsStrings.radar
- `anduin.facades`.echarts.echartsStrings.tree
- `anduin.facades`.echarts.echartsStrings.treemap
- `anduin.facades`.echarts.echartsStrings.sunburst
- `anduin.facades`.echarts.echartsStrings.boxplot
- `anduin.facades`.echarts.echartsStrings.candlestick
- `anduin.facades`.echarts.echartsStrings.heatmap
- `anduin.facades`.echarts.echartsStrings.map
- `anduin.facades`.echarts.echartsStrings.parallel
- `anduin.facades`.echarts.echartsStrings.lines
- `anduin.facades`.echarts.echartsStrings.graph
- `anduin.facades`.echarts.echartsStrings.sankey
- `anduin.facades`.echarts.echartsStrings.funnel
- `anduin.facades`.echarts.echartsStrings.gauge
- `anduin.facades`.echarts.echartsStrings.pictorialBar
- `anduin.facades`.echarts.echartsStrings.themeRiver
- `anduin.facades`.echarts.echartsStrings.custom
*/
trait EChartsSeriesType extends StObject
object EChartsSeriesType {
@scala.inline
def bar: anduin.facades.echarts.echartsStrings.bar = "bar".asInstanceOf[anduin.facades.echarts.echartsStrings.bar]
@scala.inline
def boxplot: anduin.facades.echarts.echartsStrings.boxplot = "boxplot".asInstanceOf[anduin.facades.echarts.echartsStrings.boxplot]
@scala.inline
def candlestick: anduin.facades.echarts.echartsStrings.candlestick = "candlestick".asInstanceOf[anduin.facades.echarts.echartsStrings.candlestick]
@scala.inline
def custom: anduin.facades.echarts.echartsStrings.custom = "custom".asInstanceOf[anduin.facades.echarts.echartsStrings.custom]
@scala.inline
def effectScatter: anduin.facades.echarts.echartsStrings.effectScatter = "effectScatter".asInstanceOf[anduin.facades.echarts.echartsStrings.effectScatter]
@scala.inline
def funnel: anduin.facades.echarts.echartsStrings.funnel = "funnel".asInstanceOf[anduin.facades.echarts.echartsStrings.funnel]
@scala.inline
def gauge: anduin.facades.echarts.echartsStrings.gauge = "gauge".asInstanceOf[anduin.facades.echarts.echartsStrings.gauge]
@scala.inline
def graph: anduin.facades.echarts.echartsStrings.graph = "graph".asInstanceOf[anduin.facades.echarts.echartsStrings.graph]
@scala.inline
def heatmap: anduin.facades.echarts.echartsStrings.heatmap = "heatmap".asInstanceOf[anduin.facades.echarts.echartsStrings.heatmap]
@scala.inline
def line: anduin.facades.echarts.echartsStrings.line = "line".asInstanceOf[anduin.facades.echarts.echartsStrings.line]
@scala.inline
def lines: anduin.facades.echarts.echartsStrings.lines = "lines".asInstanceOf[anduin.facades.echarts.echartsStrings.lines]
@scala.inline
def map: anduin.facades.echarts.echartsStrings.map = "map".asInstanceOf[anduin.facades.echarts.echartsStrings.map]
@scala.inline
def parallel: anduin.facades.echarts.echartsStrings.parallel = "parallel".asInstanceOf[anduin.facades.echarts.echartsStrings.parallel]
@scala.inline
def pictorialBar: anduin.facades.echarts.echartsStrings.pictorialBar = "pictorialBar".asInstanceOf[anduin.facades.echarts.echartsStrings.pictorialBar]
@scala.inline
def pie: anduin.facades.echarts.echartsStrings.pie = "pie".asInstanceOf[anduin.facades.echarts.echartsStrings.pie]
@scala.inline
def radar: anduin.facades.echarts.echartsStrings.radar = "radar".asInstanceOf[anduin.facades.echarts.echartsStrings.radar]
@scala.inline
def sankey: anduin.facades.echarts.echartsStrings.sankey = "sankey".asInstanceOf[anduin.facades.echarts.echartsStrings.sankey]
@scala.inline
def scatter: anduin.facades.echarts.echartsStrings.scatter = "scatter".asInstanceOf[anduin.facades.echarts.echartsStrings.scatter]
@scala.inline
def sunburst: anduin.facades.echarts.echartsStrings.sunburst = "sunburst".asInstanceOf[anduin.facades.echarts.echartsStrings.sunburst]
@scala.inline
def themeRiver: anduin.facades.echarts.echartsStrings.themeRiver = "themeRiver".asInstanceOf[anduin.facades.echarts.echartsStrings.themeRiver]
@scala.inline
def tree: anduin.facades.echarts.echartsStrings.tree = "tree".asInstanceOf[anduin.facades.echarts.echartsStrings.tree]
@scala.inline
def treemap: anduin.facades.echarts.echartsStrings.treemap = "treemap".asInstanceOf[anduin.facades.echarts.echartsStrings.treemap]
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Points.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Points extends StObject {
/**
* A list of points, which defines the shape, like `[[22,
* 44], [44, 55], [11, 44], ...]`.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.points
*/
var points: js.UndefOr[js.Array[_]] = js.native
/**
* Whether smooth the line.
*
* + If the value is number, bezier interpolation is
* used, and the value specified the level of smooth,
* which is in the range of `[0, 1]`.
* + If the value is `'spline'`, Catmull-Rom spline
* interpolation is used.
*
*
* @default
* "undefined"
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.smooth
*/
var smooth: js.UndefOr[Double | String] = js.native
/**
* Whether prevent the smooth process cause the line
* out of the bounding box.
*
* Only works when `smooth` is `number` (bezier smooth).
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.smoothConstraint
*/
var smoothConstraint: js.UndefOr[Boolean] = js.native
}
object Points {
@scala.inline
def apply(): Points = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Points]
}
@scala.inline
implicit class PointsMutableBuilder[Self <: Points] (val x: Self) extends AnyVal {
@scala.inline
def setPoints(value: js.Array[_]): Self = StObject.set(x, "points", value.asInstanceOf[js.Any])
@scala.inline
def setPointsUndefined: Self = StObject.set(x, "points", js.undefined)
@scala.inline
def setPointsVarargs(value: js.Any*): Self = StObject.set(x, "points", js.Array(value :_*))
@scala.inline
def setSmooth(value: Double | String): Self = StObject.set(x, "smooth", value.asInstanceOf[js.Any])
@scala.inline
def setSmoothConstraint(value: Boolean): Self = StObject.set(x, "smoothConstraint", value.asInstanceOf[js.Any])
@scala.inline
def setSmoothConstraintUndefined: Self = StObject.set(x, "smoothConstraint", js.undefined)
@scala.inline
def setSmoothUndefined: Self = StObject.set(x, "smooth", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Children.scala | <reponame>ngbinh/scalablyTypedDemo<gh_stars>0
package anduin.facades.echarts.anon
import anduin.facades.echarts.echarts.EChartOption.BaseTooltip
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Children extends StObject {
/**
* child nodes, recursive definition, configurations are the
* same as
* [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.silent.children
*/
var children: js.UndefOr[js.Array[_]] = js.native
/**
* Enable hyperlink jump when clicking on node.
* It is avaliable when
* [series-treemap.nodeClick](https://echarts.apache.org/en/option.html#series-treemap.nodeClick)
* is `'link'`.
*
* See
* [series-treemap.data.target](https://echarts.apache.org/en/option.html#series-treemap.data.target)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.silent.link
*/
var link: js.UndefOr[String] = js.native
/**
* The same meaning as `target` in `html` `<a>` label, See
* [series-treemap.data.link](https://echarts.apache.org/en/option.html#series-treemap.data.link)
* . Option values are: `'blank'` or `'self'`.
*
*
* @default
* "blank"
* @see https://echarts.apache.org/en/option.html#series-treemap.silent.target
*/
var target: js.UndefOr[String] = js.native
/**
* tooltip settings in this series data.
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.silent.tooltip
*/
var tooltip: js.UndefOr[BaseTooltip] = js.native
}
object Children {
@scala.inline
def apply(): Children = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Children]
}
@scala.inline
implicit class ChildrenMutableBuilder[Self <: Children] (val x: Self) extends AnyVal {
@scala.inline
def setChildren(value: js.Array[_]): Self = StObject.set(x, "children", value.asInstanceOf[js.Any])
@scala.inline
def setChildrenUndefined: Self = StObject.set(x, "children", js.undefined)
@scala.inline
def setChildrenVarargs(value: js.Any*): Self = StObject.set(x, "children", js.Array(value :_*))
@scala.inline
def setLink(value: String): Self = StObject.set(x, "link", value.asInstanceOf[js.Any])
@scala.inline
def setLinkUndefined: Self = StObject.set(x, "link", js.undefined)
@scala.inline
def setTarget(value: String): Self = StObject.set(x, "target", value.asInstanceOf[js.Any])
@scala.inline
def setTargetUndefined: Self = StObject.set(x, "target", js.undefined)
@scala.inline
def setTooltip(value: BaseTooltip): Self = StObject.set(x, "tooltip", value.asInstanceOf[js.Any])
@scala.inline
def setTooltipUndefined: Self = StObject.set(x, "tooltip", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ChildrenVisibleMin.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ChildrenVisibleMin extends StObject {
/**
* Children will not be shown when area size of a node is smaller
* than this value (unit: px square).
*
* This can hide the details of nodes when the rectangular area
* is not large enough.
* When users zoom nodes, the child node would show if the area
* is larger than this threshold.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `childrenVisibleMin` attribute could appear
* in more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.childrenVisibleMin
*/
var childrenVisibleMin: js.UndefOr[Double] = js.native
/**
* A color list for a level.
* Each node in the level will obtain a color from the color
* list (the rule see
* [colorMappingBy](https://echarts.apache.org/en/option.html#series-treemap.levels.colorMappingBy)
* ).
* It is empty by default, which means the global color list
* will be used.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `color` attribute could appear in more
* than one places:
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.color
*/
var color: js.UndefOr[js.Array[_]] = js.native
/**
* It indicates the range of tranparent rate (color alpha) for
* nodes in a level . The range of values is 0 ~ 1.
*
* For example, `colorAlpha` can be `[0.3, 1]`.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `colorAlpha` attribute could appear in
* more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.colorAlpha
*/
var colorAlpha: js.UndefOr[js.Array[_]] = js.native
/**
* Specify the rule according to which each node obtain color
* from
* [color list](https://echarts.apache.org/en/option.html#series-treemap.levels.color)
* . Optional values:
*
* + `'value'`:
*
* Map
* [series-treemap.data.value](https://echarts.apache.org/en/option.html#series-treemap.data.value)
* to color.
*
* In this way, the color of each node indicate its value.
*
* [visualDimension](https://echarts.apache.org/en/option.html#series-treemap.levels.visualDimension)
* can be used to specify which dimension of
* [data](https://echarts.apache.org/en/option.html#series-treemap.data)
* is used to perform visual mapping.
*
* + `'index'`:
*
* Map the `index` (ordinal number) of nodes to color.
* Namely, in a level, the first node is mapped to the first
* color of
* [color list](https://echarts.apache.org/en/option.html#series-treemap.levels.color)
* , and the second node gets the second color.
*
* In this way, adjacent nodes are distinguished by color.
*
* + `'id'`:
*
* Map
* [series-treemap.data.id](https://echarts.apache.org/en/option.html#series-treemap.data.id)
* to color.
*
* Since `id` is used to identify node, if user call `setOption`
* to modify the tree, each node will remain the original color
* before and after `setOption` called. See this
* [example](https://echarts.apache.org/examples/en/editor.html?c=treemap-obama&edit=1&reset=1)
* .
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `colorMappingBy` attribute could appear
* in more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @default
* "index"
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.colorMappingBy
*/
var colorMappingBy: js.UndefOr[String] = js.native
/**
* It indicates the range of saturation (color alpha) for nodes
* in a level . The range of values is 0 ~ 1.
*
* For example, `colorSaturation` can be `[0.3, 1]`.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `colorSaturation` attribute could appear
* in more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.colorSaturation
*/
var colorSaturation: js.UndefOr[Double] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.emphasis
*/
var emphasis: js.UndefOr[UpperLabel] = js.native
/**
*
* > Tps: In treemap, `itemStyle` attribute could appear in
* more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.itemStyle
*/
var itemStyle: js.UndefOr[BorderColorSaturation] = js.native
/**
* `label` decribes the style of the label in each node.
*
* > Tps: In treemap, `label` attribute could appear in more
* than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.label
*/
var label: js.UndefOr[Ellipsis] = js.native
/**
* `upperLabel` is used to specify whether show label when the
* node has children. When
* [upperLabel.show](https://echarts.apache.org/en/option.html#series-treemap.upperLabel.show)
* is set as `true`, the feature that "show parent label" is
* enabled.
*
* The same as
* [series-treemap.label](https://echarts.apache.org/en/option.html#series-treemap.label)
* , the option `upperLabel` can be placed at the root of
* [series-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* directly, or in
* [series-treemap.level](https://echarts.apache.org/en/option.html#series-treemap.level)
* , or in each item of
* [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* .
*
* Specifically,
* [series-treemap.label](https://echarts.apache.org/en/option.html#series-treemap.label)
* specifies the style when a node is a leaf, while `upperLabel`
* specifies the style when a node has children, in which case
* the label is displayed in the inner top of the node.
*
* See:
*
* [see doc](https://echarts.apache.org/en/option.html#series-treemap.treemap.levels)
*
* > Tps: In treemap, `label` attribute could appear in more
* than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.upperLabel
*/
var upperLabel: js.UndefOr[TextShadowColor] = js.native
/**
* A node will not be shown when its area size is smaller than
* this value (unit: px square).
*
* In this way, tiny nodes will be hidden, otherwise they will
* huddle together.
* When user zoom the treemap, the area size will increase and
* the rectangle will be shown if the area size is larger than
* this threshold.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `visibleMin` attribute could appear in
* more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @default
* 10
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.visibleMin
*/
var visibleMin: js.UndefOr[Double] = js.native
/**
* `treemap` is able to map any dimensions of data to visual.
*
* The value of
* [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* can be an array.
* And each item of the array represents a "dimension".
* `visualDimension` specifies the dimension on which visual
* mapping will be performed.
*
* About visual encoding, see details in
* [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* .
*
* > Tps: In treemap, `visualDimension` attribute could appear
* in more than one places:
* >
* > + It could appear in
* > [sereis-treemap](https://echarts.apache.org/en/option.html#series-treemap)
* > , indicating the unified setting of the series.
* >
* > + It could appear in each array element of
* > [series-treemap.levels](https://echarts.apache.org/en/option.html#series-treemap.levels)
* > , indicating the unified setting of each level of the tree.
* >
* > + It could appear in each node of
* > [series-treemap.data](https://echarts.apache.org/en/option.html#series-treemap.data)
* > , indicating the particular setting of each node.
* >
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.visualDimension
*/
var visualDimension: js.UndefOr[Double] = js.native
/**
* The maximal value of current level.
* Auto-statistics by default.
*
* When
* [colorMappingBy](https://echarts.apache.org/en/option.html#series-treemap.levels.colorMappingBy)
* is set to `'value'`, you are able to specify extent manually
* for visual mapping by specifying `visualMin` or `visualMax`.
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.visualMax
*/
var visualMax: js.UndefOr[Double] = js.native
/**
* The minimal value of current level.
* Auto-statistics by default.
*
* When
* [colorMappingBy](https://echarts.apache.org/en/option.html#series-treemap.levels.colorMappingBy)
* is set to `'value'`, you are able to specify extent manually
* for visual mapping by specifying `visualMin` or `visualMax`.
*
*
* @see https://echarts.apache.org/en/option.html#series-treemap.levels.visualMin
*/
var visualMin: js.UndefOr[Double] = js.native
}
object ChildrenVisibleMin {
@scala.inline
def apply(): ChildrenVisibleMin = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ChildrenVisibleMin]
}
@scala.inline
implicit class ChildrenVisibleMinMutableBuilder[Self <: ChildrenVisibleMin] (val x: Self) extends AnyVal {
@scala.inline
def setChildrenVisibleMin(value: Double): Self = StObject.set(x, "childrenVisibleMin", value.asInstanceOf[js.Any])
@scala.inline
def setChildrenVisibleMinUndefined: Self = StObject.set(x, "childrenVisibleMin", js.undefined)
@scala.inline
def setColor(value: js.Array[_]): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorAlpha(value: js.Array[_]): Self = StObject.set(x, "colorAlpha", value.asInstanceOf[js.Any])
@scala.inline
def setColorAlphaUndefined: Self = StObject.set(x, "colorAlpha", js.undefined)
@scala.inline
def setColorAlphaVarargs(value: js.Any*): Self = StObject.set(x, "colorAlpha", js.Array(value :_*))
@scala.inline
def setColorMappingBy(value: String): Self = StObject.set(x, "colorMappingBy", value.asInstanceOf[js.Any])
@scala.inline
def setColorMappingByUndefined: Self = StObject.set(x, "colorMappingBy", js.undefined)
@scala.inline
def setColorSaturation(value: Double): Self = StObject.set(x, "colorSaturation", value.asInstanceOf[js.Any])
@scala.inline
def setColorSaturationUndefined: Self = StObject.set(x, "colorSaturation", js.undefined)
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setColorVarargs(value: js.Any*): Self = StObject.set(x, "color", js.Array(value :_*))
@scala.inline
def setEmphasis(value: UpperLabel): Self = StObject.set(x, "emphasis", value.asInstanceOf[js.Any])
@scala.inline
def setEmphasisUndefined: Self = StObject.set(x, "emphasis", js.undefined)
@scala.inline
def setItemStyle(value: BorderColorSaturation): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: Ellipsis): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setUpperLabel(value: TextShadowColor): Self = StObject.set(x, "upperLabel", value.asInstanceOf[js.Any])
@scala.inline
def setUpperLabelUndefined: Self = StObject.set(x, "upperLabel", js.undefined)
@scala.inline
def setVisibleMin(value: Double): Self = StObject.set(x, "visibleMin", value.asInstanceOf[js.Any])
@scala.inline
def setVisibleMinUndefined: Self = StObject.set(x, "visibleMin", js.undefined)
@scala.inline
def setVisualDimension(value: Double): Self = StObject.set(x, "visualDimension", value.asInstanceOf[js.Any])
@scala.inline
def setVisualDimensionUndefined: Self = StObject.set(x, "visualDimension", js.undefined)
@scala.inline
def setVisualMax(value: Double): Self = StObject.set(x, "visualMax", value.asInstanceOf[js.Any])
@scala.inline
def setVisualMaxUndefined: Self = StObject.set(x, "visualMax", js.undefined)
@scala.inline
def setVisualMin(value: Double): Self = StObject.set(x, "visualMin", value.asInstanceOf[js.Any])
@scala.inline
def setVisualMinUndefined: Self = StObject.set(x, "visualMin", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/16.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait `16` extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-parallel.data.emphasis.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
}
object `16` {
@scala.inline
def apply(): `16` = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[`16`]
}
@scala.inline
implicit class `16MutableBuilder`[Self <: `16`] (val x: Self) extends AnyVal {
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Length2.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/Length2.scala<gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StringDictionary
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Length2
extends /**
* Some properties like "normal" or "emphasis" are not documented.
* Please, write description for them
*/
/* unknownProperty */ StringDictionary[js.Any] {
/**
* The style of visual guide line in emphasis status.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.emphasis
*/
var emphasis: js.UndefOr[Show] = js.native
/**
* The length of the first segment of visual guide line.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.length
*/
var length: js.UndefOr[Double] = js.native
/**
* The length of the second segment of visual guide line.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.length2
*/
var length2: js.UndefOr[Double] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
/**
* Whether to show the visual guide ine.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.show
*/
var show: js.UndefOr[Boolean] = js.native
/**
* Whether to smooth the visual guide line.
* It defaults to be `false` and can be set as `true` or the
* values from 0 to 1 which indicating the smoothness.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.labelLine.smooth
*/
var smooth: js.UndefOr[Boolean | Double] = js.native
}
object Length2 {
@scala.inline
def apply(): Length2 = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Length2]
}
@scala.inline
implicit class Length2MutableBuilder[Self <: Length2] (val x: Self) extends AnyVal {
@scala.inline
def setEmphasis(value: Show): Self = StObject.set(x, "emphasis", value.asInstanceOf[js.Any])
@scala.inline
def setEmphasisUndefined: Self = StObject.set(x, "emphasis", js.undefined)
@scala.inline
def setLength(value: Double): Self = StObject.set(x, "length", value.asInstanceOf[js.Any])
@scala.inline
def setLength2(value: Double): Self = StObject.set(x, "length2", value.asInstanceOf[js.Any])
@scala.inline
def setLength2Undefined: Self = StObject.set(x, "length2", js.undefined)
@scala.inline
def setLengthUndefined: Self = StObject.set(x, "length", js.undefined)
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setSmooth(value: Boolean | Double): Self = StObject.set(x, "smooth", value.asInstanceOf[js.Any])
@scala.inline
def setSmoothUndefined: Self = StObject.set(x, "smooth", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ColorOpacity.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ColorOpacity extends StObject {
var color: js.UndefOr[String] = js.native
var opacity: js.UndefOr[Double] = js.native
var shadowBlur: js.UndefOr[Double] = js.native
var shadowColor: js.UndefOr[String] = js.native
var shadowOffsetX: js.UndefOr[Double] = js.native
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object ColorOpacity {
@scala.inline
def apply(): ColorOpacity = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ColorOpacity]
}
@scala.inline
implicit class ColorOpacityMutableBuilder[Self <: ColorOpacity] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: String): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Symbol.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/Symbol.scala<gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Symbol extends StObject {
/**
* Coordinates of the starting point or ending point,
* whose format depends on the coordinate of the series.
* It can be `x`, and `y` for
* [rectangular coordinates](https://echarts.apache.org/en/option.html#grid)
* , or `radius`, and `angle` for
* [polar coordinates](https://echarts.apache.org/en/option.html#polar)
* .
*
* **Notice:** For axis with
* [axis.type](https://echarts.apache.org/en/option.html#xAixs.type)
* `'category'`:
*
* + If coord value is `number`, it represents index
* of
* [axis.data](https://echarts.apache.org/en/option.html#xAxis.data)
* .
* + If coord value is `string`, it represents concrete
* value in
* [axis.data](https://echarts.apache.org/en/option.html#xAxis.data)
*
*
* Please notice that in this case `xAxis.data`
* must not be written as \[number, number,
*
*
*
* \], but can only be written \[string, string,
*
*
*
* \].
* Otherwise it is not able to be located by markPoint
* / markLine.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-boxplot.boxplot.markLine.data.1)
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.coord
*/
var coord: js.UndefOr[js.Array[_]] = js.native
/**
* Label of this data item, which will be merged with
* `label` of starting point and ending point.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.label
*/
var label: js.UndefOr[Position] = js.native
/**
* Line style of this data item, which will be merged
* with `lineStyle` of starting point and ending point.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.lineStyle
*/
var lineStyle: js.UndefOr[ShadowOffsetX] = js.native
/**
* Name of the marker, which will display as a label.
*
*
* @see https://ecomfe.github.io/echarts-doc/public/en/option.html#series-boxplot.markLine.data.1.name
*/
var name: js.UndefOr[String] = js.native
/**
* Symbol of ending point.
*
* Icon types provided by ECharts includes `'circle'`,
* `'rect'`, `'roundRect'`, `'triangle'`, `'diamond'`,
* `'pin'`, `'arrow'`, `'none'`
*
* It can be set to an image with `'image://url'` ,
* in which URL is the link to an image, or `dataURI`
* of an image.
*
* An image URL example:
*
* ```
* 'image://http://xxx.xxx.xxx/a/b.png'
*
* ```
*
* A `dataURI` example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-boxplot.boxplot.markLine.data.1)
*
* Icons can be set to arbitrary vector path via `'path://'`
* in ECharts.
* As compared with raster image, vector paths prevent
* from jagging and blurring when scaled, and have a
* better control over changing colors.
* Size of vectoer icon will be adapted automatically.
* Refer to
* [SVG PathData](http://www.w3.org/TR/SVG/paths.html#PathData)
* for more information about format of path.
* You may export vector paths from tools like Adobe
* Illustrator.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-boxplot.boxplot.markLine.data.1)
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.symbol
*/
var symbol: js.UndefOr[String] = js.native
/**
* Whether to keep aspect for symbols in the form of
* `path://`.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.symbolKeepAspect
*/
var symbolKeepAspect: js.UndefOr[Boolean] = js.native
/**
* Offset of ending point symbol relative to original
* position.
* By default, symbol will be put in the center position
* of data.
* But if symbol is from user-defined vector path or
* image, you may not expect symbol to be in center.
* In this case, you may use this attribute to set offset
* to default position.
* It can be in absolute pixel value, or in relative
* percentage value.
*
* For example, `[0, '50%']` means to move upside side
* position of symbol height.
* It can be used to make the arrow in the bottom to
* be at data position when symbol is pin.
*
*
* @default
* [0, 0]
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.symbolOffset
*/
var symbolOffset: js.UndefOr[js.Array[_]] = js.native
/**
* Rotate degree of ending point symbol.
* Note that when `symbol` is set to be `'arrow'` in
* `markLine`, `symbolRotate` value will be ignored,
* and compulsively use tangent angle.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.symbolRotate
*/
var symbolRotate: js.UndefOr[Double] = js.native
/**
* ending point symbol size.
* It can be set to single numbers like `10`, or use
* an array to represent width and height.
* For example, `[20, 10]` means symbol width is `20`,
* and height is`10`.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.symbolSize
*/
var symbolSize: js.UndefOr[js.Array[_] | Double] = js.native
/**
* Special label types, are used to label maximum value,
* minimum value and so on.
*
* **Options are:**
*
* + `'min'` maximum value.
* + `'max'` minimum value.
* + `'average'` average value.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.type
*/
var `type`: js.UndefOr[String] = js.native
/**
* Label value, which can be ignored.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.value
*/
var value: js.UndefOr[Double] = js.native
/**
* Works only when
* [type](https://echarts.apache.org/en/option.html#series-.markLine.data.type)
* is assigned.
* It is used to state the dimension used to calculate
* maximum value or minimum value.
* It may be the direct name of a dimension, like `x`,
* or `angle` for line charts, or `open`, or `close`
* for candlestick charts.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.valueDim
*/
var valueDim: js.UndefOr[String] = js.native
/**
* Works only when
* [type](https://echarts.apache.org/en/option.html#series-.markLine.data.type)
* is assigned.
* It is used to state the dimension used to calculate
* maximum value or minimum value.
* It may be `0` (for xAxis, or radiusAxis), or `1`
* (for yAxis, or angleAxis).
* Dimension of the first numeric axis is used by default.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.valueIndex
*/
var valueIndex: js.UndefOr[Double] = js.native
/**
* X position according to container, in pixel.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.x
*/
var x: js.UndefOr[Double] = js.native
/**
* Position according to X-Axis value.
* For a line parallel to Y-Axis
*
*/
var xAxis: js.UndefOr[Double] = js.native
/**
* Y position according to container, in pixel.
*
*
* @see https://echarts.apache.org/en/option.html#series-boxplot.markLine.data.1.y
*/
var y: js.UndefOr[Double] = js.native
/**
* Position according to Y-Axis value
* For a line parallel to X-Axis
*
*/
var yAxis: js.UndefOr[Double] = js.native
}
object Symbol {
@scala.inline
def apply(): Symbol = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Symbol]
}
@scala.inline
implicit class SymbolMutableBuilder[Self <: Symbol] (val x: Self) extends AnyVal {
@scala.inline
def setCoord(value: js.Array[_]): Self = StObject.set(x, "coord", value.asInstanceOf[js.Any])
@scala.inline
def setCoordUndefined: Self = StObject.set(x, "coord", js.undefined)
@scala.inline
def setCoordVarargs(value: js.Any*): Self = StObject.set(x, "coord", js.Array(value :_*))
@scala.inline
def setLabel(value: Position): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setLineStyle(value: ShadowOffsetX): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any])
@scala.inline
def setNameUndefined: Self = StObject.set(x, "name", js.undefined)
@scala.inline
def setSymbol(value: String): Self = StObject.set(x, "symbol", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolKeepAspect(value: Boolean): Self = StObject.set(x, "symbolKeepAspect", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolKeepAspectUndefined: Self = StObject.set(x, "symbolKeepAspect", js.undefined)
@scala.inline
def setSymbolOffset(value: js.Array[_]): Self = StObject.set(x, "symbolOffset", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolOffsetUndefined: Self = StObject.set(x, "symbolOffset", js.undefined)
@scala.inline
def setSymbolOffsetVarargs(value: js.Any*): Self = StObject.set(x, "symbolOffset", js.Array(value :_*))
@scala.inline
def setSymbolRotate(value: Double): Self = StObject.set(x, "symbolRotate", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolRotateUndefined: Self = StObject.set(x, "symbolRotate", js.undefined)
@scala.inline
def setSymbolSize(value: js.Array[_] | Double): Self = StObject.set(x, "symbolSize", value.asInstanceOf[js.Any])
@scala.inline
def setSymbolSizeUndefined: Self = StObject.set(x, "symbolSize", js.undefined)
@scala.inline
def setSymbolSizeVarargs(value: js.Any*): Self = StObject.set(x, "symbolSize", js.Array(value :_*))
@scala.inline
def setSymbolUndefined: Self = StObject.set(x, "symbol", js.undefined)
@scala.inline
def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setTypeUndefined: Self = StObject.set(x, "type", js.undefined)
@scala.inline
def setValue(value: Double): Self = StObject.set(x, "value", value.asInstanceOf[js.Any])
@scala.inline
def setValueDim(value: String): Self = StObject.set(x, "valueDim", value.asInstanceOf[js.Any])
@scala.inline
def setValueDimUndefined: Self = StObject.set(x, "valueDim", js.undefined)
@scala.inline
def setValueIndex(value: Double): Self = StObject.set(x, "valueIndex", value.asInstanceOf[js.Any])
@scala.inline
def setValueIndexUndefined: Self = StObject.set(x, "valueIndex", js.undefined)
@scala.inline
def setValueUndefined: Self = StObject.set(x, "value", js.undefined)
@scala.inline
def setX(value: Double): Self = StObject.set(x, "x", value.asInstanceOf[js.Any])
@scala.inline
def setXAxis(value: Double): Self = StObject.set(x, "xAxis", value.asInstanceOf[js.Any])
@scala.inline
def setXAxisUndefined: Self = StObject.set(x, "xAxis", js.undefined)
@scala.inline
def setXUndefined: Self = StObject.set(x, "x", js.undefined)
@scala.inline
def setY(value: Double): Self = StObject.set(x, "y", value.asInstanceOf[js.Any])
@scala.inline
def setYAxis(value: Double): Self = StObject.set(x, "yAxis", value.asInstanceOf[js.Any])
@scala.inline
def setYAxisUndefined: Self = StObject.set(x, "yAxis", js.undefined)
@scala.inline
def setYUndefined: Self = StObject.set(x, "y", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echartsStrings.scala | package anduin.facades.echarts
import anduin.facades.echarts.echarts.EChartOption.BasicComponents.CartesianAxis.Type
import anduin.facades.echarts.echarts.EChartOption.Tooltip.Position.Str
import anduin.facades.echarts.echarts.EChartsSeriesType
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object echartsStrings {
@js.native
sealed trait angle extends StObject
@scala.inline
def angle: angle = "angle".asInstanceOf[angle]
@js.native
sealed trait auto extends StObject
@scala.inline
def auto: auto = "auto".asInstanceOf[auto]
@js.native
sealed trait axis extends StObject
@scala.inline
def axis: axis = "axis".asInstanceOf[axis]
@js.native
sealed trait bar extends EChartsSeriesType
@scala.inline
def bar: bar = "bar".asInstanceOf[bar]
@js.native
sealed trait bold extends StObject
@scala.inline
def bold: bold = "bold".asInstanceOf[bold]
@js.native
sealed trait bolder extends StObject
@scala.inline
def bolder: bolder = "bolder".asInstanceOf[bolder]
@js.native
sealed trait bottom extends Str
@scala.inline
def bottom: bottom = "bottom".asInstanceOf[bottom]
@js.native
sealed trait boxplot extends EChartsSeriesType
@scala.inline
def boxplot: boxplot = "boxplot".asInstanceOf[boxplot]
@js.native
sealed trait calendar extends StObject
@scala.inline
def calendar: calendar = "calendar".asInstanceOf[calendar]
@js.native
sealed trait candlestick extends EChartsSeriesType
@scala.inline
def candlestick: candlestick = "candlestick".asInstanceOf[candlestick]
@js.native
sealed trait cartesian2d extends StObject
@scala.inline
def cartesian2d: cartesian2d = "cartesian2d".asInstanceOf[cartesian2d]
@js.native
sealed trait category extends Type
@scala.inline
def category: category = "category".asInstanceOf[category]
@js.native
sealed trait center extends StObject
@scala.inline
def center: center = "center".asInstanceOf[center]
@js.native
sealed trait click extends StObject
@scala.inline
def click: click = "click".asInstanceOf[click]
@js.native
sealed trait continuous extends StObject
@scala.inline
def continuous: continuous = "continuous".asInstanceOf[continuous]
@js.native
sealed trait cross extends StObject
@scala.inline
def cross: cross = "cross".asInstanceOf[cross]
@js.native
sealed trait custom extends EChartsSeriesType
@scala.inline
def custom: custom = "custom".asInstanceOf[custom]
@js.native
sealed trait dashed extends StObject
@scala.inline
def dashed: dashed = "dashed".asInstanceOf[dashed]
@js.native
sealed trait dotted extends StObject
@scala.inline
def dotted: dotted = "dotted".asInstanceOf[dotted]
@js.native
sealed trait effectScatter extends EChartsSeriesType
@scala.inline
def effectScatter: effectScatter = "effectScatter".asInstanceOf[effectScatter]
@js.native
sealed trait empty extends StObject
@scala.inline
def empty: empty = "empty".asInstanceOf[empty]
@js.native
sealed trait end extends StObject
@scala.inline
def end: end = "end".asInstanceOf[end]
@js.native
sealed trait filter extends StObject
@scala.inline
def filter: filter = "filter".asInstanceOf[filter]
@js.native
sealed trait float extends StObject
@scala.inline
def float: float = "float".asInstanceOf[float]
@js.native
sealed trait funnel extends EChartsSeriesType
@scala.inline
def funnel: funnel = "funnel".asInstanceOf[funnel]
@js.native
sealed trait gauge extends EChartsSeriesType
@scala.inline
def gauge: gauge = "gauge".asInstanceOf[gauge]
@js.native
sealed trait geo extends StObject
@scala.inline
def geo: geo = "geo".asInstanceOf[geo]
@js.native
sealed trait graph extends EChartsSeriesType
@scala.inline
def graph: graph = "graph".asInstanceOf[graph]
@js.native
sealed trait heatmap extends EChartsSeriesType
@scala.inline
def heatmap: heatmap = "heatmap".asInstanceOf[heatmap]
@js.native
sealed trait horizontal extends StObject
@scala.inline
def horizontal: horizontal = "horizontal".asInstanceOf[horizontal]
@js.native
sealed trait html extends StObject
@scala.inline
def html: html = "html".asInstanceOf[html]
@js.native
sealed trait inside extends Str
@scala.inline
def inside: inside = "inside".asInstanceOf[inside]
@js.native
sealed trait int extends StObject
@scala.inline
def int: int = "int".asInstanceOf[int]
@js.native
sealed trait italic extends StObject
@scala.inline
def italic: italic = "italic".asInstanceOf[italic]
@js.native
sealed trait item extends StObject
@scala.inline
def item: item = "item".asInstanceOf[item]
@js.native
sealed trait left extends Str
@scala.inline
def left: left = "left".asInstanceOf[left]
@js.native
sealed trait lighter extends StObject
@scala.inline
def lighter: lighter = "lighter".asInstanceOf[lighter]
@js.native
sealed trait line extends EChartsSeriesType
@scala.inline
def line: line = "line".asInstanceOf[line]
@js.native
sealed trait linear extends StObject
@scala.inline
def linear: linear = "linear".asInstanceOf[linear]
@js.native
sealed trait lines extends EChartsSeriesType
@scala.inline
def lines: lines = "lines".asInstanceOf[lines]
@js.native
sealed trait log extends Type
@scala.inline
def log: log = "log".asInstanceOf[log]
@js.native
sealed trait map extends EChartsSeriesType
@scala.inline
def map: map = "map".asInstanceOf[map]
@js.native
sealed trait middle extends StObject
@scala.inline
def middle: middle = "middle".asInstanceOf[middle]
@js.native
sealed trait mousemove extends StObject
@scala.inline
def mousemove: mousemove = "mousemove".asInstanceOf[mousemove]
@js.native
sealed trait mousemoveVerticallineclick extends StObject
@scala.inline
def mousemoveVerticallineclick: mousemoveVerticallineclick = "mousemove|click".asInstanceOf[mousemoveVerticallineclick]
@js.native
sealed trait multiple extends StObject
@scala.inline
def multiple: multiple = "multiple".asInstanceOf[multiple]
@js.native
sealed trait `no-repeat` extends StObject
@scala.inline
def `no-repeat`: `no-repeat` = "no-repeat".asInstanceOf[`no-repeat`]
@js.native
sealed trait none extends StObject
@scala.inline
def none: none = "none".asInstanceOf[none]
@js.native
sealed trait normal extends StObject
@scala.inline
def normal: normal = "normal".asInstanceOf[normal]
@js.native
sealed trait number extends StObject
@scala.inline
def number: number = "number".asInstanceOf[number]
@js.native
sealed trait oblique extends StObject
@scala.inline
def oblique: oblique = "oblique".asInstanceOf[oblique]
@js.native
sealed trait ordinal extends StObject
@scala.inline
def ordinal: ordinal = "ordinal".asInstanceOf[ordinal]
@js.native
sealed trait parallel extends EChartsSeriesType
@scala.inline
def parallel: parallel = "parallel".asInstanceOf[parallel]
@js.native
sealed trait pictorialBar extends EChartsSeriesType
@scala.inline
def pictorialBar: pictorialBar = "pictorialBar".asInstanceOf[pictorialBar]
@js.native
sealed trait pie extends EChartsSeriesType
@scala.inline
def pie: pie = "pie".asInstanceOf[pie]
@js.native
sealed trait piecewise extends StObject
@scala.inline
def piecewise: piecewise = "piecewise".asInstanceOf[piecewise]
@js.native
sealed trait plain extends StObject
@scala.inline
def plain: plain = "plain".asInstanceOf[plain]
@js.native
sealed trait polar extends StObject
@scala.inline
def polar: polar = "polar".asInstanceOf[polar]
@js.native
sealed trait radar extends EChartsSeriesType
@scala.inline
def radar: radar = "radar".asInstanceOf[radar]
@js.native
sealed trait radial extends StObject
@scala.inline
def radial: radial = "radial".asInstanceOf[radial]
@js.native
sealed trait radius extends StObject
@scala.inline
def radius: radius = "radius".asInstanceOf[radius]
@js.native
sealed trait repeat extends StObject
@scala.inline
def repeat: repeat = "repeat".asInstanceOf[repeat]
@js.native
sealed trait `repeat-x` extends StObject
@scala.inline
def `repeat-x`: `repeat-x` = "repeat-x".asInstanceOf[`repeat-x`]
@js.native
sealed trait `repeat-y` extends StObject
@scala.inline
def `repeat-y`: `repeat-y` = "repeat-y".asInstanceOf[`repeat-y`]
@js.native
sealed trait right extends Str
@scala.inline
def right: right = "right".asInstanceOf[right]
@js.native
sealed trait sankey extends EChartsSeriesType
@scala.inline
def sankey: sankey = "sankey".asInstanceOf[sankey]
@js.native
sealed trait scatter extends EChartsSeriesType
@scala.inline
def scatter: scatter = "scatter".asInstanceOf[scatter]
@js.native
sealed trait scroll extends StObject
@scala.inline
def scroll: scroll = "scroll".asInstanceOf[scroll]
@js.native
sealed trait series extends StObject
@scala.inline
def series: series = "series".asInstanceOf[series]
@js.native
sealed trait shadow extends StObject
@scala.inline
def shadow: shadow = "shadow".asInstanceOf[shadow]
@js.native
sealed trait single extends StObject
@scala.inline
def single: single = "single".asInstanceOf[single]
@js.native
sealed trait singleAxis extends StObject
@scala.inline
def singleAxis: singleAxis = "singleAxis".asInstanceOf[singleAxis]
@js.native
sealed trait solid extends StObject
@scala.inline
def solid: solid = "solid".asInstanceOf[solid]
@js.native
sealed trait start extends StObject
@scala.inline
def start: start = "start".asInstanceOf[start]
@js.native
sealed trait sunburst extends EChartsSeriesType
@scala.inline
def sunburst: sunburst = "sunburst".asInstanceOf[sunburst]
@js.native
sealed trait themeRiver extends EChartsSeriesType
@scala.inline
def themeRiver: themeRiver = "themeRiver".asInstanceOf[themeRiver]
@js.native
sealed trait time extends Type
@scala.inline
def time: time = "time".asInstanceOf[time]
@js.native
sealed trait top extends Str
@scala.inline
def top: top = "top".asInstanceOf[top]
@js.native
sealed trait tree extends EChartsSeriesType
@scala.inline
def tree: tree = "tree".asInstanceOf[tree]
@js.native
sealed trait treemap extends EChartsSeriesType
@scala.inline
def treemap: treemap = "treemap".asInstanceOf[treemap]
@js.native
sealed trait value extends Type
@scala.inline
def value: value = "value".asInstanceOf[value]
@js.native
sealed trait vertical extends StObject
@scala.inline
def vertical: vertical = "vertical".asInstanceOf[vertical]
@js.native
sealed trait weakFilter extends StObject
@scala.inline
def weakFilter: weakFilter = "weakFilter".asInstanceOf[weakFilter]
@js.native
sealed trait x extends StObject
@scala.inline
def x: x = "x".asInstanceOf[x]
@js.native
sealed trait y extends StObject
@scala.inline
def y: y = "y".asInstanceOf[y]
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Emphasis.scala | <gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Emphasis extends StObject {
/**
* border color, whose format is similar to that
* of `color`.
*
*
* @default
* "#000"
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.borderColor
*/
var borderColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Border type, which can be `'solid'`, `'dashed'`,
* or `'dotted'`. `'solid'` by default.
*
*
* @default
* "solid"
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.borderType
*/
var borderType: js.UndefOr[String] = js.native
/**
* border width.
* No border when it is set to be 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.borderWidth
*/
var borderWidth: js.UndefOr[Double] = js.native
/**
* color.
*
* > Color can be represented in RGB, for example
* `'rgb(128, 128, 128)'`.
* RGBA can be used when you need alpha channel,
* for example `'rgba(128, 128, 128, 0.5)'`.
* You may also use hexadecimal format, for example
* `'#ccc'`.
* Gradient color and texture are also supported
* besides single colors.
* >
* > [see doc](https://echarts.apache.org/en/option.html#series-scatter.scatter.markArea.data.1.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.color
*/
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.emphasis
*/
var emphasis: js.UndefOr[BorderType] = js.native
/**
* Opacity of the component.
* Supports value from 0 to 1, and the component
* will not be drawn when set to 0.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.opacity
*/
var opacity: js.UndefOr[Double] = js.native
/**
* Size of shadow blur.
* This attribute should be used along with `shadowColor`,`shadowOffsetX`,
* `shadowOffsetY` to set shadow to component.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-scatter.scatter.markArea.data.1.itemStyle)
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color. Support same format as `color`.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.shadowColor
*/
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
/**
* Offset distance on the horizontal direction of
* shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Offset distance on the vertical direction of
* shadow.
*
*
* @see https://echarts.apache.org/en/option.html#series-scatter.markArea.data.1.itemStyle.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object Emphasis {
@scala.inline
def apply(): Emphasis = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Emphasis]
}
@scala.inline
implicit class EmphasisMutableBuilder[Self <: Emphasis] (val x: Self) extends AnyVal {
@scala.inline
def setBorderColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderType(value: String): Self = StObject.set(x, "borderType", value.asInstanceOf[js.Any])
@scala.inline
def setBorderTypeUndefined: Self = StObject.set(x, "borderType", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setEmphasis(value: BorderType): Self = StObject.set(x, "emphasis", value.asInstanceOf[js.Any])
@scala.inline
def setEmphasisUndefined: Self = StObject.set(x, "emphasis", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Downplay.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Downplay extends StObject {
/**
* Item style when mouse is hovering unrelated items. See
* [highlightPolicy](https://echarts.apache.org/en/option.html#series-sunburst.highlightPolicy)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-sunburst.levels.downplay
*/
var downplay: js.UndefOr[`22`] = js.native
/**
* Item style when mouse is hovering. See
* [highlightPolicy](https://echarts.apache.org/en/option.html#series-sunburst.highlightPolicy)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-sunburst.levels.emphasis
*/
var emphasis: js.UndefOr[`22`] = js.native
/**
* Item style when mouse is hovering related items. See
* [highlightPolicy](https://echarts.apache.org/en/option.html#series-sunburst.highlightPolicy)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-sunburst.levels.highlight
*/
var highlight: js.UndefOr[`22`] = js.native
/**
* Style of Sunburst sectors.
*
* Style can be set in
* [series.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.itemStyle)
* for sectors of this series, or
* [series.levels.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.levels.itemStyle)
* for the whole level, or
* [series.data.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.data.itemStyle)
* for single sector. If
* [series.data.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.data.itemStyle)
* is defined, it will cover the setting of
* [series.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.itemStyle)
* and
* [series.levels.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.levels.itemStyle)
* .
*
* **Priority:
* [series.data.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.data.itemStyle)
* >
* [series.levels.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.levels.itemStyle)
* >
* [series.itemStyle](https://echarts.apache.org/en/option.html#series-sunburst.itemStyle)
* .**
*
* In ECharts, _emphasis_ is for styles when mouse hovers.
* For Sunburst charts, there are two extra states: _highlight_
* for highlighting items that relates to the emphasized one,
* and _downplay_ for others when emphasizing an item. See
* [highlightPolicy](https://echarts.apache.org/en/option.html#series-sunburst.highlightPolicy)
* .
*
*
* @see https://echarts.apache.org/en/option.html#series-sunburst.levels.itemStyle
*/
var itemStyle: js.UndefOr[BorderType] = js.native
/**
* `label` sets the text style for every sectors.
*
* **Priority:
* [series.data.label](https://echarts.apache.org/en/option.html#series-sunburst.data.label)
* >
* [series.levels.label](https://echarts.apache.org/en/option.html#series-sunburst.levels.label)
* >
* [series.label](https://echarts.apache.org/en/option.html#series-sunburst.label)
* .**
*
* Text label of , to explain some data information about graphic
* item like value, name and so on.
* `label` is placed under `itemStyle` in ECharts 2.x.
* In ECharts 3, to make the configuration structure flatter,
* `label`is taken to be at the same level with `itemStyle`,
* and has `emphasis` as `itemStyle` does.
*
*
* @see https://echarts.apache.org/en/option.html#series-sunburst.levels.label
*/
var label: js.UndefOr[MinAngle] = js.native
}
object Downplay {
@scala.inline
def apply(): Downplay = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Downplay]
}
@scala.inline
implicit class DownplayMutableBuilder[Self <: Downplay] (val x: Self) extends AnyVal {
@scala.inline
def setDownplay(value: `22`): Self = StObject.set(x, "downplay", value.asInstanceOf[js.Any])
@scala.inline
def setDownplayUndefined: Self = StObject.set(x, "downplay", js.undefined)
@scala.inline
def setEmphasis(value: `22`): Self = StObject.set(x, "emphasis", value.asInstanceOf[js.Any])
@scala.inline
def setEmphasisUndefined: Self = StObject.set(x, "emphasis", js.undefined)
@scala.inline
def setHighlight(value: `22`): Self = StObject.set(x, "highlight", value.asInstanceOf[js.Any])
@scala.inline
def setHighlightUndefined: Self = StObject.set(x, "highlight", js.undefined)
@scala.inline
def setItemStyle(value: BorderType): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: MinAngle): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/AnimationAnimationDelay.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait AnimationAnimationDelay extends StObject {
/**
* Whether to enable animation.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animation
*/
var animation: js.UndefOr[Boolean] = js.native
/**
* Delay before updating the first animation, which supports
* callback function for different data to have different animation
* effect.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.markArea)
*
* See
* [this example](https://echarts.apache.org/examples/en/editor.html?c=bar-animation-delay)
* for more information.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationDelay
*/
var animationDelay: js.UndefOr[js.Function | Double] = js.native
/**
* Delay before updating animation, which supports callback
* function for different data to have different animation effect.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.markArea)
*
* See
* [this example](https://echarts.apache.org/examples/en/editor.html?c=bar-animation-delay)
* for more information.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationDelayUpdate
*/
var animationDelayUpdate: js.UndefOr[js.Function | Double] = js.native
/**
* Duration of the first animation, which supports callback
* function for different data to have different animation effect:
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.markArea)
*
*
* @default
* 1000
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationDuration
*/
var animationDuration: js.UndefOr[js.Function | Double] = js.native
/**
* Time for animation to complete, which supports callback function
* for different data to have different animation effect:
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.markArea)
*
*
* @default
* 300
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationDurationUpdate
*/
var animationDurationUpdate: js.UndefOr[js.Function | Double] = js.native
/**
* Easing method used for the first animation.
* Varied easing effects can be found at
* [easing effect example](https://echarts.apache.org/examples/en/editor.html?c=line-easing)
* .
*
*
* @default
* "cubicOut"
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationEasing
*/
var animationEasing: js.UndefOr[String] = js.native
/**
* Easing method used for animation.
*
*
* @default
* "cubicOut"
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationEasingUpdate
*/
var animationEasingUpdate: js.UndefOr[String] = js.native
/**
* Whether to set graphic number threshold to animation.
* Animation will be disabled when graphic number is larger
* than threshold.
*
*
* @default
* 2000
* @see https://echarts.apache.org/en/option.html#series-map.markArea.animationThreshold
*/
var animationThreshold: js.UndefOr[Double] = js.native
/**
* The scope of the area is defined by `data`, which is an array
* with two item, representing the left-top point and the right-bottom
* point of rectangle area.
* Each item can be defined as follows:
*
* 1.
* Specify the coordinate in screen coordinate system using
* [x](https://echarts.apache.org/en/option.html#series-map.markArea.data.0.x)
* ,
* [y](https://echarts.apache.org/en/option.html#series-map.markArea.data.0.y)
* , where the unit is pixel (e.g.,
* the value is `5`), or percent (e.g.,
* the value is `'35%'`).
*
* 2.
* Specify the coordinate in data coordinate system (i.e.,
* cartesian) using
* [coord](https://echarts.apache.org/en/option.html#series-map.markArea.data.0.coord)
* , which can be also set as `'min'`, `'max'`, `'average'`
* (e.g,
* `coord: [23, 'min']`, or `coord: ['average', 'max']`)。
*
* The priority follows as above if more than one above definition
* used.
*
* [see doc](https://echarts.apache.org/en/option.html#series-map.map.markArea)
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.data
*/
var data: js.UndefOr[`13`] = js.native
/**
* Style of the mark area.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.itemStyle
*/
var itemStyle: js.UndefOr[Emphasis] = js.native
/**
* Label in mark area.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.label
*/
var label: js.UndefOr[FontFamily] = js.native
/**
* Whether to ignore mouse events.
* Default value is false, for triggering and responding to
* mouse events.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markArea.silent
*/
var silent: js.UndefOr[Boolean] = js.native
}
object AnimationAnimationDelay {
@scala.inline
def apply(): AnimationAnimationDelay = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[AnimationAnimationDelay]
}
@scala.inline
implicit class AnimationAnimationDelayMutableBuilder[Self <: AnimationAnimationDelay] (val x: Self) extends AnyVal {
@scala.inline
def setAnimation(value: Boolean): Self = StObject.set(x, "animation", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelay(value: js.Function | Double): Self = StObject.set(x, "animationDelay", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUndefined: Self = StObject.set(x, "animationDelay", js.undefined)
@scala.inline
def setAnimationDelayUpdate(value: js.Function | Double): Self = StObject.set(x, "animationDelayUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUpdateUndefined: Self = StObject.set(x, "animationDelayUpdate", js.undefined)
@scala.inline
def setAnimationDuration(value: js.Function | Double): Self = StObject.set(x, "animationDuration", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDurationUndefined: Self = StObject.set(x, "animationDuration", js.undefined)
@scala.inline
def setAnimationDurationUpdate(value: js.Function | Double): Self = StObject.set(x, "animationDurationUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDurationUpdateUndefined: Self = StObject.set(x, "animationDurationUpdate", js.undefined)
@scala.inline
def setAnimationEasing(value: String): Self = StObject.set(x, "animationEasing", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationEasingUndefined: Self = StObject.set(x, "animationEasing", js.undefined)
@scala.inline
def setAnimationEasingUpdate(value: String): Self = StObject.set(x, "animationEasingUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationEasingUpdateUndefined: Self = StObject.set(x, "animationEasingUpdate", js.undefined)
@scala.inline
def setAnimationThreshold(value: Double): Self = StObject.set(x, "animationThreshold", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationThresholdUndefined: Self = StObject.set(x, "animationThreshold", js.undefined)
@scala.inline
def setAnimationUndefined: Self = StObject.set(x, "animation", js.undefined)
@scala.inline
def setData(value: `13`): Self = StObject.set(x, "data", value.asInstanceOf[js.Any])
@scala.inline
def setDataUndefined: Self = StObject.set(x, "data", js.undefined)
@scala.inline
def setItemStyle(value: Emphasis): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: FontFamily): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setSilent(value: Boolean): Self = StObject.set(x, "silent", value.asInstanceOf[js.Any])
@scala.inline
def setSilentUndefined: Self = StObject.set(x, "silent", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/package.scala | package anduin.facades.echarts
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
package object echarts {
type TypedArray = js.typedarray.Int8Array | js.typedarray.Uint8Array | js.typedarray.Int16Array | js.typedarray.Uint16Array | js.typedarray.Int32Array | js.typedarray.Uint32Array | js.typedarray.Uint8ClampedArray | js.typedarray.Float32Array | js.typedarray.Float64Array
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/AnimationDelayAnimationDelayUpdate.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait AnimationDelayAnimationDelayUpdate extends StObject {
/**
* Whether to enable animation.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animation
*/
var animation: js.UndefOr[Boolean] = js.native
/**
* Specify the delay time before animation start.
* Callback function can be used, where different delay time
* can be used on different element.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
*
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationDelay
*/
var animationDelay: js.UndefOr[js.Function | Double] = js.native
/**
* Specify the delay time before update animation.
* Callback function can be used, where different delay time
* can be used on different element.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
*
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationDelayUpdate
*/
var animationDelayUpdate: js.UndefOr[js.Function | Double] = js.native
/**
* Duration of the first animation, which supports callback
* function for different data to have different animation effect:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
*
* @default
* 1000
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationDuration
*/
var animationDuration: js.UndefOr[js.Function | Double] = js.native
/**
* Time for animation to complete, which supports callback function
* for different data to have different animation effect:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.hoverAnimation)
*
*
* @default
* 300
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationDurationUpdate
*/
var animationDurationUpdate: js.UndefOr[js.Function | Double] = js.native
/**
* Easing method used for the first animation.
* Varied easing effects can be found at
* [easing effect example](https://echarts.apache.org/examples/en/editor.html?c=line-easing)
* .
*
*
* @default
* "cubicOut"
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationEasing
*/
var animationEasing: js.UndefOr[String] = js.native
/**
* Easing method used for animation.
*
*
* @default
* "cubicOut"
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationEasingUpdate
*/
var animationEasingUpdate: js.UndefOr[String] = js.native
/**
* Whether to set graphic number threshold to animation.
* Animation will be disabled when graphic number is larger
* than threshold.
*
*
* @default
* 2000
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.hoverAnimation.animationThreshold
*/
var animationThreshold: js.UndefOr[Double] = js.native
}
object AnimationDelayAnimationDelayUpdate {
@scala.inline
def apply(): AnimationDelayAnimationDelayUpdate = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[AnimationDelayAnimationDelayUpdate]
}
@scala.inline
implicit class AnimationDelayAnimationDelayUpdateMutableBuilder[Self <: AnimationDelayAnimationDelayUpdate] (val x: Self) extends AnyVal {
@scala.inline
def setAnimation(value: Boolean): Self = StObject.set(x, "animation", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelay(value: js.Function | Double): Self = StObject.set(x, "animationDelay", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUndefined: Self = StObject.set(x, "animationDelay", js.undefined)
@scala.inline
def setAnimationDelayUpdate(value: js.Function | Double): Self = StObject.set(x, "animationDelayUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUpdateUndefined: Self = StObject.set(x, "animationDelayUpdate", js.undefined)
@scala.inline
def setAnimationDuration(value: js.Function | Double): Self = StObject.set(x, "animationDuration", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDurationUndefined: Self = StObject.set(x, "animationDuration", js.undefined)
@scala.inline
def setAnimationDurationUpdate(value: js.Function | Double): Self = StObject.set(x, "animationDurationUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDurationUpdateUndefined: Self = StObject.set(x, "animationDurationUpdate", js.undefined)
@scala.inline
def setAnimationEasing(value: String): Self = StObject.set(x, "animationEasing", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationEasingUndefined: Self = StObject.set(x, "animationEasing", js.undefined)
@scala.inline
def setAnimationEasingUpdate(value: String): Self = StObject.set(x, "animationEasingUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationEasingUpdateUndefined: Self = StObject.set(x, "animationEasingUpdate", js.undefined)
@scala.inline
def setAnimationThreshold(value: Double): Self = StObject.set(x, "animationThreshold", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationThresholdUndefined: Self = StObject.set(x, "animationThreshold", js.undefined)
@scala.inline
def setAnimationUndefined: Self = StObject.set(x, "animation", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/17.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait `17` extends StObject {
/**
* Specify the delay time before animation start.
* Callback function can be used, where different delay time
* can be used on different element.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.animationEasingUpdate)
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.animationEasingUpdate)
*
*
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.animationEasingUpdate.animationDelay
*/
var animationDelay: js.UndefOr[js.Function | Double] = js.native
/**
* Specify the delay time before update animation.
* Callback function can be used, where different delay time
* can be used on different element.
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.animationEasingUpdate)
*
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-pictorialBar.pictorialBar.animationEasingUpdate)
*
*
* @see https://echarts.apache.org/en/option.html#series-pictorialBar.animationEasingUpdate.animationDelayUpdate
*/
var animationDelayUpdate: js.UndefOr[js.Function | Double] = js.native
}
object `17` {
@scala.inline
def apply(): `17` = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[`17`]
}
@scala.inline
implicit class `17MutableBuilder`[Self <: `17`] (val x: Self) extends AnyVal {
@scala.inline
def setAnimationDelay(value: js.Function | Double): Self = StObject.set(x, "animationDelay", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUndefined: Self = StObject.set(x, "animationDelay", js.undefined)
@scala.inline
def setAnimationDelayUpdate(value: js.Function | Double): Self = StObject.set(x, "animationDelayUpdate", value.asInstanceOf[js.Any])
@scala.inline
def setAnimationDelayUpdateUndefined: Self = StObject.set(x, "animationDelayUpdate", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/ItemStyleLabelLineStyle.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ItemStyleLabelLineStyle extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-sankey.emphasis.itemStyle
*/
var itemStyle: js.UndefOr[BorderType] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-sankey.emphasis.label
*/
var label: js.UndefOr[BorderRadius] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-sankey.emphasis.lineStyle
*/
var lineStyle: js.UndefOr[ColorCurveness] = js.native
}
object ItemStyleLabelLineStyle {
@scala.inline
def apply(): ItemStyleLabelLineStyle = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[ItemStyleLabelLineStyle]
}
@scala.inline
implicit class ItemStyleLabelLineStyleMutableBuilder[Self <: ItemStyleLabelLineStyle] (val x: Self) extends AnyVal {
@scala.inline
def setItemStyle(value: BorderType): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: BorderRadius): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setLineStyle(value: ColorCurveness): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/SplitNumber.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/SplitNumber.scala<gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait SplitNumber extends StObject {
/**
* The length of tick line, can be a pecentage value relative
* to radius.
*
*
* @default
* 8
* @see https://echarts.apache.org/en/option.html#series-gauge.axisTick.length
*/
var length: js.UndefOr[Double | String] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-gauge.axisTick.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
/**
* Whether to show the scale.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-gauge.axisTick.show
*/
var show: js.UndefOr[Boolean] = js.native
/**
* The split scale number between split line.
*
*
* @default
* 5
* @see https://echarts.apache.org/en/option.html#series-gauge.axisTick.splitNumber
*/
var splitNumber: js.UndefOr[Double] = js.native
}
object SplitNumber {
@scala.inline
def apply(): SplitNumber = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[SplitNumber]
}
@scala.inline
implicit class SplitNumberMutableBuilder[Self <: SplitNumber] (val x: Self) extends AnyVal {
@scala.inline
def setLength(value: Double | String): Self = StObject.set(x, "length", value.asInstanceOf[js.Any])
@scala.inline
def setLengthUndefined: Self = StObject.set(x, "length", js.undefined)
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setSplitNumber(value: Double): Self = StObject.set(x, "splitNumber", value.asInstanceOf[js.Any])
@scala.inline
def setSplitNumberUndefined: Self = StObject.set(x, "splitNumber", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Value.scala | <reponame>ngbinh/scalablyTypedDemo<filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/Value.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Value extends StObject {
/**
* Style of the item.
* `itemStyle` of start point and end point will be
* merged together.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markArea.data.1.itemStyle
*/
var itemStyle: js.UndefOr[Emphasis] = js.native
/**
* Label style of the item.
* Label style of start point and end point will be
* merged together.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markArea.data.1.label
*/
var label: js.UndefOr[FontFamily] = js.native
/**
* Name of the marker, which will display as a label.
*
*
* @see https://ecomfe.github.io/echarts-doc/public/en/option.html#series-pie.markArea.data.1.name
*/
var name: js.UndefOr[String] = js.native
/**
* value of the item, not necessary.
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markArea.data.1.value
*/
var value: js.UndefOr[Double] = js.native
/**
* x value on screen coordinate system, can be pixel
* number (like `5`), or percent value (like `'20%'`).
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markArea.data.1.x
*/
var x: js.UndefOr[Double] = js.native
/**
* y value on screen coordinate system, can be pixel
* number (like `5`), or percent value (like `'20%'`).
*
*
* @see https://echarts.apache.org/en/option.html#series-pie.markArea.data.1.y
*/
var y: js.UndefOr[Double] = js.native
}
object Value {
@scala.inline
def apply(): Value = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Value]
}
@scala.inline
implicit class ValueMutableBuilder[Self <: Value] (val x: Self) extends AnyVal {
@scala.inline
def setItemStyle(value: Emphasis): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: FontFamily): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any])
@scala.inline
def setNameUndefined: Self = StObject.set(x, "name", js.undefined)
@scala.inline
def setValue(value: Double): Self = StObject.set(x, "value", value.asInstanceOf[js.Any])
@scala.inline
def setValueUndefined: Self = StObject.set(x, "value", js.undefined)
@scala.inline
def setX(value: Double): Self = StObject.set(x, "x", value.asInstanceOf[js.Any])
@scala.inline
def setXUndefined: Self = StObject.set(x, "x", js.undefined)
@scala.inline
def setY(value: Double): Self = StObject.set(x, "y", value.asInstanceOf[js.Any])
@scala.inline
def setYUndefined: Self = StObject.set(x, "y", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/InRange.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.anon
import anduin.facades.echarts.echarts.VisualMap.RangeObject
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait InRange extends StObject {
var inRange: js.UndefOr[RangeObject] = js.native
var outOfRange: js.UndefOr[RangeObject] = js.native
}
object InRange {
@scala.inline
def apply(): InRange = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[InRange]
}
@scala.inline
implicit class InRangeMutableBuilder[Self <: InRange] (val x: Self) extends AnyVal {
@scala.inline
def setInRange(value: RangeObject): Self = StObject.set(x, "inRange", value.asInstanceOf[js.Any])
@scala.inline
def setInRangeUndefined: Self = StObject.set(x, "inRange", js.undefined)
@scala.inline
def setOutOfRange(value: RangeObject): Self = StObject.set(x, "outOfRange", value.asInstanceOf[js.Any])
@scala.inline
def setOutOfRangeUndefined: Self = StObject.set(x, "outOfRange", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/ECharts.scala | <reponame>ngbinh/scalablyTypedDemo
package anduin.facades.echarts.echarts
import anduin.facades.echarts.anon.BackgroundColor
import anduin.facades.echarts.anon.Data
import anduin.facades.echarts.anon.ExcludeComponents
import anduin.facades.echarts.echarts.EChartOption.Series
import org.scalajs.dom.raw.HTMLCanvasElement
import org.scalajs.dom.raw.HTMLDivElement
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ECharts extends StObject {
/**
* The method is used in rendering millions of data
* (e.g. rendering geo data). In these scenario, the entire size of
* data is probably up to 10 or 100 MB, even using binary format.
* So chunked load data and rendering is required. When using
* `appendData`, the graphic elements that have been rendered will
* not be cleared, but keep rendering new graphic elements.
*
* @param opts Data options.
*/
def appendData(opts: Data): Unit = js.native
/**
* Clears current instance; removes all components and charts in
* current instance.
*/
def clear(): Unit = js.native
/**
* Determine whether the given point is in the given coordinate systems or series.
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be judged, in pixel
* coordinate system.
*/
def containPixel(finder: EChartsConvertFinder, value: js.Array[_]): Boolean = js.native
def convertFromPixel(finder: EChartsConvertFinder, value: String): js.Array[_] | String = js.native
/**
* Convert a point from pixel coordinate to logical coordinate
* (e.g., in geo, cartesian, graph, ...).
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be converted.
*/
def convertFromPixel(finder: EChartsConvertFinder, value: js.Array[_]): js.Array[_] | String = js.native
/**
* Convert a point from logical coordinate (e.g., in geo, cartesian,
* graph, ...) to pixel coordinate.
*
* @param {EChartsConvertFinder} finder Indicate in which coordinate
* system conversion is performed.
* Generally, index or id or name can be used to specify
* coordinate system.
* @param {string | any[]} value The value to be converted.
*/
def convertToPixel(finder: EChartsConvertFinder, value: String): String | js.Array[_] = js.native
def convertToPixel(finder: EChartsConvertFinder, value: js.Array[_]): String | js.Array[_] = js.native
/**
* Triggers chart action, like chart switch `legendToggleSelect`,
* zoom data area `dataZoom`, show tooltip `showTip` and so on.
* See [action](https://echarts.apache.org/api.html#action) and
* [events](https://echarts.apache.org/api.html#events)
* for more information.
*
* @param payload Trigger multiple actions through `batch` attribute.
*/
def dispatchAction(payload: js.Object): Unit = js.native
/**
* Disposes instance. Once disposed, the instance can not be used again.
*/
def dispose(): Unit = js.native
/**
* Exports connected chart image; returns a base64 url; can be set to
* `src` of `Image`. Position of charts in exported image are
* related to that of the container.
*
* @param opts Options.
*/
def getConnectedDataURL(opts: ExcludeComponents): String = js.native
/**
* Exports chart image; returns a base64 URL; can be set to `src` of
* `Image`.
*
* @param opts Options.
*/
def getDataURL(opts: BackgroundColor): String = js.native
/**
* Gets DOM element of ECharts instance container.
*
* @return {HTMLCanvasElement|HTMLDivElement} DOM container.
*/
def getDom(): HTMLCanvasElement | HTMLDivElement = js.native
/**
* Gets height of ECharts instance container.
*
* @return {number} Height.
*/
def getHeight(): Double = js.native
/**
* Gets `option` object maintained in current instance, which contains
* configuration item and data merged from previous `setOption`
* operations by users, along with user interaction states.
* For example, switching of legend, zooming area of data zoom,
* and so on. Therefore, a new instance that is exactly the same
* can be recovered from this option.
*/
def getOption(): EChartOption[Series] = js.native
/**
* Gets width of ECharts instance container.
*
* @return {number} Width.
*/
def getWidth(): Double = js.native
/**
* Group name to be used in chart connection
*/
var group: String = js.native
/**
* Hides animation loading effect.
*/
def hideLoading(): Unit = js.native
/**
* Returns whether current instance has been disposed.
*
* @return {boolean} Whether has been disposed.
*/
def isDisposed(): Boolean = js.native
/**
* Unbind event-handler function.
*
* @param {string} eventName Event names are all in lower-cases,
* for example, `'click'`, `'mousemove'`, `'legendselected'`
* @param {Function} [handler] The function to be unbound could be
* passed. Otherwise, all event functions of this type will be
* unbound.
*/
def off(eventName: String): Unit = js.native
def off(eventName: String, handler: js.Function): Unit = js.native
/**
* Binds event-handling function.
* There are two kinds of events in ECharts, one of which is mouse
* events, which will be triggered when the mouse clicks certain
* element in the chart, the other kind will be triggered after
* `dispatchAction` is called. Every action has a corresponding
* event.
* If event is triggered externally by `dispatchAction`, and there
* is batch attribute in action to trigger batch action, then the
* corresponding response event parameters be in batch.
*
* @param {string} eventName Event names are all in lower-cases,
* for example, `'click'`, `'mousemove'`, `'legendselected'`
* @param {Function} handler Event-handling function, whose format
* is as following:
```js
(event: object)
```
* @param {object} [context] context of callback function, what
* `this` refers to.
*/
def on(eventName: String, handler: js.Function): Unit = js.native
def on(eventName: String, handler: js.Function, context: js.Object): Unit = js.native
/**
* Binds event-handling function.
* There are two kinds of events in ECharts, one of which is mouse
* events, which will be triggered when the mouse clicks certain
* element in the chart, the other kind will be triggered after
* `dispatchAction` is called. Every action has a corresponding
* event.
* If event is triggered externally by `dispatchAction`, and there
* is batch attribute in action to trigger batch action, then the
* corresponding response event parameters be in batch.
*
* @param {string} eventName Event names are all in lower-cases,
* for example, `'click'`, `'mousemove'`, `'legendselected'`
* @param {string | Object} query Condition for filtering, optional.
* `query` enables only call handlers on graphic elements of
* specified components. Can be `string` or `Object`.
* If `string`, the formatter can be 'mainType' or 'mainType.subType'.
* For example:
* ```ts
* chart.on('click', 'series', function () {...});
* chart.on('click', 'series.line', function () {...});
* chart.on('click', 'dataZoom', function () {...});
* chart.on('click', 'xAxis.category', function () {...});
* ```
* If `Object`, one or more properties below can be included,
* and any of them is optional.
* ```ts
* {
* <mainType>Index: number // component index
* <mainType>Name: string // component name
* <mainType>Id: string // component id
* dataIndex: number // data item index
* name: string // data item name
* dataType: string // data item type, e.g.,
* // 'node' and 'edge' in graph.
* element: string // element name in custom series
* }
* ```
* For example:
* ```ts
* chart.setOption({
* // ...
* series: [{
* name: 'uuu'
* // ...
* }]
* });
* chart.on('mouseover', {seriesName: 'uuu'}, function () {
* // When the graphic elements in the series with name 'uuu' mouse
* // overed, this method is called.
* });
* ```
* For example:
* ```ts
* chart.setOption({
* // ...
* series: [{
* type: 'graph',
* nodes: [{name: 'a', value: 10}, {name: 'b', value: 20}],
* edges: [{source: 0, target: 1}]
* }]
* });
* chart.on('click', {dataType: 'node'}, function () {
* // When the nodes of the graph clicked, this method is called.
* });
* chart.on('click', {dataType: 'edge'}, function () {
* // When the edges of the graph clicked, this method is called.
* });
* ```
* For example
* ```ts
* chart.setOption({
* // ...
* series: {
* // ...
* type: 'custom',
* renderItem: function (params, api) {
* return {
* type: 'group',
* children: [{
* type: 'circle',
* name: 'my_el',
* // ...
* }, {
* // ...
* }]
* }
* },
* data: [[12, 33]]
* }
* })
* chart.on('click', {targetName: 'my_el'}, function () {
* // When the element with name 'my_el' clicked, this method is called.
* });
* ```
* @param {Function} handler Event-handling function, whose format
* is as following:
```js
(event: object)
```
* @param {object} [context] context of callback function, what
* `this` refers to.
*/
def on(eventName: String, query: String, handler: js.Function): Unit = js.native
def on(eventName: String, query: String, handler: js.Function, context: js.Object): Unit = js.native
def on(eventName: String, query: js.Object, handler: js.Function): Unit = js.native
def on(eventName: String, query: js.Object, handler: js.Function, context: js.Object): Unit = js.native
/**
* Resizes chart, which should be called manually when container size
* changes. When `opts` is not provided, DOM size is used.
*
* @param {EChartsResizeOption} opts Specify parameters explicitly.
*/
def resize(): Unit = js.native
def resize(opts: EChartsResizeOption): Unit = js.native
/**
* Configuration item, data, universal interface, all parameters and
* data can all be modified through `setOption`. ECharts will merge
* new parameters and data, and then refresh chart.
*
* @param {EChartOption} option Configuration item and data. Please
* refer to [configuration item manual](https://echarts.apache.org/option.html)
* for more information.
* @param {boolean} [notMerge=false] Whether not to merge with previous
* `option`
* @param {boolean} [lazyUpdate=false] Whether not to update chart
* immediately
*/
def setOption(option: EChartOption[Series]): Unit = js.native
def setOption(option: EChartOption[Series], notMerge: js.UndefOr[scala.Nothing], lazyUpdate: Boolean): Unit = js.native
def setOption(option: EChartOption[Series], notMerge: Boolean): Unit = js.native
def setOption(option: EChartOption[Series], notMerge: Boolean, lazyUpdate: Boolean): Unit = js.native
def setOption(option: EChartOption[Series], opts: EChartsOptionConfig): Unit = js.native
def setOption(option: EChartsResponsiveOption): Unit = js.native
def setOption(option: EChartsResponsiveOption, notMerge: js.UndefOr[scala.Nothing], lazyUpdate: Boolean): Unit = js.native
def setOption(option: EChartsResponsiveOption, notMerge: Boolean): Unit = js.native
def setOption(option: EChartsResponsiveOption, notMerge: Boolean, lazyUpdate: Boolean): Unit = js.native
/**
* Shows loading animation. You can call this interface manually before
* data is loaded, and call `hideLoading` to hide loading animation
* after data is loaded.
*
* @param {string} [type='default']
* @param {EChartsLoadingOption} [opts]
*/
def showLoading(): Unit = js.native
def showLoading(`type`: js.UndefOr[scala.Nothing], opts: EChartsLoadingOption): Unit = js.native
def showLoading(`type`: String): Unit = js.native
def showLoading(`type`: String, opts: EChartsLoadingOption): Unit = js.native
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/zrender/anon.scala | <filename>src/main/scala/scalablytyped/anduin.facades/zrender/anon.scala<gh_stars>0
package anduin.facades.zrender
import anduin.facades.zrender.zrender.ColorStops
import anduin.facades.zrender.zrender.GlobalCoords
import anduin.facades.zrender.zrender.X
import anduin.facades.zrender.zrender.X2
import anduin.facades.zrender.zrender.Y
import anduin.facades.zrender.zrender.Y2
import anduin.facades.zrender.zrenderStrings.linear
import japgolly.scalajs.react.Callback
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object anon {
@js.native
trait AddColorStop extends StObject {
def addColorStop(offset: Double, color: String): Unit = js.native
var colorStops: ColorStops = js.native
var globalCoord: GlobalCoords = js.native
var `type`: linear = js.native
var x: X = js.native
var x2: X2 = js.native
var y: Y = js.native
var y2: Y2 = js.native
}
object AddColorStop {
@scala.inline
def apply(
addColorStop: (Double, String) => Callback,
colorStops: ColorStops,
globalCoord: GlobalCoords,
`type`: linear,
x: X,
x2: X2,
y: Y,
y2: Y2
): AddColorStop = {
val __obj = js.Dynamic.literal(addColorStop = js.Any.fromFunction2((t0: Double, t1: String) => (addColorStop(t0, t1)).runNow()), colorStops = colorStops.asInstanceOf[js.Any], globalCoord = globalCoord.asInstanceOf[js.Any], x = x.asInstanceOf[js.Any], x2 = x2.asInstanceOf[js.Any], y = y.asInstanceOf[js.Any], y2 = y2.asInstanceOf[js.Any])
__obj.updateDynamic("type")(`type`.asInstanceOf[js.Any])
__obj.asInstanceOf[AddColorStop]
}
@scala.inline
implicit class AddColorStopMutableBuilder[Self <: AddColorStop] (val x: Self) extends AnyVal {
@scala.inline
def setAddColorStop(value: (Double, String) => Callback): Self = StObject.set(x, "addColorStop", js.Any.fromFunction2((t0: Double, t1: String) => (value(t0, t1)).runNow()))
@scala.inline
def setColorStops(value: ColorStops): Self = StObject.set(x, "colorStops", value.asInstanceOf[js.Any])
@scala.inline
def setColorStopsVarargs(value: Color*): Self = StObject.set(x, "colorStops", js.Array(value :_*))
@scala.inline
def setGlobalCoord(value: GlobalCoords): Self = StObject.set(x, "globalCoord", value.asInstanceOf[js.Any])
@scala.inline
def setType(value: linear): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
@scala.inline
def setX(value: X): Self = StObject.set(x, "x", value.asInstanceOf[js.Any])
@scala.inline
def setX2(value: X2): Self = StObject.set(x, "x2", value.asInstanceOf[js.Any])
@scala.inline
def setY(value: Y): Self = StObject.set(x, "y", value.asInstanceOf[js.Any])
@scala.inline
def setY2(value: Y2): Self = StObject.set(x, "y2", value.asInstanceOf[js.Any])
}
}
@js.native
trait Color extends StObject {
var color: String = js.native
var offset: Double = js.native
}
object Color {
@scala.inline
def apply(color: String, offset: Double): Color = {
val __obj = js.Dynamic.literal(color = color.asInstanceOf[js.Any], offset = offset.asInstanceOf[js.Any])
__obj.asInstanceOf[Color]
}
@scala.inline
implicit class ColorMutableBuilder[Self <: Color] (val x: Self) extends AnyVal {
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setOffset(value: Double): Self = StObject.set(x, "offset", value.asInstanceOf[js.Any])
}
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Cpx1.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Cpx1 extends StObject {
/**
* x of control point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpx1
*/
var cpx1: js.UndefOr[Double] = js.native
/**
* x of the second control point.
* If specified, cubic bezier is used.
*
* If both `cpx2` and `cpy2` are not set, quatratic
* bezier is used.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpx2
*/
var cpx2: js.UndefOr[Double] = js.native
/**
* y of control point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpy1
*/
var cpy1: js.UndefOr[Double] = js.native
/**
* y of the second control point.
* If specified, cubic bezier is used.
*
* If both `cpx2` and `cpy2` are not set, quatratic
* bezier is used.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpy2
*/
var cpy2: js.UndefOr[Double] = js.native
/**
* Specify the percentage of drawing, useful in animation.
*
* Value range: \[0, 1\].
*
*
* @default
* 1
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.percent
*/
var percent: js.UndefOr[Double] = js.native
/**
* x value of the start point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.x1
*/
var x1: js.UndefOr[Double] = js.native
/**
* x value of the end point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.x2
*/
var x2: js.UndefOr[Double] = js.native
/**
* y value of the start point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.y1
*/
var y1: js.UndefOr[Double] = js.native
/**
* y value of the end point.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.y2
*/
var y2: js.UndefOr[Double] = js.native
}
object Cpx1 {
@scala.inline
def apply(): Cpx1 = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Cpx1]
}
@scala.inline
implicit class Cpx1MutableBuilder[Self <: Cpx1] (val x: Self) extends AnyVal {
@scala.inline
def setCpx1(value: Double): Self = StObject.set(x, "cpx1", value.asInstanceOf[js.Any])
@scala.inline
def setCpx1Undefined: Self = StObject.set(x, "cpx1", js.undefined)
@scala.inline
def setCpx2(value: Double): Self = StObject.set(x, "cpx2", value.asInstanceOf[js.Any])
@scala.inline
def setCpx2Undefined: Self = StObject.set(x, "cpx2", js.undefined)
@scala.inline
def setCpy1(value: Double): Self = StObject.set(x, "cpy1", value.asInstanceOf[js.Any])
@scala.inline
def setCpy1Undefined: Self = StObject.set(x, "cpy1", js.undefined)
@scala.inline
def setCpy2(value: Double): Self = StObject.set(x, "cpy2", value.asInstanceOf[js.Any])
@scala.inline
def setCpy2Undefined: Self = StObject.set(x, "cpy2", js.undefined)
@scala.inline
def setPercent(value: Double): Self = StObject.set(x, "percent", value.asInstanceOf[js.Any])
@scala.inline
def setPercentUndefined: Self = StObject.set(x, "percent", js.undefined)
@scala.inline
def setX1(value: Double): Self = StObject.set(x, "x1", value.asInstanceOf[js.Any])
@scala.inline
def setX1Undefined: Self = StObject.set(x, "x1", js.undefined)
@scala.inline
def setX2(value: Double): Self = StObject.set(x, "x2", value.asInstanceOf[js.Any])
@scala.inline
def setX2Undefined: Self = StObject.set(x, "x2", js.undefined)
@scala.inline
def setY1(value: Double): Self = StObject.set(x, "y1", value.asInstanceOf[js.Any])
@scala.inline
def setY1Undefined: Self = StObject.set(x, "y1", js.undefined)
@scala.inline
def setY2(value: Double): Self = StObject.set(x, "y2", value.asInstanceOf[js.Any])
@scala.inline
def setY2Undefined: Self = StObject.set(x, "y2", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/echarts/EChartsConvertFinder.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/echarts/EChartsConvertFinder.scala<gh_stars>0
package anduin.facades.echarts.echarts
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait EChartsConvertFinder extends StObject {
var geoId: js.UndefOr[String] = js.native
var geoIndex: js.UndefOr[Double] = js.native
var geoName: js.UndefOr[String] = js.native
var gridId: js.UndefOr[String] = js.native
var gridIndex: js.UndefOr[Double] = js.native
var gridName: js.UndefOr[String] = js.native
var seriesId: js.UndefOr[String] = js.native
var seriesIndex: js.UndefOr[Double] = js.native
var seriesName: js.UndefOr[String] = js.native
var xAxisId: js.UndefOr[String] = js.native
var xAxisIndex: js.UndefOr[Double] = js.native
var xAxisName: js.UndefOr[String] = js.native
var yAxisId: js.UndefOr[String] = js.native
var yAxisIndex: js.UndefOr[Double] = js.native
var yAxisName: js.UndefOr[String] = js.native
}
object EChartsConvertFinder {
@scala.inline
def apply(): EChartsConvertFinder = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[EChartsConvertFinder]
}
@scala.inline
implicit class EChartsConvertFinderMutableBuilder[Self <: EChartsConvertFinder] (val x: Self) extends AnyVal {
@scala.inline
def setGeoId(value: String): Self = StObject.set(x, "geoId", value.asInstanceOf[js.Any])
@scala.inline
def setGeoIdUndefined: Self = StObject.set(x, "geoId", js.undefined)
@scala.inline
def setGeoIndex(value: Double): Self = StObject.set(x, "geoIndex", value.asInstanceOf[js.Any])
@scala.inline
def setGeoIndexUndefined: Self = StObject.set(x, "geoIndex", js.undefined)
@scala.inline
def setGeoName(value: String): Self = StObject.set(x, "geoName", value.asInstanceOf[js.Any])
@scala.inline
def setGeoNameUndefined: Self = StObject.set(x, "geoName", js.undefined)
@scala.inline
def setGridId(value: String): Self = StObject.set(x, "gridId", value.asInstanceOf[js.Any])
@scala.inline
def setGridIdUndefined: Self = StObject.set(x, "gridId", js.undefined)
@scala.inline
def setGridIndex(value: Double): Self = StObject.set(x, "gridIndex", value.asInstanceOf[js.Any])
@scala.inline
def setGridIndexUndefined: Self = StObject.set(x, "gridIndex", js.undefined)
@scala.inline
def setGridName(value: String): Self = StObject.set(x, "gridName", value.asInstanceOf[js.Any])
@scala.inline
def setGridNameUndefined: Self = StObject.set(x, "gridName", js.undefined)
@scala.inline
def setSeriesId(value: String): Self = StObject.set(x, "seriesId", value.asInstanceOf[js.Any])
@scala.inline
def setSeriesIdUndefined: Self = StObject.set(x, "seriesId", js.undefined)
@scala.inline
def setSeriesIndex(value: Double): Self = StObject.set(x, "seriesIndex", value.asInstanceOf[js.Any])
@scala.inline
def setSeriesIndexUndefined: Self = StObject.set(x, "seriesIndex", js.undefined)
@scala.inline
def setSeriesName(value: String): Self = StObject.set(x, "seriesName", value.asInstanceOf[js.Any])
@scala.inline
def setSeriesNameUndefined: Self = StObject.set(x, "seriesName", js.undefined)
@scala.inline
def setXAxisId(value: String): Self = StObject.set(x, "xAxisId", value.asInstanceOf[js.Any])
@scala.inline
def setXAxisIdUndefined: Self = StObject.set(x, "xAxisId", js.undefined)
@scala.inline
def setXAxisIndex(value: Double): Self = StObject.set(x, "xAxisIndex", value.asInstanceOf[js.Any])
@scala.inline
def setXAxisIndexUndefined: Self = StObject.set(x, "xAxisIndex", js.undefined)
@scala.inline
def setXAxisName(value: String): Self = StObject.set(x, "xAxisName", value.asInstanceOf[js.Any])
@scala.inline
def setXAxisNameUndefined: Self = StObject.set(x, "xAxisName", js.undefined)
@scala.inline
def setYAxisId(value: String): Self = StObject.set(x, "yAxisId", value.asInstanceOf[js.Any])
@scala.inline
def setYAxisIdUndefined: Self = StObject.set(x, "yAxisId", js.undefined)
@scala.inline
def setYAxisIndex(value: Double): Self = StObject.set(x, "yAxisIndex", value.asInstanceOf[js.Any])
@scala.inline
def setYAxisIndexUndefined: Self = StObject.set(x, "yAxisIndex", js.undefined)
@scala.inline
def setYAxisName(value: String): Self = StObject.set(x, "yAxisName", value.asInstanceOf[js.Any])
@scala.inline
def setYAxisNameUndefined: Self = StObject.set(x, "yAxisName", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/Cx.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait Cx extends StObject {
/**
* The x value of the center of the element in the coordinate
* system of its parent.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.cx
*/
var cx: js.UndefOr[Double] = js.native
/**
* The y value of the center of the element in the coordinate
* system of its parent.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.cy
*/
var cy: js.UndefOr[Double] = js.native
/**
* Outside radius.
*
*
* @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.r
*/
var r: js.UndefOr[Double] = js.native
}
object Cx {
@scala.inline
def apply(): Cx = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[Cx]
}
@scala.inline
implicit class CxMutableBuilder[Self <: Cx] (val x: Self) extends AnyVal {
@scala.inline
def setCx(value: Double): Self = StObject.set(x, "cx", value.asInstanceOf[js.Any])
@scala.inline
def setCxUndefined: Self = StObject.set(x, "cx", js.undefined)
@scala.inline
def setCy(value: Double): Self = StObject.set(x, "cy", value.asInstanceOf[js.Any])
@scala.inline
def setCyUndefined: Self = StObject.set(x, "cy", js.undefined)
@scala.inline
def setR(value: Double): Self = StObject.set(x, "r", value.asInstanceOf[js.Any])
@scala.inline
def setRUndefined: Self = StObject.set(x, "r", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/BorderColor.scala | package anduin.facades.echarts.anon
import anduin.facades.echarts.echartsStrings.dashed
import anduin.facades.echarts.echartsStrings.dotted
import anduin.facades.echarts.echartsStrings.solid
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BorderColor extends StObject {
var borderColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
var borderType: js.UndefOr[solid | dashed | dotted] = js.native
var borderWidth: js.UndefOr[Double] = js.native
var color: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
var opacity: js.UndefOr[Double] = js.native
var shadowBlur: js.UndefOr[Double] = js.native
var shadowColor: js.UndefOr[anduin.facades.echarts.echarts.EChartOption.Color] = js.native
var shadowOffsetX: js.UndefOr[Double] = js.native
var shadowOffsetY: js.UndefOr[Double] = js.native
}
object BorderColor {
@scala.inline
def apply(): BorderColor = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[BorderColor]
}
@scala.inline
implicit class BorderColorMutableBuilder[Self <: BorderColor] (val x: Self) extends AnyVal {
@scala.inline
def setBorderColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderType(value: solid | dashed | dotted): Self = StObject.set(x, "borderType", value.asInstanceOf[js.Any])
@scala.inline
def setBorderTypeUndefined: Self = StObject.set(x, "borderType", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setOpacity(value: Double): Self = StObject.set(x, "opacity", value.asInstanceOf[js.Any])
@scala.inline
def setOpacityUndefined: Self = StObject.set(x, "opacity", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: anduin.facades.echarts.echarts.EChartOption.Color): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/UpperLabel.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait UpperLabel extends StObject {
/**
* @see https://echarts.apache.org/en/option.html#series-treemap.data.emphasis.itemStyle
*/
var itemStyle: js.UndefOr[`25`] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-treemap.data.emphasis.label
*/
var label: js.UndefOr[Ellipsis] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-treemap.data.emphasis.upperLabel
*/
var upperLabel: js.UndefOr[Ellipsis] = js.native
}
object UpperLabel {
@scala.inline
def apply(): UpperLabel = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[UpperLabel]
}
@scala.inline
implicit class UpperLabelMutableBuilder[Self <: UpperLabel] (val x: Self) extends AnyVal {
@scala.inline
def setItemStyle(value: `25`): Self = StObject.set(x, "itemStyle", value.asInstanceOf[js.Any])
@scala.inline
def setItemStyleUndefined: Self = StObject.set(x, "itemStyle", js.undefined)
@scala.inline
def setLabel(value: Ellipsis): Self = StObject.set(x, "label", value.asInstanceOf[js.Any])
@scala.inline
def setLabelUndefined: Self = StObject.set(x, "label", js.undefined)
@scala.inline
def setUpperLabel(value: Ellipsis): Self = StObject.set(x, "upperLabel", value.asInstanceOf[js.Any])
@scala.inline
def setUpperLabelUndefined: Self = StObject.set(x, "upperLabel", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/12.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/12.scala
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait `12` extends StObject {
/**
* Data of the starting point.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markLine.data.0
*/
var `0`: js.UndefOr[SymbolSize] = js.native
/**
* Data of the ending point.
*
*
* @see https://echarts.apache.org/en/option.html#series-map.markLine.data.1
*/
var `1`: js.UndefOr[SymbolSize] = js.native
}
object `12` {
@scala.inline
def apply(): `12` = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[`12`]
}
@scala.inline
implicit class `12MutableBuilder`[Self <: `12`] (val x: Self) extends AnyVal {
@scala.inline
def set0(value: SymbolSize): Self = StObject.set(x, "0", value.asInstanceOf[js.Any])
@scala.inline
def set0Undefined: Self = StObject.set(x, "0", js.undefined)
@scala.inline
def set1(value: SymbolSize): Self = StObject.set(x, "1", value.asInstanceOf[js.Any])
@scala.inline
def set1Undefined: Self = StObject.set(x, "1", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | build.sbt | lazy val webMonaco = (project in file("."))
.enablePlugins(ScalaJSPlugin, ScalaJSBundlerPlugin, ScalablyTypedConverterGenSourcePlugin)
.settings(
scalaVersion := "2.13.4",
name := "web-monaco",
stSourceGenMode := SourceGenMode.Manual((sourceDirectory in Compile).value/ "scala" / "scalablytyped"),
libraryDependencies ++= Seq(
"com.olvind" %%% "scalablytyped-runtime" % "2.4.0"
),
Compile / npmDependencies ++= Seq(
"echarts" -> "5.0.2",
"@types/echarts" -> "4.9.3"
),
scalacOptions += s"-Wconf:cat=w-flag-dead-code&src=${(sourceDirectory in Compile).value}/scala/scalablytyped/" +
s".*:is,cat=unused&src=${(sourceDirectory in Compile).value}/scala/scalablytyped/.*:is",
stFlavour := Flavour.Japgolly,
stMinimize := Selection.AllExcept("echarts"),
stIgnore ++= List("react", "react-dom"),
stOutputPackage := "anduin.facades"
)
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/LengthLineStyle.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait LengthLineStyle extends StObject {
/**
* The length of split line, can be a pecentage value relative
* to radius.
*
*
* @default
* 30
* @see https://echarts.apache.org/en/option.html#series-gauge.splitLine.length
*/
var length: js.UndefOr[Double | String] = js.native
/**
* @see https://echarts.apache.org/en/option.html#series-gauge.splitLine.lineStyle
*/
var lineStyle: js.UndefOr[ShadowBlur] = js.native
/**
* Whether to show the split line.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-gauge.splitLine.show
*/
var show: js.UndefOr[Boolean] = js.native
}
object LengthLineStyle {
@scala.inline
def apply(): LengthLineStyle = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[LengthLineStyle]
}
@scala.inline
implicit class LengthLineStyleMutableBuilder[Self <: LengthLineStyle] (val x: Self) extends AnyVal {
@scala.inline
def setLength(value: Double | String): Self = StObject.set(x, "length", value.asInstanceOf[js.Any])
@scala.inline
def setLengthUndefined: Self = StObject.set(x, "length", js.undefined)
@scala.inline
def setLineStyle(value: ShadowBlur): Self = StObject.set(x, "lineStyle", value.asInstanceOf[js.Any])
@scala.inline
def setLineStyleUndefined: Self = StObject.set(x, "lineStyle", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/LengthShow.scala | <filename>src/main/scala/scalablytyped/anduin.facades/echarts/anon/LengthShow.scala<gh_stars>0
package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait LengthShow extends StObject {
/**
* The length of pointer which could be absolute value and also
* the percentage relative to
* [radius](https://echarts.apache.org/en/option.html#series-gauge.radius)
* .
*
*
* @default
* '80%'
* @see https://echarts.apache.org/en/option.html#series-gauge.pointer.length
*/
var length: js.UndefOr[Double | String] = js.native
/**
* Whether to show the pointer.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-gauge.pointer.show
*/
var show: js.UndefOr[Boolean] = js.native
/**
* The width of pointer.
*
*
* @default
* 8
* @see https://echarts.apache.org/en/option.html#series-gauge.pointer.width
*/
var width: js.UndefOr[Double] = js.native
}
object LengthShow {
@scala.inline
def apply(): LengthShow = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[LengthShow]
}
@scala.inline
implicit class LengthShowMutableBuilder[Self <: LengthShow] (val x: Self) extends AnyVal {
@scala.inline
def setLength(value: Double | String): Self = StObject.set(x, "length", value.asInstanceOf[js.Any])
@scala.inline
def setLengthUndefined: Self = StObject.set(x, "length", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
}
}
|
ngbinh/scalablyTypedDemo | src/main/scala/scalablytyped/anduin.facades/echarts/anon/OffsetCenter.scala | package anduin.facades.echarts.anon
import org.scalablytyped.runtime.StringDictionary
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait OffsetCenter extends StObject {
/**
* Background color of the text fregment.
*
* Can be color string, like `'#123234'`, `'red'`, `rgba(0,23,11,0.3)'`.
*
* Or image can be used, for example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-gauge.gauge.title)
*
* `width` or `height` can be specified when using background
* image, or auto adapted by default.
*
*
* @default
* "transparent"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.backgroundColor
*/
var backgroundColor: js.UndefOr[js.Object | String] = js.native
/**
* Border color of the text fregment.
*
*
* @default
* "transparent"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.borderColor
*/
var borderColor: js.UndefOr[String] = js.native
/**
* Border radius of the text fregment.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.borderRadius
*/
var borderRadius: js.UndefOr[Double] = js.native
/**
* Border width of the text fregment.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.borderWidth
*/
var borderWidth: js.UndefOr[Double] = js.native
/**
* text color.
*
*
* @default
* '#333'
* @see https://echarts.apache.org/en/option.html#series-gauge.title.color
*/
var color: js.UndefOr[String] = js.native
/**
* font family
*
* Can also be 'serif' , 'monospace', ...
*
*
* @default
* "sans-serif"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.fontFamily
*/
var fontFamily: js.UndefOr[String] = js.native
/**
* font size
*
*
* @default
* 15
* @see https://echarts.apache.org/en/option.html#series-gauge.title.fontSize
*/
var fontSize: js.UndefOr[Double] = js.native
/**
* font style
*
* Options are:
*
* + `'normal'`
* + `'italic'`
* + `'oblique'`
*
*
* @default
* "normal"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.fontStyle
*/
var fontStyle: js.UndefOr[String] = js.native
/**
* font thick weight
*
* Options are:
*
* + `'normal'`
* + `'bold'`
* + `'bolder'`
* + `'lighter'`
* + 100 | 200 | 300 | 400...
*
*
* @default
* "normal"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.fontWeight
*/
var fontWeight: js.UndefOr[String | Double] = js.native
/**
* Height of the text block.
* It is the width of the text by default.
* You may want to use it in some cases like using background
* image (see `backgroundColor`).
*
* Notice, `width` and `height` specifies the width and height
* of the content, without `padding`.
*
* Notice, `width` and `height` only work when `rich` specified.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.height
*/
var height: js.UndefOr[Double | String] = js.native
/**
* Line height of the text fregment.
*
* If `lineHeight` is not set in `rich`, `lineHeight` in parent
* level will be used. For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-gauge.gauge.title)
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.lineHeight
*/
var lineHeight: js.UndefOr[Double] = js.native
/**
* The offset position relative to the center of gauge chart.
* The first item of array is the horizontal offset; the second
* item of array is the vertical offset.
* It could be absolute value and also the percentage relative
* to the radius of gauge chart.
*
*
* @default
* [0, '-40%']
* @see https://echarts.apache.org/en/option.html#series-gauge.title.offsetCenter
*/
var offsetCenter: js.UndefOr[js.Array[_]] = js.native
/**
* Padding of the text fregment, for example:
*
* + `padding: [3, 4, 5, 6]`: represents padding of `[top, right,
* bottom, left]`.
* + `padding: 4`: represents `padding: [4, 4, 4, 4]`.
* + `padding: [3, 4]`: represents `padding: [3, 4, 3, 4]`.
*
* Notice, `width` and `height` specifies the width and height
* of the content, without `padding`.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.padding
*/
var padding: js.UndefOr[js.Array[_] | Double] = js.native
/**
* "Rich text styles" can be defined in this `rich` property.
* For example:
*
* [see doc](https://echarts.apache.org/en/option.html#series-gauge.gauge.title)
*
* For more details, see
* [Rich Text](https://echarts.apache.org/en/option.htmltutorial.html#Rich%20Text)
* please.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.rich
*/
var rich: js.UndefOr[
/**
* @see https://echarts.apache.org/en/option.html#series-gauge.title.rich.%3Cuser%20defined%20style%20name%3E
*/
StringDictionary[Align]
] = js.native
/**
* Show blur of the text block.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.shadowBlur
*/
var shadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color of the text block.
*
*
* @default
* "transparent"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.shadowColor
*/
var shadowColor: js.UndefOr[String] = js.native
/**
* Shadow X offset of the text block.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.shadowOffsetX
*/
var shadowOffsetX: js.UndefOr[Double] = js.native
/**
* Shadow Y offset of the text block.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.shadowOffsetY
*/
var shadowOffsetY: js.UndefOr[Double] = js.native
/**
* Whether to show the title.
*
*
* @default
* "true"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.show
*/
var show: js.UndefOr[Boolean] = js.native
/**
* Storke color of the text.
*
*
* @default
* "transparent"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textBorderColor
*/
var textBorderColor: js.UndefOr[String] = js.native
/**
* Storke line width of the text.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textBorderWidth
*/
var textBorderWidth: js.UndefOr[Double] = js.native
/**
* Shadow blue of the text itself.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textShadowBlur
*/
var textShadowBlur: js.UndefOr[Double] = js.native
/**
* Shadow color of the text itself.
*
*
* @default
* "transparent"
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textShadowColor
*/
var textShadowColor: js.UndefOr[String] = js.native
/**
* Shadow X offset of the text itself.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textShadowOffsetX
*/
var textShadowOffsetX: js.UndefOr[Double] = js.native
/**
* Shadow Y offset of the text itself.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.textShadowOffsetY
*/
var textShadowOffsetY: js.UndefOr[Double] = js.native
/**
* Width of the text block.
* It is the width of the text by default.
* In most cases, there is no need to specify it.
* You may want to use it in some cases like make simple table
* or using background image (see `backgroundColor`).
*
* Notice, `width` and `height` specifies the width and height
* of the content, without `padding`.
*
* `width` can also be percent string, like `'100%'`, which
* represents the percent of `contentWidth` (that is, the width
* without `padding`) of its container box.
* It is based on `contentWidth` because that each text fregment
* is layout based on the `content box`, where it makes no sense
* that calculating width based on `outerWith` in prectice.
*
* Notice, `width` and `height` only work when `rich` specified.
*
*
* @see https://echarts.apache.org/en/option.html#series-gauge.title.width
*/
var width: js.UndefOr[Double | String] = js.native
}
object OffsetCenter {
@scala.inline
def apply(): OffsetCenter = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[OffsetCenter]
}
@scala.inline
implicit class OffsetCenterMutableBuilder[Self <: OffsetCenter] (val x: Self) extends AnyVal {
@scala.inline
def setBackgroundColor(value: js.Object | String): Self = StObject.set(x, "backgroundColor", value.asInstanceOf[js.Any])
@scala.inline
def setBackgroundColorUndefined: Self = StObject.set(x, "backgroundColor", js.undefined)
@scala.inline
def setBorderColor(value: String): Self = StObject.set(x, "borderColor", value.asInstanceOf[js.Any])
@scala.inline
def setBorderColorUndefined: Self = StObject.set(x, "borderColor", js.undefined)
@scala.inline
def setBorderRadius(value: Double): Self = StObject.set(x, "borderRadius", value.asInstanceOf[js.Any])
@scala.inline
def setBorderRadiusUndefined: Self = StObject.set(x, "borderRadius", js.undefined)
@scala.inline
def setBorderWidth(value: Double): Self = StObject.set(x, "borderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setBorderWidthUndefined: Self = StObject.set(x, "borderWidth", js.undefined)
@scala.inline
def setColor(value: String): Self = StObject.set(x, "color", value.asInstanceOf[js.Any])
@scala.inline
def setColorUndefined: Self = StObject.set(x, "color", js.undefined)
@scala.inline
def setFontFamily(value: String): Self = StObject.set(x, "fontFamily", value.asInstanceOf[js.Any])
@scala.inline
def setFontFamilyUndefined: Self = StObject.set(x, "fontFamily", js.undefined)
@scala.inline
def setFontSize(value: Double): Self = StObject.set(x, "fontSize", value.asInstanceOf[js.Any])
@scala.inline
def setFontSizeUndefined: Self = StObject.set(x, "fontSize", js.undefined)
@scala.inline
def setFontStyle(value: String): Self = StObject.set(x, "fontStyle", value.asInstanceOf[js.Any])
@scala.inline
def setFontStyleUndefined: Self = StObject.set(x, "fontStyle", js.undefined)
@scala.inline
def setFontWeight(value: String | Double): Self = StObject.set(x, "fontWeight", value.asInstanceOf[js.Any])
@scala.inline
def setFontWeightUndefined: Self = StObject.set(x, "fontWeight", js.undefined)
@scala.inline
def setHeight(value: Double | String): Self = StObject.set(x, "height", value.asInstanceOf[js.Any])
@scala.inline
def setHeightUndefined: Self = StObject.set(x, "height", js.undefined)
@scala.inline
def setLineHeight(value: Double): Self = StObject.set(x, "lineHeight", value.asInstanceOf[js.Any])
@scala.inline
def setLineHeightUndefined: Self = StObject.set(x, "lineHeight", js.undefined)
@scala.inline
def setOffsetCenter(value: js.Array[_]): Self = StObject.set(x, "offsetCenter", value.asInstanceOf[js.Any])
@scala.inline
def setOffsetCenterUndefined: Self = StObject.set(x, "offsetCenter", js.undefined)
@scala.inline
def setOffsetCenterVarargs(value: js.Any*): Self = StObject.set(x, "offsetCenter", js.Array(value :_*))
@scala.inline
def setPadding(value: js.Array[_] | Double): Self = StObject.set(x, "padding", value.asInstanceOf[js.Any])
@scala.inline
def setPaddingUndefined: Self = StObject.set(x, "padding", js.undefined)
@scala.inline
def setPaddingVarargs(value: js.Any*): Self = StObject.set(x, "padding", js.Array(value :_*))
@scala.inline
def setRich(
value: /**
* @see https://echarts.apache.org/en/option.html#series-gauge.title.rich.%3Cuser%20defined%20style%20name%3E
*/
StringDictionary[Align]
): Self = StObject.set(x, "rich", value.asInstanceOf[js.Any])
@scala.inline
def setRichUndefined: Self = StObject.set(x, "rich", js.undefined)
@scala.inline
def setShadowBlur(value: Double): Self = StObject.set(x, "shadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setShadowBlurUndefined: Self = StObject.set(x, "shadowBlur", js.undefined)
@scala.inline
def setShadowColor(value: String): Self = StObject.set(x, "shadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setShadowColorUndefined: Self = StObject.set(x, "shadowColor", js.undefined)
@scala.inline
def setShadowOffsetX(value: Double): Self = StObject.set(x, "shadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetXUndefined: Self = StObject.set(x, "shadowOffsetX", js.undefined)
@scala.inline
def setShadowOffsetY(value: Double): Self = StObject.set(x, "shadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setShadowOffsetYUndefined: Self = StObject.set(x, "shadowOffsetY", js.undefined)
@scala.inline
def setShow(value: Boolean): Self = StObject.set(x, "show", value.asInstanceOf[js.Any])
@scala.inline
def setShowUndefined: Self = StObject.set(x, "show", js.undefined)
@scala.inline
def setTextBorderColor(value: String): Self = StObject.set(x, "textBorderColor", value.asInstanceOf[js.Any])
@scala.inline
def setTextBorderColorUndefined: Self = StObject.set(x, "textBorderColor", js.undefined)
@scala.inline
def setTextBorderWidth(value: Double): Self = StObject.set(x, "textBorderWidth", value.asInstanceOf[js.Any])
@scala.inline
def setTextBorderWidthUndefined: Self = StObject.set(x, "textBorderWidth", js.undefined)
@scala.inline
def setTextShadowBlur(value: Double): Self = StObject.set(x, "textShadowBlur", value.asInstanceOf[js.Any])
@scala.inline
def setTextShadowBlurUndefined: Self = StObject.set(x, "textShadowBlur", js.undefined)
@scala.inline
def setTextShadowColor(value: String): Self = StObject.set(x, "textShadowColor", value.asInstanceOf[js.Any])
@scala.inline
def setTextShadowColorUndefined: Self = StObject.set(x, "textShadowColor", js.undefined)
@scala.inline
def setTextShadowOffsetX(value: Double): Self = StObject.set(x, "textShadowOffsetX", value.asInstanceOf[js.Any])
@scala.inline
def setTextShadowOffsetXUndefined: Self = StObject.set(x, "textShadowOffsetX", js.undefined)
@scala.inline
def setTextShadowOffsetY(value: Double): Self = StObject.set(x, "textShadowOffsetY", value.asInstanceOf[js.Any])
@scala.inline
def setTextShadowOffsetYUndefined: Self = StObject.set(x, "textShadowOffsetY", js.undefined)
@scala.inline
def setWidth(value: Double | String): Self = StObject.set(x, "width", value.asInstanceOf[js.Any])
@scala.inline
def setWidthUndefined: Self = StObject.set(x, "width", js.undefined)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.