Files
myep-team/src/BusProNet/UserDataHandler.php
T
2026-08-11 12:26:13 +02:00

334 lines
12 KiB
PHP

<?php
namespace App\BusProNet;
use App\BusProNet\Model\CrmAttributesResponse;
use App\BusProNet\Model\ProfileResponse;
use App\Entity\Embeddable\Address;
use App\Entity\Embeddable\Communication;
use App\Entity\Teamer;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
class UserDataHandler
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
/**
* Collects the roles to grant on initial user creation.
*
* Administrative roles are deliberately not importable: they may only be granted
* manually by a super admin, so that nobody can escalate their own privileges via
* the BusPro CRM. They are imported as pending markers instead, which grant nothing
* but mark the user for approval. ROLE_TEAMER carries no privileges of its own and
* is granted directly.
*/
public function collectRoles(CrmAttributesResponse $crmAttributes): array
{
// Collect user's roles from CRM attributes
$roles = $this->collectPendingRoles($crmAttributes);
if ($crmAttributes->isTeamer()) {
$roles[] = 'ROLE_TEAMER';
}
return $roles;
}
/**
* Collects the pending markers for the administrative roles claimed in the CRM.
*/
public function collectPendingRoles(CrmAttributesResponse $crmAttributes): array
{
$roles = [];
if ($crmAttributes->isAdmin()) {
$roles[] = User::PENDING_ROLES['ROLE_ADMIN'];
}
if ($crmAttributes->isManager()) {
$roles[] = User::PENDING_ROLES['ROLE_MANAGER'];
} elseif ($crmAttributes->isHouseManager()) {
$roles[] = User::PENDING_ROLES['ROLE_HOUSE_MANAGER'];
}
return $roles;
}
public function findLocalUser(ProfileResponse $profileResponse): ?User
{
// Check if user is already present in local database
$repository = $this->entityManager->getRepository(User::class);
$user = $repository->findOneBy([
'busProAddressId' => $profileResponse->getAddressId(),
'busProPersonId' => $profileResponse->getPersonId(),
]);
if (null !== $user) {
return $user;
}
$email = $profileResponse->getCommunication()?->getEmail();
if (true === empty($email)) {
return null;
}
$users = $repository->findBy([
'email' => $email,
]);
if (1 !== count($users)) {
if (1 < count($users)) {
$this->logger->warning('Unable to match local user by email: multiple users found', [
'email' => $email,
'count' => count($users),
]);
}
return null;
}
/** @var User $user */
$user = $users[0];
// A deleted account still has to be matched here, otherwise the caller would take
// it for an unknown person and create a second account for them - resurrecting
// them under a new row. It is returned as found, without writing anything to it.
if (true === $user->isDeleted()) {
return $user;
}
$addressId = $profileResponse->getAddressId();
$personId = $profileResponse->getPersonId();
if (null === $addressId || null === $personId) {
$this->logger->warning('Skip BusPro ID refresh: profile response missing IDs', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
'bus_pro_address_id' => $addressId,
'bus_pro_person_id' => $personId,
]);
return $user;
}
$user
->setBusProAddressId($addressId)
->setBusProPersonId($personId)
;
$this->logger->info('Refresh BusPro IDs for existing local user', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
]);
return $user;
}
public function createLocalUser(
ProfileResponse $profileResponse,
array $roles,
bool $isTeamer = false,
array $crmSelections = [],
array $hotelCodes = [],
): User {
$user = new User();
$user
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setEmail($profileResponse->getCommunication()->getEmail())
->setBusProPersonId($profileResponse->getPersonId())
->setBusProAddressId($profileResponse->getAddressId())
->setHotelCodes($hotelCodes)
->setRoles($roles)
;
if (true === $isTeamer) {
$teamer = Teamer::fromApiResponse($profileResponse);
$teamer->setCrmSelections($crmSelections);
$user->setTeamer($teamer);
$this->logger->info('Create teamer', [
'teamer_id' => $teamer->getId(),
'teamer_name' => (string) $teamer,
]);
}
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->logger->info('Create user', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
]);
return $user;
}
/**
* Updates an existing user from BusPro data.
*
* Administrative roles and hotel codes are imported once on user creation only and are
* managed manually afterwards, so they are intentionally left untouched here. The
* exceptions are the privilege-free pending markers, which keep tracking the
* administrative roles claimed in the CRM, and ROLE_TEAMER, which needs no approval
* and is granted to whoever the CRM reports as a teamer.
*
* @param string[] $claimedRoles pending markers as returned by collectPendingRoles()
*/
public function updateLocalUser(
User $user,
ProfileResponse $profileResponse,
bool $isTeamer = false,
array $crmSelections = [],
array $claimedRoles = [],
): void {
$user
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setEmail($profileResponse->getCommunication()->getEmail())
;
$this->refreshPendingRoles($user, $claimedRoles);
if (true === $isTeamer) {
$this->grantTeamerRole($user);
$address = Address::fromApiResponse($profileResponse);
$communication = Communication::fromApiResponse($profileResponse);
if (null === $user->getTeamer()) {
$teamer = Teamer::fromApiResponse($profileResponse);
$user->setTeamer($teamer);
$this->entityManager->persist($teamer);
} else {
$teamer = $user->getTeamer();
}
$teamer
->setFirstName($profileResponse->getFirstName())
->setLastName($profileResponse->getName())
->setAcademicTitle($profileResponse->getTitle())
->setSalutation($profileResponse->getSalutation())
->setGender($profileResponse->getGender())
->setDateOfBirth($profileResponse->getDateOfBirth())
->setAddress($address)
->setCommunication($communication)
->setCrmSelections($crmSelections)
;
$this->logger->info('Update teamer', [
'teamer_id' => $teamer->getId(),
'teamer_name' => (string) $teamer,
]);
}
$this->entityManager->flush();
}
/**
* Blocks a user the CRM no longer grants anything in this application.
*
* The granted roles are deliberately kept: they stay visible for review. Only the
* privilege-free markers are dropped, as they no longer reflect the CRM. What keeps the
* user reachable is the block itself, not the roles: a teamer stays in the teamer list,
* everyone else is listed by getAdministrativeUsers() whatever roles are left.
* Regaining a CRM role does not unblock the account, that is a manual decision.
*/
public function disableForRevokedCrmRoles(User $user): void
{
// a deleted account is already excluded from everything and must not be written
// to by the CRM at all
if (true === $user->isDeleted()) {
return;
}
// an existing block may be a disciplinary one and must never be overwritten, but
// findLocalUser() may have refreshed the BusPro ids and nothing else flushes here
if (true === $user->isDisabled()) {
$this->entityManager->flush();
return;
}
$this->refreshPendingRoles($user, []);
$user
->setDisabledAt(new \DateTimeImmutable())
->setDisabledReason('Für deinen Account liegt in BusPro keine Berechtigung mehr vor.')
->setDisabledReasonInternal('Automatisch gesperrt: keine Rollen in BusPro.')
;
$this->entityManager->flush();
$this->logger->info('Disable user without CRM roles', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
]);
}
/**
* Grants ROLE_TEAMER to a user the CRM reports as a teamer.
*
* Unlike the administrative roles this one needs no approval, so it may be granted on
* any login rather than on creation only: it carries no privileges beyond the teamer
* area, and a teamer without it would be left with a teamer record they cannot reach,
* or locked out entirely for holding no assignable role at all.
*
* It is never withdrawn here. Losing the CRM attribute while holding no other role
* blocks the account anyway, and a role handed out manually must survive a login.
*/
private function grantTeamerRole(User $user): void
{
$grantedRoles = $user->getAssignedRoles();
if (true === in_array('ROLE_TEAMER', $grantedRoles, true)) {
return;
}
$user->setRoles([...$grantedRoles, 'ROLE_TEAMER', ...$user->getPendingRoles()]);
$this->logger->info('Grant teamer role', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
]);
}
/**
* Keeps the pending markers in sync with the administrative roles claimed in the CRM.
* The markers grant no privileges, so tracking them on every login is safe: only a
* super admin can turn one into an actual role, and an already granted role is never
* marked as pending again.
*
* @param string[] $claimedRoles
*/
private function refreshPendingRoles(User $user, array $claimedRoles): void
{
// an approved role needs no marker anymore
$grantedRoles = $user->getAssignedRoles();
$pendingRoles = array_values(array_filter(
$claimedRoles,
static fn (string $pendingRole): bool => false === in_array(
array_search($pendingRole, User::PENDING_ROLES, true),
$grantedRoles,
true,
),
));
if ($pendingRoles === $user->getPendingRoles()) {
return;
}
// getAssignedRoles() returns the manually assignable roles without the markers
$user->setRoles([...$grantedRoles, ...$pendingRoles]);
$this->logger->info('Refresh pending roles', [
'user_id' => $user->getId(),
'user_email' => $user->getEmail(),
'pending_roles' => $pendingRoles,
]);
}
}