Compare commits

...
6 Commits
37 changed files with 1201 additions and 93 deletions

No files matched your search

Generated
+7 -6
View File
@@ -1108,16 +1108,16 @@
},
{
"name": "doctrine/orm",
"version": "3.6.7",
"version": "3.6.8",
"source": {
"type": "git",
"url": "https://github.com/doctrine/orm.git",
"reference": "bc217c0e19c3a9eadfa67697143b87c9ba01272c"
"reference": "a4d13ed5b11e7f7b4d654b1adf95432031ae3ffc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/orm/zipball/bc217c0e19c3a9eadfa67697143b87c9ba01272c",
"reference": "bc217c0e19c3a9eadfa67697143b87c9ba01272c",
"url": "https://api.github.com/repos/doctrine/orm/zipball/a4d13ed5b11e7f7b4d654b1adf95432031ae3ffc",
"reference": "a4d13ed5b11e7f7b4d654b1adf95432031ae3ffc",
"shasum": ""
},
"require": {
@@ -1147,6 +1147,7 @@
"symfony/cache": "^5.4 || ^6.2 || ^7.0 || ^8.0"
},
"suggest": {
"ext-deepclone": "Improves performance when not using native lazy objects (Symfony 8.1+)",
"ext-dom": "Provides support for XSD validation for XML mapping files",
"symfony/cache": "Provides cache support for Setup Tool with doctrine/cache 2.0"
},
@@ -1190,9 +1191,9 @@
],
"support": {
"issues": "https://github.com/doctrine/orm/issues",
"source": "https://github.com/doctrine/orm/tree/3.6.7"
"source": "https://github.com/doctrine/orm/tree/3.6.8"
},
"time": "2026-05-25T16:45:47+00:00"
"time": "2026-08-05T19:05:32+00:00"
},
{
"name": "doctrine/persistence",
-3
View File
@@ -17,9 +17,6 @@ security:
roles: [ ROLE_MAILJET_WEBHOOK ]
role_hierarchy:
ROLE_ADMIN:
- ROLE_GROUPS_ADMIN
- ROLE_HOUSE_MANAGER
ROLE_GROUPS_ADMIN:
- ROLE_GROUPS_MANAGER
-
+29
View File
@@ -30,6 +30,31 @@ parameters:
10321389: 'Reisen-Alert Stubaital'
10554990: 'Reisen-Alert Ski & Boarderweek'
# Hausleitung hotel codes and their labels, assignable to users in /admin/user.
# Mirrors the "Hausleitung {CODE}" CRM selections published by BusProNet.
hotel_codes:
SSL: 'SSL'
SST: 'SST'
MVK: 'MVK'
ASB: 'ASB'
LPJ: 'LPJ'
DKS: 'DKS'
DGS: 'DGS'
DPW: 'DPW'
DKI: 'DKI'
DWW: 'DWW'
PMV: 'PMV'
ASG: 'ASG'
ASC: 'ASC'
SBW: 'SBW'
UCH: 'UCH'
SZO: 'SZO'
PCJ: 'PCJ'
KHH: 'KHH'
SVS: 'SVS'
SHM: 'SHM'
AGR: 'AGR'
# MailJet contact metadata names for name synchronization
mailjet_contact_metadata_fields:
firstName: 'vorname'
@@ -253,6 +278,10 @@ services:
arguments:
$mailjetLists: '%mailjet_lists%'
App\Form\Admin\UserType:
arguments:
$hotelCodes: '%hotel_codes%'
App\Service\DomainConfigProvider:
arguments:
$domainConfig: '%domain_config%'
@@ -15,7 +15,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_GROUPS_ADMIN')]
#[IsGranted('ROLE_ADMIN')]
class DeleteController extends AbstractController
{
use ReturnUrlTrait;
@@ -12,7 +12,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_GROUPS_ADMIN')]
#[IsGranted('ROLE_ADMIN')]
class ExportController extends AbstractController
{
use ReturnUrlTrait;
@@ -14,7 +14,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_GROUPS_ADMIN')]
#[IsGranted('ROLE_ADMIN')]
class FilterController extends AbstractController
{
use ListFilterTrait;
@@ -16,7 +16,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_GROUPS_ADMIN')]
#[IsGranted('ROLE_ADMIN')]
class IndexController extends AbstractController
{
use ListFilterTrait;
@@ -12,7 +12,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_GROUPS_ADMIN')]
#[IsGranted('ROLE_ADMIN')]
class ShowController extends AbstractController
{
use ReturnUrlTrait;
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\User;
use App\Controller\Traits\ReturnUrlTrait;
use App\Entity\User;
use App\Form\Admin\UserType;
use App\Htmx\HxRedirectResponse;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_ADMIN')]
class EditController extends AbstractController
{
use ReturnUrlTrait;
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/user/{id}/edit', name: 'app_admin_user_edit')]
public function index(User $user, Request $request): Response
{
$previousRoles = $user->getRoles();
$previousHotelCodes = $user->getHotelCodes();
$form = $this->createForm(UserType::class, $user, ['hx_post' => $request->getRequestUri()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($this->locksOutSelf($user)) {
$form->get('roles')->addError(new FormError('Du kannst dir die Rolle Administration nicht selbst entziehen.'));
return $this->render('admin/user/modal_edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
$this->entityManager->flush();
$this->addFlash('success', 'Der Benutzeraccount wurde aktualisiert');
$this->logger->info('Updated user permissions', [
'email' => $user->getEmail(),
'previousRoles' => $previousRoles,
'roles' => $user->getRoles(),
'previousHotelCodes' => $previousHotelCodes,
'hotelCodes' => $user->getHotelCodes(),
]);
return new HxRedirectResponse($this->getReturnUrl($request, 'app_admin_user'));
}
return $this->render('admin/user/modal_edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
private function locksOutSelf(User $user): bool
{
return $user === $this->getUser() && false === \in_array(Role::ADMIN, $user->getRoles(), true);
}
}
@@ -26,7 +26,6 @@ class FilterController extends AbstractController
UserFilterType::class,
new UserFilterDto(),
'app_admin_user',
['roles' => UserFilterType::ROLES],
);
return $this->render('admin/_modal_filter.html.twig', [
@@ -36,7 +36,6 @@ class IndexController extends AbstractController
UserFilterType::class,
$filter,
'app_admin_user',
['roles' => UserFilterType::ROLES],
);
$pagination = $this->paginator->paginate(
+10 -2
View File
@@ -15,6 +15,7 @@ use App\Repository\Groups\AccommodationPriceRepository;
use App\Repository\Groups\AccommodationRepository;
use App\Service\AccommodationPriceCoverage;
use App\Service\PriceTimelineBuilder;
use Carbon\CarbonImmutable;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -57,11 +58,18 @@ class ContingentController extends AbstractController
$yearStart = new \DateTimeImmutable("{$query->year}-01-01");
$yearEnd = new \DateTimeImmutable("{$query->year}-12-31");
$prices = $this->priceRepository->findByHotelCodeAndDateRange($query->hotelCode, $yearStart, $yearEnd);
// Past date ranges are of no use to API consumers: never start the timeline before today.
$rangeStart = max($yearStart, CarbonImmutable::now()->setTime(0, 0));
if ($rangeStart > $yearEnd) {
return $this->json([]);
}
$prices = $this->priceRepository->findByHotelCodeAndDateRange($query->hotelCode, $rangeStart, $yearEnd);
$currency = $accommodation->getCurrency();
return $this->json($this->priceTimelineBuilder->buildTimeline($prices, $yearStart, $yearEnd, $currency));
return $this->json($this->priceTimelineBuilder->buildTimeline($prices, $rangeStart, $yearEnd, $currency));
}
#[Route(path: '/contingents/calendar', name: 'api_contingents_calendar', methods: ['GET'])]
+2 -19
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Form\Admin\Filter;
use App\Form\Model\Filter\UserFilterDto;
use App\Security\Role;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -13,28 +14,12 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
*/
class UserFilterType extends AbstractListFilterType
{
/**
* The roles that are actually assigned to accounts. ROLE_USER is left out because every
* account has it implicitly and filtering by it would match everything.
*
* @var string[]
*/
public const ROLES = [
'ROLE_ADMIN',
'ROLE_MANAGER',
'ROLE_TEAMER',
'ROLE_CUSTOMER',
'ROLE_HOUSE_MANAGER',
'ROLE_GROUPS_ADMIN',
'ROLE_GROUPS_MANAGER',
];
protected function filterFields(array $options): array
{
return [
'role' => [ChoiceType::class, [
'label' => 'Rolle',
'choices' => array_combine($options['roles'], $options['roles']),
'choices' => array_flip(Role::labels()),
'placeholder' => 'alle',
'required' => false,
]],
@@ -47,9 +32,7 @@ class UserFilterType extends AbstractListFilterType
$resolver->setDefaults([
'data_class' => UserFilterDto::class,
'roles' => [],
]);
$resolver->setAllowedTypes('roles', 'string[]');
}
protected function searchPlaceholder(): string
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Form\Admin;
use App\Entity\User;
use App\Security\Role;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Lets an administrator assign roles and hotel codes to an existing account.
*
* This is the only way those two get changed after the account was created — BpnAuthenticator
* imports them once and never touches them again.
*
* @extends AbstractType<User>
*/
class UserType extends AbstractType
{
/**
* @param array<string, string> $hotelCodes code => label
*/
public function __construct(private readonly array $hotelCodes = [])
{
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$user = $builder->getData();
$builder
->add('roles', ChoiceType::class, [
'label' => 'Rollen',
'choices' => array_flip(Role::labels()),
'multiple' => true,
'expanded' => true,
'required' => false,
// User::getRoles() prepends the implicit ROLE_USER, which must not be written back.
'getter' => static fn (User $user): array => array_values(array_diff($user->getRoles(), ['ROLE_USER'])),
'setter' => static function (User $user, array $roles): void {
$user->setRoles(array_values(array_unique($roles)));
},
])
->add('hotelCodes', ChoiceType::class, [
'label' => 'Häuser',
'choices' => $this->hotelCodeChoices($user),
'multiple' => true,
'expanded' => true,
'required' => false,
'setter' => static function (User $user, array $hotelCodes): void {
$user->setHotelCodes(array_values(array_unique($hotelCodes)));
},
])
;
}
/**
* Codes already stored on the account are always offered, even when they are missing from
* the configured catalog — otherwise saving the form would silently drop them.
*
* @return array<string, string> label => code
*/
private function hotelCodeChoices(?User $user): array
{
$codes = $this->hotelCodes;
foreach ($user?->getHotelCodes() ?? [] as $code) {
$codes[$code] ??= $code;
}
ksort($codes);
return array_flip($codes);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Form\Model\Filter;
use App\Model\ListFilterChip;
use App\Security\Role;
class UserFilterDto extends AbstractListFilterDto
{
@@ -15,7 +16,7 @@ class UserFilterDto extends AbstractListFilterDto
$chips = parent::activeFilters();
if (null !== $this->role && '' !== $this->role) {
$chips[] = new ListFilterChip('Rolle', $this->role, ['role']);
$chips[] = new ListFilterChip('Rolle', Role::labels()[$this->role] ?? $this->role, ['role']);
}
return $chips;
@@ -471,11 +471,9 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
return $attributes;
}
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'skiPass')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
// No availability readonly state here: unavailable ski passes are removed from
// the choices by filterSkiPassChoices(), and the ones that survive as protected
// selections have to stay selectable
return $attributes;
},
@@ -998,8 +996,13 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
* Filters ski pass choices for display.
*
* Ski passes follow the same age evaluation rules as the rest of the booking flow.
* Participants only see passes that match their age or birth year. In edit mode,
* the currently booked ski pass is preserved even if it would otherwise be filtered
* Participants only see passes that match their age or birth year. Unlike the other
* service categories, unavailable ski passes - sold out or on Buchungsstop - are not
* rendered read-only but removed from the choices entirely, because a short-term,
* special-priced pass that is gone is no longer an offer worth showing.
*
* Passes the participant already holds are protected from that removal, and in edit
* mode the currently booked ski pass is preserved even if age rules would filter it
* out, so existing bookings remain renderable and editable.
*
* @param Service[] $services Array of ski pass Service objects to filter
@@ -1017,20 +1020,77 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
return [];
}
$filteredServices = $this->filterServicesByAgeConstraints($services, $bookingDto, $participantIndex);
$isEditMode = BookingDto::MODE_EDIT === $bookingDto->getMode();
$ageFilteredServices = $this->filterServicesByAgeConstraints($services, $bookingDto, $participantIndex);
if (BookingDto::MODE_EDIT !== $bookingDto->getMode() || null === $participant->skiPass?->id) {
return $filteredServices;
}
$filteredServices = $this->serviceAvailabilityCalculator->filterAvailableServices(
$ageFilteredServices,
$bookingDto,
$participantIndex
);
$currentSkiPassId = $participant->skiPass->id;
if (false === isset($filteredServices[$currentSkiPassId])) {
$filteredServices[$currentSkiPassId] = $services[$currentSkiPassId] ?? $participant->skiPass;
foreach ($this->getProtectedSkiPassIds($bookingDto, $participantIndex) as $protectedId) {
if (true === isset($filteredServices[$protectedId])) {
continue;
}
$protectedService = $ageFilteredServices[$protectedId] ?? null;
// Age rules are only bypassed in edit mode, where a booked pass has to stay renderable
if (null === $protectedService && true === $isEditMode) {
$protectedService = $services[$protectedId] ?? null;
if (null === $protectedService && $participant->skiPass?->id === $protectedId) {
$protectedService = $participant->skiPass;
}
}
if (null !== $protectedService) {
$filteredServices[$protectedId] = $protectedService;
}
}
return $filteredServices;
}
/**
* Collects the ski pass IDs that have to stay selectable regardless of availability.
*
* Both the current selection and - in edit mode - the pass of the underlying booking are
* protected. Without this, a participant holding a pass that sold out or went on
* Buchungsstop meanwhile would lose it on the next refresh, and switching to another pass
* would be a one-way decision.
*
* @param BookingDto $bookingDto The booking DTO containing participant and booking data
* @param int $participantIndex Index of the participant to evaluate
*
* @return int[] Ski pass service IDs that must not be filtered out
*/
private function getProtectedSkiPassIds(BookingDto $bookingDto, int $participantIndex): array
{
$protectedIds = [];
$currentSkiPassId = $bookingDto->getParticipant($participantIndex)?->skiPass?->id;
if (null !== $currentSkiPassId) {
$protectedIds[] = $currentSkiPassId;
}
if (BookingDto::MODE_EDIT === $bookingDto->getMode() && null !== $bookingDto->booking) {
$bookedSkiPasses = $bookingDto->booking->getAdditionalServicesForParticipantByGroup(
$participantIndex,
Constants::TOKEN_SKI_PASS
);
foreach ($bookedSkiPasses as $bookedSkiPass) {
if (null !== $bookedSkiPass->id) {
$protectedIds[] = $bookedSkiPass->id;
}
}
}
return array_values(array_unique($protectedIds));
}
/**
* Generates a German tooltip explaining age restrictions for a service.
*
+34 -8
View File
@@ -31,9 +31,13 @@ use Symfony\Component\Security\Http\Util\TargetPathTrait;
/**
* Authenticates users against the BPN API.
*
* Validates credentials via BPN's getPersonalData endpoint, creates or updates
* local User entities, and retrieves CRM attributes (roles, hotel codes) for
* authorization. Passwords are stored encrypted with RSA for subsequent API calls.
* Validates credentials via BPN's getPersonalData endpoint and creates or updates
* local User entities. Passwords are stored encrypted with RSA for subsequent API calls.
*
* CRM attributes (roles, hotel codes) seed a *new* account only: BusPro backend users can
* edit their own CRM selections, so taking roles over on every login would let anybody grant
* themselves Role::PRIVILEGED here. Privileged roles are never imported at all, and from the
* second login on both roles and hotel codes are managed by an administrator in /admin/user.
*/
class BpnAuthenticator extends AbstractLoginFormAuthenticator implements AuthenticationEntryPointInterface
{
@@ -96,15 +100,17 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
throw new CustomUserMessageAuthenticationException($message);
}
$roles = $crmAttributes->roles;
$hotelCodes = $crmAttributes->hotelCodes;
$encryptedPassword = $this->crypt->encrypt($password);
$userRepository = $this->entityManager->getRepository(User::class);
if (null === $user = $userRepository->findOneBy(['email' => $email])) {
$user = new User($email);
$user
->setRoles($this->importableRoles($email, $crmAttributes->roles))
->setHotelCodes(array_values(array_unique($crmAttributes->hotelCodes)))
;
$this->entityManager->persist($user);
}
@@ -112,8 +118,6 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
->setPassword($encryptedPassword)
->setPersonId($personalData->personId)
->setAddressId($personalData->addressId)
->setRoles($roles)
->setHotelCodes($hotelCodes)
->setLastLoginAt(new \DateTimeImmutable())
->setProfileComplete($this->completenessChecker->isComplete($personalData))
;
@@ -123,6 +127,28 @@ class BpnAuthenticator extends AbstractLoginFormAuthenticator implements Authent
return $user;
}
/**
* @param string[] $crmRoles
*
* @return string[]
*/
private function importableRoles(string $email, array $crmRoles): array
{
$roles = Role::filterImportable($crmRoles);
$dropped = array_values(array_intersect($crmRoles, Role::PRIVILEGED));
if ([] !== $dropped) {
// Somebody holds a privileged CRM selection in BusPro. We do not honour it, but it
// should stay visible: it either needs to be revoked there or granted in /admin/user.
$this->authLogger->warning('Ignored privileged roles from BPN CRM attributes', [
'email' => $email,
'roles' => $dropped,
]);
}
return $roles;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$this->authLogger->info('Login', [
+84
View File
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Security;
/**
* The roles this application knows about.
*
* Roles are stored as plain strings in the User::$roles JSON column and consumed as strings
* by #[IsGranted], the voters and security.yaml's role_hierarchy, so they are constants
* rather than an enum.
*/
final class Role
{
public const ADMIN = 'ROLE_ADMIN';
public const MANAGER = 'ROLE_MANAGER';
public const TEAMER = 'ROLE_TEAMER';
public const CUSTOMER = 'ROLE_CUSTOMER';
public const HOUSE_MANAGER = 'ROLE_HOUSE_MANAGER';
public const GROUPS_ADMIN = 'ROLE_GROUPS_ADMIN';
public const GROUPS_MANAGER = 'ROLE_GROUPS_MANAGER';
/**
* The roles that are actually assigned to accounts. ROLE_USER is left out because every
* account has it implicitly (see User::getRoles()) and it is never stored.
*
* @var string[]
*/
public const ALL = [
self::ADMIN,
self::MANAGER,
self::TEAMER,
self::CUSTOMER,
self::HOUSE_MANAGER,
self::GROUPS_ADMIN,
self::GROUPS_MANAGER,
];
/**
* Roles that are never taken over from BusProNet. Many people can edit CRM selections in
* the BusPro backend, so these are granted by an administrator in /admin/user only.
*
* @var string[]
*/
public const PRIVILEGED = [
self::ADMIN,
self::GROUPS_ADMIN,
self::GROUPS_MANAGER,
];
/**
* Reduces the roles derived from BPN CRM attributes to the ones we accept from there.
*
* Falls back to ROLE_CUSTOMER the way CrmAttributesResponseParser does, so an account
* whose only selection was a privileged one does not end up without any role.
*
* @param string[] $roles
*
* @return string[]
*/
public static function filterImportable(array $roles): array
{
$importable = array_values(array_unique(array_diff($roles, self::PRIVILEGED)));
return [] === $importable ? [self::CUSTOMER] : $importable;
}
/**
* @return array<string, string> role => label
*/
public static function labels(): array
{
return [
self::ADMIN => 'Administration',
self::MANAGER => 'Manager:in',
self::TEAMER => 'Teamer:in',
self::CUSTOMER => 'Kund:in',
self::HOUSE_MANAGER => 'Hausleitung',
self::GROUPS_ADMIN => 'Preisrechner Admin',
self::GROUPS_MANAGER => 'Preisrechner',
];
}
}
+11 -4
View File
@@ -244,10 +244,17 @@ class GroupsPriceCalculator
$shortTermSurcharge = (int) round(($basePrice + $additionalPersonsPrice) * self::SHORT_TERM_FACTORS[$nights] / 100);
}
// Rule 4: undersubscription surcharge (only when board is selected)
// Board is only billable — and only triggers the catering surcharge — when it costs
// something. A free "Selbstversorgung" board is stored as 0 (BoardService::$price is
// non-nullable), so a plain null check would charge the surcharge for it.
$paidBoardPricePerPersonNight = ($boardServicePricePerPersonNight ?? 0) > 0
? $boardServicePricePerPersonNight
: null;
// Rule 4: undersubscription surcharge (only when a paid board is selected)
$undersubscriptionSurcharge = 0;
$undersubscriptionThreshold = null;
if ($boardServicePricePerPersonNight !== null) {
if ($paidBoardPricePerPersonNight !== null) {
$surcharge30 = (int) round(('CHF' === $currency ? $this->config['undersubscription30Chf'] : $this->config['undersubscription30Eur']) * 100);
$surcharge40 = (int) round(('CHF' === $currency ? $this->config['undersubscription40Chf'] : $this->config['undersubscription40Eur']) * 100);
@@ -262,8 +269,8 @@ class GroupsPriceCalculator
// Rule 5: board price
$boardPrice = 0;
if ($boardServicePricePerPersonNight !== null) {
$boardPrice = $boardServicePricePerPersonNight * $effectivePax * $nights;
if ($paidBoardPricePerPersonNight !== null) {
$boardPrice = $paidBoardPricePerPersonNight * $effectivePax * $nights;
}
// Rule 6: additional services
+11 -11
View File
@@ -11,16 +11,16 @@ use App\Model\PriceTimelineItem;
class PriceTimelineBuilder
{
/**
* Builds a flat, non-overlapping timeline of effective price rows for the given year.
* Builds a flat, non-overlapping timeline of effective price rows for the given date range.
*
* Base price periods are split wherever an override or discount applies, so each
* returned row represents a contiguous date range with a single effective price.
* Periods with no price configured are omitted. Prices that start before or end after
* the queried year are clamped to its boundaries.
* the queried range are clamped to its boundaries.
*
* The algorithm is an interval sweep:
* 1. Collect every dateFrom and (dateTo + 1 day) from all prices as boundary points,
* plus the year start and (yearEnd + 1 day). This ensures the sweep slices at
* plus the range start and (rangeEnd + 1 day). This ensures the sweep slices at
* every point where the set of active prices changes.
* 2. Walk adjacent boundary pairs [start, end). For each segment, find all prices
* active at `start` and resolve the winner via resolveWinner(), which prefers
@@ -39,20 +39,20 @@ class PriceTimelineBuilder
*/
public function buildTimeline(
array $prices,
\DateTimeImmutable $yearStart,
\DateTimeImmutable $yearEnd,
\DateTimeImmutable $rangeStart,
\DateTimeImmutable $rangeEnd,
string $currency,
): array {
if (empty($prices)) {
return [];
}
$yearEndNext = $yearEnd->modify('+1 day');
$rangeEndNext = $rangeEnd->modify('+1 day');
// Step 1: collect all boundary points, keyed by timestamp for deduplication.
$boundaries = [
$yearStart->getTimestamp() => $yearStart,
$yearEndNext->getTimestamp() => $yearEndNext,
$rangeStart->getTimestamp() => $rangeStart,
$rangeEndNext->getTimestamp() => $rangeEndNext,
];
foreach ($prices as $price) {
$from = $price->getDateFrom();
@@ -73,9 +73,9 @@ class PriceTimelineBuilder
$segStart = $boundaries[$i];
$segEndNext = $boundaries[$i + 1];
// Boundaries from prices outside the year are included to correctly detect
// overlaps at the year edges, but the segments themselves are skipped.
if ($segStart < $yearStart || $segStart >= $yearEndNext) {
// Boundaries from prices outside the range are included to correctly detect
// overlaps at the range edges, but the segments themselves are skipped.
if ($segStart < $rangeStart || $segStart >= $rangeEndNext) {
continue;
}
+18 -15
View File
@@ -51,7 +51,9 @@ class ServiceAvailabilityCalculator
}
/**
* Filter services array to only include those with remaining availability.
* Filter services array to only include those that are still bookable.
*
* Delegates to isServiceUnavailable() so that both entry points share one rule set.
*
* @param array<int, Service> $services Array of Service objects to filter
* @param BookingDto $bookingDto The booking data with participant selections
@@ -61,32 +63,28 @@ class ServiceAvailabilityCalculator
*/
public function filterAvailableServices(array $services, BookingDto $bookingDto, int $participantIndex): array
{
$remainingAvailability = $this->calculateRemainingAvailability($bookingDto, $participantIndex);
return array_filter($services, function (Service $service) use ($remainingAvailability) {
// If service has no availability limit set (null), treat as unlimited
if (null === $service->available) {
return array_filter($services, function (Service $service) use ($bookingDto, $participantIndex) {
// Services without an ID cannot be resolved against travel data - treat as available
if (null === $service->id) {
return true;
}
// If availability is 0, service is sold out at the API level
if (0 === $service->available) {
return false;
}
// For services with positive availability, check remaining availability
return ($remainingAvailability[$service->id] ?? $service->available) > 0;
return false === $this->isServiceUnavailable($service->id, $bookingDto, $participantIndex);
});
}
/**
* Check if a specific service is unavailable (sold out) for the current participant.
* Check if a specific service is unavailable for the current participant.
*
* A service is unavailable when it carries a booking stop (Buchungsstop) or when its
* contingent is exhausted, either at the API level or through selections made by the
* other participants of the current booking.
*
* @param int $serviceId The ID of the service to check
* @param BookingDto $bookingDto The booking data with participant selections
* @param int $participantIndex The index of the participant currently filling the form
*
* @return bool True if the service is unavailable (has availability limit and remaining is 0)
* @return bool True if the service is unavailable
*/
public function isServiceUnavailable(int $serviceId, BookingDto $bookingDto, int $participantIndex): bool
{
@@ -105,6 +103,11 @@ class ServiceAvailabilityCalculator
return false;
}
// A booking stop blocks the service regardless of its contingent
if (Constants::STATUS_BLOCKED === $service->status) {
return true;
}
// If no availability tracking (null), service is unlimited and available
if (null === $service->available) {
return false;
+1
View File
@@ -27,6 +27,7 @@ class AppExtension extends AbstractExtension
new TwigFilter('map_status', [AppRuntime::class, 'mapStatus']),
new TwigFilter('map_country', [AppRuntime::class, 'mapCountry']),
new TwigFilter('map_nationality', [AppRuntime::class, 'mapNationality']),
new TwigFilter('map_roles', [AppRuntime::class, 'mapRoles']),
];
}
+28
View File
@@ -12,6 +12,7 @@ use App\Form\Service\Condition\TravelStartCutoffReachedCondition;
use App\Form\Service\CreateFieldStateProvider;
use App\Form\Service\EditFieldStateProvider;
use App\Model\DomainConfig;
use App\Security\Role;
use App\Service\ParticipantEligibilityChecker;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RequestStack;
@@ -124,6 +125,33 @@ class AppRuntime implements RuntimeExtensionInterface
return $this->countryDataProvider->get($nationality)?->nationality;
}
/**
* Turns the roles stored on a User into the labels the edit form uses.
*
* ROLE_USER is dropped because every account holds it implicitly; a role without a label
* is passed through unchanged so it stays visible instead of silently disappearing.
*
* @param string[] $roles
*
* @return string[]
*/
public function mapRoles(array $roles): array
{
$labels = Role::labels();
$mapped = [];
foreach ($roles as $role) {
if ('ROLE_USER' === $role) {
continue;
}
$mapped[] = $labels[$role] ?? $role;
}
return $mapped;
}
public function isParticipantEligible(BookingDto $bookingDto, int $participantIndex): bool
{
return $this->participantEligibilityService->isParticipantEligible($bookingDto, $participantIndex);
+1 -1
View File
@@ -21,7 +21,7 @@
<span class="text-xl uppercase text-white group-hover:text-primary-light">Meine Daten</span>
</a>
</li>
{% if is_granted('ROLE_ADMIN') %}
{% if is_granted(constant('App\\Security\\Voter\\AdministrativeAccessVoter::ADMINISTRATIVE_ACCESS')) %}
<li class="py-4">
<a href="{{ path('app_admin_dashboard') }}" class="flex items-center space-x-2 group" hx-boost="false">
<svg class="w-8 h-8 text-white group-hover:text-primary-light" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><rect width="256" height="256" fill="none"/><circle cx="128" cy="128" r="40" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/><path d="M41.43,178.09A99.14,99.14,0,0,1,31.36,153.8l16.78-21a81.59,81.59,0,0,1,0-9.64l-16.77-21a99.43,99.43,0,0,1,10.05-24.3l26.71-3a81,81,0,0,1,6.81-6.81l3-26.7A99.14,99.14,0,0,1,102.2,31.36l21,16.78a81.59,81.59,0,0,1,9.64,0l21-16.77a99.43,99.43,0,0,1,24.3,10.05l3,26.71a81,81,0,0,1,6.81,6.81l26.7,3a99.14,99.14,0,0,1,10.07,24.29l-16.78,21a81.59,81.59,0,0,1,0,9.64l16.77,21a99.43,99.43,0,0,1-10,24.3l-26.71,3a81,81,0,0,1-6.81,6.81l-3,26.7a99.14,99.14,0,0,1-24.29,10.07l-21-16.78a81.59,81.59,0,0,1-9.64,0l-21,16.77a99.43,99.43,0,0,1-24.3-10l-3-26.71a81,81,0,0,1-6.81-6.81Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/></svg>
+21 -1
View File
@@ -22,9 +22,16 @@
<th>
{{ knp_pagination_sortable(pagination, 'BusPro Personen Id', 'user.personId') }}
</th>
<th>
Rollen
</th>
<th>
Häuser
</th>
<th>
{{ knp_pagination_sortable(pagination, 'Letzter Login', 'user.lastLoginAt') }}
</th>
<th></th>
</tr>
</thead>
<tbody>
@@ -39,13 +46,26 @@
<td>
{{ user.personId | default('-') }}
</td>
<td>
{{ user.roles | map_roles | join(', ') | default('-') }}
</td>
<td>
{{ user.hotelCodes | join(', ') | default('-') }}
</td>
<td>
{{ user.lastLoginAt | date('d.m.Y, H:i') }}
</td>
<td class="text-right">
<twig:dropdown>
<twig:dropdown:hxbutton url="{{ path('app_admin_user_edit', { 'id': user.id, 'r': return_url() }) }}">
Berechtigungen bearbeiten
</twig:dropdown:hxbutton>
</twig:dropdown>
</td>
</tr>
{% else %}
<tr>
<td colspan="4">
<td colspan="7">
{{ filter.isActive ? 'Keine Treffer für diesen Filter.' : 'Keine Daten...' }}
</td>
</tr>
+24
View File
@@ -0,0 +1,24 @@
{% extends 'htmx_modal_admin.html.twig' %}
{% form_theme form 'forms_admin.html.twig' %}
{% block title %}
Berechtigungen
{% endblock %}
{% block content %}
<div class="pb-4 text-sm text-gray-500">
{{ user.email }}
</div>
{{ form_start(form) }}
<div class="grid lg:grid-cols-2 gap-y-4 lg:gap-x-8">
{{ form_row(form.roles) }}
{{ form_row(form.hotelCodes) }}
</div>
<div class="flex justify-end pt-8">
<button type="submit" class="button button--primary button--small">
speichern
</button>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
{% endblock %}
@@ -62,7 +62,6 @@ class CrmAttributesResponseParserTest extends TestCase
self::assertContains('ROLE_ADMIN', $roles);
self::assertContains('ROLE_MANAGER', $roles);
self::assertContains('ROLE_TEAMER', $roles);
self::assertContains('ROLE_HOUSE_MANAGER', $roles);
}
/**
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Admin;
use App\Entity\User;
use App\Form\Admin\UserType;
use App\Security\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Forms;
class UserTypeTest extends TestCase
{
public function testStoredRolesArePreselectedWithoutTheImplicitRoleUser(): void
{
$user = (new User('[email protected]'))->setRoles([Role::TEAMER]);
self::assertSame([Role::TEAMER], $this->createForm($user)->get('roles')->getData());
}
public function testSubmittingRolesDoesNotStoreTheImplicitRoleUser(): void
{
$user = (new User('[email protected]'))->setRoles([Role::TEAMER]);
$form = $this->createForm($user);
$form->submit(['roles' => [Role::TEAMER, Role::GROUPS_MANAGER], 'hotelCodes' => []]);
self::assertTrue($form->isSynchronized());
// getRoles() prepends ROLE_USER; it must not have been persisted a second time.
self::assertSame(['ROLE_USER', Role::TEAMER, Role::GROUPS_MANAGER], $user->getRoles());
}
public function testClearingEveryCheckboxEmptiesTheAssignment(): void
{
$user = (new User('[email protected]'))
->setRoles([Role::TEAMER])
->setHotelCodes(['SSL'])
;
$form = $this->createForm($user);
$form->submit([]);
self::assertTrue($form->isSynchronized());
self::assertSame(['ROLE_USER'], $user->getRoles());
self::assertSame([], $user->getHotelCodes());
}
public function testHotelCodeMissingFromTheCatalogSurvivesAnEdit(): void
{
$user = (new User('[email protected]'))->setHotelCodes(['SSL', 'XYZ']);
$form = $this->createForm($user);
$form->submit(['roles' => [], 'hotelCodes' => ['SSL', 'XYZ']]);
self::assertTrue($form->isSynchronized());
self::assertSame(['SSL', 'XYZ'], $user->getHotelCodes());
}
public function testHotelCodesAreOfferedAlphabetically(): void
{
$user = (new User('[email protected]'))->setHotelCodes(['ASB']);
$choices = $this->createForm($user)->get('hotelCodes')->getConfig()->getOption('choices');
self::assertSame(['ASB', 'DKS', 'SSL'], array_values($choices));
}
/**
* @return FormInterface<User>
*/
private function createForm(User $user): FormInterface
{
return Forms::createFormFactoryBuilder()
->addType(new UserType(['SSL' => 'SSL', 'DKS' => 'DKS']))
->getFormFactory()
->create(UserType::class, $user)
;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Model\Filter;
use App\Form\Model\Filter\UserFilterDto;
use App\Security\Role;
use PHPUnit\Framework\TestCase;
class UserFilterDtoTest extends TestCase
{
public function testTheRoleChipShowsTheLabelRatherThanTheRoleName(): void
{
$filter = new UserFilterDto();
$filter->role = Role::GROUPS_ADMIN;
$chip = $filter->activeFilters()[0];
self::assertSame('Rolle', $chip->label);
self::assertSame('Preisrechner Admin', $chip->value);
self::assertSame(['role'], $chip->removeKeys);
}
public function testAnUnknownRoleIsShownVerbatim(): void
{
$filter = new UserFilterDto();
$filter->role = 'ROLE_LEGACY';
self::assertSame('ROLE_LEGACY', $filter->activeFilters()[0]->value);
}
public function testNoRoleMeansNoChip(): void
{
self::assertSame([], (new UserFilterDto())->activeFilters());
}
}
@@ -29,6 +29,12 @@ class ParticipantFieldOptionsProviderBabyTest extends TestCase
protected function setUp(): void
{
$this->serviceAvailabilityCalculator = $this->createMock(ServiceAvailabilityCalculator::class);
// These tests target age filtering, so availability filtering passes everything through
// unless a test stubs it explicitly
$this->serviceAvailabilityCalculator
->method('filterAvailableServices')
->willReturnArgument(0)
;
$insuranceService = $this->createMock(InsuranceManager::class);
$priceCalculatorService = $this->createMock(BookingPriceCalculator::class);
$serviceLabelFormatter = new ServiceLabelFormatter();
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Service;
use App\BusProNet\Constants;
use App\BusProNet\Model\Booking;
use App\BusProNet\Model\Service;
use App\BusProNet\Model\Travel;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Service\ParticipantFieldOptionsProvider;
use App\Service\BookingPriceCalculator;
use App\Service\InsuranceManager;
use App\Service\ServiceAvailabilityCalculator;
use App\Service\ServiceLabelFormatter;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Unavailable ski passes are removed from the choices instead of being rendered read-only.
*
* Uses a real ServiceAvailabilityCalculator so the filtering and the availability rules are
* covered together.
*/
class ParticipantFieldOptionsProviderSkiPassAvailabilityTest extends TestCase
{
private ParticipantFieldOptionsProvider $provider;
protected function setUp(): void
{
$translator = $this->createMock(TranslatorInterface::class);
$translator->method('trans')->willReturnArgument(0);
$this->provider = new ParticipantFieldOptionsProvider(
new ServiceAvailabilityCalculator(),
$this->createMock(InsuranceManager::class),
$this->createMock(BookingPriceCalculator::class),
new ServiceLabelFormatter(),
$translator
);
}
public function testSoldOutSkiPassIsNotRendered(): void
{
$bookingDto = $this->createBookingDto([
$this->createSkiPass(id: 1, available: null),
$this->createSkiPass(id: 2, available: 0),
]);
$this->assertSame([1], $this->getSkiPassChoiceIds($bookingDto));
}
public function testSkiPassOnBookingStopIsNotRendered(): void
{
$bookingDto = $this->createBookingDto([
$this->createSkiPass(id: 1, available: null),
$this->createSkiPass(id: 2, available: 20, status: Constants::STATUS_BLOCKED),
]);
$this->assertSame([1], $this->getSkiPassChoiceIds($bookingDto));
}
public function testSkiPassClaimedByOtherParticipantIsNotRendered(): void
{
$limitedSkiPass = $this->createSkiPass(id: 2, available: 1);
$bookingDto = $this->createBookingDto([
$this->createSkiPass(id: 1, available: null),
$limitedSkiPass,
]);
$otherParticipant = new ParticipantDto();
$otherParticipant->index = 1;
$otherParticipant->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$otherParticipant->skiPass = $limitedSkiPass;
$bookingDto->participants[1] = $otherParticipant;
$this->assertSame([1], $this->getSkiPassChoiceIds($bookingDto));
}
public function testSelectedSkiPassStaysRenderedWhenItSoldOut(): void
{
$soldOutSkiPass = $this->createSkiPass(id: 2, available: 0);
$bookingDto = $this->createBookingDto([
$this->createSkiPass(id: 1, available: null),
$soldOutSkiPass,
]);
$bookingDto->participants[0]->skiPass = $soldOutSkiPass;
$this->assertSame([1, 2], $this->getSkiPassChoiceIds($bookingDto));
}
public function testBookedSkiPassStaysRenderedAfterSwitchingToAnotherPassInEditMode(): void
{
$blockedSkiPass = $this->createSkiPass(id: 2, available: null, status: Constants::STATUS_BLOCKED);
$bookableSkiPass = $this->createSkiPass(id: 1, available: null);
$bookingDto = $this->createBookingDto([$bookableSkiPass, $blockedSkiPass]);
$bookedSkiPass = clone $blockedSkiPass;
$bookedSkiPass->mapping = [0];
$booking = new Booking();
$booking->additionalServices = [2 => $bookedSkiPass];
$bookingDto->booking = $booking;
// The participant already moved away from the booked pass - it still has to be offered
// so the switch stays reversible
$bookingDto->participants[0]->skiPass = $bookableSkiPass;
$this->assertSame(BookingDto::MODE_EDIT, $bookingDto->getMode());
$this->assertSame([1, 2], $this->getSkiPassChoiceIds($bookingDto));
}
public function testRenderedSkiPassesCarryNoSoldOutTooltip(): void
{
$soldOutSkiPass = $this->createSkiPass(id: 2, available: 0);
$bookingDto = $this->createBookingDto([
$this->createSkiPass(id: 1, available: null),
$soldOutSkiPass,
]);
$bookingDto->participants[0]->skiPass = $soldOutSkiPass;
$options = $this->provider->getFieldOptions('skiPass', $bookingDto, 0);
$choiceAttr = $options['choice_attr'];
foreach ($options['choices'] as $choice) {
$attributes = $choiceAttr($choice);
$this->assertArrayNotHasKey('readonly', $attributes);
$this->assertArrayNotHasKey('data-tooltip', $attributes);
}
}
/** @return int[] */
private function getSkiPassChoiceIds(BookingDto $bookingDto): array
{
$options = $this->provider->getFieldOptions('skiPass', $bookingDto, 0);
if (true === empty($options)) {
return [];
}
$choiceIds = array_map(static fn (Service $service): ?int => $service->id, $options['choices']);
sort($choiceIds);
return $choiceIds;
}
/** @param Service[] $skiPasses */
private function createBookingDto(array $skiPasses): BookingDto
{
$travel = new Travel();
$travel->dateFrom = new \DateTimeImmutable('2027-01-09');
$travel->dateTo = new \DateTimeImmutable('2027-01-16');
foreach ($skiPasses as $skiPass) {
$travel->additionalServices[$skiPass->id] = $skiPass;
}
$bookingDto = new BookingDto($travel, 1);
$participant = new ParticipantDto();
$participant->index = 0;
$participant->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$bookingDto->participants[0] = $participant;
return $bookingDto;
}
private function createSkiPass(int $id, ?int $available, string $status = Constants::STATUS_AVAILABLE): Service
{
$service = new Service();
$service->id = $id;
$service->label = sprintf('Skipass %d', $id);
$service->subType = Constants::TOKEN_SKI_PASS;
$service->price = (float) $id;
$service->available = $available;
$service->status = $status;
return $service;
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
declare(strict_types=1);
namespace App\Tests\Security;
use App\BusProNet\ApiClient;
use App\BusProNet\Model\CrmAttributes;
use App\BusProNet\Model\PersonalData;
use App\Entity\User;
use App\Security\BpnAuthenticator;
use App\Security\Crypt;
use App\Security\Role;
use App\Service\ProfileCompletenessChecker;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
/**
* Covers who may grant roles: BusPro backend users can edit their own CRM selections, so the
* import must not be a channel for privilege escalation.
*/
class BpnAuthenticatorTest extends TestCase
{
public function testNewAccountIsSeededWithTheImportableRolesOnly(): void
{
$persisted = null;
$authenticator = $this->authenticator(
$this->crmAttributes([Role::ADMIN, Role::TEAMER, Role::GROUPS_ADMIN], ['SSL', 'SSL']),
null,
$persisted,
);
$user = $this->loadUser($authenticator);
self::assertSame($persisted, $user);
self::assertSame(['ROLE_USER', Role::TEAMER], $user->getRoles());
self::assertSame(['SSL'], $user->getHotelCodes());
}
public function testExistingAccountKeepsTheRolesAnAdministratorAssigned(): void
{
$existing = (new User('[email protected]'))
->setRoles([Role::TEAMER, Role::GROUPS_MANAGER])
->setHotelCodes(['DKS'])
;
$persisted = null;
$authenticator = $this->authenticator(
$this->crmAttributes([Role::ADMIN, Role::CUSTOMER], ['SSL']),
$existing,
$persisted,
);
$user = $this->loadUser($authenticator);
self::assertNull($persisted, 'an existing account must not be persisted again');
self::assertSame(['ROLE_USER', Role::TEAMER, Role::GROUPS_MANAGER], $user->getRoles());
self::assertSame(['DKS'], $user->getHotelCodes());
self::assertNotNull($user->getLastLoginAt(), 'the rest of the profile is still synced');
}
/**
* @param string[] $roles
* @param string[] $hotelCodes
*/
private function crmAttributes(array $roles, array $hotelCodes): CrmAttributes
{
$attributes = new CrmAttributes();
$attributes->roles = $roles;
$attributes->hotelCodes = $hotelCodes;
return $attributes;
}
private function authenticator(CrmAttributes $crmAttributes, ?User $existing, ?User &$persisted): BpnAuthenticator
{
$personalData = new PersonalData();
$personalData->personId = 42;
$personalData->addressId = 4711;
$apiClient = $this->createMock(ApiClient::class);
$apiClient->method('getPersonalData')->willReturn($personalData);
$apiClient->method('getCrmAttributes')->willReturn($crmAttributes);
$repository = $this->createMock(EntityRepository::class);
$repository->method('findOneBy')->willReturn($existing);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->method('getRepository')->willReturn($repository);
$entityManager
->method('persist')
->willReturnCallback(static function (object $entity) use (&$persisted): void {
$persisted = $entity;
})
;
$crypt = $this->createMock(Crypt::class);
$crypt->method('encrypt')->willReturn('encrypted');
$completenessChecker = $this->createMock(ProfileCompletenessChecker::class);
$completenessChecker->method('isComplete')->willReturn(true);
return new BpnAuthenticator(
$this->createMock(UrlGeneratorInterface::class),
$apiClient,
$entityManager,
$crypt,
$completenessChecker,
$this->createMock(LoggerInterface::class),
);
}
private function loadUser(BpnAuthenticator $authenticator): User
{
$request = new Request();
$request->request->set('_username', '[email protected]');
$request->request->set('_password', 'secret');
$badge = $authenticator->authenticate($request)->getBadge(UserBadge::class);
self::assertInstanceOf(UserBadge::class, $badge);
$user = $badge->getUser();
self::assertInstanceOf(User::class, $user);
return $user;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Tests\Security;
use App\Security\Role;
use PHPUnit\Framework\TestCase;
class RoleTest extends TestCase
{
public function testPrivilegedRolesAreNeverImported(): void
{
$roles = Role::filterImportable([
Role::TEAMER,
Role::ADMIN,
Role::GROUPS_ADMIN,
Role::GROUPS_MANAGER,
Role::HOUSE_MANAGER,
]);
self::assertSame([Role::TEAMER, Role::HOUSE_MANAGER], $roles);
}
public function testResultIsADedupedList(): void
{
// CrmAttributesResponseParser applies array_unique(), which preserves keys — a
// non-list would be persisted as a JSON object instead of an array.
$roles = Role::filterImportable([0 => Role::ADMIN, 2 => Role::TEAMER, 5 => Role::TEAMER]);
self::assertSame([Role::TEAMER], $roles);
self::assertSame(array_keys($roles), range(0, \count($roles) - 1));
}
public function testAccountWithOnlyPrivilegedRolesFallsBackToCustomer(): void
{
self::assertSame([Role::CUSTOMER], Role::filterImportable([Role::ADMIN]));
self::assertSame([Role::CUSTOMER], Role::filterImportable([]));
}
public function testEveryRoleHasALabel(): void
{
self::assertSame(Role::ALL, array_keys(Role::labels()));
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Entity\Groups\AccommodationPrice;
use App\Service\GroupsPriceCalculator;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
class GroupsPriceCalculatorTest extends TestCase
{
private const int NIGHTS = 3;
public function testFreeBoardDoesNotTriggerUndersubscriptionSurcharge(): void
{
$result = $this->calculate(30, 0);
self::assertSame(0, $result['undersubscriptionSurcharge']);
self::assertNull($result['undersubscriptionThreshold']);
self::assertSame(0, $result['boardPrice']);
}
public function testNoBoardDoesNotTriggerUndersubscriptionSurcharge(): void
{
$result = $this->calculate(30, null);
self::assertSame(0, $result['undersubscriptionSurcharge']);
self::assertNull($result['undersubscriptionThreshold']);
self::assertSame(0, $result['boardPrice']);
}
public function testPaidBoardBelow40TriggersTheLowerThresholdSurcharge(): void
{
$result = $this->calculate(30, 1500);
self::assertSame(30 * 500 * self::NIGHTS, $result['undersubscriptionSurcharge']);
self::assertSame(40, $result['undersubscriptionThreshold']);
self::assertSame(1500 * 30 * self::NIGHTS, $result['boardPrice']);
}
public function testPaidBoardBelow50TriggersTheUpperThresholdSurcharge(): void
{
$result = $this->calculate(45, 1500);
self::assertSame(45 * 250 * self::NIGHTS, $result['undersubscriptionSurcharge']);
self::assertSame(50, $result['undersubscriptionThreshold']);
}
/**
* @return array<string, mixed>
*/
private function calculate(int $paxCount, ?int $boardServicePrice): array
{
$dateFrom = new \DateTimeImmutable('2026-07-01');
$dateTo = $dateFrom->modify(sprintf('+%d days', self::NIGHTS));
$price = (new AccommodationPrice())
->setDateFrom($dateFrom->modify('-1 month'))
->setDateTo($dateTo->modify('+1 month'))
->setIncludedPax(20)
->setPricePerNight(100_00)
->setPriceAdditionalPerson(10_00)
->setMinNights(1);
$calculator = new GroupsPriceCalculator(new PriceTimelineBuilder(), [
'runningCostsEur' => 0,
'runningCostsChf' => 0,
'undersubscription30Eur' => 5.0,
'undersubscription30Chf' => 6.0,
'undersubscription40Eur' => 2.5,
'undersubscription40Chf' => 3.0,
]);
return $calculator->calculateFromSnapshots(
$paxCount,
0,
self::NIGHTS,
$dateFrom,
$dateTo,
[$price],
$boardServicePrice,
[],
'EUR',
);
}
}
@@ -67,6 +67,27 @@ class PriceTimelineBuilderTest extends TestCase
$this->assertSame('2026-12-31', $result[0]->dateTo);
}
public function testInProgressPriceIsClampedToMidYearRangeStart(): void
{
$price = $this->makePrice('2026-06-01', '2026-09-30', pricePerNight: 8000);
$result = $this->builder->buildTimeline([$price], new \DateTimeImmutable('2026-08-06'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(1, $result);
$this->assertSame('2026-08-06', $result[0]->dateFrom);
$this->assertSame('2026-09-30', $result[0]->dateTo);
$this->assertSame(80.0, $result[0]->pricePerNight);
}
public function testPriceEndingBeforeRangeStartIsOmitted(): void
{
$price = $this->makePrice('2026-02-01', '2026-05-31', pricePerNight: 8000);
$result = $this->builder->buildTimeline([$price], new \DateTimeImmutable('2026-08-06'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertSame([], $result);
}
public function testDiscountSplitsBasePeriodIntoThreeRows(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
@@ -51,6 +51,40 @@ class ServiceAvailabilityCalculatorTest extends TestCase
$this->assertTrue($this->calculator->isServiceUnavailable(1, $bookingDto, 0));
}
public function testServiceOnBookingStopIsUnavailableDespiteUnlimitedQuota(): void
{
$skiPass = $this->createSkiPass(id: 1, available: null, status: Constants::STATUS_BLOCKED);
$bookingDto = $this->createBookingDtoWithServices([$skiPass]);
$this->assertTrue($this->calculator->isServiceUnavailable(1, $bookingDto, 0));
}
public function testServiceOnBookingStopIsUnavailableDespiteRemainingQuota(): void
{
$skiPass = $this->createSkiPass(id: 1, available: 10, status: Constants::STATUS_BLOCKED);
$bookingDto = $this->createBookingDtoWithServices([$skiPass]);
$this->assertTrue($this->calculator->isServiceUnavailable(1, $bookingDto, 0));
}
public function testFilterAvailableServicesRemovesSoldOutAndBlockedServices(): void
{
$bookable = $this->createSkiPass(id: 1, available: 5);
$soldOut = $this->createSkiPass(id: 2, available: 0);
$blocked = $this->createSkiPass(id: 3, available: null, status: Constants::STATUS_BLOCKED);
$unlimited = $this->createSkiPass(id: 4, available: null);
$bookingDto = $this->createBookingDtoWithServices([$bookable, $soldOut, $blocked, $unlimited]);
$filtered = $this->calculator->filterAvailableServices(
$bookingDto->travel->additionalServices,
$bookingDto,
0
);
$this->assertSame([1, 4], array_keys($filtered));
}
private function createParkingService(int $id, int $available): Service
{
$service = new Service();
@@ -62,6 +96,18 @@ class ServiceAvailabilityCalculatorTest extends TestCase
return $service;
}
private function createSkiPass(int $id, ?int $available, string $status = Constants::STATUS_AVAILABLE): Service
{
$service = new Service();
$service->id = $id;
$service->label = sprintf('Skipass %d', $id);
$service->subType = Constants::TOKEN_SKI_PASS;
$service->available = $available;
$service->status = $status;
return $service;
}
private function createBookingDtoWithServices(array $services): BookingDto
{
$travel = new Travel();
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Tests\Twig;
use App\Security\Role;
use App\Twig\AppRuntime;
use PHPUnit\Framework\TestCase;
class AppRuntimeMapRolesTest extends TestCase
{
public function testStoredRolesAreLabelledLikeInTheEditForm(): void
{
self::assertSame(
['Teamer:in', 'Preisrechner'],
$this->runtime()->mapRoles([Role::TEAMER, Role::GROUPS_MANAGER]),
);
}
public function testImplicitRoleUserIsNotListed(): void
{
self::assertSame(['Administration'], $this->runtime()->mapRoles(['ROLE_USER', Role::ADMIN]));
self::assertSame([], $this->runtime()->mapRoles(['ROLE_USER']));
}
public function testUnknownRoleStaysVisible(): void
{
self::assertSame(['ROLE_LEGACY'], $this->runtime()->mapRoles(['ROLE_LEGACY']));
}
private function runtime(): AppRuntime
{
return (new \ReflectionClass(AppRuntime::class))->newInstanceWithoutConstructor();
}
}