Skip to content

Commit

Permalink
Les nouveaux comptes instructeurs sont automatiquement ajoutés aux de…
Browse files Browse the repository at this point in the history
…mandes
  • Loading branch information
niladic committed Sep 19, 2023
1 parent 95e5836 commit d5de523
Show file tree
Hide file tree
Showing 8 changed files with 384 additions and 159 deletions.
52 changes: 3 additions & 49 deletions app/controllers/ApplicationController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -169,59 +169,13 @@ case class ApplicationController @Inject() (
)
}

private def contextualizedUserName(
def contextualizedUserName(
user: User,
currentAreaId: UUID,
creatorGroupId: Option[UUID]
): String = {
val groups = userGroupService.byIds(user.groupIds)

val defaultContexts: List[String] = groups
.filter(_.areaIds.contains[UUID](currentAreaId))
.flatMap { userGroup: UserGroup =>
if (user.instructor) {
for {
areaInseeCode <- userGroup.areaIds.flatMap(Area.fromId).map(_.inseeCode).headOption
organisation <- userGroup.organisation
} yield {
s"(${organisation.name} - $areaInseeCode)"
}
} else {
List(s"(${userGroup.name})")
}
}
.distinct

val creatorGroup = creatorGroupId.flatMap(id => groups.find(_.id === id))
val isInCreatorGroup: Boolean =
creatorGroupId.map(id => user.groupIds.contains[UUID](id)).getOrElse(false)

val contexts: List[String] =
if (isInCreatorGroup)
creatorGroup.fold(defaultContexts) { group =>
val creatorGroupIsInApplicationArea: Boolean =
group.areaIds.contains[UUID](currentAreaId)
val name: String =
if (creatorGroupIsInApplicationArea)
group.name
else
group.areaIds
.flatMap(Area.fromId)
.map(_.inseeCode)
.headOption
.fold(group.name)(code =>
if (group.name.contains(code)) group.name else s"${group.name} - $code"
)
s"($name)" :: Nil
}
else
defaultContexts

val capitalizedUserName = user.name.split(' ').map(_.capitalize).mkString(" ")
if (contexts.isEmpty)
s"$capitalizedUserName ( ${user.qualite} )"
else
s"$capitalizedUserName ${contexts.mkString(",")}"
val userGroups = userGroupService.byIds(user.groupIds)
Application.invitedUserContextualizedName(user, userGroups, currentAreaId.some, creatorGroupId)
}

private def handlingFiles(applicationId: UUID, answerId: Option[UUID])(
Expand Down
276 changes: 181 additions & 95 deletions app/controllers/UserController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import models._
import models.formModels.{
normalizedOptionalText,
AddUserFormData,
AddUsersFormData,
EditProfileFormData,
EditUserFormData,
ValidateSubscriptionForm
Expand Down Expand Up @@ -525,6 +526,164 @@ case class UserController @Inject() (
}
}

private def addUsersToGroupApplications(users: List[User], group: UserGroup)(implicit
request: RequestWithUserData[_]
): Future[Unit] = {
val currentAreaId = group.areaIds.headOption
applicationService.byInvitedGroupIdAndOpen(group.id).map { applications =>
applications.foreach { application =>
val alreadyInvitedUsers: Set[UUID] = application.invitedUsers.keySet
val invitedUsers: Map[UUID, String] = users
.filter(user => !alreadyInvitedUsers.contains(user.id))
.map(user =>
(
user.id,
Application.invitedUserContextualizedName(
user,
group :: Nil,
currentAreaId,
application.creatorGroupId
)
)
)
.toMap
val answer = Answer(
UUID.randomUUID(),
application.id,
Time.nowParis(),
Answer.AnswerType.Custom,
"Les nouveaux instructeurs ont automatiquement accès à la demande.",
request.currentUser.id,
Application.invitedUserContextualizedName(
request.currentUser,
group :: Nil, // Not exactly true, but fine for this specific context
currentAreaId,
application.creatorGroupId
),
invitedUsers,
visibleByHelpers = false,
declareApplicationHasIrrelevant = false,
Map.empty[String, String].some,
invitedGroupIds = List.empty[UUID]
)

if (applicationService.addAnswer(application.id, answer) === 1) {
answer.invitedUsers.foreach { case (userId, _) =>
eventService.log(
EventType.AgentsAdded,
s"L'utilisateur $userId nouvellement ajouté au groupe ${group.id} a été ajouté sur la demande ${application.id} (réponse ${answer.id})",
applicationId = application.id.some,
involvesUser = userId.some
)
}
}
}
}
}

private def addUsers(usersToAdd: AddUsersFormData, group: UserGroup)(implicit
request: RequestWithUserData[_]
): Future[Result] =
try {
val users: List[User] = usersToAdd.users.map(userToAdd =>
User(
id = UUID.randomUUID(),
key = "", // generated by UserService
firstName = userToAdd.firstName,
lastName = userToAdd.lastName,
name = userToAdd.name,
qualite = userToAdd.qualite,
email = userToAdd.email,
helper = true,
instructor = userToAdd.instructor,
admin = false,
areas = group.areaIds,
creationDate = Time.nowParis(),
communeCode = "0",
groupAdmin = userToAdd.groupAdmin,
disabled = false,
expert = false,
groupIds = group.id :: Nil,
cguAcceptationDate = None,
newsletterAcceptationDate = None,
phoneNumber = userToAdd.phoneNumber,
observableOrganisationIds = Nil,
sharedAccount = userToAdd.sharedAccount,
internalSupportComment = None
)
)
userService
.add(users)
.fold(
{ error =>
eventService.log(
AddUserError,
"Impossible d'ajouter les utilisateurs",
s"Erreur '$error'".some
)
val form = AddUserFormData.addUsersForm
.fill(usersToAdd)
.withGlobalError(s"Impossible d'ajouter les utilisateurs. $error")
Future(
InternalServerError(
views.html.addUsers(request.currentUser, request.rights)(
form,
usersToAdd.users.length,
routes.UserController.addPost(group.id),
false,
0
)
)
)
},
_ =>
addUsersToGroupApplications(users.filter(_.instructor), group).map { _ =>
users.foreach { user =>
val host = notificationsService.newUser(user)
eventService.log(
EventType.UserCreated,
s"Utilisateur ${user.id} ajouté [email envoyé via '$host']",
s"Utilisateur ${user.toLogString}".some,
involvesUser = Some(user.id)
)
}
eventService.log(UsersCreated, "Utilisateurs ajoutés")

Redirect(routes.GroupController.editGroup(group.id))
.flashing("success" -> "Utilisateurs ajoutés")
}
)
} catch {
case ex: PSQLException =>
val EmailErrorPattern =
"""[^()@]+@[^()@.]+\.[^()@]+""".r // This didn't work in that case : """ Detail: Key \(email\)=\(([^()]*)\) already exists."""".r (don't know why, the regex is correct)
val errorMessage =
EmailErrorPattern.findFirstIn(ex.getServerErrorMessage.toString) match {
case Some(email) => s"Un utilisateur avec l'adresse $email existe déjà."
case _ =>
"Erreur d'insertion dans la base de donnée : contacter l'administrateur."
}
val form = AddUserFormData.addUsersForm
.fill(usersToAdd)
.withGlobalError(errorMessage)
eventService.log(
AddUserError,
"Impossible d'ajouter des utilisateurs dans la BDD",
s"Exception ${ex.getServerErrorMessage}".some
)
Future(
BadRequest(
views.html.addUsers(request.currentUser, request.rights)(
form,
usersToAdd.users.length,
routes.UserController.addPost(group.id),
false,
0
)
)
)
}

def addPost(groupId: UUID): Action[AnyContent] =
loginAction.async { implicit request =>
withGroup(groupId) { group: UserGroup =>
Expand All @@ -544,107 +703,32 @@ case class UserController @Inject() (
views.html.addUsers(request.currentUser, request.rights)(
formWithErrors,
0,
routes.UserController.addPost(groupId)
routes.UserController.addPost(groupId),
false,
0,
)
)
)
},
usersToAdd =>
try {
val users: List[User] = usersToAdd.map(userToAdd =>
User(
id = UUID.randomUUID(),
key = "", // generated by UserService
firstName = userToAdd.firstName,
lastName = userToAdd.lastName,
name = userToAdd.name,
qualite = userToAdd.qualite,
email = userToAdd.email,
helper = true,
instructor = userToAdd.instructor,
admin = false,
areas = group.areaIds,
creationDate = Time.nowParis(),
communeCode = "0",
groupAdmin = userToAdd.groupAdmin,
disabled = false,
expert = false,
groupIds = groupId :: Nil,
cguAcceptationDate = None,
newsletterAcceptationDate = None,
phoneNumber = userToAdd.phoneNumber,
observableOrganisationIds = Nil,
sharedAccount = userToAdd.sharedAccount,
internalSupportComment = None
)
)
userService
.add(users)
.fold(
{ error =>
eventService.log(
AddUserError,
"Impossible d'ajouter les utilisateurs",
s"Erreur '$error'".some
)
val form = AddUserFormData.addUsersForm
.fill(usersToAdd)
.withGlobalError(s"Impossible d'ajouter les utilisateurs. $error")
Future(
InternalServerError(
views.html.addUsers(request.currentUser, request.rights)(
form,
usersToAdd.length,
routes.UserController.addPost(groupId)
)
)
)
},
{ _ =>
users.foreach { user =>
val host = notificationsService.newUser(user)
eventService.log(
EventType.UserCreated,
s"Utilisateur ${user.id} ajouté [email envoyé via '$host']",
s"Utilisateur ${user.toLogString}".some,
involvesUser = Some(user.id)
)
}
eventService.log(UsersCreated, "Utilisateurs ajoutés")
Future(
Redirect(routes.GroupController.editGroup(groupId))
.flashing("success" -> "Utilisateurs ajoutés")
)
}
)
} catch {
case ex: PSQLException =>
val EmailErrorPattern =
"""[^()@]+@[^()@.]+\.[^()@]+""".r // This didn't work in that case : """ Detail: Key \(email\)=\(([^()]*)\) already exists."""".r (don't know why, the regex is correct)
val errorMessage =
EmailErrorPattern.findFirstIn(ex.getServerErrorMessage.toString) match {
case Some(email) => s"Un utilisateur avec l'adresse $email existe déjà."
case _ =>
"Erreur d'insertion dans la base de donnée : contacter l'administrateur."
}
val form = AddUserFormData.addUsersForm
.fill(usersToAdd)
.withGlobalError(errorMessage)
eventService.log(
AddUserError,
"Impossible d'ajouter des utilisateurs dans la BDD",
s"Exception ${ex.getServerErrorMessage}".some
)
Future(
BadRequest(
views.html.addUsers(request.currentUser, request.rights)(
form,
usersToAdd.length,
routes.UserController.addPost(groupId)
)
usersToAdd => {
if (usersToAdd.users.exists(_.instructor) && !usersToAdd.confirmInstructors) {
val form = AddUserFormData.addUsersForm.fill(usersToAdd)
applicationService.byInvitedGroupIdAndOpen(groupId).map { applications =>
val numberOfApplications = applications.size
Ok(
views.html.addUsers(request.currentUser, request.rights)(
form,
usersToAdd.users.length,
routes.UserController.addPost(groupId),
true,
numberOfApplications,
)
)
}
} else {
addUsers(usersToAdd, group)
}
}
)
}
}
Expand Down Expand Up @@ -822,7 +906,9 @@ case class UserController @Inject() (
views.html.addUsers(request.currentUser, request.rights)(
AddUserFormData.addUsersForm,
rows,
routes.UserController.addPost(groupId)
routes.UserController.addPost(groupId),
false,
0
)
)
)
Expand Down
Loading

0 comments on commit d5de523

Please sign in to comment.