feat: email the administrators when a role nomination appears

This commit is contained in:
2026-09-13 12:50:01 +02:00
parent fab89dead6
commit b41820c39d
12 changed files with 458 additions and 36 deletions
@@ -6,19 +6,20 @@ namespace App\Dashboard\Widget;
use App\Dashboard\Contract\DashboardWidgetProviderInterface;
use App\Entity\User;
use App\Form\Model\Filter\AbstractListFilterDto;
use App\Model\DashboardWidget;
use App\Model\DashboardWidgetEntry;
use App\Repository\UserRepository;
use App\Security\Role;
use App\Service\RoleApprovalUrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* The accounts waiting on an administrator to act.
*
* A nomination grants nothing until it is approved, and nothing else in the application
* announces that one is waiting — without this widget an administrator only finds out by
* opening the user list.
* A nomination grants nothing until it is approved. RoleNominationHandler emails the
* administrators the moment one appears, but that fires once, on the login that produced it —
* this widget is the standing list, and the only thing that still shows a nomination somebody
* has left sitting.
*/
class PendingRoleApprovalsWidgetProvider implements DashboardWidgetProviderInterface
{
@@ -27,6 +28,7 @@ class PendingRoleApprovalsWidgetProvider implements DashboardWidgetProviderInter
public function __construct(
private readonly UserRepository $userRepository,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly RoleApprovalUrlGenerator $approvalUrlGenerator,
) {
}
@@ -46,7 +48,7 @@ class PendingRoleApprovalsWidgetProvider implements DashboardWidgetProviderInter
'Offene Rollenfreigaben',
array_map(fn (User $user): DashboardWidgetEntry => new DashboardWidgetEntry(
$this->label($user),
$this->approvalUrl($user),
$this->approvalUrlGenerator->forUser($user),
'user',
), $this->userRepository->findWithPendingRoles(self::LIMIT)),
'Keine offenen Rollenfreigaben.',
@@ -65,20 +67,4 @@ class PendingRoleApprovalsWidgetProvider implements DashboardWidgetProviderInter
return sprintf('%s: %s', $user->getDisplayName(), implode(', ', $nominated));
}
/**
* The user list, filtered down to this account.
*
* Approving happens in a modal that app_admin_user_permissions renders as a bare fragment,
* so it cannot be linked to directly. The filtered list is one click away from it and shows
* the nomination badge on the way. The query string is flat because the list filter forms
* declare no block prefix.
*/
private function approvalUrl(User $user): string
{
return $this->urlGenerator->generate('app_admin_user', [
AbstractListFilterDto::MARKER => 1,
'q' => $user->getEmail(),
]);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Message;
/**
* Dispatched when the BusPro CRM newly nominates an account for one or more administrative roles,
* so that the administrators who can approve it are told there is something waiting in
* /admin/user.
*
* Carries the ids only, never the User: the handler runs in a separate process, where a
* serialized entity would be stale by the time it is read.
*/
final class RoleNominationMessage
{
/**
* @param string[] $roles the nominated roles themselves, not their _PENDING markers
*/
public function __construct(
public readonly int $userId,
public readonly array $roles,
) {
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\MessageHandler;
use App\Email\Mailer;
use App\Message\RoleNominationMessage;
use App\Repository\UserRepository;
use App\Security\Role;
use App\Service\RoleApprovalUrlGenerator;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Tells the administrators that an account is waiting for a role to be approved.
*
* Runs off the request: mail is routed sync in this application, so sending it inline would put
* SMTP latency and SMTP failures into the login path.
*/
#[AsMessageHandler]
final class RoleNominationHandler
{
public function __construct(
private readonly UserRepository $userRepository,
private readonly Mailer $mailer,
private readonly RoleApprovalUrlGenerator $approvalUrlGenerator,
private readonly LoggerInterface $authLogger,
) {
}
public function __invoke(RoleNominationMessage $message): void
{
$user = $this->userRepository->find($message->userId);
if (null === $user) {
// The account is gone — a retry cannot bring it back.
$this->authLogger->warning('Nominated user not found, skipping the role nomination email', [
'userId' => $message->userId,
]);
return;
}
$recipients = array_values(array_filter(array_map(
static fn ($admin): ?string => $admin->getEmail(),
$this->userRepository->findAdministrators(),
)));
if ([] === $recipients) {
// Worth a warning rather than a silent return: nobody can approve the nomination, and
// without this line nobody would find out that the notification goes nowhere.
$this->authLogger->warning('No administrator to notify about a role nomination', [
'userId' => $message->userId,
'roles' => $message->roles,
]);
return;
}
$labels = Role::labels();
$this->mailer->createAndSendEmail(
[
'user' => $user,
'roles' => array_values(array_map(
static fn (string $role): string => $labels[$role] ?? $role,
$message->roles,
)),
// Absolute: generated in a worker, where there is no request to borrow a host
// from (see framework.router.default_uri).
'approvalUrl' => $this->approvalUrlGenerator->forUser($user, UrlGeneratorInterface::ABSOLUTE_URL),
],
[
'template' => 'email/role_nomination.html.twig',
'subject' => 'Neue Rollen-Freischaltung angefordert',
'to' => $recipients,
],
);
}
}
+26
View File
@@ -71,6 +71,32 @@ class UserRepository extends ServiceEntityRepository
->getResult();
}
/**
* The administrators who can approve a role nomination.
*
* The quote-anchored needle is load-bearing. ROLE_ADMIN_PENDING lives in the same JSON column,
* and an unanchored '%ROLE_ADMIN%' would match it — which would mail the very people whose own
* nomination is unapproved about other people's nominations. The result is filtered through
* Role::effectiveOnly() as well, so the guarantee does not rest on the LIKE alone.
*
* @return User[]
*/
public function findAdministrators(): array
{
/** @var User[] $candidates */
$candidates = $this->createQueryBuilder('u')
->andWhere('u.roles LIKE :admin')
->setParameter('admin', '%"'.Role::ADMIN.'"%')
->orderBy('u.email', 'ASC')
->getQuery()
->getResult();
return array_values(array_filter(
$candidates,
static fn (User $user): bool => \in_array(Role::ADMIN, Role::effectiveOnly($user->getRoles()), true),
));
}
/**
* Everyone worth filtering an accommodation booking by: current groups staff, plus whoever
* a booking is still assigned to even after losing the role — otherwise a booking assigned
+33 -11
View File
@@ -12,12 +12,14 @@ use App\BusProNet\Model\CrmAttributes;
use App\BusProNet\Model\PersonalData;
use App\Entity\User;
use App\Htmx\HxRedirectResponse;
use App\Message\RoleNominationMessage;
use App\Service\ProfileCompletenessChecker;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
@@ -54,6 +56,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
private readonly ProfileCompletenessChecker $completenessChecker,
private readonly LoggerInterface $authLogger,
private readonly EmployeeDomainMatcher $employeeDomainMatcher,
private readonly MessageBusInterface $messageBus,
) {
}
@@ -120,7 +123,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
->setProfileComplete($this->completenessChecker->isComplete($personalData))
;
$this->syncFromCrm($user, $crmAttributes);
$nominated = $this->syncFromCrm($user, $crmAttributes);
// Registered only once it is fully populated: syncFromCrm() logs on a channel that writes
// to the database, and an account already managed at that point would be flushed
@@ -129,14 +132,24 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
$this->entityManager->persist($user);
$this->entityManager->flush();
// After the flush, deliberately: a first login has no id before it, and the transport is
// Doctrine-backed, so a message queued ahead of a failing flush would announce a
// nomination that was never stored.
if ([] !== $nominated) {
$this->messageBus->dispatch(new RoleNominationMessage((int) $user->getId(), $nominated));
}
return $user;
}
/**
* Writes back what the CRM currently claims: the roles per Role::sync() and the hotel codes
* verbatim. Both replace what is stored, which is what makes BusPro the source of truth.
*
* @return string[] the roles this login newly nominated the account for — the roles
* themselves, not their markers, and empty whenever nothing changed
*/
private function syncFromCrm(User $user, CrmAttributes $crmAttributes): void
private function syncFromCrm(User $user, CrmAttributes $crmAttributes): array
{
$previousRoles = $user->getRoles();
@@ -151,7 +164,7 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
// An existing account keeps everything it has. A brand new one still needs a role,
// and an empty claim set is exactly what Role::sync() answers with the fallback.
if ([] !== Role::assignedOnly($previousRoles)) {
return;
return [];
}
}
@@ -169,16 +182,25 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
->setHotelCodes(array_values(array_unique($crmAttributes->hotelCodes)))
;
$nominated = array_diff(Role::pendingOnly($user->getRoles()), Role::pendingOnly($previousRoles));
$nominated = array_values(array_diff(
Role::pendingOnly($user->getRoles()),
Role::pendingOnly($previousRoles),
));
if ([] !== $nominated) {
// The CRM claims an administrative role for somebody who does not hold it. It grants
// nothing until an administrator approves it in /admin/user.
$this->authLogger->info('Nominated for administrative roles by the BPN CRM', [
'email' => $user->getEmail(),
'roles' => array_values($nominated),
]);
if ([] === $nominated) {
return [];
}
// The CRM claims an administrative role for somebody who does not hold it. It grants
// nothing until an administrator approves it in /admin/user.
$this->authLogger->info('Nominated for administrative roles by the BPN CRM', [
'email' => $user->getEmail(),
'roles' => $nominated,
]);
// Only the newly appeared markers reach this point, so a repeat login with a nomination
// still standing announces nothing. That difference is the whole de-duplication.
return array_keys(Role::nominatedFrom($nominated));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Entity\User;
use App\Form\Model\Filter\AbstractListFilterDto;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Where to send somebody who should act on a role nomination.
*
* Deliberately not app_admin_user_permissions. That route renders the approval modal, which
* extends htmx_modal_admin.html.twig — a bare <div> with no page chrome, meant to be swapped
* into a page that is already open. Following it as a normal navigation, which is what a link
* in an email or a dashboard does, yields an unstyled fragment.
*
* The user list filtered down to the one account is one click away from the modal and shows the
* nomination badge on the way. The query string is flat because the list filter forms declare no
* block prefix.
*/
class RoleApprovalUrlGenerator
{
public function __construct(
private readonly UrlGeneratorInterface $urlGenerator,
) {
}
public function forUser(User $user, int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
return $this->urlGenerator->generate(
'app_admin_user',
[
AbstractListFilterDto::MARKER => 1,
'q' => $user->getEmail(),
],
$referenceType,
);
}
}