Skip to content

Instantly share code, notes, and snippets.

@valdo404
Created June 23, 2015 18:23
Show Gist options
  • Save valdo404/3eed2bca7cd07bd385fd to your computer and use it in GitHub Desktop.
Save valdo404/3eed2bca7cd07bd385fd to your computer and use it in GitHub Desktop.
extreme
package main
import akka.actor.ActorSystem
import spray.json.DefaultJsonProtocol
import spray.json._
import spray.routing.SimpleRoutingApp
case class Order(prices: Seq[Float], quantities: Seq[Int], country: String, reduction: String)
object Server extends App with SimpleRoutingApp {
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val colorFormat = jsonFormat4(Order)
}
import MyJsonProtocol.colorFormat
implicit val system = ActorSystem("my-system")
type ProcessOrder = Order => Option[Float]
val address = "192.168.20.60"
val port: Int = 9000
val orderRoute = "order"
val feedbackRoute = "feedback"
startServer(interface = address, port = port) {
path(orderRoute) {
post {
entity(as[String]) {
order =>
complete {
val entity: Order = order.parseJson.convertTo[Order]
if(entity.reduction!="STANDARD")
"""{}"""
else {
val total = BillCalculator.compute(entity)
"""{
"total": $total
}""".stripMargin
}
}
}
}
} ~
path("feedback") {
post {
entity(as[String]) {
feedback =>
complete {
println(feedback)
""
}
}
}
}
}
}
object BillCalculator {
val STANDARD = "STANDARD"
val HALF_PRICE = "HALF_PRICE"
val taxes = Map(("DE", 20), ("UK", 21), ("FR", 20), ("IT", 25), ("ES", 19),
("PL", 21), ("RO", 20), ("NL", 20), ("BE", 24), ("EL", 20),
("CZ", 19), ("PT", 23), ("HU", 27), ("SE", 23), ("AT", 22),
("BG", 21), ("DK", 21), ("FI", 17), ("SK", 18), ("IE", 21),
("HR", 23), ("LT", 23), ("SI", 24), ("LV", 20), ("EE", 22),
("CY", 21), ("LU", 25), ("MT", 20))
def compute(order: Order): Float = {
def compute(tuple: ((Int, Float))): Float = tuple._1 * tuple._2 * (taxes.getOrElse(order.country, 0)/100)
(order.quantities zip order.prices).map(compute).sum
}
def reduction(price: Float, code: String): Float = {
code match {
case STANDARD => standard(price)
case HALF_PRICE => halfPrice(price)
}
}
def standard(price: Float): Float = price match {
case price: Float if price>=50000 => price * 15/100
case price: Float if price>=10000 => price * 10/100
case price: Float if price>=7000 => price * 7/100
case price: Float if price>=5000 => price * 5/100
case price: Float if price>=1000 => price * 3/100
}
def halfPrice(price: Float): Float = price / 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment