feat: add admin crud for resources and rooms

This commit is contained in:
fromme committed 2026-09-17 16:26:29 +02:00
1 parent ad5d5acb00
commit 3d67942c62
19 files changed
+1059 -4

No files matched your search

@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Resource;
use App\Entity\Resource;
use App\Enum\ResourceType;
use App\Form\Admin\ResourceFormType;
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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(Role::ADMIN)]
final class CreateController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly LoggerInterface $logger,
) {
}
/**
* GET renders the modal, POST saves it. An invalid submit re-renders the modal as a 422, which
* htmx swaps in place; a valid one navigates back to the list.
*/
#[Route('/admin/resources/new/{type}', name: 'app_admin_resource_new', methods: ['GET', 'POST'])]
public function index(Request $request, ResourceType $type): Response
{
$resource = new Resource($type, '');
$form = $this->createForm(ResourceFormType::class, $resource, [
'action' => $this->generateUrl('app_admin_resource_new', ['type' => $type->value]),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->persist($resource);
$this->em->flush();
$this->logger->info('Admin created a resource.', [
'admin' => $this->getUser()?->getUserIdentifier(),
'resource_id' => $resource->getId(),
'type' => $type->value,
'label' => $resource->getLabel(),
]);
$this->addFlash('success', \sprintf('%s angelegt.', $resource->getLabel()));
return new HxRedirectResponse($this->generateUrl('app_admin_resource'));
}
return $this->render('admin/_modal_resource.html.twig', [
'form' => $form,
'resource' => $resource,
]);
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Resource;
use App\Entity\Resource;
use App\Form\Admin\ResourceFormType;
use App\Htmx\HxRedirectResponse;
use App\Repository\BookingRepository;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Renaming, moving to another room, and retiring or reactivating.
*
* Retiring is a checkbox here rather than a confirmation modal of its own: it deletes nothing and
* is undone by ticking the box again. What it does leave behind -- bookings that still point at
* the resource -- is named in the flash, so the administrator can release them from
* /admin/bookings if they should not stand.
*/
#[IsGranted(Role::ADMIN)]
final class EditController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly BookingRepository $bookings,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/resources/{id}/edit', name: 'app_admin_resource_edit', methods: ['GET', 'POST'])]
public function index(Request $request, Resource $resource): Response
{
$wasActive = $resource->isActive();
$form = $this->createForm(ResourceFormType::class, $resource, [
'action' => $this->generateUrl('app_admin_resource_edit', ['id' => $resource->getId()]),
'with_active' => true,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->flush();
$this->logger->info('Admin edited a resource.', [
'admin' => $this->getUser()?->getUserIdentifier(),
'resource_id' => $resource->getId(),
'label' => $resource->getLabel(),
'group' => $resource->getGroup()?->getLabel(),
'active' => $resource->isActive(),
]);
$remaining = $wasActive && !$resource->isActive()
? $this->bookings->countFromDate($resource, new \DateTimeImmutable('today'))
: 0;
if ($remaining > 0) {
$this->addFlash('warning', \sprintf(
'%s ist nicht mehr buchbar. %d bestehende Buchungen ab heute bleiben erhalten.',
$resource->getLabel(),
$remaining,
));
} else {
$this->addFlash('success', \sprintf('%s gespeichert.', $resource->getLabel()));
}
return new HxRedirectResponse($this->generateUrl('app_admin_resource'));
}
return $this->render('admin/_modal_resource.html.twig', [
'form' => $form,
'resource' => $resource,
]);
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Resource;
use App\Enum\ResourceType;
use App\Repository\ResourceGroupRepository;
use App\Repository\ResourceRepository;
use App\Security\Role;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Everything that can be booked, per type and room, retired resources included.
*
* Creating and editing happen in modals that navigate back here once saved. Nothing is ever
* deleted except an empty room: a resource with history is retired instead, so its bookings keep
* resolving.
*/
#[IsGranted(Role::ADMIN)]
final class IndexController extends AbstractController
{
public function __construct(
private readonly ResourceRepository $resources,
private readonly ResourceGroupRepository $groups,
) {
}
#[Route('/admin/resources', name: 'app_admin_resource', methods: ['GET'])]
public function index(): Response
{
$sections = [];
foreach (ResourceType::cases() as $type) {
$byGroup = [];
$ungrouped = [];
foreach ($this->resources->findAllByType($type) as $resource) {
if (null === $resource->getGroup()) {
$ungrouped[] = $resource;
} else {
$byGroup[$resource->getGroup()->getId()][] = $resource;
}
}
$sections[] = [
'type' => $type,
// Every group, empty ones too -- an empty room is the only thing that can be
// deleted, so it has to be visible.
'groups' => array_map(
static fn ($group): array => ['group' => $group, 'resources' => $byGroup[$group->getId()] ?? []],
$this->groups->findByType($type),
),
'ungrouped' => $ungrouped,
];
}
return $this->render('admin/resources.html.twig', [
'sections' => $sections,
]);
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\ResourceGroup;
use App\Entity\ResourceGroup;
use App\Enum\ResourceType;
use App\Form\Admin\ResourceGroupFormType;
use App\Htmx\HxRedirectResponse;
use App\Repository\ResourceGroupRepository;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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)]
final class CreateController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly ResourceGroupRepository $groups,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/resource-groups/new/{type}', name: 'app_admin_resource_group_new', methods: ['GET', 'POST'])]
public function index(Request $request, ResourceType $type): Response
{
// Prefilled to come after the existing ones, which is where a new room usually belongs.
$existing = $this->groups->findByType($type);
$position = [] === $existing ? 0 : max(array_map(static fn (ResourceGroup $group): int => $group->getPosition(), $existing)) + 1;
$group = new ResourceGroup($type, '', $position);
$form = $this->createForm(ResourceGroupFormType::class, $group, [
'action' => $this->generateUrl('app_admin_resource_group_new', ['type' => $type->value]),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->persist($group);
$this->em->flush();
$this->logger->info('Admin created a resource group.', [
'admin' => $this->getUser()?->getUserIdentifier(),
'group_id' => $group->getId(),
'type' => $type->value,
'label' => $group->getLabel(),
]);
$this->addFlash('success', \sprintf('%s angelegt.', $group->getLabel()));
return new HxRedirectResponse($this->generateUrl('app_admin_resource'));
}
return $this->render('admin/_modal_resource_group.html.twig', [
'form' => $form,
'group' => $group,
]);
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\ResourceGroup;
use App\Controller\Traits\ConfirmedActionTrait;
use App\Entity\ResourceGroup;
use App\Htmx\HxRedirectResponse;
use App\Repository\ResourceRepository;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Only an empty room can be deleted -- retired resources count, since they still sit in it.
*
* The foreign key would allow more (ON DELETE SET NULL), but silently turning a room's desks into
* ungrouped ones is never what deleting a room means. Move them first.
*/
#[IsGranted(Role::ADMIN)]
final class DeleteController extends AbstractController
{
use ConfirmedActionTrait;
public function __construct(
private readonly EntityManagerInterface $em,
private readonly ResourceRepository $resources,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/resource-groups/{id}/delete', name: 'app_admin_resource_group_delete', methods: ['GET', 'POST'])]
public function index(Request $request, ResourceGroup $group): Response
{
if ($this->resources->count(['group' => $group]) > 0) {
throw $this->createAccessDeniedException('Only an empty resource group can be deleted.');
}
if (!$request->isMethod(Request::METHOD_POST)) {
return $this->render('admin/_modal_resource_group_delete.html.twig', [
'group' => $group,
'csrf_token_id' => 'delete-resource-group-'.$group->getId(),
]);
}
$this->denyUnlessCsrfValid($request, 'delete-resource-group-'.$group->getId());
$this->logger->info('Admin deleted a resource group.', [
'admin' => $this->getUser()?->getUserIdentifier(),
'group_id' => $group->getId(),
'label' => $group->getLabel(),
]);
$label = $group->getLabel();
$this->em->remove($group);
$this->em->flush();
$this->addFlash('success', \sprintf('%s gelöscht.', $label));
return new HxRedirectResponse($this->generateUrl('app_admin_resource'));
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\ResourceGroup;
use App\Entity\ResourceGroup;
use App\Form\Admin\ResourceGroupFormType;
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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted(Role::ADMIN)]
final class EditController extends AbstractController
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/resource-groups/{id}/edit', name: 'app_admin_resource_group_edit', methods: ['GET', 'POST'])]
public function index(Request $request, ResourceGroup $group): Response
{
$form = $this->createForm(ResourceGroupFormType::class, $group, [
'action' => $this->generateUrl('app_admin_resource_group_edit', ['id' => $group->getId()]),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->flush();
$this->logger->info('Admin edited a resource group.', [
'admin' => $this->getUser()?->getUserIdentifier(),
'group_id' => $group->getId(),
'label' => $group->getLabel(),
'position' => $group->getPosition(),
]);
$this->addFlash('success', \sprintf('%s gespeichert.', $group->getLabel()));
return new HxRedirectResponse($this->generateUrl('app_admin_resource'));
}
return $this->render('admin/_modal_resource_group.html.twig', [
'form' => $form,
'group' => $group,
]);
}
}
+3
View File
@@ -7,6 +7,7 @@ namespace App\Entity;
use App\Enum\ResourceType;
use App\Repository\ResourceRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
@@ -14,6 +15,7 @@ use Symfony\Component\Validator\Constraints as Assert;
*/
#[ORM\Entity(repositoryClass: ResourceRepository::class)]
#[ORM\UniqueConstraint(name: 'uniq_resource_label', columns: ['type', 'label'])]
#[UniqueEntity(fields: ['type', 'label'], message: 'Diese Bezeichnung ist bereits vergeben.', errorPath: 'label')]
class Resource
{
#[ORM\Id]
@@ -26,6 +28,7 @@ class Resource
#[ORM\Column(length: 50)]
#[Assert\NotBlank]
#[Assert\Length(max: 50)]
private string $label;
/**
+4 -2
View File
@@ -7,14 +7,14 @@ namespace App\Entity;
use App\Enum\ResourceType;
use App\Repository\ResourceGroupRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Where a bookable thing physically is: a room of the office, an area of the car park.
*
* A group belongs to exactly one ResourceType, because "Raum Nord" means nothing for parking.
* It is a description of the building, so it is configuration seeded alongside the resources
* rather than something a user creates.
* It is a description of the building, maintained by an administrator under /admin/resources.
*
* Note there is deliberately no method named `group`, `label` or `position` other than the plain
* accessors: Twig resolves `x.label` to a method of that literal name before trying getLabel(),
@@ -22,6 +22,7 @@ use Symfony\Component\Validator\Constraints as Assert;
*/
#[ORM\Entity(repositoryClass: ResourceGroupRepository::class)]
#[ORM\UniqueConstraint(name: 'uniq_resource_group_label', columns: ['type', 'label'])]
#[UniqueEntity(fields: ['type', 'label'], message: 'Diese Bezeichnung ist bereits vergeben.', errorPath: 'label')]
class ResourceGroup
{
#[ORM\Id]
@@ -34,6 +35,7 @@ class ResourceGroup
#[ORM\Column(length: 50)]
#[Assert\NotBlank]
#[Assert\Length(max: 50)]
private string $label;
/** Draw and list order within the type. */
+13 -2
View File
@@ -8,8 +8,8 @@ namespace App\Enum;
* The kinds of thing that can be booked.
*
* **This enum is the extension point.** The dashboard builds one tile per case, the board route
* accepts one backing value per case, and the floor plan renders every kind the same way.
* Adding a third bookable kind is therefore: a case here and rows in `app:seed`.
* accepts one backing value per case, and the floor plan and the admin screen render every kind
* the same way. Adding a third bookable kind is therefore: a case here.
* Nothing else needs editing — in particular no template lists the kinds by hand.
*
* The backing value is both what is persisted in `resource.type` and what appears in a URL, so
@@ -45,6 +45,17 @@ enum ResourceType: string
};
}
/**
* What a ResourceGroup of this kind is called: an office has rooms, a car park has areas.
*/
public function groupLabel(): string
{
return match ($this) {
self::DESK => 'Raum',
self::PARKING => 'Bereich',
};
}
public function icon(): string
{
return match ($this) {
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace App\Form\Admin;
use App\Entity\Resource;
use App\Entity\ResourceGroup;
use App\Enum\ResourceType;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* A desk or parking spot. The type is not a field: it is fixed by the route that creates the
* resource and never changes afterwards, which is what lets the group choices be limited to it.
*/
final class ResourceFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$resource = $builder->getData();
\assert($resource instanceof Resource);
$type = $resource->getType();
$builder
->add('label', TextType::class, [
'label' => 'Bezeichnung',
])
->add('group', EntityType::class, [
'label' => $type->groupLabel(),
'class' => ResourceGroup::class,
'required' => false,
'placeholder' => 'Ohne '.$type->groupLabel(),
'choice_label' => 'label',
// A group of another type would be tampering, and the choice list rejects it.
'query_builder' => static fn (EntityRepository $repository) => $repository
->createQueryBuilder('g')
->andWhere('g.type = :type')
->setParameter('type', $type)
->orderBy('g.position', 'ASC')
->addOrderBy('g.label', 'ASC'),
]);
// Only on edit: a resource is created bookable, and retiring it is a later decision.
if ($options['with_active']) {
$builder->add('active', CheckboxType::class, [
'label' => 'Buchbar',
'help' => 'Nicht buchbare Plätze erscheinen nicht mehr im Plan. Bestehende Buchungen bleiben erhalten.',
'required' => false,
]);
}
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Resource::class,
'with_active' => false,
]);
$resolver->setAllowedTypes('with_active', 'bool');
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Form\Admin;
use App\Entity\ResourceGroup;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* A room or area. Like a resource, its type is fixed by the route that creates it.
*/
final class ResourceGroupFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('label', TextType::class, [
'label' => 'Bezeichnung',
])
->add('position', IntegerType::class, [
'label' => 'Reihenfolge',
'help' => 'Kleinere Zahlen stehen im Plan weiter oben.',
// The setter takes an int, so a cleared field must not reach it as null.
'empty_data' => '0',
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ResourceGroup::class,
]);
}
}
+15
View File
@@ -205,6 +205,21 @@ class BookingRepository extends ServiceEntityRepository
return $qb->getQuery()->getResult();
}
/**
* Bookings from a day onwards, so retiring a resource can say what it leaves behind.
*/
public function countFromDate(Resource $resource, \DateTimeImmutable $from): int
{
return (int) $this->createQueryBuilder('b')
->select('COUNT(b.id)')
->andWhere('b.resource = :resource')
->andWhere('b.date >= :from')
->setParameter('resource', $resource)
->setParameter('from', $from->setTime(0, 0))
->getQuery()
->getSingleScalarResult();
}
/**
* The occurrences an "end this series" would remove.
*
+17
View File
@@ -42,6 +42,23 @@ class ResourceRepository extends ServiceEntityRepository
->getResult();
}
/**
* Retired ones included, for the admin screen -- which is where they are reactivated.
*
* @return list<Resource>
*/
public function findAllByType(ResourceType $type): array
{
return $this->createQueryBuilder('r')
->leftJoin('r.group', 'g')
->addSelect('g')
->andWhere('r.type = :type')
->setParameter('type', $type)
->orderBy('r.label', 'ASC')
->getQuery()
->getResult();
}
/**
* @return list<Resource>
*/