Compare commits

..

4 commits

16 changed files with 1067 additions and 12 deletions

View file

@ -9,6 +9,8 @@ use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElementRequest; use App\Element\UseCases\DeleteChildElement\DeleteChildElementRequest;
use App\Element\UseCases\GetElement\GetElement; use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\GetElement\GetElementRequest; use App\Element\UseCases\GetElement\GetElementRequest;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\ReorderChildElements\ReorderChildElementsRequest;
use App\Element\UseCases\UpdateElement\UpdateElement; use App\Element\UseCases\UpdateElement\UpdateElement;
use App\Element\UseCases\UpdateElement\UpdateElementRequest; use App\Element\UseCases\UpdateElement\UpdateElementRequest;
use App\Exceptions\BadRequestException; use App\Exceptions\BadRequestException;
@ -24,6 +26,7 @@ class ElementController
private GetElement $getElement, private GetElement $getElement,
private CreateChildElement $createChildElement, private CreateChildElement $createChildElement,
private DeleteChildElement $deleteChildElement, private DeleteChildElement $deleteChildElement,
private ReorderChildElements $reorderChildElements,
private UpdateElement $updateElement, private UpdateElement $updateElement,
private FileUploader $fileUploader, private FileUploader $fileUploader,
) { ) {
@ -104,6 +107,37 @@ class ElementController
return new JsonResponse(null, 204); return new JsonResponse(null, 204);
} }
public function reorderChildren(
Request $request,
?int $parentId,
): JsonResponse {
try {
$childElements = $this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentId,
childElementIds: $this->intArrayInput(
$request,
'childElementIds',
),
)
);
} catch (BadRequestException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 400);
} catch (NotFoundException $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
], 404);
}
return new JsonResponse([
'childElements' => $this->buildElementSummaryPayloads(
$childElements,
),
], 200);
}
public function update(Request $request): JsonResponse public function update(Request $request): JsonResponse
{ {
$file = $this->uploadedFileInput($request, 'file'); $file = $this->uploadedFileInput($request, 'file');
@ -158,6 +192,38 @@ class ElementController
return null; return null;
} }
/**
* @return int[]|null
*/
private function intArrayInput(Request $request, string $key): ?array
{
if (! $request->exists($key)) {
return null;
}
$value = $request->input($key);
if (! is_array($value)) {
return null;
}
$integerValues = [];
foreach ($value as $item) {
if (is_int($item)) {
$integerValues[] = $item;
continue;
}
if (is_string($item) && ctype_digit($item)) {
$integerValues[] = (int) $item;
continue;
}
return null;
}
return $integerValues;
}
private function stringInput(Request $request, string $key): ?string private function stringInput(Request $request, string $key): ?string
{ {
if (! $request->exists($key)) { if (! $request->exists($key)) {

View file

@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $long_pdf_path * @property string|null $long_pdf_path
* @property string|null $youtube_url * @property string|null $youtube_url
* @property int|null $parent_element_id * @property int|null $parent_element_id
* @property int $sort_order
* *
* @method static Builder<static>|ElementModel newModelQuery() * @method static Builder<static>|ElementModel newModelQuery()
* @method static Builder<static>|ElementModel newQuery() * @method static Builder<static>|ElementModel newQuery()
@ -30,6 +31,7 @@ use Illuminate\Database\Eloquent\Model;
* @method static Builder<static>|ElementModel whereShortPdfPath($value) * @method static Builder<static>|ElementModel whereShortPdfPath($value)
* @method static Builder<static>|ElementModel whereLongPdfPath($value) * @method static Builder<static>|ElementModel whereLongPdfPath($value)
* @method static Builder<static>|ElementModel whereYoutubeUrl($value) * @method static Builder<static>|ElementModel whereYoutubeUrl($value)
* @method static Builder<static>|ElementModel whereSortOrder($value)
* *
* @mixin \Eloquent * @mixin \Eloquent
*/ */
@ -49,10 +51,12 @@ class ElementModel extends Model
'long_pdf_path', 'long_pdf_path',
'youtube_url', 'youtube_url',
'parent_element_id', 'parent_element_id',
'sort_order',
]; ];
protected $casts = [ protected $casts = [
'set_id' => 'integer', 'set_id' => 'integer',
'parent_element_id' => 'integer', 'parent_element_id' => 'integer',
'sort_order' => 'integer',
]; ];
} }

View file

@ -25,4 +25,13 @@ interface ElementRepository
* @return Element[] * @return Element[]
*/ */
public function findByParentElement(Element $parentElement): array; public function findByParentElement(Element $parentElement): array;
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array;
} }

View file

@ -5,6 +5,7 @@ namespace App\Element;
use App\Set\Set as DomainSet; use App\Set\Set as DomainSet;
use App\Set\SetRepository; use App\Set\SetRepository;
use DomainException; use DomainException;
use Illuminate\Support\Facades\DB;
class EloquentElementRepository implements ElementRepository class EloquentElementRepository implements ElementRepository
{ {
@ -14,6 +15,7 @@ class EloquentElementRepository implements ElementRepository
public function create(CreateElementDto $dto): Element public function create(CreateElementDto $dto): Element
{ {
$parentElementId = $dto->parentElement?->getId();
$model = ElementModel::create([ $model = ElementModel::create([
'set_id' => $dto->set->getId(), 'set_id' => $dto->set->getId(),
'title' => $dto->title, 'title' => $dto->title,
@ -23,7 +25,8 @@ class EloquentElementRepository implements ElementRepository
'short_pdf_path' => $dto->shortPdfPath, 'short_pdf_path' => $dto->shortPdfPath,
'long_pdf_path' => $dto->longPdfPath, 'long_pdf_path' => $dto->longPdfPath,
'youtube_url' => $dto->youtubeUrl, 'youtube_url' => $dto->youtubeUrl,
'parent_element_id' => $dto->parentElement?->getId(), 'parent_element_id' => $parentElementId,
'sort_order' => $this->nextSortOrder($dto->set, $parentElementId),
]); ]);
return new Element( return new Element(
@ -86,6 +89,7 @@ class EloquentElementRepository implements ElementRepository
{ {
$model = ElementModel::where('set_id', $set->getId()) $model = ElementModel::where('set_id', $set->getId())
->whereNull('parent_element_id') ->whereNull('parent_element_id')
->orderBy('sort_order')
->orderBy('id') ->orderBy('id')
->first(); ->first();
@ -117,6 +121,7 @@ class EloquentElementRepository implements ElementRepository
'parent_element_id', 'parent_element_id',
$parentElement->getId(), $parentElement->getId(),
) )
->orderBy('sort_order')
->orderBy('id') ->orderBy('id')
->get(); ->get();
$elements = []; $elements = [];
@ -127,6 +132,46 @@ class EloquentElementRepository implements ElementRepository
return $elements; return $elements;
} }
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array {
DB::transaction(function () use ($parentElement, $childElementIds) {
$sortOrder = 1;
foreach ($childElementIds as $childElementId) {
ElementModel::where('id', $childElementId)
->where('parent_element_id', $parentElement->getId())
->update(['sort_order' => $sortOrder]);
$sortOrder++;
}
});
return $this->findByParentElement($parentElement);
}
private function nextSortOrder(
DomainSet $set,
?int $parentElementId,
): int {
$query = ElementModel::where('set_id', $set->getId());
if ($parentElementId === null) {
$query->whereNull('parent_element_id');
} else {
$query->where('parent_element_id', $parentElementId);
}
$currentMaxSortOrder = $query->max('sort_order');
if ($currentMaxSortOrder === null) {
return 1;
}
return (int) $currentMaxSortOrder + 1;
}
private function toDomain(ElementModel $model): Element private function toDomain(ElementModel $model): Element
{ {
$set = $this->setRepo->find($model->set_id); $set = $this->setRepo->find($model->set_id);

View file

@ -0,0 +1,154 @@
<?php
namespace App\Element\UseCases\ReorderChildElements;
use App\Element\Element;
use App\Element\ElementRepository;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
class ReorderChildElements
{
public function __construct(private ElementRepository $elementRepository)
{
}
/**
* @return Element[]
* @throws BadRequestException
* @throws NotFoundException
*/
public function execute(ReorderChildElementsRequest $request): array
{
if ($request->parentElementId === null) {
throw new BadRequestException('parentElementId is required');
}
if ($request->childElementIds === null) {
throw new BadRequestException('childElementIds is required');
}
$parentElement = $this->elementRepository->find(
$request->parentElementId,
);
if ($parentElement === null) {
throw new NotFoundException('Parent element not found');
}
$childElementIds = $this->validatedChildElementIds(
$request->childElementIds,
);
$directChildElementIds = $this->elementIds(
$this->elementRepository->findByParentElement($parentElement),
);
$this->validateNoDuplicateIds($childElementIds);
$this->validateAllIdsAreDirectChildren(
$childElementIds,
$directChildElementIds,
);
$this->validateEveryDirectChildWasSubmitted(
$childElementIds,
$directChildElementIds,
);
return $this->elementRepository->reorderChildren(
$parentElement,
$childElementIds,
);
}
/**
* @param mixed[] $childElementIds
* @return int[]
* @throws BadRequestException
*/
private function validatedChildElementIds(array $childElementIds): array
{
$validatedChildElementIds = [];
foreach ($childElementIds as $childElementId) {
if (! is_int($childElementId)) {
throw new BadRequestException(
'childElementIds must contain integers',
);
}
$validatedChildElementIds[] = $childElementId;
}
return $validatedChildElementIds;
}
/**
* @param int[] $childElementIds
* @throws BadRequestException
*/
private function validateNoDuplicateIds(array $childElementIds): void
{
$seenChildElementIds = [];
foreach ($childElementIds as $childElementId) {
if (isset($seenChildElementIds[$childElementId])) {
throw new BadRequestException(
'Child order contains duplicate ids',
);
}
$seenChildElementIds[$childElementId] = true;
}
}
/**
* @param int[] $childElementIds
* @param int[] $directChildElementIds
* @throws BadRequestException
*/
private function validateAllIdsAreDirectChildren(
array $childElementIds,
array $directChildElementIds,
): void {
$directChildElementIdsById = [];
foreach ($directChildElementIds as $directChildElementId) {
$directChildElementIdsById[$directChildElementId] = true;
}
foreach ($childElementIds as $childElementId) {
if (! isset($directChildElementIdsById[$childElementId])) {
throw new BadRequestException(
'Child order contains invalid child',
);
}
}
}
/**
* @param int[] $childElementIds
* @param int[] $directChildElementIds
* @throws BadRequestException
*/
private function validateEveryDirectChildWasSubmitted(
array $childElementIds,
array $directChildElementIds,
): void {
if (count($childElementIds) === count($directChildElementIds)) {
return;
}
throw new BadRequestException(
'Child order must include every direct child',
);
}
/**
* @param Element[] $elements
* @return int[]
*/
private function elementIds(array $elements): array
{
$elementIds = [];
foreach ($elements as $element) {
$elementIds[] = $element->getId();
}
return $elementIds;
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Element\UseCases\ReorderChildElements;
class ReorderChildElementsRequest
{
/**
* @param int[]|null $childElementIds
*/
public function __construct(
public ?int $parentElementId,
public ?array $childElementIds,
) {
}
}

View file

@ -13,7 +13,14 @@ $allowedOrigins = array_values(array_filter(array_map(
return [ return [
'paths' => ['api/*'], 'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PATCH', 'OPTIONS', 'DELETE'], 'allowed_methods' => [
'GET',
'POST',
'PATCH',
'OPTIONS',
'DELETE',
'PUT',
],
'allowed_origins' => $allowedOrigins, 'allowed_origins' => $allowedOrigins,
'allowed_origins_patterns' => [], 'allowed_origins_patterns' => [],
'allowed_headers' => [ 'allowed_headers' => [

View file

@ -21,6 +21,7 @@ return new class extends Migration
$table->foreignId('parent_element_id') $table->foreignId('parent_element_id')
->nullable() ->nullable()
->constrained('elements'); ->constrained('elements');
$table->unsignedInteger('sort_order');
}); });
} }

View file

@ -17,6 +17,11 @@ Route::post('/elements/{parentId}/children', [
'createChild', 'createChild',
]) ])
->middleware(AuthMiddleware::class); ->middleware(AuthMiddleware::class);
Route::put('/elements/{parentId}/children/order', [
ElementController::class,
'reorderChildren',
])
->middleware(AuthMiddleware::class);
Route::delete('/elements/{parentId}/children/{childId}', [ Route::delete('/elements/{parentId}/children/{childId}', [
ElementController::class, ElementController::class,
'deleteChild', 'deleteChild',

View file

@ -14,6 +14,11 @@ class FakeElementRepository implements ElementRepository
*/ */
private array $elementsById = []; private array $elementsById = [];
/**
* @var array<int, int>
*/
private array $sortOrdersById = [];
public function create(CreateElementDto $dto): Element public function create(CreateElementDto $dto): Element
{ {
$id = count($this->elementsById) + 1; $id = count($this->elementsById) + 1;
@ -30,6 +35,9 @@ class FakeElementRepository implements ElementRepository
parentElement: $dto->parentElement, parentElement: $dto->parentElement,
); );
$this->elementsById[$id] = $element; $this->elementsById[$id] = $element;
$this->sortOrdersById[$id] = $this->nextSortOrder(
$dto->parentElement,
);
return $element; return $element;
} }
@ -45,6 +53,7 @@ class FakeElementRepository implements ElementRepository
public function delete(Element $element): void public function delete(Element $element): void
{ {
unset($this->elementsById[$element->getId()]); unset($this->elementsById[$element->getId()]);
unset($this->sortOrdersById[$element->getId()]);
} }
public function find(int $id): ?Element public function find(int $id): ?Element
@ -100,10 +109,43 @@ class FakeElementRepository implements ElementRepository
$elements[] = $this->cloneElement($element); $elements[] = $this->cloneElement($element);
} }
} }
usort($elements, function (
Element $firstElement,
Element $secondElement,
): int {
$firstSortOrder = $this->sortOrdersById[
$firstElement->getId()
] ?? $firstElement->getId();
$secondSortOrder = $this->sortOrdersById[
$secondElement->getId()
] ?? $secondElement->getId();
if ($firstSortOrder === $secondSortOrder) {
return $firstElement->getId() <=> $secondElement->getId();
}
return $firstSortOrder <=> $secondSortOrder;
});
return $elements; return $elements;
} }
/**
* @param int[] $childElementIds
* @return Element[]
*/
public function reorderChildren(
Element $parentElement,
array $childElementIds,
): array {
$sortOrder = 1;
foreach ($childElementIds as $childElementId) {
$this->sortOrdersById[$childElementId] = $sortOrder;
$sortOrder++;
}
return $this->findByParentElement($parentElement);
}
private function cloneElement(Element $element): Element private function cloneElement(Element $element): Element
{ {
$parentElement = $element->getParentElement(); $parentElement = $element->getParentElement();
@ -124,4 +166,24 @@ class FakeElementRepository implements ElementRepository
parentElement: $parentElement, parentElement: $parentElement,
); );
} }
private function nextSortOrder(?Element $parentElement): int
{
$parentElementId = $parentElement?->getId();
$nextSortOrder = 1;
foreach ($this->elementsById as $element) {
$currentParentElement = $element->getParentElement();
$currentParentElementId = $currentParentElement?->getId();
if ($currentParentElementId !== $parentElementId) {
continue;
}
$currentSortOrder = $this->sortOrdersById[$element->getId()] ?? 0;
if ($currentSortOrder >= $nextSortOrder) {
$nextSortOrder = $currentSortOrder + 1;
}
}
return $nextSortOrder;
}
} }

View file

@ -297,6 +297,234 @@ class ElementsEndpointTest extends TestCase
); );
} }
public function testReorderChildElementsRequiresAuthentication(): void
{
$setRepository = app(SetRepository::class);
$elementRepository = app(ElementRepository::class);
$set = $this->createSet($setRepository);
$parentElement = $this->createElement(
$elementRepository,
$set,
'Baderech HaAvodah',
'A structured path for growth',
null,
'<p>A structured path for growth</p>',
null,
null,
null,
null,
);
$firstChildElement = $this->createElement(
$elementRepository,
$set,
'First child',
'First child description',
null,
'',
null,
null,
null,
$parentElement,
);
$response = $this->putJson(
"/api/elements/{$parentElement->getId()}/children/order",
[
'childElementIds' => [$firstChildElement->getId()],
],
);
$response->assertUnauthorized();
$response->assertExactJson([
'error' => 'unauthenticated',
]);
}
public function testAuthenticatedReorderChildElementsPersistsOrder(): void
{
$setRepository = app(SetRepository::class);
$elementRepository = app(ElementRepository::class);
$set = $this->createSet($setRepository);
$parentElement = $this->createElement(
$elementRepository,
$set,
'Baderech HaAvodah',
'A structured path for growth',
null,
'<p>A structured path for growth</p>',
null,
null,
null,
null,
);
$firstChildElement = $this->createElement(
$elementRepository,
$set,
'First child',
'First child description',
null,
'',
null,
null,
null,
$parentElement,
);
$secondChildElement = $this->createElement(
$elementRepository,
$set,
'Second child',
'Second child description',
null,
'',
null,
null,
null,
$parentElement,
);
$thirdChildElement = $this->createElement(
$elementRepository,
$set,
'Third child',
'Third child description',
null,
'',
null,
null,
null,
$parentElement,
);
$this->createSession('valid-token');
$response = $this->withCredentials()
->withUnencryptedCookie('auth_token', 'valid-token')
->putJson(
"/api/elements/{$parentElement->getId()}/children/order",
[
'childElementIds' => [
$thirdChildElement->getId(),
$firstChildElement->getId(),
$secondChildElement->getId(),
],
],
);
$response->assertOk();
$response->assertExactJson([
'childElements' => [
[
'id' => $thirdChildElement->getId(),
'title' => 'Third child',
'description' => 'Third child description',
],
[
'id' => $firstChildElement->getId(),
'title' => 'First child',
'description' => 'First child description',
],
[
'id' => $secondChildElement->getId(),
'title' => 'Second child',
'description' => 'Second child description',
],
],
]);
$this->getJson("/api/elements/{$parentElement->getId()}")
->assertJsonPath('childElements.0.id', $thirdChildElement->getId())
->assertJsonPath('childElements.1.id', $firstChildElement->getId())
->assertJsonPath(
'childElements.2.id',
$secondChildElement->getId(),
);
$this->getJson("/api/elements/{$thirdChildElement->getId()}")
->assertJsonPath(
'siblingElements.0.id',
$thirdChildElement->getId(),
)
->assertJsonPath(
'siblingElements.1.id',
$firstChildElement->getId(),
)
->assertJsonPath(
'siblingElements.2.id',
$secondChildElement->getId(),
);
}
public function testAuthenticatedReorderRejectsNestedChildElement(): void
{
$setRepository = app(SetRepository::class);
$elementRepository = app(ElementRepository::class);
$set = $this->createSet($setRepository);
$parentElement = $this->createElement(
$elementRepository,
$set,
'Baderech HaAvodah',
'A structured path for growth',
null,
'<p>A structured path for growth</p>',
null,
null,
null,
null,
);
$firstChildElement = $this->createElement(
$elementRepository,
$set,
'First child',
'First child description',
null,
'',
null,
null,
null,
$parentElement,
);
$secondChildElement = $this->createElement(
$elementRepository,
$set,
'Second child',
'Second child description',
null,
'',
null,
null,
null,
$parentElement,
);
$nestedChildElement = $this->createElement(
$elementRepository,
$set,
'Nested child',
'Nested child description',
null,
'',
null,
null,
null,
$firstChildElement,
);
$this->createSession('valid-token');
$response = $this->withCredentials()
->withUnencryptedCookie('auth_token', 'valid-token')
->putJson(
"/api/elements/{$parentElement->getId()}/children/order",
[
'childElementIds' => [
$firstChildElement->getId(),
$nestedChildElement->getId(),
$secondChildElement->getId(),
],
],
);
$response->assertBadRequest();
$response->assertExactJson([
'error' => 'Child order contains invalid child',
]);
}
public function testDeleteChildRequiresAuthentication(): void public function testDeleteChildRequiresAuthentication(): void
{ {
$setRepository = app(SetRepository::class); $setRepository = app(SetRepository::class);

View file

@ -8,6 +8,7 @@ use App\Element\Element;
use App\Element\UseCases\CreateChildElement\CreateChildElement; use App\Element\UseCases\CreateChildElement\CreateChildElement;
use App\Element\UseCases\DeleteChildElement\DeleteChildElement; use App\Element\UseCases\DeleteChildElement\DeleteChildElement;
use App\Element\UseCases\GetElement\GetElement; use App\Element\UseCases\GetElement\GetElement;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\UpdateElement\UpdateDescription; use App\Element\UseCases\UpdateElement\UpdateDescription;
use App\Element\UseCases\UpdateElement\UpdateElement; use App\Element\UseCases\UpdateElement\UpdateElement;
use App\Element\UseCases\UpdateElement\UpdateIconImage; use App\Element\UseCases\UpdateElement\UpdateIconImage;
@ -65,6 +66,7 @@ class ElementControllerTest extends TestCase
$getElement, $getElement,
new CreateChildElement($this->elementRepo), new CreateChildElement($this->elementRepo),
new DeleteChildElement($this->elementRepo, $this->fileUploader), new DeleteChildElement($this->elementRepo, $this->fileUploader),
new ReorderChildElements($this->elementRepo),
$updateElement, $updateElement,
$this->fileUploader, $this->fileUploader,
); );

View file

@ -0,0 +1,237 @@
<?php
namespace Tests\Unit\Element\UseCases;
use App\Element\CreateElementDto;
use App\Element\Element;
use App\Element\UseCases\ReorderChildElements\ReorderChildElements;
use App\Element\UseCases\ReorderChildElements\ReorderChildElementsRequest;
use App\Exceptions\BadRequestException;
use App\Exceptions\NotFoundException;
use App\Set\Set as DomainSet;
use Tests\Fakes\FakeElementRepository;
use Tests\TestCase;
class ReorderChildElementsTest extends TestCase
{
private FakeElementRepository $elementRepository;
private ReorderChildElements $reorderChildElements;
protected function setUp(): void
{
$this->elementRepository = new FakeElementRepository();
$this->reorderChildElements = new ReorderChildElements(
$this->elementRepository,
);
}
public function testReordersDirectChildElements(): void
{
$set = $this->createSet(1, 'Baderech');
$parentElement = $this->createElement($set, 'Parent', null);
$firstChildElement = $this->createElement(
$set,
'First child',
$parentElement,
);
$secondChildElement = $this->createElement(
$set,
'Second child',
$parentElement,
);
$thirdChildElement = $this->createElement(
$set,
'Third child',
$parentElement,
);
$this->createElement($set, 'Nested child', $firstChildElement);
$childElements = $this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentElement->getId(),
childElementIds: [
$thirdChildElement->getId(),
$firstChildElement->getId(),
$secondChildElement->getId(),
],
)
);
$this->assertSame(
[
$thirdChildElement->getId(),
$firstChildElement->getId(),
$secondChildElement->getId(),
],
$this->elementIds($childElements),
);
$this->assertSame(
[
$thirdChildElement->getId(),
$firstChildElement->getId(),
$secondChildElement->getId(),
],
$this->elementIds(
$this->elementRepository->findByParentElement($parentElement),
),
);
}
public function testThrowsWhenParentElementIsMissing(): void
{
$this->expectException(NotFoundException::class);
$this->expectExceptionMessage('Parent element not found');
$this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: 999,
childElementIds: [1, 2],
)
);
}
public function testThrowsWhenChildIdsAreMissing(): void
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('childElementIds is required');
$this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: 1,
childElementIds: null,
)
);
}
public function testThrowsWhenChildOrderHasDuplicates(): void
{
$set = $this->createSet(1, 'Baderech');
$parentElement = $this->createElement($set, 'Parent', null);
$firstChildElement = $this->createElement(
$set,
'First child',
$parentElement,
);
$secondChildElement = $this->createElement(
$set,
'Second child',
$parentElement,
);
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('Child order contains duplicate ids');
$this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentElement->getId(),
childElementIds: [
$firstChildElement->getId(),
$firstChildElement->getId(),
$secondChildElement->getId(),
],
)
);
}
public function testThrowsWhenChildOrderHasInvalidElement(): void
{
$set = $this->createSet(1, 'Baderech');
$parentElement = $this->createElement($set, 'Parent', null);
$firstChildElement = $this->createElement(
$set,
'First child',
$parentElement,
);
$secondChildElement = $this->createElement(
$set,
'Second child',
$parentElement,
);
$nestedChildElement = $this->createElement(
$set,
'Nested child',
$firstChildElement,
);
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('Child order contains invalid child');
$this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentElement->getId(),
childElementIds: [
$firstChildElement->getId(),
$nestedChildElement->getId(),
$secondChildElement->getId(),
],
)
);
}
public function testThrowsWhenChildOrderOmitsDirectChild(): void
{
$set = $this->createSet(1, 'Baderech');
$parentElement = $this->createElement($set, 'Parent', null);
$firstChildElement = $this->createElement(
$set,
'First child',
$parentElement,
);
$this->createElement($set, 'Second child', $parentElement);
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage(
'Child order must include every direct child',
);
$this->reorderChildElements->execute(
new ReorderChildElementsRequest(
parentElementId: $parentElement->getId(),
childElementIds: [$firstChildElement->getId()],
)
);
}
private function createSet(int $id, string $name): DomainSet
{
return new DomainSet(
id: $id,
name: $name,
description: "$name description",
iconImageUrl: '/assets/baderech-icon.png',
);
}
private function createElement(
DomainSet $set,
string $title,
?Element $parentElement,
): Element {
return $this->elementRepository->create(new CreateElementDto(
set: $set,
title: $title,
description: "$title description",
iconImageUrl: null,
richText: '',
shortPdfPath: null,
longPdfPath: null,
youtubeUrl: null,
parentElement: $parentElement,
));
}
/**
* @param Element[] $elements
* @return int[]
*/
private function elementIds(array $elements): array
{
$elementIds = [];
foreach ($elements as $element) {
$elementIds[] = $element->getId();
}
return $elementIds;
}
}

View file

@ -191,6 +191,46 @@ describe('admin element editing', () => {
cy.resetDb() cy.resetDb()
}) })
it('reorders child elements through admin controls', () => {
cy.resetDb()
loginAsAdmin()
cy.visit('/admin/element/1')
cy.intercept('PUT', /\/api\/elements\/1\/children\/order$/)
.as('reorderChildElements')
cy.contains('[data-cy="admin-child-item"]', '2. Foundations')
.within(() => {
cy.get('[data-cy="admin-move-child-up"]').click()
})
cy.wait('@reorderChildElements')
cy.get('[data-cy="admin-child-status"]')
.should('be.visible')
.and('contain.text', 'Child order saved')
cy.get('[data-cy="admin-child-item"]')
.eq(0)
.should('contain.text', '2. Foundations')
cy.get('[data-cy="admin-child-item"]')
.eq(1)
.should('contain.text', '1. Introduction')
cy.contains('header.site-header a', 'View Element').click()
cy.get('[data-cy="child-element-link"]')
.eq(0)
.should('contain.text', '2. Foundations')
cy.get('[data-cy="child-element-link"]')
.eq(1)
.should('contain.text', '1. Introduction')
cy.visit('/element/3')
cy.get('[data-cy="element-sibling-previous"]')
.should('have.attr', 'href', '/element/7')
cy.get('[data-cy="element-sibling-next"]')
.should('have.attr', 'href', '/element/2')
cy.resetDb()
})
it('uploads icon and pdf files immediately through the UI', () => { it('uploads icon and pdf files immediately through the UI', () => {
cy.resetDb() cy.resetDb()
loginAsAdmin() loginAsAdmin()

View file

@ -38,6 +38,10 @@ interface UpdateElementResponse {
element: Element element: Element
} }
interface ReorderChildElementsResponse {
childElements: ChildElement[]
}
interface ElementPatchInput { interface ElementPatchInput {
title?: string title?: string
description?: string description?: string
@ -145,6 +149,34 @@ export const useElementsStore = defineStore('elements', () => {
} }
} }
async function reorderChildElements(
parentElementId: string,
childElementIds: number[],
): Promise<boolean> {
childActionError.value = null
isManagingChildren.value = true
try {
const encodedParentElementId = encodeURIComponent(parentElementId)
const response = await fetch(
`${ELEMENTS_URL}/${encodedParentElementId}/children/order`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ childElementIds }),
},
)
return await handleReorderChildElementsResponse(response)
} catch {
childActionError.value = 'Network error - could not save child order'
return false
} finally {
isManagingChildren.value = false
}
}
async function deleteChildElement( async function deleteChildElement(
parentElementId: string, parentElementId: string,
childElementId: number, childElementId: number,
@ -350,6 +382,32 @@ export const useElementsStore = defineStore('elements', () => {
return data.element return data.element
} }
async function handleReorderChildElementsResponse(
response: Response,
): Promise<boolean> {
if (response.status === 401) {
childActionError.value = 'Please log in again'
return false
}
if (response.status === 400 || response.status === 404) {
childActionError.value = await errorMessage(
response,
'Could not save child order',
)
return false
}
if (!response.ok) {
childActionError.value = 'Could not save child order'
return false
}
const data: ReorderChildElementsResponse = await response.json()
childElements.value = data.childElements
return true
}
async function handleDeleteChildElementResponse( async function handleDeleteChildElementResponse(
response: Response, response: Response,
childElementId: number, childElementId: number,
@ -406,6 +464,7 @@ export const useElementsStore = defineStore('elements', () => {
fetchElement, fetchElement,
updateElement, updateElement,
createChildElement, createChildElement,
reorderChildElements,
deleteChildElement, deleteChildElement,
uploadElementIconImage, uploadElementIconImage,
uploadElementShortPdf, uploadElementShortPdf,

View file

@ -1,12 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { computed, reactive, ref, watch } from 'vue' import { computed, reactive, ref, watch } from 'vue'
import {
ChevronDown as ChevronDownIcon,
ChevronUp as ChevronUpIcon,
} from 'lucide-vue-next'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import ElementSiblingNavigation from '@/components/ElementSiblingNavigation.vue' import ElementSiblingNavigation from '@/components/ElementSiblingNavigation.vue'
import RichTextEditor from '@/components/RichTextEditor.vue' import RichTextEditor from '@/components/RichTextEditor.vue'
import SiteHeader from '@/components/SiteHeader.vue' import SiteHeader from '@/components/SiteHeader.vue'
import { useElementsStore } from '@/stores/elements' import { useElementsStore } from '@/stores/elements'
type ChildMoveDirection = 'up' | 'down'
interface ElementForm { interface ElementForm {
title: string title: string
description: string description: string
@ -168,6 +174,50 @@ async function handleRemoveChild(childElementId: number): Promise<void> {
} }
} }
async function handleMoveChild(
childElementId: number,
direction: ChildMoveDirection,
): Promise<void> {
if (elementId.value === '') {
return
}
const currentIndex = childElements.value.findIndex((childElement) => {
return childElement.id === childElementId
})
if (currentIndex === -1) {
return
}
const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1
if (targetIndex < 0 || targetIndex >= childElements.value.length) {
return
}
const reorderedChildElements = [...childElements.value]
const movingChildElement = reorderedChildElements[currentIndex]
const targetChildElement = reorderedChildElements[targetIndex]
if (movingChildElement === undefined || targetChildElement === undefined) {
return
}
reorderedChildElements[currentIndex] = targetChildElement
reorderedChildElements[targetIndex] = movingChildElement
const childElementIds = reorderedChildElements.map((childElement) => {
return childElement.id
})
childStatus.value = null
const saved = await elementsStore.reorderChildElements(
elementId.value,
childElementIds,
)
if (saved) {
childStatus.value = 'Child order saved'
}
}
function chooseIconImage(): void { function chooseIconImage(): void {
iconImageInput.value?.click() iconImageInput.value?.click()
} }
@ -522,7 +572,7 @@ function resetInput(changeEvent: Event): void {
data-cy="admin-child-list" data-cy="admin-child-list"
> >
<li <li
v-for="childElement in childElements" v-for="(childElement, childIndex) in childElements"
:key="childElement.id" :key="childElement.id"
class="admin-element-page__child-item" class="admin-element-page__child-item"
data-cy="admin-child-item" data-cy="admin-child-item"
@ -545,6 +595,34 @@ function resetInput(changeEvent: Event): void {
{{ childElement.description }} {{ childElement.description }}
</p> </p>
</div> </div>
<div class="admin-element-page__child-actions">
<div class="admin-element-page__child-order-actions">
<button
class="admin-element-page__icon-button"
data-cy="admin-move-child-up"
type="button"
:disabled="isManagingChildren || childIndex === 0"
aria-label="Move child up"
title="Move child up"
@click="handleMoveChild(childElement.id, 'up')"
>
<ChevronUpIcon :size="16" aria-hidden="true" />
</button>
<button
class="admin-element-page__icon-button"
data-cy="admin-move-child-down"
type="button"
:disabled="
isManagingChildren ||
childIndex === childElements.length - 1
"
aria-label="Move child down"
title="Move child down"
@click="handleMoveChild(childElement.id, 'down')"
>
<ChevronDownIcon :size="16" aria-hidden="true" />
</button>
</div>
<button <button
class="admin-element-page__secondary-button" class="admin-element-page__secondary-button"
data-cy="admin-remove-child" data-cy="admin-remove-child"
@ -554,6 +632,7 @@ function resetInput(changeEvent: Event): void {
> >
Remove Remove
</button> </button>
</div>
</li> </li>
</ul> </ul>
<p <p
@ -778,6 +857,44 @@ function resetInput(changeEvent: Event): void {
line-height: 1.45; line-height: 1.45;
} }
.admin-element-page__child-actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 0.45rem;
}
.admin-element-page__child-order-actions {
display: flex;
align-items: center;
gap: 0.35rem;
}
.admin-element-page__icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.25rem;
height: 2.25rem;
padding: 0;
border: 1px solid var(--color-border);
border-radius: 4px;
color: var(--color-text);
background: var(--color-white);
cursor: pointer;
}
.admin-element-page__icon-button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.admin-element-page__icon-button:hover:not(:disabled),
.admin-element-page__icon-button:focus-visible {
border-color: var(--color-slate);
color: var(--color-slate);
}
.admin-element-page__child-add { .admin-element-page__child-add {
display: flex; display: flex;
align-items: end; align-items: end;
@ -890,5 +1007,9 @@ function resetInput(changeEvent: Event): void {
.admin-element-page__child-item { .admin-element-page__child-item {
flex-direction: column; flex-direction: column;
} }
.admin-element-page__child-actions {
align-self: flex-end;
}
} }
</style> </style>