Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
larousso committed Oct 10, 2024
1 parent 0b3ed63 commit 381224a
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 26 deletions.
26 changes: 25 additions & 1 deletion nio-server/app/models/ConsentFact.scala
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,15 @@ case class Consent(key: String, label: String, checked: Boolean, expiredAt: Opti
<checked>
{checked}
</checked>
{expiredAt.map(l => <expiredAt>{l.format(DateUtils.utcDateFormatter)}</expiredAt>)}
</consent>.clean()
}

object Consent {
implicit val consentFormats: OFormat[Consent] = Json.format[Consent]
implicit val consentFormats: OFormat[Consent] = {
implicit val dateFormat: Format[LocalDateTime] = DateUtils.utcDateTimeFormats
Json.format[Consent]
}

implicit val xmlRead: XMLRead[Consent] =
(xml: NodeSeq, path: Option[String]) => {
Expand Down Expand Up @@ -444,6 +448,26 @@ case class ConsentFact(
}.get
}
</consentFact>.clean()

case class KeyPermissionGroup(group: String, permission: String)

def setUpValidityPeriods(organisation: Organisation): ConsentFact = {
val indexedKeys: Seq[(KeyPermissionGroup, Permission)] = for {
g <- organisation.groups
p <- g.permissions
} yield (KeyPermissionGroup(g.key, p.key), p)
val indexed: Map[KeyPermissionGroup, Seq[(KeyPermissionGroup, Permission)]] = indexedKeys.groupBy(_._1)
this.copy(groups = this.groups.map( group =>
group.copy(
consents = group.consents.map ( consent =>
consent.copy(expiredAt = indexed.get(KeyPermissionGroup(group.key, consent.key))
.flatMap(_.headOption)
.flatMap(_._2.getValidityPeriod)
)
)
)
))
}
}

object ConsentFact extends ReadableEntity[ConsentFact] {
Expand Down
4 changes: 2 additions & 2 deletions nio-server/app/models/Permission.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import play.api.libs.json._
import play.api.libs.json.Reads._
import utils.Result.AppErrors

import java.time.{LocalDateTime, ZoneId}
import java.time.{Clock, LocalDateTime, ZoneId}
import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.util.{Failure, Success, Try}
import scala.xml.{Elem, NodeSeq}
Expand Down Expand Up @@ -57,7 +57,7 @@ object PermissionType {

case class Permission(key: String, label: String, `type`: PermissionType = OptIn, validityPeriod: Option[FiniteDuration] = None) {

def getValidityPeriod: Option[LocalDateTime] = validityPeriod.map(fd => LocalDateTime.now(ZoneId.systemDefault()).plusMinutes(fd.toMinutes))
def getValidityPeriod: Option[LocalDateTime] = validityPeriod.map(fd => LocalDateTime.now(Clock.systemUTC()).plusMinutes(fd.toMinutes).withNano(0))

def checkDefault(): Boolean = `type` match {
case OptIn => false
Expand Down
13 changes: 7 additions & 6 deletions nio-server/app/service/ConsentManagerService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,17 @@ class ConsentManagerService(
author: String,
metadata: Option[Seq[(String, String)]],
organisation: Organisation,
consentFact: ConsentFact,
consentFactInput: ConsentFact,
maybeLastConsentFact: Option[ConsentFact] = None,
command: JsValue
): IO[AppErrorWithStatus, ConsentFact] =
for {
_ <- IO.fromEither(organisation.isValidWith(consentFact, maybeLastConsentFact)).mapError(m => AppErrorWithStatus(m))
organisationKey: String = organisation.key
userId: String = consentFact.userId
_ <- validateOffersStructures(tenant, organisationKey, userId, consentFact.offers).doOnError{ e => NioLogger.error(s"validate offers structure $e") }
res <- maybeLastConsentFact match {
_ <- IO.fromEither(organisation.isValidWith(consentFactInput, maybeLastConsentFact)).mapError(m => AppErrorWithStatus(m))
consentFact: ConsentFact = consentFactInput.setUpValidityPeriods(organisation)
organisationKey: String = organisation.key
userId: String = consentFact.userId
_ <- validateOffersStructures(tenant, organisationKey, userId, consentFact.offers).doOnError{ e => NioLogger.error(s"validate offers structure $e") }
res <- maybeLastConsentFact match {
// Create a new user, consent fact and last consent fact
case None =>
for {
Expand Down
5 changes: 4 additions & 1 deletion nio-server/app/utils/DefaultLoader.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import db.OrganisationMongoDataStore
import models._
import play.api.Configuration

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future}

class DefaultLoader(conf: Configuration, organisationStore: OrganisationMongoDataStore)(implicit ec: ExecutionContext) {
Expand All @@ -27,7 +28,9 @@ class DefaultLoader(conf: Configuration, organisationStore: OrganisationMongoDat
permissions = groupsConf.get[Seq[Configuration]]("permissions").map { permissionsConf =>
Permission(
key = permissionsConf.get[String]("key"),
label = permissionsConf.get[String]("label")
label = permissionsConf.get[String]("label"),
`type` = permissionsConf.getOptional[String]("type").flatMap(s => PermissionType.parse(s).toOption).getOrElse(OptIn),
validityPeriod = permissionsConf.getOptional[FiniteDuration]("validityPeriod")
)
}
)
Expand Down
2 changes: 0 additions & 2 deletions nio-server/conf/application.conf
Original file line number Diff line number Diff line change
Expand Up @@ -237,5 +237,3 @@ healthcheck {

mongodb.uri = "mongodb://localhost:27017/nio"
mongodb.uri = ${?MONGODB_ADDON_URI}

include "default"
46 changes: 38 additions & 8 deletions nio-server/test/controllers/ConsentControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package controllers
import org.apache.pekko.japi.Option
import models._

import java.time.{Clock, LocalDateTime}
import java.time.{Clock, LocalDateTime, ZoneId}
import utils.NioLogger
import play.api.libs.json.{JsArray, JsObject, JsValue, Json}
import play.api.libs.ws.WSResponse
import utils.{DateUtils, TestUtils}
import play.api.test.Helpers._

import java.time.format.DateTimeFormatter
import scala.concurrent.duration.DurationInt

class ConsentControllerSpec extends TestUtils {

Expand Down Expand Up @@ -230,6 +231,26 @@ class ConsentControllerSpec extends TestUtils {
"ConsentController" should {
val organisationKey: String = "maif"

// val organisation: Organisation = Organisation(
// key = organisationKey,
// label = "maif",
// groups = Seq(
// PermissionGroup(
// key = "maifNotifs",
// label = "J'accepte de recevoir par téléphone, mail et SMS des offres personnalisées du groupe MAIF",
// permissions = Seq(
// Permission(key = "phone", label = "Par contact téléphonique", validityPeriod = Some(1.minute)),
// Permission(key = "mail", label = "Par contact électronique"),
// Permission(key = "sms", label = "Par SMS / MMS / VMS")
// )
// )
// )
// )
// postJson(s"/$tenant/organisations", organisation.asJson()).status mustBe CREATED
// postJson(s"/$tenant/organisations/$organisationKey/draft/_release", organisation.asJson()).status mustBe OK
// postJson(s"/$tenant/organisations/$organisationKey/draft/_release", organisation.asJson()).status mustBe OK


"user not exist" in {
val path: String =
s"/$tenant/organisations/$organisationKey/users/$userId1"
Expand Down Expand Up @@ -297,6 +318,9 @@ class ConsentControllerSpec extends TestUtils {
}

"create user consents" in {

println(getJson(s"/$tenant/organisations/$organisationKey").json)

val path: String =
s"/$tenant/organisations/$organisationKey/users/$userId1"
val putResponse = putJson(path, user1AsJson)
Expand Down Expand Up @@ -336,9 +360,12 @@ class ConsentControllerSpec extends TestUtils {

consents1.value.size mustBe 3

(consents1 \ 0 \ "key").as[String] mustBe "phone"
(consents1 \ 0 \ "label").as[String] mustBe "Par contact téléphonique"
(consents1 \ 0 \ "checked").as[Boolean] mustBe true
val consent0 = consents1 \ 0
(consent0 \ "key").as[String] mustBe "phone"
(consent0 \ "label").as[String] mustBe "Par contact téléphonique"
(consent0 \ "checked").as[Boolean] mustBe true
(consent0 \ "expiredAt").asOpt[LocalDateTime](DateUtils.utcDateTimeReads)
.map(_.withSecond(0)) mustBe Some(LocalDateTime.now(Clock.systemUTC()).plusHours(1).withSecond(0).withNano(0))

(consents1 \ 1 \ "key").as[String] mustBe "mail"
(consents1 \ 1 \ "label").as[String] mustBe "Par contact électronique"
Expand Down Expand Up @@ -809,15 +836,18 @@ class ConsentControllerSpec extends TestUtils {
)
))

println(patchResponse.json)
val json = patchResponse.json
println(json)
patchResponse.status mustBe OK

val expectedDate: LocalDateTime = (patchResponse.json \ "lastUpdate").validate(DateUtils.utcDateTimeReads).get
patchResponse.json mustBe user1.copy(
val expectedDate: LocalDateTime = (json \ "lastUpdate").validate(DateUtils.utcDateTimeReads).get
json mustBe user1.copy(
orgKey = Some("maif"),
lastUpdate = expectedDate,
groups = user1.groups.updated(0, user1.groups(0).copy(
consents = user1.groups(0).consents.updated(0, user1.groups(0).consents(0).copy(checked = false))
consents = user1.groups(0).consents.updated(0, user1.groups(0).consents(0).copy(
checked = false,
expiredAt = Some(LocalDateTime.now(Clock.systemUTC()).plusHours(1).withNano(0))))
))
).asJson()
}
Expand Down
16 changes: 11 additions & 5 deletions nio-server/test/controllers/OrganisationControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import play.api.libs.ws.WSResponse
import play.api.test.Helpers._

import java.time.format.DateTimeFormatter
import scala.concurrent.duration.DurationInt

class OrganisationControllerSpec extends TestUtils {

Expand All @@ -19,7 +20,10 @@ class OrganisationControllerSpec extends TestUtils {
key = org1Key,
label = "lbl",
groups = Seq(
PermissionGroup(key = "group1", label = "blalba", permissions = Seq(Permission("sms", "Please accept sms")))
PermissionGroup(key = "group1", label = "blalba", permissions = Seq(
Permission("sms", "Please accept sms"),
Permission("call", "Please accept call", validityPeriod = Some(1.hour)),
))
)
)
val org1AsJson = org1.asJson()
Expand Down Expand Up @@ -116,10 +120,12 @@ class OrganisationControllerSpec extends TestUtils {
(groups \ 0 \ "label").as[String] mustBe org1.groups.head.label

val permissions = (groups \ 0 \ "permissions").as[JsArray]
(permissions \ 0 \ "key")
.as[String] mustBe org1.groups.head.permissions.head.key
(permissions \ 0 \ "label")
.as[String] mustBe org1.groups.head.permissions.head.label
(permissions \ 0 \ "key").as[String] mustBe org1.groups.head.permissions.head.key
(permissions \ 0 \ "label").as[String] mustBe org1.groups.head.permissions.head.label
(permissions \ 0 \ "validityPeriod").asOpt[String] mustBe None
(permissions \ 1 \ "key").as[String] mustBe "call"
(permissions \ 1 \ "label").as[String] mustBe "Please accept call"
(permissions \ 1 \ "validityPeriod").as[String] mustBe "1 hour"

val getOrganisationsResponse: WSResponse = getJson(path)
getOrganisationsResponse.status mustBe OK
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ organisations = [
{
key = "phone"
label = "Par contact téléphonique"
validityPeriod = "1 hour"
},
{
key = "mail"
Expand Down Expand Up @@ -56,6 +57,7 @@ organisations = [
{
key = "phone"
label = "Par contact téléphonique"
validityPeriod = "1 hour"
},
{
key = "mail"
Expand Down Expand Up @@ -100,6 +102,7 @@ organisations = [
{
key = "phone"
label = "Par contact téléphonique"
validityPeriod = "1 hour"
},
{
key = "mail"
Expand Down
2 changes: 1 addition & 1 deletion nio-server/test/utils/TestUtils.scala
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ trait TestUtils
|db.tenants=["$tenant"]
|nio.filter.securityMode="default"
""".stripMargin)
.resolve()
.resolve().withFallback(ConfigFactory.load("default.conf"))
}

protected lazy val authInfo: AuthInfoMock = new AuthInfoTest
Expand Down

0 comments on commit 381224a

Please sign in to comment.