From 57efac736a24f4761a7676de98670f507b088ad4 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Thu, 22 Oct 2026 15:10:23 +0200 Subject: [PATCH 01/16] feat(api): add grid pages and widget types to api/2 Read, add, change and delete grid pages with their widgets, and list the widget types with their settings schemas. Reading needs read access to the application, changes need manage access. Page creation is limited to 20 a minute per user. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Controller/ContextPageController.php | 195 +++++++++ lib/Db/PageMapper.php | 16 + lib/ResponseDefinitions.php | 45 ++ lib/Service/ContextService.php | 1 - lib/Service/GridWidgetTypes.php | 26 +- lib/Service/PageService.php | 337 +++++++++++++++ lib/Service/WidgetService.php | 13 +- .../Controller/ContextPageControllerTest.php | 113 +++++ tests/unit/Db/WidgetMapperTest.php | 2 +- tests/unit/Service/PageServiceTest.php | 405 ++++++++++++++++++ tests/unit/Service/WidgetServiceTest.php | 2 +- 11 files changed, 1130 insertions(+), 25 deletions(-) create mode 100644 lib/Controller/ContextPageController.php create mode 100644 lib/Service/PageService.php create mode 100644 tests/unit/Controller/ContextPageControllerTest.php create mode 100644 tests/unit/Service/PageServiceTest.php diff --git a/lib/Controller/ContextPageController.php b/lib/Controller/ContextPageController.php new file mode 100644 index 0000000000..2f7e4d0857 --- /dev/null +++ b/lib/Controller/ContextPageController.php @@ -0,0 +1,195 @@ +|DataResponse + * + * 200: Page returned + * 404: Not found, also when the user has no access to the application + */ + #[NoAdminRequired] + #[RequirePermission(permission: Application::PERMISSION_READ, typeParam: 'context', idParam: 'contextId')] + #[ApiRoute(verb: 'GET', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] + public function show(int $contextId, int $pageId): DataResponse { + try { + return new DataResponse($this->pageService->find($contextId, $pageId, $this->userId)); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (Exception $e) { + return $this->handleError($e); + } + } + + /** + * [api v2] Add a grid page to an application + * + * @param int $contextId ID of the application + * @param string $title Title of the page + * @param string|null $slug Slug of the page, unique in the application; `page_` when left out, a form reserved for automatic names + * @param string|null $icon Name of the icon shown with the title + * @param string|null $description Description of the page + * @return DataResponse|DataResponse + * + * 200: Page created + * 400: Invalid title, icon or description, or an invalid or taken slug + * 403: No permissions + * 404: Not found + */ + #[NoAdminRequired] + #[UserRateLimit(limit: 20, period: 60)] + #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] + #[ApiRoute(verb: 'POST', url: '/api/2/contexts/{contextId}/pages', requirements: ['contextId' => '\d+'])] + public function create(int $contextId, string $title, ?string $slug = null, ?string $icon = null, ?string $description = null): DataResponse { + try { + return new DataResponse($this->pageService->create($contextId, $title, $slug, $icon, $description, $this->userId)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($e); + } catch (PermissionError $e) { + return $this->handlePermissionError($e); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (Exception $e) { + return $this->handleError($e); + } + } + + /** + * [api v2] Change a page or its widgets + * + * Fields left out keep their value; an empty icon or description removes it. A given + * `widgets` list replaces the widgets of the grid page: listed widgets with an `id` + * are updated, others are added, and widgets not listed are deleted. + * + * A widget has a `type`, `gridX`, `gridY`, `gridWidth` and `gridHeight` on a grid of + * 12 columns, `settings` following the schema of its type, and optionally an `id`, + * `title`, `icon` and `description`. A data widget's `source` is `{nodeRelId}` of a + * table or view of this application, or null. + * + * @param int $contextId ID of the application + * @param int $pageId ID of the page + * @param string|null $title New title + * @param string|null $slug New slug + * @param string|null $icon New icon name, empty to remove it + * @param string|null $description New description, empty to remove it + * @param list>|null $widgets All widgets of the page + * @return DataResponse|DataResponse + * + * 200: Page updated + * 400: Invalid page field or widget, too many widgets, or the page changed in between + * 403: No permissions + * 404: Not found + */ + #[NoAdminRequired] + #[UserRateLimit(limit: 60, period: 60)] + #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] + #[ApiRoute(verb: 'PATCH', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] + public function update(int $contextId, int $pageId, ?string $title = null, ?string $slug = null, ?string $icon = null, ?string $description = null, ?array $widgets = null): DataResponse { + try { + return new DataResponse($this->pageService->update($contextId, $pageId, $title, $slug, $icon, $description, $widgets, $this->userId)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($e); + } catch (PermissionError $e) { + return $this->handlePermissionError($e); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (DoesNotExistException|MultipleObjectsReturnedException $e) { + return $this->handleNotFoundError(new NotFoundError($e->getMessage(), $e->getCode(), $e)); + } catch (Exception $e) { + return $this->handleError($e); + } + } + + /** + * [api v2] Delete a grid page with its widgets + * + * The start page of an application cannot be deleted. + * + * @param int $contextId ID of the application + * @param int $pageId ID of the page + * @return DataResponse|DataResponse + * + * 200: Page deleted + * 400: The page is the start page + * 403: No permissions + * 404: Not found + */ + #[NoAdminRequired] + #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] + #[ApiRoute(verb: 'DELETE', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] + public function destroy(int $contextId, int $pageId): DataResponse { + try { + return new DataResponse($this->pageService->delete($contextId, $pageId, $this->userId)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($e); + } catch (PermissionError $e) { + return $this->handlePermissionError($e); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (Exception $e) { + return $this->handleError($e); + } + } + + /** + * [api v2] Get the widget types a grid page can hold + * + * Every type carries the schema of its settings and whether it shows a table or view. + * + * @return DataResponse, array{}> + * + * 200: Widget types returned + */ + #[NoAdminRequired] + #[ApiRoute(verb: 'GET', url: '/api/2/widget-types')] + public function widgetTypes(): DataResponse { + return new DataResponse(array_values($this->gridWidgetTypes->all())); + } +} diff --git a/lib/Db/PageMapper.php b/lib/Db/PageMapper.php index a612e76130..e90e02e4fd 100644 --- a/lib/Db/PageMapper.php +++ b/lib/Db/PageMapper.php @@ -7,6 +7,8 @@ namespace OCA\Tables\Db; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Db\QBMapper; use OCP\AppFramework\Db\TTransactional; use OCP\DB\Exception; @@ -37,6 +39,20 @@ public function insertWithDefaultName(Page $page): Page { }, $this->db); } + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + */ + public function findById(int $pageId): Page { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->table) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($pageId, IQueryBuilder::PARAM_INT))); + + return $this->findEntity($qb); + } + /** * @return int[] */ diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index dd41a0bf4f..1b87b6b68e 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -243,6 +243,51 @@ * ownerType: int, * } * + * @psalm-type TablesWidgetValue = string + * + * @psalm-type TablesWidgetSettingSchema = array{ + * type: 'string'|'text'|'enum', + * title: string, + * default: TablesWidgetValue, + * options?: list, + * required?: bool, + * hint?: string, + * } + * + * @psalm-type TablesWidgetType = array{ + * type: string, + * title: string, + * defaultWidth: int, + * defaultHeight: int, + * hasSource: bool, + * settings: array, + * } + * + * @psalm-type TablesWidget = array{ + * id: int, + * type: string, + * title: ?string, + * icon: ?string, + * description: ?string, + * gridX: int, + * gridY: int, + * gridWidth: int, + * gridHeight: int, + * settings: array|\stdClass, + * source: ?array{nodeRelId: int}, + * } + * + * @psalm-type TablesPage = array{ + * id: int, + * contextId: int, + * pageType: string, + * slug: string, + * title: ?string, + * icon: ?string, + * description: ?string, + * widgets: list, + * } + * * @psalm-type TablesContextNavigation = array{ * id: int, * shareId: int, diff --git a/lib/Service/ContextService.php b/lib/Service/ContextService.php index f54228335c..464c00ccfc 100644 --- a/lib/Service/ContextService.php +++ b/lib/Service/ContextService.php @@ -871,7 +871,6 @@ public function addWidgetsToPages(array $contexts): void { * @param list $widgets * @param array $nodeRelMap new node relations by exported id * @throws Exception - * @throws \JsonException */ private function importWidgets(int $pageId, array $widgets, array $nodeRelMap): void { $inputs = []; diff --git a/lib/Service/GridWidgetTypes.php b/lib/Service/GridWidgetTypes.php index d3f46413cc..cef8d01360 100644 --- a/lib/Service/GridWidgetTypes.php +++ b/lib/Service/GridWidgetTypes.php @@ -9,11 +9,11 @@ namespace OCA\Tables\Service; -use OCA\Tables\Db\Widget; use OCA\Tables\Errors\BadRequestError; use OCA\Tables\Helper\IconHelper; use OCA\Tables\Helper\TextHelper; use OCA\Tables\Model\WidgetInput; +use OCA\Tables\ResponseDefinitions; use OCP\IL10N; /** @@ -21,23 +21,9 @@ * the frontend renders its form from it and saved widgets are validated against it. * A type with a source shows a table or view of the application. * - * @psalm-import-type TablesWidgetSettingValue from Widget - * @psalm-type TablesWidgetSettingSchema = array{ - * type: 'string'|'text'|'enum', - * title: string, - * default: TablesWidgetSettingValue, - * options?: list, - * required?: bool, - * hint?: string, - * } - * @psalm-type TablesWidgetType = array{ - * type: string, - * title: string, - * defaultWidth: int, - * defaultHeight: int, - * hasSource: bool, - * settings: array, - * } + * @psalm-import-type TablesWidgetValue from ResponseDefinitions + * @psalm-import-type TablesWidgetSettingSchema from ResponseDefinitions + * @psalm-import-type TablesWidgetType from ResponseDefinitions */ class GridWidgetTypes { public const TYPE_HEADER = 'header'; @@ -132,7 +118,7 @@ public function get(string $type): array { * with defaults filled in and unknown settings dropped. Stored as JSON they take at * most {@see self::SETTINGS_MAX_BYTES} bytes. * - * @return array + * @return array * @throws BadRequestError */ public function sanitizeSettings(string $type, mixed $settings): array { @@ -158,7 +144,7 @@ public function sanitizeSettings(string $type, mixed $settings): array { /** * @param TablesWidgetSettingSchema $property - * @return TablesWidgetSettingValue + * @return TablesWidgetValue * @throws BadRequestError */ private function sanitizeValue(string $label, array $property, mixed $value): string { diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php new file mode 100644 index 0000000000..1eeec3af52 --- /dev/null +++ b/lib/Service/PageService.php @@ -0,0 +1,337 @@ +contextMapper->findById($contextId, $userId); + $page = $this->getPageArray($context, $pageId); + $widgets = $this->widgetService->findByPageIds([$pageId]); + + return [ + 'id' => $pageId, + 'contextId' => $contextId, + 'pageType' => (string)$page['page_type'], + 'slug' => (string)$page['slug'], + 'title' => $page['title'] ?? null, + 'icon' => $page['icon'] ?? null, + 'description' => $page['description'] ?? null, + 'widgets' => $widgets[$pageId] ?? [], + ]; + } + + /** + * Adds a grid page to an application. Without a slug the page is named + * `page_`; a given slug that is taken is refused. + * + * @return TablesPage + * @throws BadRequestError + * @throws NotFoundError + * @throws PermissionError + * @throws Exception + */ + public function create(int $contextId, string $title, ?string $slug, ?string $icon, ?string $description, string $userId): array { + $context = $this->getManageableContext($contextId, $userId); + + $page = new Page(); + $page->setContextId($contextId); + $page->setPageType(Page::TYPE_GRID); + $page->setTitle($this->validateTitle($title)); + $page->setIcon($this->validateIcon($icon)); + $page->setDescription($this->validateDescription($description)); + + if ($slug !== null) { + $page->setSlug($this->validateSlug($slug, $context, null)); + $this->saveNamed(fn () => $this->pageMapper->insert($page), $slug); + } else { + $page = $this->pageMapper->insertWithDefaultName($page); + } + + return $this->find($contextId, $page->getId(), $userId); + } + + /** + * Changes the fields of a page and, when widgets are given, makes its widgets match + * them in one transaction. A null argument keeps the current value; an empty icon + * or description removes it. A widget's `source` is `{nodeRelId}` of a table or view + * of this application, or null. + * + * @param list|null $widgets + * @return TablesPage + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws BadRequestError + * @throws NotFoundError + * @throws PermissionError + * @throws Exception + */ + public function update(int $contextId, int $pageId, ?string $title, ?string $slug, ?string $icon, ?string $description, ?array $widgets, string $userId): array { + $context = $this->getManageableContext($contextId, $userId); + $pageArray = $this->getPageArray($context, $pageId); + + $page = $this->pageMapper->findById($pageId); + if ($title !== null) { + $page->setTitle($this->validateTitle($title)); + } + if ($slug !== null && $slug !== $page->getSlug()) { + $page->setSlug($this->validateSlug($slug, $context, $pageId)); + } + if ($icon !== null) { + $page->setIcon($this->validateIcon($icon)); + } + if ($description !== null) { + $page->setDescription($this->validateDescription($description)); + } + + $rows = null; + if ($widgets !== null) { + if ($pageArray['page_type'] !== Page::TYPE_GRID) { + throw new BadRequestError('Only grid pages hold widgets.'); + } + $rows = $this->readWidgets($widgets, $context, $pageId); + } + + $renamed = array_key_exists('slug', $page->getUpdatedFields()); + $this->saveChanges(fn () => $this->atomic(function () use ($page, $rows, $pageId): void { + if ($page->getUpdatedFields() !== []) { + $this->pageMapper->update($page); + } + if ($rows !== null) { + $this->widgetService->syncPage($pageId, $rows); + } + }, $this->dbc), $renamed ? (string)$page->getSlug() : null); + + return $this->find($contextId, $pageId, $userId); + } + + /** + * Deletes a grid page with its widgets. The start page cannot be deleted. + * + * @return TablesPage the deleted page + * @throws BadRequestError + * @throws NotFoundError + * @throws PermissionError + * @throws Exception + */ + public function delete(int $contextId, int $pageId, string $userId): array { + $context = $this->getManageableContext($contextId, $userId); + $pageArray = $this->getPageArray($context, $pageId); + if ($pageArray['page_type'] !== Page::TYPE_GRID) { + throw new BadRequestError('The start page of an application cannot be deleted.'); + } + $page = $this->find($contextId, $pageId, $userId); + + $this->atomic(function () use ($pageId): void { + $this->widgetService->deleteByPageIds([$pageId]); + $this->pageContentMapper->deleteByPageId($pageId); + $this->pageMapper->deleteByPageId($pageId); + }, $this->dbc); + + return $page; + } + + /** + * @throws NotFoundError + * @throws PermissionError + * @throws Exception + */ + private function getManageableContext(int $contextId, string $userId): Context { + $context = $this->contextMapper->findById($contextId, $userId); + if (!$this->permissionsService->canManageContext($context, $userId)) { + throw new PermissionError(sprintf('User %s cannot manage application %d', $userId, $contextId)); + } + return $context; + } + + /** + * @return array + * @throws NotFoundError + */ + private function getPageArray(Context $context, int $pageId): array { + $pages = $context->getPages() ?? []; + if (!isset($pages[$pageId])) { + throw new NotFoundError('Page ' . $pageId . ' does not belong to application ' . $context->getId()); + } + return $pages[$pageId]; + } + + /** + * @param list $widgets + * @return list + * @throws BadRequestError + * @throws Exception + */ + private function readWidgets(array $widgets, Context $context, int $pageId): array { + if (count($widgets) > GridWidgetTypes::MAX_WIDGETS_PER_PAGE) { + throw new BadRequestError('A page holds at most ' . GridWidgetTypes::MAX_WIDGETS_PER_PAGE . ' widgets.'); + } + $existingIds = array_flip($this->widgetService->findIdsByPageId($pageId)); + $nodes = $context->getNodes() ?? []; + $rows = []; + $seenIds = []; + foreach (array_values($widgets) as $index => $widget) { + $input = $this->gridWidgetTypes->readWidget($index, $widget); + if ($input->id !== null && (!isset($existingIds[$input->id]) || isset($seenIds[$input->id]))) { + throw new BadRequestError('Widget ' . $index . ' has the id of no other widget on this page.'); + } + if ($input->id !== null) { + $seenIds[$input->id] = true; + } + if ($input->nodeRelId !== null && !isset($nodes[$input->nodeRelId])) { + throw new BadRequestError('The source of widget ' . $index . ' must be {nodeRelId} of a table or view of this application.'); + } + $rows[] = $input; + } + return $rows; + } + + /** + * @throws BadRequestError + */ + private function validateTitle(string $title): string { + $title = trim($title); + if ($title === '' || mb_strlen($title) > Page::TITLE_MAX_LENGTH) { + throw new BadRequestError('A page title needs 1 to ' . Page::TITLE_MAX_LENGTH . ' characters.'); + } + return $title; + } + + /** + * Runs a save of the fields and widgets of a page. A unique index refusing the save + * means the new slug was taken; a widget no longer on the page, or another + * refusal of the index, means a concurrent save changed the page in between. + * + * @throws BadRequestError + * @throws Exception + */ + private function saveChanges(callable $save, ?string $newSlug): void { + try { + $save(); + } catch (\InvalidArgumentException $e) { + throw new BadRequestError(self::CHANGED_IN_BETWEEN, 0, $e); + } catch (Exception $e) { + if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + throw $e; + } + if ($newSlug !== null) { + throw new BadRequestError('The slug ' . $newSlug . ' is already used by a page of this application.', 0, $e); + } + throw new BadRequestError(self::CHANGED_IN_BETWEEN, 0, $e); + } + } + + /** + * Runs a save of a page under a slug that was given, reporting a save the + * unique index refused as a taken name. + * + * @throws BadRequestError + * @throws Exception + */ + private function saveNamed(callable $save, string $slug): void { + try { + $save(); + } catch (Exception $e) { + if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + throw $e; + } + throw new BadRequestError('The slug ' . $slug . ' is already used by a page of this application.'); + } + } + + /** + * @throws BadRequestError + */ + private function validateSlug(string $slug, Context $context, ?int $pageId): string { + if (!TechnicalNameValidator::isValid($slug)) { + throw new BadRequestError('A slug has 1 to ' . TechnicalNameValidator::MAX_LENGTH . ' lower case letters, digits and underscores and starts with a letter.'); + } + if (Page::isDefaultSlug($slug) && $slug !== Page::DEFAULT_SLUG_PREFIX . $pageId) { + throw new BadRequestError('The slug ' . $slug . ' is reserved for automatic names.'); + } + foreach ($context->getPages() ?? [] as $id => $page) { + if ((int)$id !== $pageId && ($page['slug'] ?? null) === $slug) { + throw new BadRequestError('The slug ' . $slug . ' is already used by a page of this application.'); + } + } + return $slug; + } + + /** + * A named icon, or null for an empty one. + * + * @throws BadRequestError + */ + private function validateIcon(?string $icon, string $of = 'A page'): ?string { + $icon = trim((string)$icon); + if ($icon === '') { + return null; + } + if (!IconHelper::isValid($icon)) { + throw new BadRequestError($of . ' has an unknown icon: ' . $icon); + } + return $icon; + } + + /** + * @throws BadRequestError + */ + private function validateDescription(?string $description): ?string { + $description = trim((string)$description); + if (mb_strlen($description) > Page::DESCRIPTION_MAX_LENGTH) { + throw new BadRequestError('A page description has at most ' . Page::DESCRIPTION_MAX_LENGTH . ' characters.'); + } + return $description === '' ? null : $description; + } +} diff --git a/lib/Service/WidgetService.php b/lib/Service/WidgetService.php index 22453bc32d..1033baa1a4 100644 --- a/lib/Service/WidgetService.php +++ b/lib/Service/WidgetService.php @@ -13,6 +13,7 @@ use OCA\Tables\Db\Widget; use OCA\Tables\Db\WidgetMapper; use OCA\Tables\Model\WidgetInput; +use OCA\Tables\ResponseDefinitions; use OCP\DB\Exception; use OCP\IDBConnection; @@ -22,7 +23,7 @@ * in their own transaction. * * @psalm-import-type TablesWidgetSettingValue from Widget - * @psalm-type TablesWidgetRecord = array{id: int, type: string, title: ?string, icon: ?string, description: ?string, gridX: int, gridY: int, gridWidth: int, gridHeight: int, settings: \stdClass, source: ?array{nodeRelId: int}} + * @psalm-import-type TablesWidget from ResponseDefinitions */ class WidgetService { use \OCP\AppFramework\Db\TTransactional; @@ -36,7 +37,7 @@ public function __construct( /** * @param int[] $pageIds - * @return array> widgets by page id, in grid order + * @return array> widgets by page id, in grid order * @throws Exception */ public function findByPageIds(array $pageIds): array { @@ -88,6 +89,14 @@ private function insertWidget(int $pageId, WidgetInput $input): Widget { return $this->widgetMapper->insert($widget); } + /** + * @return int[] + * @throws Exception + */ + public function findIdsByPageId(int $pageId): array { + return $this->widgetMapper->findIdsByPageId($pageId); + } + /** * Makes the widgets of a page match the given list: widgets with an id are updated, * widgets without one are inserted and widgets of the page that are not listed are diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php new file mode 100644 index 0000000000..77ca557d9e --- /dev/null +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -0,0 +1,113 @@ +pageService = $this->createMock(PageService::class); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnArgument(0); + $this->controller = new ContextPageController( + $this->createMock(IRequest::class), + $this->createMock(LoggerInterface::class), + $l10n, + 'alice', + $this->pageService, + new GridWidgetTypes($l10n), + ); + } + + /** + * @return array, 2: \Closure(ContextPageController): DataResponse}> + */ + public static function endpoints(): array { + $widgets = [['type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]]; + return [ + 'show' => ['find', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->show(7, 2)], + 'create' => ['create', [7, 'Overview', 'overview', 'star', 'At a glance', 'alice'], static fn (ContextPageController $controller) => $controller->create(7, 'Overview', 'overview', 'star', 'At a glance')], + 'update' => ['update', [7, 2, null, 'planning', '', null, $widgets, 'alice'], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'planning', '', null, $widgets)], + 'destroy' => ['delete', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->destroy(7, 2)], + ]; + } + + /** + * @dataProvider endpoints + */ + public function testAnEndpointReturnsThePage(string $method, array $arguments, \Closure $call): void { + $page = ['id' => 2, 'contextId' => 7, 'pageType' => 'grid', 'slug' => 'overview', 'title' => 'Overview', 'icon' => null, 'description' => null, 'widgets' => []]; + $this->pageService->expects($this->once())->method($method)->with(...$arguments)->willReturn($page); + + $response = $call($this->controller); + + $this->assertSame([Http::STATUS_OK, $page], [$response->getStatus(), $response->getData()]); + } + + public static function errors(): array { + $endpoints = self::endpoints(); + $cases = [ + 'show' => [new NotFoundError('Page 9 does not belong to application 7'), Http::STATUS_NOT_FOUND], + ]; + foreach (['create', 'update', 'destroy'] as $endpoint) { + $cases[$endpoint . ', bad request'] = [new BadRequestError('Widget 0 needs a type.'), Http::STATUS_BAD_REQUEST]; + $cases[$endpoint . ', no permission'] = [new PermissionError('User bob cannot manage application 7'), Http::STATUS_FORBIDDEN]; + $cases[$endpoint . ', not found'] = [new NotFoundError('Context does not exist'), Http::STATUS_NOT_FOUND]; + } + $cases['update, page gone'] = [new DoesNotExistException('Page does not exist'), Http::STATUS_NOT_FOUND]; + $errors = []; + foreach ($cases as $case => [$error, $status]) { + [$method, , $call] = $endpoints[explode(',', $case)[0]]; + $errors[$case] = [$method, $call, $error, $status]; + } + return $errors; + } + + /** + * @dataProvider errors + */ + public function testAnErrorIsAnsweredWithItsStatus(string $method, \Closure $call, \Exception $error, int $status): void { + $this->pageService->method($method)->willThrowException($error); + + $response = $call($this->controller); + + $this->assertSame($status, $response->getStatus()); + $this->assertArrayHasKey('message', $response->getData()); + } + + public function testABadRequestExplainsWhy(): void { + $this->pageService->method('update')->willThrowException(new BadRequestError('Widget 0 needs a type.')); + + $this->assertSame('Widget 0 needs a type.', $this->controller->update(7, 2, null, null, null, null, [[]])->getData()['message']); + } + + public function testWidgetTypesListsEveryType(): void { + $response = $this->controller->widgetTypes(); + + $this->assertSame(['header', 'text', 'data'], array_column($response->getData(), 'type')); + } +} diff --git a/tests/unit/Db/WidgetMapperTest.php b/tests/unit/Db/WidgetMapperTest.php index f088dd4e82..9b965c0c4e 100644 --- a/tests/unit/Db/WidgetMapperTest.php +++ b/tests/unit/Db/WidgetMapperTest.php @@ -140,7 +140,7 @@ private function widget(int $pageId, string $type, ?string $title, int $x, int $ $widget->setGridY($y); $widget->setGridWidth($width); $widget->setGridHeight($height); - $widget->setSettingsArray($settings); + $widget->setSettings($settings); return $widget; } } diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php new file mode 100644 index 0000000000..2e1cdd6fac --- /dev/null +++ b/tests/unit/Service/PageServiceTest.php @@ -0,0 +1,405 @@ +context = new Context(); + $this->context->id = 7; + $this->context->setNodes([self::NODE_REL => ['id' => self::NODE_REL, 'node_id' => 3, 'node_type' => Application::NODE_TYPE_TABLE, 'permissions' => 1]]); + $this->context->setPages([ + self::START_PAGE => ['id' => self::START_PAGE, 'page_type' => Page::TYPE_STARTPAGE, 'slug' => 'dashboard', 'title' => null, 'icon' => null, 'description' => null, 'content' => []], + self::GRID_PAGE => ['id' => self::GRID_PAGE, 'page_type' => Page::TYPE_GRID, 'slug' => 'overview', 'title' => 'Overview', 'icon' => 'star', 'description' => null, 'content' => []], + ]); + $contextMapper = $this->createMock(ContextMapper::class); + $contextMapper->method('findById')->willReturnCallback(function (int $contextId): Context { + if ($contextId !== 7) { + throw new NotFoundError('Context does not exist'); + } + return $this->context; + }); + $this->pageMapper = $this->createMock(PageMapper::class); + $this->pageContentMapper = $this->createMock(PageContentMapper::class); + $this->widgetService = $this->createMock(WidgetService::class); + $this->widgetService->method('findIdsByPageId')->willReturnMap([[self::GRID_PAGE, [31, 32]], [self::START_PAGE, []]]); + $this->permissionsService = $this->createMock(PermissionsService::class); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnArgument(0); + + $this->service = new PageService( + $contextMapper, + $this->pageMapper, + $this->pageContentMapper, + $this->widgetService, + $this->permissionsService, + new GridWidgetTypes($l10n), + $this->createMock(IDBConnection::class), + ); + } + + public function testFindReturnsThePageWithItsWidgets(): void { + $widget = ['id' => 31, 'type' => 'text', 'title' => null, 'icon' => null, 'description' => null, 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2, 'settings' => ['text' => 'Hi'], 'source' => null]; + $this->widgetService->method('findByPageIds')->with([self::GRID_PAGE])->willReturn([self::GRID_PAGE => [$widget]]); + + $this->assertSame([ + 'id' => self::GRID_PAGE, + 'contextId' => 7, + 'pageType' => Page::TYPE_GRID, + 'slug' => 'overview', + 'title' => 'Overview', + 'icon' => 'star', + 'description' => null, + 'widgets' => [$widget], + ], $this->service->find(7, self::GRID_PAGE, 'alice')); + } + + public function testAnApplicationOrPageOutsideTheUsersReachIsNotFound(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->expects($this->never())->method('insert'); + $this->pageMapper->expects($this->never())->method('update'); + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + $this->widgetService->expects($this->never())->method('syncPage'); + + foreach ([ + 'application of no access' => fn () => $this->service->find(8, self::GRID_PAGE, 'mallory'), + 'create in it' => fn () => $this->service->create(8, 'Overview', null, null, null, 'mallory'), + 'update in it' => fn () => $this->service->update(8, self::GRID_PAGE, 'Mine', null, null, null, [], 'mallory'), + 'delete in it' => fn () => $this->service->delete(8, self::GRID_PAGE, 'mallory'), + 'page of another application' => fn () => $this->service->find(7, 99, 'alice'), + 'update it' => fn () => $this->service->update(7, 99, 'Taken over', null, null, null, [], 'alice'), + 'delete it' => fn () => $this->service->delete(7, 99, 'alice'), + ] as $case => $call) { + try { + $call(); + $this->fail($case . ' was found.'); + } catch (NotFoundError) { + } + } + } + + public function testCreateInsertsAGridPageNamedByItsId(): void { + $this->permissionsService->method('canManageContext')->with($this->context, 'alice')->willReturn(true); + $inserted = null; + $this->pageMapper->expects($this->never())->method('insert'); + $this->pageMapper->expects($this->once())->method('insertWithDefaultName')->willReturnCallback(function (Page $page) use (&$inserted): Page { + $page->id = self::GRID_PAGE; + $page->setSlug('page_' . self::GRID_PAGE); + $inserted = $page; + return $page; + }); + + $this->service->create(7, ' Team Overview ', null, ' home ', '', 'alice'); + + $this->assertSame([7, Page::TYPE_GRID, 'Team Overview', 'home', null], [$inserted->getContextId(), $inserted->getPageType(), $inserted->getTitle(), $inserted->getIcon(), $inserted->getDescription()]); + } + + public function testCreateKeepsAGivenSlug(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->expects($this->never())->method('insertWithDefaultName'); + $inserted = null; + $this->pageMapper->expects($this->once())->method('insert')->willReturnCallback(function (Page $page) use (&$inserted): Page { + $page->id = self::GRID_PAGE; + $inserted = $page; + return $page; + }); + + $this->service->create(7, 'Overview', 'team_board', null, null, 'alice'); + + $this->assertSame('team_board', $inserted->getSlug()); + } + + public function testCreateRefusesAGivenNameAConcurrentSaveTook(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->expects($this->once())->method('insert') + ->willThrowException(DbErrorStub::uniqueViolation()); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('already used'); + $this->service->create(7, 'Overview', 'team_board', null, null, 'alice'); + } + + public function testCreateNeedsATitle(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->expects($this->never())->method('insert'); + + $this->expectException(BadRequestError::class); + $this->service->create(7, ' ', null, null, null, 'alice'); + } + + public function testUpdateSyncsWidgetsById(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $synced = null; + $this->widgetService->expects($this->once())->method('syncPage')->willReturnCallback(function (int $pageId, array $rows) use (&$synced): void { + $this->assertSame(self::GRID_PAGE, $pageId); + $synced = $rows; + }); + $this->pageMapper->expects($this->never())->method('update'); + + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [ + ['id' => 31, 'type' => 'header', 'title' => ' Intro ', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 12, 'gridHeight' => 2, 'settings' => ['heading' => 'Welcome']], + ['type' => 'data', 'icon' => 'star', 'description' => ' Open tasks ', 'gridX' => 0, 'gridY' => 2, 'gridWidth' => 6, 'gridHeight' => 5, 'source' => ['nodeRelId' => self::NODE_REL]], + ['type' => 'data', 'icon' => '', 'description' => '', 'gridX' => 0, 'gridY' => 7, 'gridWidth' => 12, 'gridHeight' => 5, 'source' => null], + ], 'alice'); + + $this->assertSame([ + ['id' => 31, 'type' => 'header', 'title' => 'Intro', 'icon' => null, 'description' => null, 'position' => ['gridX' => 0, 'gridY' => 0, 'gridWidth' => 12, 'gridHeight' => 2], 'settings' => ['heading' => 'Welcome', 'subheading' => '', 'textAlign' => 'start', 'backgroundColor' => '', 'textColor' => ''], 'nodeRelId' => null], + ['id' => null, 'type' => 'data', 'title' => null, 'icon' => 'star', 'description' => 'Open tasks', 'position' => ['gridX' => 0, 'gridY' => 2, 'gridWidth' => 6, 'gridHeight' => 5], 'settings' => [], 'nodeRelId' => self::NODE_REL], + ['id' => null, 'type' => 'data', 'title' => null, 'icon' => null, 'description' => null, 'position' => ['gridX' => 0, 'gridY' => 7, 'gridWidth' => 12, 'gridHeight' => 5], 'settings' => [], 'nodeRelId' => null], + ], $synced); + } + + public function testChangesNeedManagePermission(): void { + $this->permissionsService->method('canManageContext')->with($this->context, 'bob')->willReturn(false); + $this->pageMapper->expects($this->never())->method('insert'); + $this->pageMapper->expects($this->never())->method('update'); + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + $this->widgetService->expects($this->never())->method('syncPage'); + + foreach ([ + 'create' => fn () => $this->service->create(7, 'Overview', null, null, null, 'bob'), + 'update' => fn () => $this->service->update(7, self::GRID_PAGE, 'New', null, null, null, [], 'bob'), + 'delete' => fn () => $this->service->delete(7, self::GRID_PAGE, 'bob'), + ] as $case => $call) { + try { + $call(); + $this->fail($case . ' was allowed.'); + } catch (PermissionError) { + } + } + } + + public function testUpdateChangesPageFields(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $stored = new Page(); + $stored->id = self::GRID_PAGE; + $stored->setSlug('overview'); + $stored->setTitle('Overview'); + $stored->setIcon('star'); + $stored->resetUpdatedFields(); + $this->pageMapper->method('findById')->with(self::GRID_PAGE)->willReturn($stored); + $updated = null; + $this->pageMapper->expects($this->once())->method('update')->willReturnCallback(function (Page $page) use (&$updated): Page { + $updated = $page; + return $page; + }); + $this->widgetService->expects($this->never())->method('syncPage'); + + $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', '', 'What is next', null, 'alice'); + + $this->assertSame([self::GRID_PAGE, 'planning', 'Planning', null, 'What is next'], [$updated->getId(), $updated->getSlug(), $updated->getTitle(), $updated->getIcon(), $updated->getDescription()]); + $this->assertSame(['title', 'slug', 'icon', 'description'], array_keys($updated->getUpdatedFields())); + } + + public function testUpdateKeepsTheSlugWhenTheTitleChanges(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $stored = $this->storedGridPage(); + $this->pageMapper->method('findById')->willReturn($stored); + $this->pageMapper->expects($this->once())->method('update')->willReturnArgument(0); + + $this->service->update(7, self::GRID_PAGE, 'Planning', null, null, null, null, 'alice'); + + $this->assertSame('overview', $stored->getSlug()); + } + + public function testAPageKeepsOrTakesItsOwnNames(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $stored = $this->storedGridPage(); + $this->pageMapper->method('findById')->willReturn($stored); + $this->pageMapper->expects($this->once())->method('update')->willReturnArgument(0); + + $this->service->update(7, self::GRID_PAGE, null, 'overview', null, null, null, 'alice'); + $this->service->update(7, self::GRID_PAGE, null, 'page_' . self::GRID_PAGE, null, null, null, 'alice'); + + $this->assertSame('page_' . self::GRID_PAGE, $stored->getSlug()); + } + + public static function refusedSlugs(): array { + return [ + 'upper case' => ['Board', 'lower case letters'], + 'leading digit' => ['2026_plan', 'lower case letters'], + 'empty' => ['', 'lower case letters'], + 'too long' => [str_repeat('a', 201), 'lower case letters'], + 'taken' => ['dashboard', 'already used'], + 'reserved' => ['page_9', 'reserved for automatic names'], + ]; + } + + /** + * @dataProvider refusedSlugs + */ + public function testUpdateRefusesAnInvalidOrTakenSlug(string $slug, string $message): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); + $this->pageMapper->expects($this->never())->method('update'); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage($message); + $this->service->update(7, self::GRID_PAGE, null, $slug, null, null, null, 'alice'); + } + + public function testUpdateRefusesANameAConcurrentSaveTook(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); + $this->pageMapper->method('update') + ->willThrowException(DbErrorStub::uniqueViolation()); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('already used'); + $this->service->update(7, self::GRID_PAGE, null, 'planning', null, null, null, 'alice'); + } + + public function testUpdateRefusesAnUnknownIcon(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); + $this->pageMapper->expects($this->never())->method('update'); + + $this->expectException(BadRequestError::class); + $this->service->update(7, self::GRID_PAGE, null, null, 'no-such-icon', null, null, 'alice'); + } + + private function storedGridPage(): Page { + $stored = new Page(); + $stored->id = self::GRID_PAGE; + $stored->setContextId(7); + $stored->setSlug('overview'); + $stored->setTitle('Overview'); + $stored->resetUpdatedFields(); + return $stored; + } + + public static function invalidWidgets(): array { + $at = ['gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]; + $foreignSource = 'must be {nodeRelId} of a table or view of this application'; + return [ + 'not an object' => [['x'], 'Widget 0 must be an object'], + 'no type' => [[$at], 'Widget 0 needs a type'], + 'unknown type' => [[['type' => 'chart'] + $at], 'Unknown widget type'], + 'id of another page' => [[['id' => 99, 'type' => 'text'] + $at], 'Widget 0 has the id of no other widget on this page'], + 'id twice' => [[['id' => 31, 'type' => 'text'] + $at, ['id' => 31, 'type' => 'text'] + $at], 'Widget 1 has the id'], + 'invalid setting' => [[['type' => 'header', 'settings' => ['heading' => '']] + $at], 'header.heading is required'], + 'outside the grid' => [[['type' => 'text', 'gridX' => 8, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'does not fit in 12 columns'], + 'invalid title' => [[['type' => 'text', 'title' => 5] + $at], 'The title of widget 0'], + 'unknown icon' => [[['type' => 'text', 'icon' => 'no-such-icon'] + $at], 'Widget 0 has an unknown icon'], + 'icon not text' => [[['type' => 'text', 'icon' => 5] + $at], 'The icon of widget 0'], + 'source on a header' => [[['type' => 'header', 'settings' => ['heading' => 'A'], 'source' => ['nodeRelId' => self::NODE_REL]] + $at], 'shows no table or view'], + 'node of another application' => [[['type' => 'data', 'source' => ['nodeRelId' => 21]] + $at], $foreignSource], + 'table outside the application' => [[['type' => 'data', 'source' => ['nodeType' => Application::NODE_TYPE_TABLE, 'nodeId' => 3]] + $at], $foreignSource], + 'source not an object' => [[['type' => 'data', 'source' => self::NODE_REL] + $at], $foreignSource], + ]; + } + + /** + * @dataProvider invalidWidgets + */ + public function testUpdateRejectsInvalidWidgets(array $widgets, string $message): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->widgetService->expects($this->never())->method('syncPage'); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage($message); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); + } + + public function testTheStartPageHoldsNoWidgets(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + + $this->expectException(BadRequestError::class); + $this->service->update(7, self::START_PAGE, null, null, null, null, [], 'alice'); + } + + public function testDeleteRemovesAGridPageWithItsWidgets(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([]); + $this->widgetService->expects($this->once())->method('deleteByPageIds')->with([self::GRID_PAGE]); + $this->pageMapper->expects($this->once())->method('deleteByPageId')->with(self::GRID_PAGE); + + $this->assertSame('Overview', $this->service->delete(7, self::GRID_PAGE, 'alice')['title']); + } + + public function testTheStartPageCannotBeDeleted(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + + $this->expectException(BadRequestError::class); + $this->service->delete(7, self::START_PAGE, 'alice'); + } + + public function testAPageHoldsAtMostTheMaximumNumberOfWidgets(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->widgetService->expects($this->once())->method('syncPage'); + $widgets = []; + for ($i = 0; $i < GridWidgetTypes::MAX_WIDGETS_PER_PAGE; $i++) { + $widgets[] = ['type' => 'text', 'gridX' => 0, 'gridY' => $i * 2, 'gridWidth' => 6, 'gridHeight' => 2]; + } + $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); + + $widgets[] = ['type' => 'text', 'gridX' => 6, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]; + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('at most 100 widgets'); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); + } + + /** + * A concurrent save removed a listed widget between the check and the sync. + */ + public function testAWidgetRemovedByAConcurrentSaveAsksForARetry(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->widgetService->method('syncPage')->willThrowException(new \InvalidArgumentException('Widget 31 is not on page 2')); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('changed by another save'); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [['id' => 31, 'type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'alice'); + } + + /** + * Two saves adding a source to the same widget at once collide on the source key; that + * is no taken slug. + */ + public function testAConcurrentCollisionWithoutARenameAsksForARetry(): void { + $this->permissionsService->method('canManageContext')->willReturn(true); + $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); + $this->widgetService->method('syncPage')->willThrowException(DbErrorStub::uniqueViolation()); + + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('changed by another save'); + $this->service->update(7, self::GRID_PAGE, 'Renamed title', 'overview', null, null, [['id' => 31, 'type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'alice'); + } +} diff --git a/tests/unit/Service/WidgetServiceTest.php b/tests/unit/Service/WidgetServiceTest.php index 57604b6b8d..87f3eba4e9 100644 --- a/tests/unit/Service/WidgetServiceTest.php +++ b/tests/unit/Service/WidgetServiceTest.php @@ -236,7 +236,7 @@ public function testAFailedSyncChangesNothing(): void { ['id' => null, 'type' => 'text', 'title' => null, 'position' => $this->position(0, 0, 6, 2), 'settings' => ['text' => NAN], 'nodeRelId' => null], ]); $this->fail('Settings that are no JSON were saved.'); - } catch (\JsonException) { + } catch (\OCP\DB\Exception) { } $this->assertSame([$kept->getId()], array_column($this->service->findByPageIds([$this->page])[$this->page], 'id')); From 1a3b8c649facd4b1e1d88ea215e16f4f353c7403 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Thu, 22 Oct 2026 15:10:23 +0200 Subject: [PATCH 02/16] chore(api): regenerate the OpenAPI spec and TypeScript types Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- openapi.json | 1569 +++++++++++++++++++++++++++++++--- src/types/openapi/openapi.ts | 718 ++++++++++++++-- 2 files changed, 2124 insertions(+), 163 deletions(-) diff --git a/openapi.json b/openapi.json index 616e897e24..6f0ae8f7a2 100644 --- a/openapi.json +++ b/openapi.json @@ -463,6 +463,53 @@ } } }, + "Page": { + "type": "object", + "required": [ + "id", + "contextId", + "pageType", + "technicalName", + "title", + "icon", + "description", + "widgets" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "contextId": { + "type": "integer", + "format": "int64" + }, + "pageType": { + "type": "string" + }, + "technicalName": { + "type": "string" + }, + "title": { + "type": "string", + "nullable": true + }, + "icon": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "widgets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Widget" + } + } + } + }, "PublicColumn": { "type": "object", "required": [ @@ -1312,6 +1359,180 @@ "nullable": true } } + }, + "Widget": { + "type": "object", + "required": [ + "id", + "type", + "title", + "icon", + "description", + "gridX", + "gridY", + "gridWidth", + "gridHeight", + "settings", + "source" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "type": { + "type": "string" + }, + "title": { + "type": "string", + "nullable": true + }, + "icon": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "gridX": { + "type": "integer", + "format": "int64" + }, + "gridY": { + "type": "integer", + "format": "int64" + }, + "gridWidth": { + "type": "integer", + "format": "int64" + }, + "gridHeight": { + "type": "integer", + "format": "int64" + }, + "settings": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/WidgetValue" + } + }, + "source": { + "type": "object", + "nullable": true, + "required": [ + "nodeRelId" + ], + "properties": { + "nodeRelId": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "WidgetSettingSchema": { + "type": "object", + "required": [ + "type", + "title", + "default" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "text", + "color", + "boolean", + "enum" + ] + }, + "title": { + "type": "string" + }, + "default": { + "$ref": "#/components/schemas/WidgetValue" + }, + "options": { + "type": "array", + "items": { + "type": "object", + "required": [ + "value", + "label" + ], + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + } + } + } + }, + "required": { + "type": "boolean" + } + } + }, + "WidgetType": { + "type": "object", + "required": [ + "type", + "title", + "defaultWidth", + "defaultHeight", + "hasSource", + "settings" + ], + "properties": { + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "defaultWidth": { + "type": "integer", + "format": "int64" + }, + "defaultHeight": { + "type": "integer", + "format": "int64" + }, + "hasSource": { + "type": "boolean" + }, + "settings": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/WidgetSettingSchema" + } + } + } + }, + "WidgetValue": { + "nullable": true, + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "int64" + }, + { + "type": "number", + "format": "double" + }, + { + "type": "boolean" + } + ] } } }, @@ -14581,14 +14802,12 @@ } } } - } - }, - "/ocs/v2.php/apps/tables/api/2/config/table/{id}": { + }, "get": { - "operationId": "config-get-table-config", - "summary": "Gets the config for a specific table", + "operationId": "context_page-show", + "summary": "[api v2] Get a page of an application with its widgets", "tags": [ - "config" + "context_page" ], "security": [ { @@ -14600,9 +14819,19 @@ ], "parameters": [ { - "name": "id", + "name": "contextId", "in": "path", - "description": "Table id", + "description": "ID of the application", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "pageId", + "in": "path", + "description": "ID of the page", "required": true, "schema": { "type": "integer", @@ -14622,7 +14851,7 @@ ], "responses": { "200": { - "description": "Table config returned", + "description": "Page returned", "content": { "application/json": { "schema": { @@ -14642,7 +14871,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/NotifyConfig" + "$ref": "#/components/schemas/Page" } } } @@ -14651,8 +14880,8 @@ } } }, - "401": { - "description": "Current user is not logged in", + "500": { + "description": "", "content": { "application/json": { "schema": { @@ -14671,57 +14900,26 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": {} + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } } } } } } } - } - } - } - }, - "/ocs/v2.php/apps/tables/api/2/config/view/{id}": { - "get": { - "operationId": "config-get-view-config", - "summary": "Gets the config for a specific view", - "tags": [ - "config" - ], - "security": [ - { - "bearer_auth": [] - }, - { - "basic_auth": [] - } - ], - "parameters": [ - { - "name": "id", - "in": "path", - "description": "View id", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } }, - { - "name": "OCS-APIRequest", - "in": "header", - "description": "Required to be true for the API request to pass", - "required": true, - "schema": { - "type": "boolean", - "default": true - } - } - ], - "responses": { - "200": { - "description": "View config returned", + "404": { + "description": "Not found, also when the user has no access to the application", "content": { "application/json": { "schema": { @@ -14741,15 +14939,23 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/NotifyConfig" - } - } - } - } - } - } - } - }, + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -14779,14 +14985,13 @@ } } } - } - }, - "/ocs/v2.php/apps/tables/api/2/config/{key}": { - "post": { - "operationId": "config-set-value", - "summary": "Sets a config value for a specific key", + }, + "patch": { + "operationId": "context_page-update", + "summary": "[api v2] Change a page or its widgets", + "description": "Fields left out keep their value; an empty icon or description removes it. A given `widgets` list replaces the widgets of the grid page: listed widgets with an `id` are updated, others are added, and widgets not listed are deleted.\nA widget has a `type`, `gridX`, `gridY`, `gridWidth` and `gridHeight` on a grid of 12 columns, `settings` following the schema of its type, and optionally an `id`, `title`, `icon` and `description`. A data widget's `source` is `{nodeRelId}` of a table or view of this application, or null.", "tags": [ - "config" + "context_page" ], "security": [ { @@ -14797,18 +15002,47 @@ } ], "requestBody": { - "required": true, + "required": false, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "value" - ], "properties": { - "value": { - "type": "object", - "description": "Config value" + "title": { + "type": "string", + "nullable": true, + "default": null, + "description": "New title" + }, + "technicalName": { + "type": "string", + "nullable": true, + "default": null, + "description": "New technical name" + }, + "icon": { + "type": "string", + "nullable": true, + "default": null, + "description": "New icon name, empty to remove it" + }, + "description": { + "type": "string", + "nullable": true, + "default": null, + "description": "New description, empty to remove it" + }, + "widgets": { + "type": "array", + "nullable": true, + "default": null, + "description": "All widgets of the page", + "items": { + "type": "object", + "additionalProperties": { + "type": "object" + } + } } } } @@ -14817,12 +15051,23 @@ }, "parameters": [ { - "name": "key", + "name": "contextId", "in": "path", - "description": "Config key", + "description": "ID of the application", "required": true, "schema": { - "type": "string" + "type": "integer", + "format": "int64" + } + }, + { + "name": "pageId", + "in": "path", + "description": "ID of the page", + "required": true, + "schema": { + "type": "integer", + "format": "int64" } }, { @@ -14838,7 +15083,7 @@ ], "responses": { "200": { - "description": "Config updated", + "description": "Page updated", "content": { "application/json": { "schema": { @@ -14858,7 +15103,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "type": "boolean" + "$ref": "#/components/schemas/Page" } } } @@ -14868,7 +15113,7 @@ } }, "400": { - "description": "bad request", + "description": "Invalid page field or widget, too many widgets, or the page changed in between", "content": { "application/json": { "schema": { @@ -14943,6 +15188,82 @@ } } }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "500": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -14972,18 +15293,15 @@ } } } - } - }, - "/ocs/v2.php/apps/tables/api/2/public/{token}/columns": { - "get": { - "operationId": "api_public_columns-index-by-public-link", - "summary": "[api v2] Get all columns for a table or a view shared by link", - "description": "Return an empty array if no columns were found", + }, + "delete": { + "operationId": "context_page-destroy", + "summary": "[api v2] Delete a grid page with its widgets", + "description": "The start page of an application cannot be deleted.", "tags": [ - "api_public_columns" + "context_page" ], "security": [ - {}, { "bearer_auth": [] }, @@ -14993,13 +15311,23 @@ ], "parameters": [ { - "name": "token", + "name": "contextId", "in": "path", - "description": "The share token", + "description": "ID of the application", "required": true, "schema": { - "type": "string", - "pattern": "^[a-zA-Z0-9]{16}$" + "type": "integer", + "format": "int64" + } + }, + { + "name": "pageId", + "in": "path", + "description": "ID of the page", + "required": true, + "schema": { + "type": "integer", + "format": "int64" } }, { @@ -15015,7 +15343,7 @@ ], "responses": { "200": { - "description": "Columns are returned", + "description": "Page deleted", "content": { "application/json": { "schema": { @@ -15035,10 +15363,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PublicColumn" - } + "$ref": "#/components/schemas/Page" } } } @@ -15047,8 +15372,8 @@ } } }, - "403": { - "description": "No permissions", + "400": { + "description": "The page is the start page", "content": { "application/json": { "schema": { @@ -15085,8 +15410,8 @@ } } }, - "400": { - "description": "Invalid request parameters", + "403": { + "description": "No permissions", "content": { "application/json": { "schema": { @@ -15162,7 +15487,7 @@ } }, "500": { - "description": "Internal error", + "description": "", "content": { "application/json": { "schema": { @@ -15198,6 +15523,1034 @@ } } } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/config/table/{id}": { + "get": { + "operationId": "config-get-table-config", + "summary": "Gets the config for a specific table", + "tags": [ + "config" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Table id", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Table config returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/NotifyConfig" + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/config/view/{id}": { + "get": { + "operationId": "config-get-view-config", + "summary": "Gets the config for a specific view", + "tags": [ + "config" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "View id", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "View config returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/NotifyConfig" + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/config/{key}": { + "post": { + "operationId": "config-set-value", + "summary": "Sets a config value for a specific key", + "tags": [ + "config" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "object", + "description": "Config value" + } + } + } + } + } + }, + "parameters": [ + { + "name": "key", + "in": "path", + "description": "Config key", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Config updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "400": { + "description": "bad request", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "403": { + "description": "No permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/public/{token}/columns": { + "get": { + "operationId": "api_public_columns-index-by-public-link", + "summary": "[api v2] Get all columns for a table or a view shared by link", + "description": "Return an empty array if no columns were found", + "tags": [ + "api_public_columns" + ], + "security": [ + {}, + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "token", + "in": "path", + "description": "The share token", + "required": true, + "schema": { + "type": "string", + "pattern": "^[a-zA-Z0-9]{16}$" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Columns are returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PublicColumn" + } + } + } + } + } + } + } + } + }, + "403": { + "description": "No permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "400": { + "description": "Invalid request parameters", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages": { + "post": { + "operationId": "context_page-create", + "summary": "[api v2] Add a grid page to an application", + "tags": [ + "context_page" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "title" + ], + "properties": { + "title": { + "type": "string", + "description": "Title of the page" + }, + "technicalName": { + "type": "string", + "nullable": true, + "default": null, + "description": "Technical name of the page, unique in the application; `page_` when left out, a form reserved for automatic names" + }, + "icon": { + "type": "string", + "nullable": true, + "default": null, + "description": "Name of the icon shown with the title" + }, + "description": { + "type": "string", + "nullable": true, + "default": null, + "description": "Description of the page" + } + } + } + } + } + }, + "parameters": [ + { + "name": "contextId", + "in": "path", + "description": "ID of the application", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Page created", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/Page" + } + } + } + } + } + } + } + }, + "400": { + "description": "Invalid title, icon or description, or an invalid or taken technical name", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "403": { + "description": "No permissions", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "500": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/tables/api/2/widget-types": { + "get": { + "operationId": "context_page-widget-types", + "summary": "[api v2] Get the widget types a grid page can hold", + "description": "Every type carries the schema of its settings and whether it shows a table or view.", + "tags": [ + "context_page" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Widget types returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WidgetType" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } } } } diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 01e375c046..a88cdc258c 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -940,14 +940,24 @@ export type paths = { readonly path?: never; readonly cookie?: never; }; - readonly get?: never; + /** [api v2] Get a page of an application with its widgets */ + readonly get: operations["context_page-show"]; /** [api v2] Update the order on a page of a context */ readonly put: operations["context-update-content-order"]; readonly post?: never; - readonly delete?: never; + /** + * [api v2] Delete a grid page with its widgets + * @description The start page of an application cannot be deleted. + */ + readonly delete: operations["context_page-destroy"]; readonly options?: never; readonly head?: never; - readonly patch?: never; + /** + * [api v2] Change a page or its widgets + * @description Fields left out keep their value; an empty icon or description removes it. A given `widgets` list replaces the widgets of the grid page: listed widgets with an `id` are updated, others are added, and widgets not listed are deleted. + * A widget has a `type`, `gridX`, `gridY`, `gridWidth` and `gridHeight` on a grid of 12 columns, `settings` following the schema of its type, and optionally an `id`, `title`, `icon` and `description`. A data widget's `source` is `{nodeRelId}` of a table or view of this application, or null. + */ + readonly patch: operations["context_page-update"]; readonly trace?: never; }; readonly "/ocs/v2.php/apps/tables/api/2/config/table/{id}": { @@ -1021,6 +1031,43 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + readonly get?: never; + readonly put?: never; + /** [api v2] Add a grid page to an application */ + readonly post: operations["context_page-create"]; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; + readonly "/ocs/v2.php/apps/tables/api/2/widget-types": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** + * [api v2] Get the widget types a grid page can hold + * @description Every type carries the schema of its settings and whether it shows a table or view. + */ + readonly get: operations["context_page-widget-types"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/ocs/v2.php/apps/tables/api/2/public/{token}/rows": { readonly parameters: { readonly query?: never; @@ -1244,6 +1291,18 @@ export type components = { readonly totalitems?: string; readonly itemsperpage?: string; }; + readonly Page: { + /** Format: int64 */ + readonly id: number; + /** Format: int64 */ + readonly contextId: number; + readonly pageType: string; + readonly technicalName: string; + readonly title: string | null; + readonly icon: string | null; + readonly description: string | null; + readonly widgets: readonly components["schemas"]["Widget"][]; + }; readonly PublicColumn: { /** Format: int64 */ readonly id: number; @@ -1477,6 +1536,53 @@ export type components = { /** Format: int64 */ readonly sidebarOrder: number | null; }; + readonly Widget: { + /** Format: int64 */ + readonly id: number; + readonly type: string; + readonly title: string | null; + readonly icon: string | null; + readonly description: string | null; + /** Format: int64 */ + readonly gridX: number; + /** Format: int64 */ + readonly gridY: number; + /** Format: int64 */ + readonly gridWidth: number; + /** Format: int64 */ + readonly gridHeight: number; + readonly settings: { + readonly [key: string]: components["schemas"]["WidgetValue"]; + }; + readonly source: { + /** Format: int64 */ + readonly nodeRelId: number; + } | null; + }; + readonly WidgetSettingSchema: { + /** @enum {string} */ + readonly type: "string" | "text" | "color" | "boolean" | "enum"; + readonly title: string; + readonly default: components["schemas"]["WidgetValue"]; + readonly options?: readonly { + readonly value: string; + readonly label: string; + }[]; + readonly required?: boolean; + }; + readonly WidgetType: { + readonly type: string; + readonly title: string; + /** Format: int64 */ + readonly defaultWidth: number; + /** Format: int64 */ + readonly defaultHeight: number; + readonly hasSource: boolean; + readonly settings: { + readonly [key: string]: components["schemas"]["WidgetSettingSchema"]; + }; + }; + readonly WidgetValue: (string | number | boolean) | null; }; responses: never; parameters: never; @@ -7949,6 +8055,84 @@ export interface operations { }; }; }; + readonly "context_page-show": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description ID of the application */ + readonly contextId: number; + /** @description ID of the page */ + readonly pageId: number; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Page returned */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: components["schemas"]["Page"]; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + /** @description Not found, also when the user has no access to the application */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + readonly 500: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + }; + }; readonly "context-update-content-order": { readonly parameters: { readonly query?: never; @@ -8071,7 +8255,7 @@ export interface operations { }; }; }; - readonly "config-get-table-config": { + readonly "context_page-destroy": { readonly parameters: { readonly query?: never; readonly header: { @@ -8079,14 +8263,16 @@ export interface operations { readonly "OCS-APIRequest": boolean; }; readonly path: { - /** @description Table id */ - readonly id: number; + /** @description ID of the application */ + readonly contextId: number; + /** @description ID of the page */ + readonly pageId: number; }; readonly cookie?: never; }; readonly requestBody?: never; readonly responses: { - /** @description Table config returned */ + /** @description Page deleted */ readonly 200: { headers: { readonly [name: string]: unknown; @@ -8095,7 +8281,23 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: components["schemas"]["NotifyConfig"]; + readonly data: components["schemas"]["Page"]; + }; + }; + }; + }; + /** @description The page is the start page */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; }; }; }; @@ -8114,25 +8316,24 @@ export interface operations { }; }; }; - }; - }; - readonly "config-get-view-config": { - readonly parameters: { - readonly query?: never; - readonly header: { - /** @description Required to be true for the API request to pass */ - readonly "OCS-APIRequest": boolean; - }; - readonly path: { - /** @description View id */ - readonly id: number; + /** @description No permissions */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; }; - readonly cookie?: never; - }; - readonly requestBody?: never; - readonly responses: { - /** @description View config returned */ - readonly 200: { + /** @description Not found */ + readonly 404: { headers: { readonly [name: string]: unknown; }; @@ -8140,13 +8341,14 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: components["schemas"]["NotifyConfig"]; + readonly data: { + readonly message: string; + }; }; }; }; }; - /** @description Current user is not logged in */ - readonly 401: { + readonly 500: { headers: { readonly [name: string]: unknown; }; @@ -8154,14 +8356,16 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: unknown; + readonly data: { + readonly message: string; + }; }; }; }; }; }; }; - readonly "config-set-value": { + readonly "context_page-update": { readonly parameters: { readonly query?: never; readonly header: { @@ -8169,21 +8373,48 @@ export interface operations { readonly "OCS-APIRequest": boolean; }; readonly path: { - /** @description Config key */ - readonly key: string; + /** @description ID of the application */ + readonly contextId: number; + /** @description ID of the page */ + readonly pageId: number; }; readonly cookie?: never; }; - readonly requestBody: { + readonly requestBody?: { readonly content: { readonly "application/json": { - /** @description Config value */ - readonly value: Record; + /** + * @description New title + * @default null + */ + readonly title?: string | null; + /** + * @description New technical name + * @default null + */ + readonly technicalName?: string | null; + /** + * @description New icon name, empty to remove it + * @default null + */ + readonly icon?: string | null; + /** + * @description New description, empty to remove it + * @default null + */ + readonly description?: string | null; + /** + * @description All widgets of the page + * @default null + */ + readonly widgets?: readonly { + readonly [key: string]: Record; + }[] | null; }; }; }; readonly responses: { - /** @description Config updated */ + /** @description Page updated */ readonly 200: { headers: { readonly [name: string]: unknown; @@ -8192,12 +8423,12 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: boolean; + readonly data: components["schemas"]["Page"]; }; }; }; }; - /** @description bad request */ + /** @description Invalid page field or widget, too many widgets, or the page changed in between */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -8243,22 +8474,227 @@ export interface operations { }; }; }; - }; - }; - readonly "api_public_columns-index-by-public-link": { - readonly parameters: { - readonly query?: never; - readonly header: { - /** @description Required to be true for the API request to pass */ - readonly "OCS-APIRequest": boolean; - }; - readonly path: { - /** @description The share token */ - readonly token: string; - }; - readonly cookie?: never; - }; - readonly requestBody?: never; + /** @description Not found */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + readonly 500: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + }; + }; + readonly "config-get-table-config": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description Table id */ + readonly id: number; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Table config returned */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: components["schemas"]["NotifyConfig"]; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + }; + }; + readonly "config-get-view-config": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description View id */ + readonly id: number; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description View config returned */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: components["schemas"]["NotifyConfig"]; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + }; + }; + readonly "config-set-value": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description Config key */ + readonly key: string; + }; + readonly cookie?: never; + }; + readonly requestBody: { + readonly content: { + readonly "application/json": { + /** @description Config value */ + readonly value: Record; + }; + }; + }; + readonly responses: { + /** @description Config updated */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: boolean; + }; + }; + }; + }; + /** @description bad request */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + /** @description No permissions */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + }; + }; + readonly "api_public_columns-index-by-public-link": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description The share token */ + readonly token: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; readonly responses: { /** @description Columns are returned */ readonly 200: { @@ -8340,6 +8776,178 @@ export interface operations { }; }; }; + readonly "context_page-create": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description ID of the application */ + readonly contextId: number; + }; + readonly cookie?: never; + }; + readonly requestBody: { + readonly content: { + readonly "application/json": { + /** @description Title of the page */ + readonly title: string; + /** + * @description Technical name of the page, unique in the application; `page_` when left out, a form reserved for automatic names + * @default null + */ + readonly technicalName?: string | null; + /** + * @description Name of the icon shown with the title + * @default null + */ + readonly icon?: string | null; + /** + * @description Description of the page + * @default null + */ + readonly description?: string | null; + }; + }; + }; + readonly responses: { + /** @description Page created */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: components["schemas"]["Page"]; + }; + }; + }; + }; + /** @description Invalid title, icon or description, or an invalid or taken technical name */ + readonly 400: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + /** @description No permissions */ + readonly 403: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + /** @description Not found */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + readonly 500: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + }; + }; + readonly "context_page-widget-types": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path?: never; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Widget types returned */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: readonly components["schemas"]["WidgetType"][]; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + }; + }; readonly "public_rowocs-get-rows": { readonly parameters: { readonly query?: { From 10f8f815716201507972859ec023bfdc43f551a8 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 6 Nov 2026 16:49:44 +0100 Subject: [PATCH 03/16] feat(api): read a page of an application by its technical name Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Controller/ContextPageController.php | 23 +++++++++++++++++ lib/Service/PageService.php | 25 ++++++++++++++++++- .../Controller/ContextPageControllerTest.php | 1 + tests/unit/Service/PageServiceTest.php | 8 ++++++ 4 files changed, 56 insertions(+), 1 deletion(-) diff --git a/lib/Controller/ContextPageController.php b/lib/Controller/ContextPageController.php index 2f7e4d0857..5f16cf6c58 100644 --- a/lib/Controller/ContextPageController.php +++ b/lib/Controller/ContextPageController.php @@ -68,6 +68,29 @@ public function show(int $contextId, int $pageId): DataResponse { } } + /** + * [api v2] Get a page of an application by its slug + * + * @param int $contextId ID of the application + * @param string $slug Slug of the page + * @return DataResponse|DataResponse + * + * 200: Page returned + * 404: Not found, also when the user has no access to the application + */ + #[NoAdminRequired] + #[RequirePermission(permission: Application::PERMISSION_READ, typeParam: 'context', idParam: 'contextId')] + #[ApiRoute(verb: 'GET', url: '/api/2/contexts/{contextId}/pages/{slug}', requirements: ['contextId' => '\d+', 'slug' => '[a-z][a-z0-9_]*'])] + public function showBySlug(int $contextId, string $slug): DataResponse { + try { + return new DataResponse($this->pageService->findBySlug($contextId, $slug, $this->userId)); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (Exception $e) { + return $this->handleError($e); + } + } + /** * [api v2] Add a grid page to an application * diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index 1eeec3af52..475b205640 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -56,13 +56,36 @@ public function __construct( * @throws Exception */ public function find(int $contextId, int $pageId, string $userId): array { + return $this->readPage($this->contextMapper->findById($contextId, $userId), $pageId); + } + + /** + * @return TablesPage + * @throws NotFoundError + * @throws Exception + */ + public function findBySlug(int $contextId, string $slug, string $userId): array { $context = $this->contextMapper->findById($contextId, $userId); + foreach ($context->getPages() ?? [] as $pageId => $page) { + if ($page['slug'] === $slug) { + return $this->readPage($context, (int)$pageId); + } + } + throw new NotFoundError('Application ' . $contextId . ' has no page ' . $slug); + } + + /** + * @return TablesPage + * @throws NotFoundError + * @throws Exception + */ + private function readPage(Context $context, int $pageId): array { $page = $this->getPageArray($context, $pageId); $widgets = $this->widgetService->findByPageIds([$pageId]); return [ 'id' => $pageId, - 'contextId' => $contextId, + 'contextId' => $context->getId(), 'pageType' => (string)$page['page_type'], 'slug' => (string)$page['slug'], 'title' => $page['title'] ?? null, diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php index 77ca557d9e..f4b4ef1e99 100644 --- a/tests/unit/Controller/ContextPageControllerTest.php +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -50,6 +50,7 @@ public static function endpoints(): array { $widgets = [['type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]]; return [ 'show' => ['find', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->show(7, 2)], + 'show by name' => ['findBySlug', [7, 'overview', 'alice'], static fn (ContextPageController $controller) => $controller->showBySlug(7, 'overview')], 'create' => ['create', [7, 'Overview', 'overview', 'star', 'At a glance', 'alice'], static fn (ContextPageController $controller) => $controller->create(7, 'Overview', 'overview', 'star', 'At a glance')], 'update' => ['update', [7, 2, null, 'planning', '', null, $widgets, 'alice'], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'planning', '', null, $widgets)], 'destroy' => ['delete', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->destroy(7, 2)], diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index 2e1cdd6fac..1aae764def 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -91,6 +91,12 @@ public function testFindReturnsThePageWithItsWidgets(): void { ], $this->service->find(7, self::GRID_PAGE, 'alice')); } + public function testFindBySlugReturnsTheSamePageAsItsId(): void { + $this->widgetService->method('findByPageIds')->willReturn([]); + + $this->assertSame($this->service->find(7, self::GRID_PAGE, 'alice'), $this->service->findBySlug(7, 'overview', 'alice')); + } + public function testAnApplicationOrPageOutsideTheUsersReachIsNotFound(): void { $this->permissionsService->method('canManageContext')->willReturn(true); $this->pageMapper->expects($this->never())->method('insert'); @@ -103,7 +109,9 @@ public function testAnApplicationOrPageOutsideTheUsersReachIsNotFound(): void { 'create in it' => fn () => $this->service->create(8, 'Overview', null, null, null, 'mallory'), 'update in it' => fn () => $this->service->update(8, self::GRID_PAGE, 'Mine', null, null, null, [], 'mallory'), 'delete in it' => fn () => $this->service->delete(8, self::GRID_PAGE, 'mallory'), + 'application of no access by name' => fn () => $this->service->findBySlug(8, 'overview', 'mallory'), 'page of another application' => fn () => $this->service->find(7, 99, 'alice'), + 'unknown name' => fn () => $this->service->findBySlug(7, 'missing', 'alice'), 'update it' => fn () => $this->service->update(7, 99, 'Taken over', null, null, null, [], 'alice'), 'delete it' => fn () => $this->service->delete(7, 99, 'alice'), ] as $case => $call) { From 498990958385dd30e8a0df1d31609a2c073c1261 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 6 Nov 2026 16:50:02 +0100 Subject: [PATCH 04/16] chore(api): regenerate the OpenAPI spec and TypeScript types Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- openapi.json | 185 +++++++++++++++++++++++++++++++++++ src/types/openapi/openapi.ts | 95 ++++++++++++++++++ 2 files changed, 280 insertions(+) diff --git a/openapi.json b/openapi.json index 6f0ae8f7a2..88e564a90a 100644 --- a/openapi.json +++ b/openapi.json @@ -16174,6 +16174,191 @@ } } }, + "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{technicalName}": { + "get": { + "operationId": "context_page-show-by-technical-name", + "summary": "[api v2] Get a page of an application by its technical name", + "tags": [ + "context_page" + ], + "security": [ + { + "bearer_auth": [] + }, + { + "basic_auth": [] + } + ], + "parameters": [ + { + "name": "contextId", + "in": "path", + "description": "ID of the application", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "technicalName", + "in": "path", + "description": "Technical name of the page", + "required": true, + "schema": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + } + }, + { + "name": "OCS-APIRequest", + "in": "header", + "description": "Required to be true for the API request to pass", + "required": true, + "schema": { + "type": "boolean", + "default": true + } + } + ], + "responses": { + "200": { + "description": "Page returned", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/Page" + } + } + } + } + } + } + } + }, + "500": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "404": { + "description": "Not found, also when the user has no access to the application", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages": { "post": { "operationId": "context_page-create", diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index a88cdc258c..af6a6ebc86 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1031,6 +1031,23 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + readonly "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{technicalName}": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** [api v2] Get a page of an application by its technical name */ + readonly get: operations["context_page-show-by-technical-name"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages": { readonly parameters: { readonly query?: never; @@ -8776,6 +8793,84 @@ export interface operations { }; }; }; + readonly "context_page-show-by-technical-name": { + readonly parameters: { + readonly query?: never; + readonly header: { + /** @description Required to be true for the API request to pass */ + readonly "OCS-APIRequest": boolean; + }; + readonly path: { + /** @description ID of the application */ + readonly contextId: number; + /** @description Technical name of the page */ + readonly technicalName: string; + }; + readonly cookie?: never; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Page returned */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: components["schemas"]["Page"]; + }; + }; + }; + }; + /** @description Current user is not logged in */ + readonly 401: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: unknown; + }; + }; + }; + }; + /** @description Not found, also when the user has no access to the application */ + readonly 404: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + readonly 500: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; + }; + }; readonly "context_page-create": { readonly parameters: { readonly query?: never; From d739b8defd67b608ff9307436b4ff7cffeea71f0 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Mon, 9 Nov 2026 14:40:26 +0100 Subject: [PATCH 05/16] fix(api): follow the review of the pages API - every page has a version that each save raises as its first write; a save of the widgets names the version it was edited from and gets a 409 when another save raised it since, so two editors no longer undo each other without a word - raising the version locks the page, so a save and a delete of the same page run one after the other, and adding a page locks its application against a delete - create, update and delete answer from what they wrote instead of loading the application again; reads look up the page itself - the controller's permission checks are the only ones, as for the other endpoints - the start page accepts widgets from the start and can lose its title again; the delete rule names the start page - titles and descriptions follow TextHelper, so a title of invisible spaces is refused - widget settings are stored as text, not as a JSON column, and come back as an array, or as {} when empty, so XML keeps them and JSON shows an object - the widget types answer {} for a type without settings - the widgets parameter has a named shape in the OpenAPI spec - deleting a page is rate limited like the other changes - the database error stub moves here from the data model Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Controller/AOCSController.php | 9 + lib/Controller/ContextPageController.php | 42 +- lib/Db/Page.php | 3 +- lib/Db/PageMapper.php | 53 ++ lib/Db/Widget.php | 10 +- lib/Errors/ConflictError.php | 14 + lib/ResponseDefinitions.php | 17 +- lib/Service/ContextService.php | 3 +- lib/Service/GridWidgetTypes.php | 1 + lib/Service/PageService.php | 258 +++++----- lib/Service/WidgetService.php | 8 +- openapi.json | 144 +++++- src/types/openapi/openapi.ts | 57 ++- .../Controller/ContextPageControllerTest.php | 18 +- tests/unit/Database/DbErrorStub.php | 31 ++ tests/unit/Db/PageTest.php | 1 + tests/unit/Db/WidgetMapperTest.php | 4 +- tests/unit/Db/WidgetTest.php | 2 +- tests/unit/Service/PageServiceTest.php | 468 ++++++++---------- tests/unit/Service/WidgetServiceTest.php | 2 +- tests/unit/bootstrap.php | 1 + 21 files changed, 677 insertions(+), 469 deletions(-) create mode 100644 lib/Errors/ConflictError.php create mode 100644 tests/unit/Database/DbErrorStub.php diff --git a/lib/Controller/AOCSController.php b/lib/Controller/AOCSController.php index 5dce758437..827b728b0a 100644 --- a/lib/Controller/AOCSController.php +++ b/lib/Controller/AOCSController.php @@ -10,6 +10,7 @@ use Exception; use OCA\Tables\AppInfo\Application; use OCA\Tables\Errors\BadRequestError; +use OCA\Tables\Errors\ConflictError; use OCA\Tables\Errors\InternalError; use OCA\Tables\Errors\NotFoundError; use OCA\Tables\Errors\PermissionError; @@ -58,6 +59,14 @@ protected function handleNotFoundError(NotFoundError $e): DataResponse { return new DataResponse(['message' => $this->n->t('A not found error occurred. More details can be found in the logs. Please reach out to your administration.')], Http::STATUS_NOT_FOUND); } + /** + * @return DataResponse + */ + protected function handleConflictError(ConflictError $e): DataResponse { + $this->logger->info('A conflict was encountered: ' . $e->getMessage(), ['exception' => $e]); + return new DataResponse(['message' => $e->getMessage()], Http::STATUS_CONFLICT); + } + /** * @param BadRequestError $e * @return DataResponse diff --git a/lib/Controller/ContextPageController.php b/lib/Controller/ContextPageController.php index 5f16cf6c58..6eb7e9858d 100644 --- a/lib/Controller/ContextPageController.php +++ b/lib/Controller/ContextPageController.php @@ -11,14 +11,12 @@ use OCA\Tables\AppInfo\Application; use OCA\Tables\Errors\BadRequestError; +use OCA\Tables\Errors\ConflictError; use OCA\Tables\Errors\NotFoundError; -use OCA\Tables\Errors\PermissionError; use OCA\Tables\Middleware\Attribute\RequirePermission; use OCA\Tables\ResponseDefinitions; use OCA\Tables\Service\GridWidgetTypes; use OCA\Tables\Service\PageService; -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\AppFramework\Http; use OCP\AppFramework\Http\Attribute\ApiRoute; use OCP\AppFramework\Http\Attribute\NoAdminRequired; @@ -32,6 +30,7 @@ /** * @psalm-import-type TablesPage from ResponseDefinitions * @psalm-import-type TablesWidgetType from ResponseDefinitions + * @psalm-import-type TablesWidgetInput from ResponseDefinitions */ class ContextPageController extends AOCSController { public function __construct( @@ -60,7 +59,7 @@ public function __construct( #[ApiRoute(verb: 'GET', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] public function show(int $contextId, int $pageId): DataResponse { try { - return new DataResponse($this->pageService->find($contextId, $pageId, $this->userId)); + return new DataResponse($this->pageService->find($contextId, $pageId)); } catch (NotFoundError $e) { return $this->handleNotFoundError($e); } catch (Exception $e) { @@ -83,7 +82,7 @@ public function show(int $contextId, int $pageId): DataResponse { #[ApiRoute(verb: 'GET', url: '/api/2/contexts/{contextId}/pages/{slug}', requirements: ['contextId' => '\d+', 'slug' => '[a-z][a-z0-9_]*'])] public function showBySlug(int $contextId, string $slug): DataResponse { try { - return new DataResponse($this->pageService->findBySlug($contextId, $slug, $this->userId)); + return new DataResponse($this->pageService->findBySlug($contextId, $slug)); } catch (NotFoundError $e) { return $this->handleNotFoundError($e); } catch (Exception $e) { @@ -112,11 +111,9 @@ public function showBySlug(int $contextId, string $slug): DataResponse { #[ApiRoute(verb: 'POST', url: '/api/2/contexts/{contextId}/pages', requirements: ['contextId' => '\d+'])] public function create(int $contextId, string $title, ?string $slug = null, ?string $icon = null, ?string $description = null): DataResponse { try { - return new DataResponse($this->pageService->create($contextId, $title, $slug, $icon, $description, $this->userId)); + return new DataResponse($this->pageService->create($contextId, $title, $slug, $icon, $description)); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); - } catch (PermissionError $e) { - return $this->handlePermissionError($e); } catch (NotFoundError $e) { return $this->handleNotFoundError($e); } catch (Exception $e) { @@ -142,29 +139,29 @@ public function create(int $contextId, string $title, ?string $slug = null, ?str * @param string|null $slug New slug * @param string|null $icon New icon name, empty to remove it * @param string|null $description New description, empty to remove it - * @param list>|null $widgets All widgets of the page - * @return DataResponse|DataResponse + * @param list|null $widgets All widgets of the page + * @param int|null $version The version of the page the widgets were edited from, needed with widgets + * @return DataResponse|DataResponse * * 200: Page updated - * 400: Invalid page field or widget, too many widgets, or the page changed in between + * 400: Invalid page field or widget, or too many widgets * 403: No permissions * 404: Not found + * 409: The page was saved by someone else since the given version */ #[NoAdminRequired] #[UserRateLimit(limit: 60, period: 60)] #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] #[ApiRoute(verb: 'PATCH', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] - public function update(int $contextId, int $pageId, ?string $title = null, ?string $slug = null, ?string $icon = null, ?string $description = null, ?array $widgets = null): DataResponse { + public function update(int $contextId, int $pageId, ?string $title = null, ?string $slug = null, ?string $icon = null, ?string $description = null, ?array $widgets = null, ?int $version = null): DataResponse { try { - return new DataResponse($this->pageService->update($contextId, $pageId, $title, $slug, $icon, $description, $widgets, $this->userId)); + return new DataResponse($this->pageService->update($contextId, $pageId, $title, $slug, $icon, $description, $widgets, $version)); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); - } catch (PermissionError $e) { - return $this->handlePermissionError($e); + } catch (ConflictError $e) { + return $this->handleConflictError($e); } catch (NotFoundError $e) { return $this->handleNotFoundError($e); - } catch (DoesNotExistException|MultipleObjectsReturnedException $e) { - return $this->handleNotFoundError(new NotFoundError($e->getMessage(), $e->getCode(), $e)); } catch (Exception $e) { return $this->handleError($e); } @@ -185,15 +182,14 @@ public function update(int $contextId, int $pageId, ?string $title = null, ?stri * 404: Not found */ #[NoAdminRequired] + #[UserRateLimit(limit: 20, period: 60)] #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] #[ApiRoute(verb: 'DELETE', url: '/api/2/contexts/{contextId}/pages/{pageId}', requirements: ['contextId' => '\d+', 'pageId' => '\d+'])] public function destroy(int $contextId, int $pageId): DataResponse { try { - return new DataResponse($this->pageService->delete($contextId, $pageId, $this->userId)); + return new DataResponse($this->pageService->delete($contextId, $pageId)); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); - } catch (PermissionError $e) { - return $this->handlePermissionError($e); } catch (NotFoundError $e) { return $this->handleNotFoundError($e); } catch (Exception $e) { @@ -213,6 +209,10 @@ public function destroy(int $contextId, int $pageId): DataResponse { #[NoAdminRequired] #[ApiRoute(verb: 'GET', url: '/api/2/widget-types')] public function widgetTypes(): DataResponse { - return new DataResponse(array_values($this->gridWidgetTypes->all())); + // a type without settings shows them as {}, the object the schema promises + return new DataResponse(array_values(array_map( + static fn (array $type): array => $type['settings'] === [] ? ['settings' => new \stdClass()] + $type : $type, + $this->gridWidgetTypes->all(), + ))); } } diff --git a/lib/Db/Page.php b/lib/Db/Page.php index b3e7b9136d..feb2f329be 100644 --- a/lib/Db/Page.php +++ b/lib/Db/Page.php @@ -32,8 +32,6 @@ class Page extends Entity implements \JsonSerializable { public const TYPE_GRID = 'grid'; public const START_PAGE_SLUG = 'dashboard'; public const DEFAULT_SLUG_PREFIX = 'page_'; - public const TITLE_MAX_LENGTH = 200; - public const DESCRIPTION_MAX_LENGTH = 2000; protected ?int $contextId = null; protected ?string $pageType = null; @@ -64,6 +62,7 @@ public function jsonSerialize(): array { 'title' => $this->getTitle(), 'icon' => $this->getIcon(), 'description' => $this->getDescription(), + 'version' => (int)$this->getVersion(), ]; } } diff --git a/lib/Db/PageMapper.php b/lib/Db/PageMapper.php index e90e02e4fd..6533edfd22 100644 --- a/lib/Db/PageMapper.php +++ b/lib/Db/PageMapper.php @@ -53,6 +53,59 @@ public function findById(int $pageId): Page { return $this->findEntity($qb); } + /** + * @throws DoesNotExistException + * @throws MultipleObjectsReturnedException + * @throws Exception + */ + public function findBySlug(int $contextId, string $slug): Page { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->table) + ->where($qb->expr()->eq('context_id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT))) + ->andWhere($qb->expr()->eq('slug', $qb->createNamedParameter($slug))); + + return $this->findEntity($qb); + } + + /** + * Raises the version of a page, the first write of a save. It locks the page row until + * the transaction ends, so saves and the delete of one page run one after the other. + * + * @param ?int $expected the version the save was based on, or null to take any + * @return bool false when the page is gone or has another version + * @throws Exception + */ + public function raiseVersion(int $pageId, ?int $expected): bool { + $qb = $this->db->getQueryBuilder(); + $qb->update($this->table) + ->set('version', $qb->func()->add('version', $qb->createNamedParameter(1, IQueryBuilder::PARAM_INT))) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($pageId, IQueryBuilder::PARAM_INT))); + if ($expected !== null) { + $qb->andWhere($qb->expr()->eq('version', $qb->createNamedParameter($expected, IQueryBuilder::PARAM_INT))); + } + return $qb->executeStatement() === 1; + } + + /** + * Locks an application until the transaction ends, so a page is never added to one + * that is being deleted. + * + * @return bool false when the application is gone + * @throws Exception + */ + public function lockContext(int $contextId): bool { + $qb = $this->db->getQueryBuilder(); + $qb->select('id') + ->from('tables_contexts_context') + ->where($qb->expr()->eq('id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT))) + ->forUpdate(); + $result = $qb->executeQuery(); + $found = $result->fetchOne() !== false; + $result->closeCursor(); + return $found; + } + /** * @return int[] */ diff --git a/lib/Db/Widget.php b/lib/Db/Widget.php index 0c855ed2c9..670a6faba9 100644 --- a/lib/Db/Widget.php +++ b/lib/Db/Widget.php @@ -91,12 +91,14 @@ public function setSettingsArray(array $settings): void { } /** - * The settings as an object, so they serialise as a JSON object also when empty, - * ordered by name: a JSON column does not keep the stored order on every database. + * The settings for a response, ordered by name: an array, which OCS also renders as + * XML, or an empty object when there are none, so JSON shows `{}` and not `[]`. + * + * @return array|\stdClass */ - public function getSettingsObject(): \stdClass { + public function getSettingsForResponse(): array|\stdClass { $settings = $this->getSettingsArray(); ksort($settings); - return (object)$settings; + return $settings === [] ? new \stdClass() : $settings; } } diff --git a/lib/Errors/ConflictError.php b/lib/Errors/ConflictError.php new file mode 100644 index 0000000000..12e5c7f02e --- /dev/null +++ b/lib/Errors/ConflictError.php @@ -0,0 +1,14 @@ +, + * settings: array|\stdClass, + * } + * + * @psalm-type TablesWidgetInput = array{ + * id?: int, + * type: string, + * title?: string, + * icon?: string, + * description?: string, + * gridX: int, + * gridY: int, + * gridWidth: int, + * gridHeight: int, + * settings?: array, + * source?: array{nodeRelId: int}, * } * * @psalm-type TablesWidget = array{ @@ -285,6 +299,7 @@ * title: ?string, * icon: ?string, * description: ?string, + * version: int, * widgets: list, * } * diff --git a/lib/Service/ContextService.php b/lib/Service/ContextService.php index 464c00ccfc..368a6cbbd2 100644 --- a/lib/Service/ContextService.php +++ b/lib/Service/ContextService.php @@ -356,7 +356,8 @@ public function delete(int $contextId, string $userId): Context { $context = $this->contextMapper->findById($contextId, $userId); $this->atomic(function () use ($context): void { - // a delete that waited for another one finds the application gone + // a page added in the meantime waits for this and then finds no application, + // and a delete that waited for another one finds it gone if (!$this->contextMapper->lock($context->getId())) { throw new NotFoundError('Application ' . $context->getId() . ' does not exist'); } diff --git a/lib/Service/GridWidgetTypes.php b/lib/Service/GridWidgetTypes.php index cef8d01360..7006d12001 100644 --- a/lib/Service/GridWidgetTypes.php +++ b/lib/Service/GridWidgetTypes.php @@ -9,6 +9,7 @@ namespace OCA\Tables\Service; +use OCA\Tables\Db\Widget; use OCA\Tables\Errors\BadRequestError; use OCA\Tables\Helper\IconHelper; use OCA\Tables\Helper\TextHelper; diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index 475b205640..d48b2a0ea0 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -9,15 +9,15 @@ namespace OCA\Tables\Service; -use OCA\Tables\Db\Context; use OCA\Tables\Db\ContextMapper; use OCA\Tables\Db\Page; use OCA\Tables\Db\PageContentMapper; use OCA\Tables\Db\PageMapper; use OCA\Tables\Errors\BadRequestError; +use OCA\Tables\Errors\ConflictError; use OCA\Tables\Errors\NotFoundError; -use OCA\Tables\Errors\PermissionError; use OCA\Tables\Helper\IconHelper; +use OCA\Tables\Helper\TextHelper; use OCA\Tables\Model\WidgetInput; use OCA\Tables\ResponseDefinitions; use OCA\Tables\Validation\TechnicalNameValidator; @@ -28,11 +28,14 @@ use OCP\IDBConnection; /** - * The pages of an application and the widgets on them. + * The pages of an application and the widgets on them. The controller checks access to + * the application before any call; this class checks that a page belongs to it. * - * Reads need access to the application, writes need manage permissions on it. + * Every save raises the version of its page as its first write, which also locks the + * page, so saves and the delete of a page run one after the other. * * @psalm-import-type TablesPage from ResponseDefinitions + * @psalm-import-type TablesWidget from ResponseDefinitions */ class PageService { use TTransactional; @@ -44,7 +47,6 @@ public function __construct( private readonly PageMapper $pageMapper, private readonly PageContentMapper $pageContentMapper, private readonly WidgetService $widgetService, - private readonly PermissionsService $permissionsService, private readonly GridWidgetTypes $gridWidgetTypes, private readonly IDBConnection $dbc, ) { @@ -55,8 +57,9 @@ public function __construct( * @throws NotFoundError * @throws Exception */ - public function find(int $contextId, int $pageId, string $userId): array { - return $this->readPage($this->contextMapper->findById($contextId, $userId), $pageId); + public function find(int $contextId, int $pageId): array { + $page = $this->getPage($contextId, $pageId); + return $this->response($page, $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); } /** @@ -64,35 +67,13 @@ public function find(int $contextId, int $pageId, string $userId): array { * @throws NotFoundError * @throws Exception */ - public function findBySlug(int $contextId, string $slug, string $userId): array { - $context = $this->contextMapper->findById($contextId, $userId); - foreach ($context->getPages() ?? [] as $pageId => $page) { - if ($page['slug'] === $slug) { - return $this->readPage($context, (int)$pageId); - } + public function findBySlug(int $contextId, string $slug): array { + try { + $page = $this->pageMapper->findBySlug($contextId, $slug); + } catch (DoesNotExistException|MultipleObjectsReturnedException $e) { + throw new NotFoundError('Application ' . $contextId . ' has no page ' . $slug, 0, $e); } - throw new NotFoundError('Application ' . $contextId . ' has no page ' . $slug); - } - - /** - * @return TablesPage - * @throws NotFoundError - * @throws Exception - */ - private function readPage(Context $context, int $pageId): array { - $page = $this->getPageArray($context, $pageId); - $widgets = $this->widgetService->findByPageIds([$pageId]); - - return [ - 'id' => $pageId, - 'contextId' => $context->getId(), - 'pageType' => (string)$page['page_type'], - 'slug' => (string)$page['slug'], - 'title' => $page['title'] ?? null, - 'icon' => $page['icon'] ?? null, - 'description' => $page['description'] ?? null, - 'widgets' => $widgets[$pageId] ?? [], - ]; + return $this->response($page, $this->widgetService->findByPageIds([$page->getId()])[$page->getId()] ?? []); } /** @@ -102,54 +83,53 @@ private function readPage(Context $context, int $pageId): array { * @return TablesPage * @throws BadRequestError * @throws NotFoundError - * @throws PermissionError * @throws Exception */ - public function create(int $contextId, string $title, ?string $slug, ?string $icon, ?string $description, string $userId): array { - $context = $this->getManageableContext($contextId, $userId); - + public function create(int $contextId, string $title, ?string $slug, ?string $icon, ?string $description): array { $page = new Page(); $page->setContextId($contextId); $page->setPageType(Page::TYPE_GRID); - $page->setTitle($this->validateTitle($title)); + $page->setTitle($this->validateTitle($title, Page::TYPE_GRID)); $page->setIcon($this->validateIcon($icon)); $page->setDescription($this->validateDescription($description)); - if ($slug !== null) { - $page->setSlug($this->validateSlug($slug, $context, null)); - $this->saveNamed(fn () => $this->pageMapper->insert($page), $slug); - } else { - $page = $this->pageMapper->insertWithDefaultName($page); + $page->setSlug($this->validateSlug($slug, null)); } - return $this->find($contextId, $page->getId(), $userId); + $page = $this->save(fn (): Page => $this->atomic(function () use ($contextId, $page): Page { + if (!$this->pageMapper->lockContext($contextId)) { + throw new NotFoundError('Application ' . $contextId . ' does not exist'); + } + return $page->getSlug() === null ? $this->pageMapper->insertWithDefaultName($page) : $this->pageMapper->insert($page); + }, $this->dbc), $slug); + + return $this->response($page, []); } /** * Changes the fields of a page and, when widgets are given, makes its widgets match * them in one transaction. A null argument keeps the current value; an empty icon - * or description removes it. A widget's `source` is `{nodeRelId}` of a table or view - * of this application, or null. + * or description removes it, and so does an empty title of the start page. A + * widget's `source` is `{nodeRelId}` of a table or view of this application, or null. + * + * A save with widgets names the version of the page it was based on, and is refused + * when another save raised it since. * * @param list|null $widgets * @return TablesPage - * @throws DoesNotExistException - * @throws MultipleObjectsReturnedException * @throws BadRequestError + * @throws ConflictError * @throws NotFoundError - * @throws PermissionError * @throws Exception */ - public function update(int $contextId, int $pageId, ?string $title, ?string $slug, ?string $icon, ?string $description, ?array $widgets, string $userId): array { - $context = $this->getManageableContext($contextId, $userId); - $pageArray = $this->getPageArray($context, $pageId); - - $page = $this->pageMapper->findById($pageId); + public function update(int $contextId, int $pageId, ?string $title, ?string $slug, ?string $icon, ?string $description, ?array $widgets, ?int $version): array { + $page = $this->getPage($contextId, $pageId); + $page->resetUpdatedFields(); if ($title !== null) { - $page->setTitle($this->validateTitle($title)); + $page->setTitle($this->validateTitle($title, $page->getPageType())); } if ($slug !== null && $slug !== $page->getSlug()) { - $page->setSlug($this->validateSlug($slug, $context, $pageId)); + $page->setSlug($this->validateSlug($slug, $pageId)); } if ($icon !== null) { $page->setIcon($this->validateIcon($icon)); @@ -158,96 +138,101 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu $page->setDescription($this->validateDescription($description)); } - $rows = null; + $inputs = null; if ($widgets !== null) { - if ($pageArray['page_type'] !== Page::TYPE_GRID) { - throw new BadRequestError('Only grid pages hold widgets.'); + if ($version === null) { + throw new BadRequestError('A save of the widgets of a page names the version of the page it is based on.'); } - $rows = $this->readWidgets($widgets, $context, $pageId); + $inputs = $this->readWidgets($widgets, $contextId); } $renamed = array_key_exists('slug', $page->getUpdatedFields()); - $this->saveChanges(fn () => $this->atomic(function () use ($page, $rows, $pageId): void { - if ($page->getUpdatedFields() !== []) { - $this->pageMapper->update($page); - } - if ($rows !== null) { - $this->widgetService->syncPage($pageId, $rows); + $stored = $this->save(fn (): ?array => $this->atomic(function () use ($page, $pageId, $version, $inputs): ?array { + if (!$this->pageMapper->raiseVersion($pageId, $version)) { + $this->getPage($page->getContextId(), $pageId); + throw new ConflictError(self::CHANGED_IN_BETWEEN); } + $this->pageMapper->update($page); + return $inputs === null ? null : $this->widgetService->syncPage($pageId, $inputs); }, $this->dbc), $renamed ? (string)$page->getSlug() : null); - return $this->find($contextId, $pageId, $userId); + $page->setVersion($page->getVersion() + 1); + return $this->response($page, $stored ?? $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); } /** - * Deletes a grid page with its widgets. The start page cannot be deleted. + * Deletes a page with its widgets. The start page cannot be deleted. * * @return TablesPage the deleted page * @throws BadRequestError * @throws NotFoundError - * @throws PermissionError * @throws Exception */ - public function delete(int $contextId, int $pageId, string $userId): array { - $context = $this->getManageableContext($contextId, $userId); - $pageArray = $this->getPageArray($context, $pageId); - if ($pageArray['page_type'] !== Page::TYPE_GRID) { + public function delete(int $contextId, int $pageId): array { + $page = $this->getPage($contextId, $pageId); + if ($page->getPageType() === Page::TYPE_STARTPAGE) { throw new BadRequestError('The start page of an application cannot be deleted.'); } - $page = $this->find($contextId, $pageId, $userId); - $this->atomic(function () use ($pageId): void { + $widgets = $this->atomic(function () use ($contextId, $pageId): array { + if (!$this->pageMapper->raiseVersion($pageId, null)) { + throw new NotFoundError('Page ' . $pageId . ' does not belong to application ' . $contextId); + } + $widgets = $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []; $this->widgetService->deleteByPageIds([$pageId]); $this->pageContentMapper->deleteByPageId($pageId); $this->pageMapper->deleteByPageId($pageId); + return $widgets; }, $this->dbc); - return $page; + return $this->response($page, $widgets); } /** * @throws NotFoundError - * @throws PermissionError * @throws Exception */ - private function getManageableContext(int $contextId, string $userId): Context { - $context = $this->contextMapper->findById($contextId, $userId); - if (!$this->permissionsService->canManageContext($context, $userId)) { - throw new PermissionError(sprintf('User %s cannot manage application %d', $userId, $contextId)); + private function getPage(int $contextId, int $pageId): Page { + try { + $page = $this->pageMapper->findById($pageId); + } catch (DoesNotExistException|MultipleObjectsReturnedException $e) { + throw new NotFoundError('Page ' . $pageId . ' does not exist', 0, $e); + } + if ($page->getContextId() !== $contextId) { + throw new NotFoundError('Page ' . $pageId . ' does not belong to application ' . $contextId); + } + if ($page->getPageType() !== Page::TYPE_GRID && $page->getPageType() !== Page::TYPE_STARTPAGE) { + throw new NotFoundError('Page ' . $pageId . ' is neither a grid page nor a start page'); } - return $context; + return $page; } /** - * @return array - * @throws NotFoundError + * @param list $widgets + * @return TablesPage */ - private function getPageArray(Context $context, int $pageId): array { - $pages = $context->getPages() ?? []; - if (!isset($pages[$pageId])) { - throw new NotFoundError('Page ' . $pageId . ' does not belong to application ' . $context->getId()); - } - return $pages[$pageId]; + private function response(Page $page, array $widgets): array { + return $page->jsonSerialize() + ['widgets' => $widgets]; } /** * @param list $widgets * @return list * @throws BadRequestError + * @throws NotFoundError * @throws Exception */ - private function readWidgets(array $widgets, Context $context, int $pageId): array { + private function readWidgets(array $widgets, int $contextId): array { if (count($widgets) > GridWidgetTypes::MAX_WIDGETS_PER_PAGE) { throw new BadRequestError('A page holds at most ' . GridWidgetTypes::MAX_WIDGETS_PER_PAGE . ' widgets.'); } - $existingIds = array_flip($this->widgetService->findIdsByPageId($pageId)); - $nodes = $context->getNodes() ?? []; - $rows = []; + $nodes = $this->contextMapper->findById($contextId, null, false)->getNodes() ?? []; + $inputs = []; $seenIds = []; foreach (array_values($widgets) as $index => $widget) { $input = $this->gridWidgetTypes->readWidget($index, $widget); - if ($input->id !== null && (!isset($existingIds[$input->id]) || isset($seenIds[$input->id]))) { - throw new BadRequestError('Widget ' . $index . ' has the id of no other widget on this page.'); + if ($input->id !== null && isset($seenIds[$input->id])) { + throw new BadRequestError('Widget ' . $index . ' has the id of another widget in the list.'); } if ($input->id !== null) { $seenIds[$input->id] = true; @@ -255,79 +240,64 @@ private function readWidgets(array $widgets, Context $context, int $pageId): arr if ($input->nodeRelId !== null && !isset($nodes[$input->nodeRelId])) { throw new BadRequestError('The source of widget ' . $index . ' must be {nodeRelId} of a table or view of this application.'); } - $rows[] = $input; - } - return $rows; - } - - /** - * @throws BadRequestError - */ - private function validateTitle(string $title): string { - $title = trim($title); - if ($title === '' || mb_strlen($title) > Page::TITLE_MAX_LENGTH) { - throw new BadRequestError('A page title needs 1 to ' . Page::TITLE_MAX_LENGTH . ' characters.'); + $inputs[] = $input; } - return $title; + return $inputs; } /** - * Runs a save of the fields and widgets of a page. A unique index refusing the save - * means the new slug was taken; a widget no longer on the page, or another - * refusal of the index, means a concurrent save changed the page in between. + * Runs a save. A unique index refusing a new slug means the name was + * taken; a widget the save lists that is not on the page means the list was built + * from another state of the page. * + * @template T + * @param callable(): T $save + * @return T * @throws BadRequestError + * @throws ConflictError * @throws Exception */ - private function saveChanges(callable $save, ?string $newSlug): void { + private function save(callable $save, ?string $newSlug): mixed { try { - $save(); + return $save(); } catch (\InvalidArgumentException $e) { - throw new BadRequestError(self::CHANGED_IN_BETWEEN, 0, $e); + throw new ConflictError(self::CHANGED_IN_BETWEEN, 0, $e); } catch (Exception $e) { - if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + if ($newSlug === null || $e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { throw $e; } - if ($newSlug !== null) { - throw new BadRequestError('The slug ' . $newSlug . ' is already used by a page of this application.', 0, $e); - } - throw new BadRequestError(self::CHANGED_IN_BETWEEN, 0, $e); + throw new BadRequestError('The slug ' . $newSlug . ' is already used by a page of this application.', 0, $e); } } /** - * Runs a save of a page under a slug that was given, reporting a save the - * unique index refused as a taken name. + * A grid page needs a title, as its tab shows nothing else; the start page may have + * none, and an empty title gives it back its default name. * * @throws BadRequestError - * @throws Exception */ - private function saveNamed(callable $save, string $slug): void { + private function validateTitle(string $title, string $pageType): ?string { try { - $save(); - } catch (Exception $e) { - if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { - throw $e; - } - throw new BadRequestError('The slug ' . $slug . ' is already used by a page of this application.'); + $title = TextHelper::optional($title, TextHelper::TITLE_MAX_LENGTH); + } catch (\InvalidArgumentException) { + $title = ''; } + if ($title === '' || ($title === null && $pageType !== Page::TYPE_STARTPAGE)) { + throw new BadRequestError('A page title needs 1 to ' . TextHelper::TITLE_MAX_LENGTH . ' characters.'); + } + return $title; } /** * @throws BadRequestError */ - private function validateSlug(string $slug, Context $context, ?int $pageId): string { + private function validateSlug(string $slug, ?int $pageId): string { if (!TechnicalNameValidator::isValid($slug)) { throw new BadRequestError('A slug has 1 to ' . TechnicalNameValidator::MAX_LENGTH . ' lower case letters, digits and underscores and starts with a letter.'); } if (Page::isDefaultSlug($slug) && $slug !== Page::DEFAULT_SLUG_PREFIX . $pageId) { throw new BadRequestError('The slug ' . $slug . ' is reserved for automatic names.'); } - foreach ($context->getPages() ?? [] as $id => $page) { - if ((int)$id !== $pageId && ($page['slug'] ?? null) === $slug) { - throw new BadRequestError('The slug ' . $slug . ' is already used by a page of this application.'); - } - } return $slug; } @@ -336,13 +306,13 @@ private function validateSlug(string $slug, Context $context, ?int $pageId): str * * @throws BadRequestError */ - private function validateIcon(?string $icon, string $of = 'A page'): ?string { + private function validateIcon(?string $icon): ?string { $icon = trim((string)$icon); if ($icon === '') { return null; } if (!IconHelper::isValid($icon)) { - throw new BadRequestError($of . ' has an unknown icon: ' . $icon); + throw new BadRequestError('A page has an unknown icon: ' . $icon); } return $icon; } @@ -351,10 +321,10 @@ private function validateIcon(?string $icon, string $of = 'A page'): ?string { * @throws BadRequestError */ private function validateDescription(?string $description): ?string { - $description = trim((string)$description); - if (mb_strlen($description) > Page::DESCRIPTION_MAX_LENGTH) { - throw new BadRequestError('A page description has at most ' . Page::DESCRIPTION_MAX_LENGTH . ' characters.'); + try { + return TextHelper::optional($description, TextHelper::DESCRIPTION_MAX_LENGTH); + } catch (\InvalidArgumentException) { + throw new BadRequestError('A page description has at most ' . TextHelper::DESCRIPTION_MAX_LENGTH . ' characters.'); } - return $description === '' ? null : $description; } } diff --git a/lib/Service/WidgetService.php b/lib/Service/WidgetService.php index 1033baa1a4..105c4b1fef 100644 --- a/lib/Service/WidgetService.php +++ b/lib/Service/WidgetService.php @@ -55,7 +55,7 @@ public function findByPageIds(array $pageIds): array { 'gridY' => $widget->getGridY(), 'gridWidth' => $widget->getGridWidth(), 'gridHeight' => $widget->getGridHeight(), - 'settings' => $widget->getSettingsObject(), + 'settings' => $widget->getSettingsForResponse(), 'source' => $widget->getNodeRelId() !== null ? ['nodeRelId' => $widget->getNodeRelId()] : null, ]; } @@ -104,13 +104,14 @@ public function findIdsByPageId(int $pageId): array { * are locked first, so the checks still hold when the writes run. * * @param list $widgets + * @return list the widgets of the page as stored, in grid order * @throws \InvalidArgumentException when an id is not one of a widget of the page, or a * source is not a node of the application of the page * @throws Exception * @throws \JsonException */ - public function syncPage(int $pageId, array $widgets): void { - $this->atomic(function () use ($pageId, $widgets): void { + public function syncPage(int $pageId, array $widgets): array { + return $this->atomic(function () use ($pageId, $widgets): array { $existing = []; foreach ($this->widgetMapper->findByPageIds([$pageId], true) as $widget) { $existing[$widget->getId()] = $widget; @@ -138,6 +139,7 @@ public function syncPage(int $pageId, array $widgets): void { $this->applyFields($widget, $input); $this->widgetMapper->update($widget); } + return $this->findByPageIds([$pageId])[$pageId] ?? []; }, $this->db); } diff --git a/openapi.json b/openapi.json index 88e564a90a..c86f30404b 100644 --- a/openapi.json +++ b/openapi.json @@ -473,6 +473,7 @@ "title", "icon", "description", + "version", "widgets" ], "properties": { @@ -502,6 +503,10 @@ "type": "string", "nullable": true }, + "version": { + "type": "integer", + "format": "int64" + }, "widgets": { "type": "array", "items": { @@ -1432,6 +1437,74 @@ } } }, + "WidgetInput": { + "type": "object", + "required": [ + "type", + "gridX", + "gridY", + "gridWidth", + "gridHeight" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64", + "nullable": true + }, + "type": { + "type": "string" + }, + "title": { + "type": "string", + "nullable": true + }, + "icon": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "gridX": { + "type": "integer", + "format": "int64" + }, + "gridY": { + "type": "integer", + "format": "int64" + }, + "gridWidth": { + "type": "integer", + "format": "int64" + }, + "gridHeight": { + "type": "integer", + "format": "int64" + }, + "settings": { + "type": "object", + "nullable": true, + "additionalProperties": { + "$ref": "#/components/schemas/WidgetValue" + } + }, + "source": { + "type": "object", + "nullable": true, + "required": [ + "nodeRelId" + ], + "properties": { + "nodeRelId": { + "type": "integer", + "format": "int64" + } + } + } + } + }, "WidgetSettingSchema": { "type": "object", "required": [ @@ -1446,7 +1519,6 @@ "string", "text", "color", - "boolean", "enum" ] }, @@ -1516,23 +1588,7 @@ } }, "WidgetValue": { - "nullable": true, - "anyOf": [ - { - "type": "string" - }, - { - "type": "integer", - "format": "int64" - }, - { - "type": "number", - "format": "double" - }, - { - "type": "boolean" - } - ] + "type": "string" } } }, @@ -15038,11 +15094,15 @@ "default": null, "description": "All widgets of the page", "items": { - "type": "object", - "additionalProperties": { - "type": "object" - } + "$ref": "#/components/schemas/WidgetInput" } + }, + "version": { + "type": "integer", + "format": "int64", + "nullable": true, + "default": null, + "description": "The version of the page the widgets were edited from, needed with widgets" } } } @@ -15113,7 +15173,7 @@ } }, "400": { - "description": "Invalid page field or widget, too many widgets, or the page changed in between", + "description": "Invalid page field or widget, or too many widgets", "content": { "application/json": { "schema": { @@ -15226,6 +15286,44 @@ } } }, + "409": { + "description": "The page was saved by someone else since the given version", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } + } + } + } + } + } + } + } + }, "500": { "description": "", "content": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index af6a6ebc86..639c9cf426 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1318,6 +1318,8 @@ export type components = { readonly title: string | null; readonly icon: string | null; readonly description: string | null; + /** Format: int64 */ + readonly version: number; readonly widgets: readonly components["schemas"]["Widget"][]; }; readonly PublicColumn: { @@ -1576,9 +1578,32 @@ export type components = { readonly nodeRelId: number; } | null; }; + readonly WidgetInput: { + /** Format: int64 */ + readonly id?: number | null; + readonly type: string; + readonly title?: string | null; + readonly icon?: string | null; + readonly description?: string | null; + /** Format: int64 */ + readonly gridX: number; + /** Format: int64 */ + readonly gridY: number; + /** Format: int64 */ + readonly gridWidth: number; + /** Format: int64 */ + readonly gridHeight: number; + readonly settings?: { + readonly [key: string]: components["schemas"]["WidgetValue"]; + } | null; + readonly source?: { + /** Format: int64 */ + readonly nodeRelId: number; + } | null; + }; readonly WidgetSettingSchema: { /** @enum {string} */ - readonly type: "string" | "text" | "color" | "boolean" | "enum"; + readonly type: "string" | "text" | "color" | "enum"; readonly title: string; readonly default: components["schemas"]["WidgetValue"]; readonly options?: readonly { @@ -1599,7 +1624,7 @@ export type components = { readonly [key: string]: components["schemas"]["WidgetSettingSchema"]; }; }; - readonly WidgetValue: (string | number | boolean) | null; + readonly WidgetValue: string; }; responses: never; parameters: never; @@ -8424,9 +8449,13 @@ export interface operations { * @description All widgets of the page * @default null */ - readonly widgets?: readonly { - readonly [key: string]: Record; - }[] | null; + readonly widgets?: readonly components["schemas"]["WidgetInput"][] | null; + /** + * Format: int64 + * @description The version of the page the widgets were edited from, needed with widgets + * @default null + */ + readonly version?: number | null; }; }; }; @@ -8445,7 +8474,7 @@ export interface operations { }; }; }; - /** @description Invalid page field or widget, too many widgets, or the page changed in between */ + /** @description Invalid page field or widget, or too many widgets */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -8507,6 +8536,22 @@ export interface operations { }; }; }; + /** @description The page was saved by someone else since the given version */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly ocs: { + readonly meta: components["schemas"]["OCSMeta"]; + readonly data: { + readonly message: string; + }; + }; + }; + }; + }; readonly 500: { headers: { readonly [name: string]: unknown; diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php index f4b4ef1e99..e49b8a702f 100644 --- a/tests/unit/Controller/ContextPageControllerTest.php +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -11,11 +11,10 @@ use OCA\Tables\Controller\ContextPageController; use OCA\Tables\Errors\BadRequestError; +use OCA\Tables\Errors\ConflictError; use OCA\Tables\Errors\NotFoundError; -use OCA\Tables\Errors\PermissionError; use OCA\Tables\Service\GridWidgetTypes; use OCA\Tables\Service\PageService; -use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\IL10N; @@ -49,11 +48,11 @@ protected function setUp(): void { public static function endpoints(): array { $widgets = [['type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]]; return [ - 'show' => ['find', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->show(7, 2)], - 'show by name' => ['findBySlug', [7, 'overview', 'alice'], static fn (ContextPageController $controller) => $controller->showBySlug(7, 'overview')], - 'create' => ['create', [7, 'Overview', 'overview', 'star', 'At a glance', 'alice'], static fn (ContextPageController $controller) => $controller->create(7, 'Overview', 'overview', 'star', 'At a glance')], - 'update' => ['update', [7, 2, null, 'planning', '', null, $widgets, 'alice'], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'planning', '', null, $widgets)], - 'destroy' => ['delete', [7, 2, 'alice'], static fn (ContextPageController $controller) => $controller->destroy(7, 2)], + 'show' => ['find', [7, 2], static fn (ContextPageController $controller) => $controller->show(7, 2)], + 'show by name' => ['findBySlug', [7, 'overview'], static fn (ContextPageController $controller) => $controller->showBySlug(7, 'overview')], + 'create' => ['create', [7, 'Overview', 'overview', 'star', 'At a glance'], static fn (ContextPageController $controller) => $controller->create(7, 'Overview', 'overview', 'star', 'At a glance')], + 'update' => ['update', [7, 2, null, 'planning', '', null, $widgets, 4], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'planning', '', null, $widgets, 4)], + 'destroy' => ['delete', [7, 2], static fn (ContextPageController $controller) => $controller->destroy(7, 2)], ]; } @@ -76,10 +75,9 @@ public static function errors(): array { ]; foreach (['create', 'update', 'destroy'] as $endpoint) { $cases[$endpoint . ', bad request'] = [new BadRequestError('Widget 0 needs a type.'), Http::STATUS_BAD_REQUEST]; - $cases[$endpoint . ', no permission'] = [new PermissionError('User bob cannot manage application 7'), Http::STATUS_FORBIDDEN]; $cases[$endpoint . ', not found'] = [new NotFoundError('Context does not exist'), Http::STATUS_NOT_FOUND]; } - $cases['update, page gone'] = [new DoesNotExistException('Page does not exist'), Http::STATUS_NOT_FOUND]; + $cases['update, saved by someone else'] = [new ConflictError('The page was changed by another save in the meantime.'), Http::STATUS_CONFLICT]; $errors = []; foreach ($cases as $case => [$error, $status]) { [$method, , $call] = $endpoints[explode(',', $case)[0]]; @@ -110,5 +108,7 @@ public function testWidgetTypesListsEveryType(): void { $response = $this->controller->widgetTypes(); $this->assertSame(['header', 'text', 'data'], array_column($response->getData(), 'type')); + $this->assertSame('{}', json_encode($response->getData()[2]['settings']), 'a type without settings has an empty object'); + $this->assertIsArray($response->getData()[0]['settings']); } } diff --git a/tests/unit/Database/DbErrorStub.php b/tests/unit/Database/DbErrorStub.php new file mode 100644 index 0000000000..17ac605167 --- /dev/null +++ b/tests/unit/Database/DbErrorStub.php @@ -0,0 +1,31 @@ +reason; + } +} diff --git a/tests/unit/Db/PageTest.php b/tests/unit/Db/PageTest.php index 1554891731..e2ae2d28f6 100644 --- a/tests/unit/Db/PageTest.php +++ b/tests/unit/Db/PageTest.php @@ -56,6 +56,7 @@ public function testAGridPageKeepsItsTitleIconAndDescription(): void { 'title' => 'Overview', 'icon' => 'star', 'description' => 'Open tasks by team', + 'version' => 0, ], $this->load($page->getId())->jsonSerialize()); } diff --git a/tests/unit/Db/WidgetMapperTest.php b/tests/unit/Db/WidgetMapperTest.php index 9b965c0c4e..da07f17047 100644 --- a/tests/unit/Db/WidgetMapperTest.php +++ b/tests/unit/Db/WidgetMapperTest.php @@ -49,7 +49,7 @@ public function testAWidgetIsStoredWithAllItsFields(): void { $inserted->getId(), self::PAGE, 'header', 'Welcome', 'star', 'What the team works on', 2, 3, 8, 4, '{"heading":"Projects","showTitle":false}', ], [ $widget->getId(), $widget->getPageId(), $widget->getType(), $widget->getTitle(), $widget->getIcon(), $widget->getDescription(), - $widget->getGridX(), $widget->getGridY(), $widget->getGridWidth(), $widget->getGridHeight(), json_encode($widget->getSettingsObject()), + $widget->getGridX(), $widget->getGridY(), $widget->getGridWidth(), $widget->getGridHeight(), json_encode($widget->getSettingsForResponse()), ]); } @@ -140,7 +140,7 @@ private function widget(int $pageId, string $type, ?string $title, int $x, int $ $widget->setGridY($y); $widget->setGridWidth($width); $widget->setGridHeight($height); - $widget->setSettings($settings); + $widget->setSettingsArray($settings); return $widget; } } diff --git a/tests/unit/Db/WidgetTest.php b/tests/unit/Db/WidgetTest.php index 643e5d0bdc..2884a25299 100644 --- a/tests/unit/Db/WidgetTest.php +++ b/tests/unit/Db/WidgetTest.php @@ -29,6 +29,6 @@ public function testSettingsSerialiseAsAJsonObject(?string $stored, string $seri $widget = new Widget(); $widget->setSettings($stored); - $this->assertSame($serialised, json_encode($widget->getSettingsObject())); + $this->assertSame($serialised, json_encode($widget->getSettingsForResponse())); } } diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index 1aae764def..d6aae27cbf 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -16,13 +16,14 @@ use OCA\Tables\Db\PageContentMapper; use OCA\Tables\Db\PageMapper; use OCA\Tables\Errors\BadRequestError; +use OCA\Tables\Errors\ConflictError; use OCA\Tables\Errors\NotFoundError; -use OCA\Tables\Errors\PermissionError; +use OCA\Tables\Model\WidgetInput; use OCA\Tables\Service\GridWidgetTypes; use OCA\Tables\Service\PageService; -use OCA\Tables\Service\PermissionsService; use OCA\Tables\Service\WidgetService; use OCA\Tables\Tests\Unit\Database\DbErrorStub; +use OCP\AppFramework\Db\DoesNotExistException; use OCP\IDBConnection; use OCP\IL10N; use PHPUnit\Framework\MockObject\MockObject; @@ -34,33 +35,34 @@ class PageServiceTest extends TestCase { private const NODE_REL = 20; private PageService $service; - private Context $context; + /** @var array stored pages by id */ + private array $pages = []; private PageMapper&MockObject $pageMapper; private PageContentMapper&MockObject $pageContentMapper; private WidgetService&MockObject $widgetService; - private PermissionsService&MockObject $permissionsService; protected function setUp(): void { parent::setUp(); - $this->context = new Context(); - $this->context->id = 7; - $this->context->setNodes([self::NODE_REL => ['id' => self::NODE_REL, 'node_id' => 3, 'node_type' => Application::NODE_TYPE_TABLE, 'permissions' => 1]]); - $this->context->setPages([ - self::START_PAGE => ['id' => self::START_PAGE, 'page_type' => Page::TYPE_STARTPAGE, 'slug' => 'dashboard', 'title' => null, 'icon' => null, 'description' => null, 'content' => []], - self::GRID_PAGE => ['id' => self::GRID_PAGE, 'page_type' => Page::TYPE_GRID, 'slug' => 'overview', 'title' => 'Overview', 'icon' => 'star', 'description' => null, 'content' => []], - ]); + $this->pages = [ + self::START_PAGE => $this->page(self::START_PAGE, Page::TYPE_STARTPAGE, 'dashboard', null), + self::GRID_PAGE => $this->page(self::GRID_PAGE, Page::TYPE_GRID, 'overview', 'Overview'), + ]; + $context = new Context(); + $context->id = 7; + $context->setNodes([self::NODE_REL => ['id' => self::NODE_REL, 'node_id' => 3, 'node_type' => Application::NODE_TYPE_TABLE, 'permissions' => 1]]); $contextMapper = $this->createMock(ContextMapper::class); - $contextMapper->method('findById')->willReturnCallback(function (int $contextId): Context { - if ($contextId !== 7) { - throw new NotFoundError('Context does not exist'); + $contextMapper->method('findById')->willReturn($context); + + $this->pageMapper = $this->createMock(PageMapper::class); + $this->pageMapper->method('findById')->willReturnCallback(function (int $pageId): Page { + if (!isset($this->pages[$pageId])) { + throw new DoesNotExistException('Page does not exist'); } - return $this->context; + return clone $this->pages[$pageId]; }); - $this->pageMapper = $this->createMock(PageMapper::class); + $this->pageMapper->method('lockContext')->willReturn(true); $this->pageContentMapper = $this->createMock(PageContentMapper::class); $this->widgetService = $this->createMock(WidgetService::class); - $this->widgetService->method('findIdsByPageId')->willReturnMap([[self::GRID_PAGE, [31, 32]], [self::START_PAGE, []]]); - $this->permissionsService = $this->createMock(PermissionsService::class); $l10n = $this->createMock(IL10N::class); $l10n->method('t')->willReturnArgument(0); @@ -69,345 +71,309 @@ protected function setUp(): void { $this->pageMapper, $this->pageContentMapper, $this->widgetService, - $this->permissionsService, new GridWidgetTypes($l10n), $this->createMock(IDBConnection::class), ); } - public function testFindReturnsThePageWithItsWidgets(): void { - $widget = ['id' => 31, 'type' => 'text', 'title' => null, 'icon' => null, 'description' => null, 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2, 'settings' => ['text' => 'Hi'], 'source' => null]; + private function page(int $id, string $type, string $slug, ?string $title): Page { + $page = new Page(); + $page->id = $id; + $page->setContextId(7); + $page->setPageType($type); + $page->setSlug($slug); + $page->setTitle($title); + $page->setVersion(4); + $page->resetUpdatedFields(); + return $page; + } + + /** + * @return array + */ + private static function widget(array $fields = []): array { + return $fields + ['type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2, 'settings' => ['text' => 'Hi']]; + } + + public function testFindReturnsThePageWithItsWidgetsAndVersion(): void { + $widget = ['id' => 31, 'type' => 'text']; $this->widgetService->method('findByPageIds')->with([self::GRID_PAGE])->willReturn([self::GRID_PAGE => [$widget]]); - $this->assertSame([ - 'id' => self::GRID_PAGE, - 'contextId' => 7, - 'pageType' => Page::TYPE_GRID, - 'slug' => 'overview', - 'title' => 'Overview', - 'icon' => 'star', - 'description' => null, - 'widgets' => [$widget], - ], $this->service->find(7, self::GRID_PAGE, 'alice')); + $page = $this->service->find(7, self::GRID_PAGE); + + $this->assertSame([self::GRID_PAGE, 7, Page::TYPE_GRID, 'overview', 'Overview', 4, [$widget]], [ + $page['id'], $page['contextId'], $page['pageType'], $page['slug'], $page['title'], $page['version'], $page['widgets'], + ]); } - public function testFindBySlugReturnsTheSamePageAsItsId(): void { + public function testFindBySlugAsksTheMapperAndAnUnknownNameIsNotFound(): void { + $this->pageMapper->method('findBySlug')->willReturnCallback(function (int $contextId, string $name): Page { + return $name === 'overview' ? $this->pages[self::GRID_PAGE] : throw new DoesNotExistException('none'); + }); $this->widgetService->method('findByPageIds')->willReturn([]); - $this->assertSame($this->service->find(7, self::GRID_PAGE, 'alice'), $this->service->findBySlug(7, 'overview', 'alice')); + $this->assertSame(self::GRID_PAGE, $this->service->findBySlug(7, 'overview')['id']); + $this->expectException(NotFoundError::class); + $this->service->findBySlug(7, 'missing'); } - public function testAnApplicationOrPageOutsideTheUsersReachIsNotFound(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->expects($this->never())->method('insert'); - $this->pageMapper->expects($this->never())->method('update'); - $this->pageMapper->expects($this->never())->method('deleteByPageId'); - $this->widgetService->expects($this->never())->method('syncPage'); - + public function testAPageOfAnotherApplicationIsNotFound(): void { + $this->pageMapper->expects($this->never())->method('raiseVersion'); foreach ([ - 'application of no access' => fn () => $this->service->find(8, self::GRID_PAGE, 'mallory'), - 'create in it' => fn () => $this->service->create(8, 'Overview', null, null, null, 'mallory'), - 'update in it' => fn () => $this->service->update(8, self::GRID_PAGE, 'Mine', null, null, null, [], 'mallory'), - 'delete in it' => fn () => $this->service->delete(8, self::GRID_PAGE, 'mallory'), - 'application of no access by name' => fn () => $this->service->findBySlug(8, 'overview', 'mallory'), - 'page of another application' => fn () => $this->service->find(7, 99, 'alice'), - 'unknown name' => fn () => $this->service->findBySlug(7, 'missing', 'alice'), - 'update it' => fn () => $this->service->update(7, 99, 'Taken over', null, null, null, [], 'alice'), - 'delete it' => fn () => $this->service->delete(7, 99, 'alice'), + 'find' => fn () => $this->service->find(8, self::GRID_PAGE), + 'update' => fn () => $this->service->update(8, self::GRID_PAGE, 'Mine', null, null, null, null, null), + 'delete' => fn () => $this->service->delete(8, self::GRID_PAGE), + 'unknown page' => fn () => $this->service->find(7, 99), ] as $case => $call) { try { $call(); $this->fail($case . ' was found.'); } catch (NotFoundError) { + $this->addToAssertionCount(1); } } } public function testCreateInsertsAGridPageNamedByItsId(): void { - $this->permissionsService->method('canManageContext')->with($this->context, 'alice')->willReturn(true); - $inserted = null; - $this->pageMapper->expects($this->never())->method('insert'); - $this->pageMapper->expects($this->once())->method('insertWithDefaultName')->willReturnCallback(function (Page $page) use (&$inserted): Page { - $page->id = self::GRID_PAGE; - $page->setSlug('page_' . self::GRID_PAGE); - $inserted = $page; + $this->pageMapper->expects($this->once())->method('insertWithDefaultName')->willReturnCallback(static function (Page $page): Page { + $page->id = 9; + $page->setSlug('page_9'); return $page; }); - $this->service->create(7, ' Team Overview ', null, ' home ', '', 'alice'); + $page = $this->service->create(7, ' Planning ', null, 'star', ' Next steps '); - $this->assertSame([7, Page::TYPE_GRID, 'Team Overview', 'home', null], [$inserted->getContextId(), $inserted->getPageType(), $inserted->getTitle(), $inserted->getIcon(), $inserted->getDescription()]); + $this->assertSame([9, Page::TYPE_GRID, 'page_9', 'Planning', 'star', 'Next steps', []], [ + $page['id'], $page['pageType'], $page['slug'], $page['title'], $page['icon'], $page['description'], $page['widgets'], + ]); } - public function testCreateKeepsAGivenSlug(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->expects($this->never())->method('insertWithDefaultName'); - $inserted = null; - $this->pageMapper->expects($this->once())->method('insert')->willReturnCallback(function (Page $page) use (&$inserted): Page { - $page->id = self::GRID_PAGE; - $inserted = $page; + public function testCreateKeepsAGivenSlugAndReportsATakenOne(): void { + $this->pageMapper->method('insert')->willReturnCallback(static function (Page $page): Page { + if ($page->getSlug() === 'taken') { + throw DbErrorStub::uniqueViolation(); + } + $page->id = 9; return $page; }); - $this->service->create(7, 'Overview', 'team_board', null, null, 'alice'); + $this->assertSame('planning', $this->service->create(7, 'Planning', 'planning', null, null)['slug']); + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('The slug taken is already used'); + $this->service->create(7, 'Planning', 'taken', null, null); + } + + public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { + $this->pageMapper = $this->createMock(PageMapper::class); + $this->pageMapper->method('lockContext')->willReturn(false); + $this->pageMapper->expects($this->never())->method('insertWithDefaultName'); + $service = new PageService($this->createMock(ContextMapper::class), $this->pageMapper, $this->pageContentMapper, $this->widgetService, new GridWidgetTypes($this->createMock(IL10N::class)), $this->createMock(IDBConnection::class)); - $this->assertSame('team_board', $inserted->getSlug()); + $this->expectException(NotFoundError::class); + $service->create(7, 'Planning', null, null, null); } - public function testCreateRefusesAGivenNameAConcurrentSaveTook(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->expects($this->once())->method('insert') - ->willThrowException(DbErrorStub::uniqueViolation()); + public static function blankTitles(): array { + return [ + 'empty' => [''], + 'spaces' => [' '], + 'no-break and zero width spaces' => ["\u{00A0}\u{200B}"], + 'too long' => [str_repeat('a', 201)], + ]; + } + /** + * @dataProvider blankTitles + */ + public function testAGridPageNeedsATitle(string $title): void { + $this->pageMapper->expects($this->never())->method('raiseVersion'); + try { + $this->service->create(7, $title, null, null, null); + $this->fail('A page was created without a title.'); + } catch (BadRequestError $e) { + $this->assertStringContainsString('A page title needs 1 to 200 characters', $e->getMessage()); + } $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('already used'); - $this->service->create(7, 'Overview', 'team_board', null, null, 'alice'); + $this->service->update(7, self::GRID_PAGE, $title, null, null, null, null, null); } - public function testCreateNeedsATitle(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->expects($this->never())->method('insert'); + public function testTheStartPageCanLoseItsTitleAgain(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([]); + $saved = []; + $this->pageMapper->method('update')->willReturnCallback(static function (Page $page) use (&$saved): Page { + $saved[] = $page->getTitle(); + return $page; + }); - $this->expectException(BadRequestError::class); - $this->service->create(7, ' ', null, null, null, 'alice'); + $this->service->update(7, self::START_PAGE, 'Start', null, null, null, null, null); + $page = $this->service->update(7, self::START_PAGE, '', null, null, null, null, null); + + $this->assertSame(['Start', null], $saved); + $this->assertNull($page['title']); } - public function testUpdateSyncsWidgetsById(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); + public function testUpdateSyncsWidgetsAndAnswersWithWhatWasStored(): void { + $this->pageMapper->expects($this->once())->method('raiseVersion')->with(self::GRID_PAGE, 4)->willReturn(true); + $stored = [['id' => 31, 'type' => 'text'], ['id' => 32, 'type' => 'data']]; $synced = null; - $this->widgetService->expects($this->once())->method('syncPage')->willReturnCallback(function (int $pageId, array $rows) use (&$synced): void { - $this->assertSame(self::GRID_PAGE, $pageId); - $synced = $rows; + $this->widgetService->expects($this->once())->method('syncPage')->willReturnCallback(function (int $pageId, array $widgets) use (&$synced, $stored): array { + $synced = $widgets; + return $stored; }); - $this->pageMapper->expects($this->never())->method('update'); - - $this->service->update(7, self::GRID_PAGE, null, null, null, null, [ - ['id' => 31, 'type' => 'header', 'title' => ' Intro ', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 12, 'gridHeight' => 2, 'settings' => ['heading' => 'Welcome']], - ['type' => 'data', 'icon' => 'star', 'description' => ' Open tasks ', 'gridX' => 0, 'gridY' => 2, 'gridWidth' => 6, 'gridHeight' => 5, 'source' => ['nodeRelId' => self::NODE_REL]], - ['type' => 'data', 'icon' => '', 'description' => '', 'gridX' => 0, 'gridY' => 7, 'gridWidth' => 12, 'gridHeight' => 5, 'source' => null], - ], 'alice'); - - $this->assertSame([ - ['id' => 31, 'type' => 'header', 'title' => 'Intro', 'icon' => null, 'description' => null, 'position' => ['gridX' => 0, 'gridY' => 0, 'gridWidth' => 12, 'gridHeight' => 2], 'settings' => ['heading' => 'Welcome', 'subheading' => '', 'textAlign' => 'start', 'backgroundColor' => '', 'textColor' => ''], 'nodeRelId' => null], - ['id' => null, 'type' => 'data', 'title' => null, 'icon' => 'star', 'description' => 'Open tasks', 'position' => ['gridX' => 0, 'gridY' => 2, 'gridWidth' => 6, 'gridHeight' => 5], 'settings' => [], 'nodeRelId' => self::NODE_REL], - ['id' => null, 'type' => 'data', 'title' => null, 'icon' => null, 'description' => null, 'position' => ['gridX' => 0, 'gridY' => 7, 'gridWidth' => 12, 'gridHeight' => 5], 'settings' => [], 'nodeRelId' => null], - ], $synced); + $this->widgetService->expects($this->never())->method('findByPageIds'); + + $page = $this->service->update(7, self::GRID_PAGE, null, null, null, null, [ + self::widget(['id' => 31]), + self::widget(['type' => 'data', 'settings' => [], 'source' => ['nodeRelId' => self::NODE_REL]]), + ], 4); + + $this->assertSame([[31, 'text', null], [null, 'data', self::NODE_REL]], array_map(static fn (WidgetInput $w): array => [$w->id, $w->type, $w->nodeRelId], $synced)); + $this->assertSame([$stored, 5], [$page['widgets'], $page['version']]); } - public function testChangesNeedManagePermission(): void { - $this->permissionsService->method('canManageContext')->with($this->context, 'bob')->willReturn(false); - $this->pageMapper->expects($this->never())->method('insert'); - $this->pageMapper->expects($this->never())->method('update'); - $this->pageMapper->expects($this->never())->method('deleteByPageId'); + public function testTheStartPageHoldsWidgets(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->expects($this->once())->method('syncPage')->with(self::START_PAGE)->willReturn([]); + + $this->service->update(7, self::START_PAGE, null, null, null, null, [self::widget()], 4); + } + + public function testASaveOfWidgetsNamesTheVersionItIsBasedOn(): void { $this->widgetService->expects($this->never())->method('syncPage'); + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('names the version of the page'); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], null); + } - foreach ([ - 'create' => fn () => $this->service->create(7, 'Overview', null, null, null, 'bob'), - 'update' => fn () => $this->service->update(7, self::GRID_PAGE, 'New', null, null, null, [], 'bob'), - 'delete' => fn () => $this->service->delete(7, self::GRID_PAGE, 'bob'), - ] as $case => $call) { - try { - $call(); - $this->fail($case . ' was allowed.'); - } catch (PermissionError) { - } - } + public function testASaveBasedOnAnOlderVersionIsAConflict(): void { + $this->pageMapper->method('raiseVersion')->willReturn(false); + $this->widgetService->expects($this->never())->method('syncPage'); + + $this->expectException(ConflictError::class); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 3); } - public function testUpdateChangesPageFields(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $stored = new Page(); - $stored->id = self::GRID_PAGE; - $stored->setSlug('overview'); - $stored->setTitle('Overview'); - $stored->setIcon('star'); - $stored->resetUpdatedFields(); - $this->pageMapper->method('findById')->with(self::GRID_PAGE)->willReturn($stored); - $updated = null; - $this->pageMapper->expects($this->once())->method('update')->willReturnCallback(function (Page $page) use (&$updated): Page { - $updated = $page; - return $page; + public function testASaveOfAPageDeletedInTheMeantimeIsNotFound(): void { + $this->pageMapper->method('raiseVersion')->willReturnCallback(function (): bool { + unset($this->pages[self::GRID_PAGE]); + return false; }); $this->widgetService->expects($this->never())->method('syncPage'); - $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', '', 'What is next', null, 'alice'); + $this->expectException(NotFoundError::class); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 4); + } + + public function testAWidgetRemovedByAConcurrentSaveIsAConflict(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('syncPage')->willThrowException(new \InvalidArgumentException('Widget 31 is not on page 2')); - $this->assertSame([self::GRID_PAGE, 'planning', 'Planning', null, 'What is next'], [$updated->getId(), $updated->getSlug(), $updated->getTitle(), $updated->getIcon(), $updated->getDescription()]); - $this->assertSame(['title', 'slug', 'icon', 'description'], array_keys($updated->getUpdatedFields())); + $this->expectException(ConflictError::class); + $this->expectExceptionMessage('Load it again and retry'); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget(['id' => 31])], 4); } - public function testUpdateKeepsTheSlugWhenTheTitleChanges(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $stored = $this->storedGridPage(); - $this->pageMapper->method('findById')->willReturn($stored); - $this->pageMapper->expects($this->once())->method('update')->willReturnArgument(0); + public function testUpdateChangesThePageFields(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([]); + $updated = null; + $this->pageMapper->expects($this->once())->method('update')->willReturnCallback(static function (Page $page) use (&$updated): Page { + $updated = [$page->getTitle(), $page->getSlug(), $page->getIcon(), $page->getDescription()]; + return $page; + }); - $this->service->update(7, self::GRID_PAGE, 'Planning', null, null, null, null, 'alice'); + $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', 'star', 'Next steps', null, null); - $this->assertSame('overview', $stored->getSlug()); + $this->assertSame(['Planning', 'planning', 'star', 'Next steps'], $updated); } - public function testAPageKeepsOrTakesItsOwnNames(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $stored = $this->storedGridPage(); - $this->pageMapper->method('findById')->willReturn($stored); - $this->pageMapper->expects($this->once())->method('update')->willReturnArgument(0); + public function testARenameToANameAConcurrentSaveTookIsReported(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->pageMapper->method('update')->willThrowException(DbErrorStub::uniqueViolation()); - $this->service->update(7, self::GRID_PAGE, null, 'overview', null, null, null, 'alice'); - $this->service->update(7, self::GRID_PAGE, null, 'page_' . self::GRID_PAGE, null, null, null, 'alice'); + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('The slug planning is already used'); + $this->service->update(7, self::GRID_PAGE, null, 'planning', null, null, null, null); + } + + public function testAUniqueViolationWithoutARenameIsNotTakenForOne(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('syncPage')->willThrowException(DbErrorStub::uniqueViolation()); - $this->assertSame('page_' . self::GRID_PAGE, $stored->getSlug()); + $this->expectException(DbErrorStub::class); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 4); } public static function refusedSlugs(): array { return [ - 'upper case' => ['Board', 'lower case letters'], - 'leading digit' => ['2026_plan', 'lower case letters'], - 'empty' => ['', 'lower case letters'], - 'too long' => [str_repeat('a', 201), 'lower case letters'], - 'taken' => ['dashboard', 'already used'], - 'reserved' => ['page_9', 'reserved for automatic names'], + 'upper case' => ['Planning', 'A slug has 1 to 200 lower case letters'], + 'reserved for another page' => ['page_5', 'The slug page_5 is reserved'], ]; } /** * @dataProvider refusedSlugs */ - public function testUpdateRefusesAnInvalidOrTakenSlug(string $slug, string $message): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); - $this->pageMapper->expects($this->never())->method('update'); - + public function testAnInvalidSlugIsRefused(string $slug, string $message): void { $this->expectException(BadRequestError::class); $this->expectExceptionMessage($message); - $this->service->update(7, self::GRID_PAGE, null, $slug, null, null, null, 'alice'); + $this->service->update(7, self::GRID_PAGE, null, $slug, null, null, null, null); } - public function testUpdateRefusesANameAConcurrentSaveTook(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); - $this->pageMapper->method('update') - ->willThrowException(DbErrorStub::uniqueViolation()); + public function testAPageKeepsItsOwnAutomaticName(): void { + $this->pages[self::GRID_PAGE]->setSlug('page_2'); + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([]); - $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('already used'); - $this->service->update(7, self::GRID_PAGE, null, 'planning', null, null, null, 'alice'); + $this->assertSame('page_2', $this->service->update(7, self::GRID_PAGE, null, 'page_2', null, null, null, null)['slug']); } - public function testUpdateRefusesAnUnknownIcon(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); - $this->pageMapper->expects($this->never())->method('update'); - + public function testAnUnknownIconIsRefused(): void { $this->expectException(BadRequestError::class); - $this->service->update(7, self::GRID_PAGE, null, null, 'no-such-icon', null, null, 'alice'); - } - - private function storedGridPage(): Page { - $stored = new Page(); - $stored->id = self::GRID_PAGE; - $stored->setContextId(7); - $stored->setSlug('overview'); - $stored->setTitle('Overview'); - $stored->resetUpdatedFields(); - return $stored; + $this->expectExceptionMessage('unknown icon'); + $this->service->update(7, self::GRID_PAGE, null, null, 'no-such-icon', null, null, null); } public static function invalidWidgets(): array { - $at = ['gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]; - $foreignSource = 'must be {nodeRelId} of a table or view of this application'; return [ 'not an object' => [['x'], 'Widget 0 must be an object'], - 'no type' => [[$at], 'Widget 0 needs a type'], - 'unknown type' => [[['type' => 'chart'] + $at], 'Unknown widget type'], - 'id of another page' => [[['id' => 99, 'type' => 'text'] + $at], 'Widget 0 has the id of no other widget on this page'], - 'id twice' => [[['id' => 31, 'type' => 'text'] + $at, ['id' => 31, 'type' => 'text'] + $at], 'Widget 1 has the id'], - 'invalid setting' => [[['type' => 'header', 'settings' => ['heading' => '']] + $at], 'header.heading is required'], - 'outside the grid' => [[['type' => 'text', 'gridX' => 8, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'does not fit in 12 columns'], - 'invalid title' => [[['type' => 'text', 'title' => 5] + $at], 'The title of widget 0'], - 'unknown icon' => [[['type' => 'text', 'icon' => 'no-such-icon'] + $at], 'Widget 0 has an unknown icon'], - 'icon not text' => [[['type' => 'text', 'icon' => 5] + $at], 'The icon of widget 0'], - 'source on a header' => [[['type' => 'header', 'settings' => ['heading' => 'A'], 'source' => ['nodeRelId' => self::NODE_REL]] + $at], 'shows no table or view'], - 'node of another application' => [[['type' => 'data', 'source' => ['nodeRelId' => 21]] + $at], $foreignSource], - 'table outside the application' => [[['type' => 'data', 'source' => ['nodeType' => Application::NODE_TYPE_TABLE, 'nodeId' => 3]] + $at], $foreignSource], - 'source not an object' => [[['type' => 'data', 'source' => self::NODE_REL] + $at], $foreignSource], + 'unknown type' => [[self::widget(['type' => 'chart'])], 'Unknown widget type'], + 'source of another application' => [[self::widget(['type' => 'data', 'settings' => [], 'source' => ['nodeRelId' => 99]])], 'The source of widget 0'], + 'the same id twice' => [[self::widget(['id' => 31]), self::widget(['id' => 31])], 'Widget 1 has the id of another widget'], + 'too many' => [array_fill(0, 101, self::widget()), 'A page holds at most 100 widgets'], ]; } /** * @dataProvider invalidWidgets */ - public function testUpdateRejectsInvalidWidgets(array $widgets, string $message): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->widgetService->expects($this->never())->method('syncPage'); - + public function testInvalidWidgetsAreRefusedBeforeAnyWrite(array $widgets, string $message): void { + $this->pageMapper->expects($this->never())->method('raiseVersion'); $this->expectException(BadRequestError::class); $this->expectExceptionMessage($message); - $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); - } - - public function testTheStartPageHoldsNoWidgets(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - - $this->expectException(BadRequestError::class); - $this->service->update(7, self::START_PAGE, null, null, null, null, [], 'alice'); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 4); } public function testDeleteRemovesAGridPageWithItsWidgets(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->widgetService->method('findByPageIds')->willReturn([]); + $this->pageMapper->expects($this->once())->method('raiseVersion')->with(self::GRID_PAGE, null)->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([self::GRID_PAGE => [['id' => 31]]]); $this->widgetService->expects($this->once())->method('deleteByPageIds')->with([self::GRID_PAGE]); $this->pageMapper->expects($this->once())->method('deleteByPageId')->with(self::GRID_PAGE); - $this->assertSame('Overview', $this->service->delete(7, self::GRID_PAGE, 'alice')['title']); + $this->assertSame([['id' => 31]], $this->service->delete(7, self::GRID_PAGE)['widgets']); } public function testTheStartPageCannotBeDeleted(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); $this->pageMapper->expects($this->never())->method('deleteByPageId'); - - $this->expectException(BadRequestError::class); - $this->service->delete(7, self::START_PAGE, 'alice'); - } - - public function testAPageHoldsAtMostTheMaximumNumberOfWidgets(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->widgetService->expects($this->once())->method('syncPage'); - $widgets = []; - for ($i = 0; $i < GridWidgetTypes::MAX_WIDGETS_PER_PAGE; $i++) { - $widgets[] = ['type' => 'text', 'gridX' => 0, 'gridY' => $i * 2, 'gridWidth' => 6, 'gridHeight' => 2]; - } - $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); - - $widgets[] = ['type' => 'text', 'gridX' => 6, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]; - $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('at most 100 widgets'); - $this->service->update(7, self::GRID_PAGE, null, null, null, null, $widgets, 'alice'); - } - - /** - * A concurrent save removed a listed widget between the check and the sync. - */ - public function testAWidgetRemovedByAConcurrentSaveAsksForARetry(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->widgetService->method('syncPage')->willThrowException(new \InvalidArgumentException('Widget 31 is not on page 2')); - $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('changed by another save'); - $this->service->update(7, self::GRID_PAGE, null, null, null, null, [['id' => 31, 'type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'alice'); + $this->service->delete(7, self::START_PAGE); } - /** - * Two saves adding a source to the same widget at once collide on the source key; that - * is no taken slug. - */ - public function testAConcurrentCollisionWithoutARenameAsksForARetry(): void { - $this->permissionsService->method('canManageContext')->willReturn(true); - $this->pageMapper->method('findById')->willReturn($this->storedGridPage()); - $this->widgetService->method('syncPage')->willThrowException(DbErrorStub::uniqueViolation()); - - $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('changed by another save'); - $this->service->update(7, self::GRID_PAGE, 'Renamed title', 'overview', null, null, [['id' => 31, 'type' => 'text', 'gridX' => 0, 'gridY' => 0, 'gridWidth' => 6, 'gridHeight' => 2]], 'alice'); + public function testADeleteOfAPageDeletedInTheMeantimeIsNotFound(): void { + $this->pageMapper->method('raiseVersion')->willReturn(false); + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + $this->expectException(NotFoundError::class); + $this->service->delete(7, self::GRID_PAGE); } } diff --git a/tests/unit/Service/WidgetServiceTest.php b/tests/unit/Service/WidgetServiceTest.php index 87f3eba4e9..57604b6b8d 100644 --- a/tests/unit/Service/WidgetServiceTest.php +++ b/tests/unit/Service/WidgetServiceTest.php @@ -236,7 +236,7 @@ public function testAFailedSyncChangesNothing(): void { ['id' => null, 'type' => 'text', 'title' => null, 'position' => $this->position(0, 0, 6, 2), 'settings' => ['text' => NAN], 'nodeRelId' => null], ]); $this->fail('Settings that are no JSON were saved.'); - } catch (\OCP\DB\Exception) { + } catch (\JsonException) { } $this->assertSame([$kept->getId()], array_column($this->service->findByPageIds([$this->page])[$this->page], 'id')); diff --git a/tests/unit/bootstrap.php b/tests/unit/bootstrap.php index ce471574ad..f070cdbd48 100644 --- a/tests/unit/bootstrap.php +++ b/tests/unit/bootstrap.php @@ -20,6 +20,7 @@ require_once __DIR__ . '/../../../../tests/autoload.php'; require_once __DIR__ . '/Database/DatabaseTestCase.php'; +require_once __DIR__ . '/Database/DbErrorStub.php'; require_once __DIR__ . '/Db/Row2MapperTestDependencies.php'; From 9421c5c529ea94cf4d38f83221ecce9a2ead60ed Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Mon, 9 Nov 2026 14:42:36 +0100 Subject: [PATCH 06/16] chore(api): regenerate the OpenAPI spec and TypeScript types Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- openapi.json | 14 ++++---------- src/types/openapi/openapi.ts | 12 ++++++------ 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/openapi.json b/openapi.json index c86f30404b..4a64ba2135 100644 --- a/openapi.json +++ b/openapi.json @@ -1449,23 +1449,19 @@ "properties": { "id": { "type": "integer", - "format": "int64", - "nullable": true + "format": "int64" }, "type": { "type": "string" }, "title": { - "type": "string", - "nullable": true + "type": "string" }, "icon": { - "type": "string", - "nullable": true + "type": "string" }, "description": { - "type": "string", - "nullable": true + "type": "string" }, "gridX": { "type": "integer", @@ -1485,14 +1481,12 @@ }, "settings": { "type": "object", - "nullable": true, "additionalProperties": { "$ref": "#/components/schemas/WidgetValue" } }, "source": { "type": "object", - "nullable": true, "required": [ "nodeRelId" ], diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 639c9cf426..f017bb7929 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1580,11 +1580,11 @@ export type components = { }; readonly WidgetInput: { /** Format: int64 */ - readonly id?: number | null; + readonly id?: number; readonly type: string; - readonly title?: string | null; - readonly icon?: string | null; - readonly description?: string | null; + readonly title?: string; + readonly icon?: string; + readonly description?: string; /** Format: int64 */ readonly gridX: number; /** Format: int64 */ @@ -1595,11 +1595,11 @@ export type components = { readonly gridHeight: number; readonly settings?: { readonly [key: string]: components["schemas"]["WidgetValue"]; - } | null; + }; readonly source?: { /** Format: int64 */ readonly nodeRelId: number; - } | null; + }; }; readonly WidgetSettingSchema: { /** @enum {string} */ From 773768912f2dab25d6c7815d767b9ece3b88afa4 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Tue, 10 Nov 2026 11:09:26 +0100 Subject: [PATCH 07/16] fix(api): skip the row lock of a new page on SQLite Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Db/PageMapper.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/Db/PageMapper.php b/lib/Db/PageMapper.php index 6533edfd22..e1cbd6796b 100644 --- a/lib/Db/PageMapper.php +++ b/lib/Db/PageMapper.php @@ -98,8 +98,11 @@ public function lockContext(int $contextId): bool { $qb = $this->db->getQueryBuilder(); $qb->select('id') ->from('tables_contexts_context') - ->where($qb->expr()->eq('id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT))) - ->forUpdate(); + ->where($qb->expr()->eq('id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT))); + // SQLite has no row locks and runs one write transaction at a time anyway + if ($this->db->getDatabaseProvider() !== IDBConnection::PLATFORM_SQLITE) { + $qb->forUpdate(); + } $result = $qb->executeQuery(); $found = $result->fetchOne() !== false; $result->closeCursor(); From 035ec31e2872e08f2b6049df51113c1b891cd917 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Tue, 10 Nov 2026 12:16:05 +0100 Subject: [PATCH 08/16] test(api): write the technical name lookup as an arrow function, as Rector asks Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- tests/unit/Service/PageServiceTest.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index d6aae27cbf..03f2ea49c4 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -107,9 +107,7 @@ public function testFindReturnsThePageWithItsWidgetsAndVersion(): void { } public function testFindBySlugAsksTheMapperAndAnUnknownNameIsNotFound(): void { - $this->pageMapper->method('findBySlug')->willReturnCallback(function (int $contextId, string $name): Page { - return $name === 'overview' ? $this->pages[self::GRID_PAGE] : throw new DoesNotExistException('none'); - }); + $this->pageMapper->method('findBySlug')->willReturnCallback(fn (int $contextId, string $name): Page => $name === 'overview' ? $this->pages[self::GRID_PAGE] : throw new DoesNotExistException('none')); $this->widgetService->method('findByPageIds')->willReturn([]); $this->assertSame(self::GRID_PAGE, $this->service->findBySlug(7, 'overview')['id']); From 86c9c06d70749dd549047c5f6ec25862afce9bd1 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Mon, 16 Nov 2026 10:07:50 +0100 Subject: [PATCH 09/16] refactor(pages): lock the application through ContextMapper when a page is added One lock for the application row, which also takes the write lock first on SQLite. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Db/PageMapper.php | 22 ---------------------- lib/Service/PageService.php | 2 +- tests/unit/Service/PageServiceTest.php | 7 ++++--- 3 files changed, 5 insertions(+), 26 deletions(-) diff --git a/lib/Db/PageMapper.php b/lib/Db/PageMapper.php index e1cbd6796b..268819727c 100644 --- a/lib/Db/PageMapper.php +++ b/lib/Db/PageMapper.php @@ -87,28 +87,6 @@ public function raiseVersion(int $pageId, ?int $expected): bool { return $qb->executeStatement() === 1; } - /** - * Locks an application until the transaction ends, so a page is never added to one - * that is being deleted. - * - * @return bool false when the application is gone - * @throws Exception - */ - public function lockContext(int $contextId): bool { - $qb = $this->db->getQueryBuilder(); - $qb->select('id') - ->from('tables_contexts_context') - ->where($qb->expr()->eq('id', $qb->createNamedParameter($contextId, IQueryBuilder::PARAM_INT))); - // SQLite has no row locks and runs one write transaction at a time anyway - if ($this->db->getDatabaseProvider() !== IDBConnection::PLATFORM_SQLITE) { - $qb->forUpdate(); - } - $result = $qb->executeQuery(); - $found = $result->fetchOne() !== false; - $result->closeCursor(); - return $found; - } - /** * @return int[] */ diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index d48b2a0ea0..9c99ca482e 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -97,7 +97,7 @@ public function create(int $contextId, string $title, ?string $slug, ?string $ic } $page = $this->save(fn (): Page => $this->atomic(function () use ($contextId, $page): Page { - if (!$this->pageMapper->lockContext($contextId)) { + if (!$this->contextMapper->lock($contextId)) { throw new NotFoundError('Application ' . $contextId . ' does not exist'); } return $page->getSlug() === null ? $this->pageMapper->insertWithDefaultName($page) : $this->pageMapper->insert($page); diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index 03f2ea49c4..b0494da6a7 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -52,6 +52,7 @@ protected function setUp(): void { $context->setNodes([self::NODE_REL => ['id' => self::NODE_REL, 'node_id' => 3, 'node_type' => Application::NODE_TYPE_TABLE, 'permissions' => 1]]); $contextMapper = $this->createMock(ContextMapper::class); $contextMapper->method('findById')->willReturn($context); + $contextMapper->method('lock')->willReturn(true); $this->pageMapper = $this->createMock(PageMapper::class); $this->pageMapper->method('findById')->willReturnCallback(function (int $pageId): Page { @@ -60,7 +61,6 @@ protected function setUp(): void { } return clone $this->pages[$pageId]; }); - $this->pageMapper->method('lockContext')->willReturn(true); $this->pageContentMapper = $this->createMock(PageContentMapper::class); $this->widgetService = $this->createMock(WidgetService::class); $l10n = $this->createMock(IL10N::class); @@ -162,10 +162,11 @@ public function testCreateKeepsAGivenSlugAndReportsATakenOne(): void { } public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { + $contextMapper = $this->createMock(ContextMapper::class); + $contextMapper->method('lock')->willReturn(false); $this->pageMapper = $this->createMock(PageMapper::class); - $this->pageMapper->method('lockContext')->willReturn(false); $this->pageMapper->expects($this->never())->method('insertWithDefaultName'); - $service = new PageService($this->createMock(ContextMapper::class), $this->pageMapper, $this->pageContentMapper, $this->widgetService, new GridWidgetTypes($this->createMock(IL10N::class)), $this->createMock(IDBConnection::class)); + $service = new PageService($contextMapper, $this->pageMapper, $this->pageContentMapper, $this->widgetService, new GridWidgetTypes($this->createMock(IL10N::class)), $this->createMock(IDBConnection::class)); $this->expectException(NotFoundError::class); $service->create(7, 'Planning', null, null, null); From c6da0296ab8ecfb73dec038e6321285c75577cac Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Wed, 18 Nov 2026 12:58:06 +0100 Subject: [PATCH 10/16] test(api): list the tables widget type Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- tests/unit/Controller/ContextPageControllerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php index e49b8a702f..3bb241bc05 100644 --- a/tests/unit/Controller/ContextPageControllerTest.php +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -107,7 +107,7 @@ public function testABadRequestExplainsWhy(): void { public function testWidgetTypesListsEveryType(): void { $response = $this->controller->widgetTypes(); - $this->assertSame(['header', 'text', 'data'], array_column($response->getData(), 'type')); + $this->assertSame(['header', 'text', 'data', 'tables'], array_column($response->getData(), 'type')); $this->assertSame('{}', json_encode($response->getData()[2]['settings']), 'a type without settings has an empty object'); $this->assertIsArray($response->getData()[0]['settings']); } From 9ede0065577e0f0bb0898fe7f5a150fb1ee45bb9 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Wed, 18 Nov 2026 12:59:09 +0100 Subject: [PATCH 11/16] chore(api): regenerate the OpenAPI spec and TypeScript types Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- openapi.json | 1 - src/types/openapi/openapi.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/openapi.json b/openapi.json index 4a64ba2135..7cec594d37 100644 --- a/openapi.json +++ b/openapi.json @@ -1512,7 +1512,6 @@ "enum": [ "string", "text", - "color", "enum" ] }, diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index f017bb7929..22ac8cdef2 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1603,7 +1603,7 @@ export type components = { }; readonly WidgetSettingSchema: { /** @enum {string} */ - readonly type: "string" | "text" | "color" | "enum"; + readonly type: "string" | "text" | "enum"; readonly title: string; readonly default: components["schemas"]["WidgetValue"]; readonly options?: readonly { From 640d66c8ca62833a71a1375a1ec1dfa8741f105f Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Thu, 19 Nov 2026 14:55:38 +0100 Subject: [PATCH 12/16] fix(api): lock the application first when a page is saved or deleted Page update() and delete() now take the application lock before they raise the page version, as create() already did. Every writer then locks application, page and relations in that order, so a save can no longer leave widgets behind after a concurrent delete of the application, and the two cannot deadlock. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Service/PageService.php | 26 +++++++++++++++++------ tests/unit/Service/PageServiceTest.php | 29 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index 9c99ca482e..fc90842d34 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -31,8 +31,9 @@ * The pages of an application and the widgets on them. The controller checks access to * the application before any call; this class checks that a page belongs to it. * - * Every save raises the version of its page as its first write, which also locks the - * page, so saves and the delete of a page run one after the other. + * Every write first locks the application, so it runs after a delete of the application + * or before it. A save then raises the version of its page, which also locks the page, + * so saves and the delete of a page run one after the other. * * @psalm-import-type TablesPage from ResponseDefinitions * @psalm-import-type TablesWidget from ResponseDefinitions @@ -97,9 +98,7 @@ public function create(int $contextId, string $title, ?string $slug, ?string $ic } $page = $this->save(fn (): Page => $this->atomic(function () use ($contextId, $page): Page { - if (!$this->contextMapper->lock($contextId)) { - throw new NotFoundError('Application ' . $contextId . ' does not exist'); - } + $this->lockApplication($contextId); return $page->getSlug() === null ? $this->pageMapper->insertWithDefaultName($page) : $this->pageMapper->insert($page); }, $this->dbc), $slug); @@ -147,7 +146,8 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu } $renamed = array_key_exists('slug', $page->getUpdatedFields()); - $stored = $this->save(fn (): ?array => $this->atomic(function () use ($page, $pageId, $version, $inputs): ?array { + $stored = $this->save(fn (): ?array => $this->atomic(function () use ($page, $contextId, $pageId, $version, $inputs): ?array { + $this->lockApplication($contextId); if (!$this->pageMapper->raiseVersion($pageId, $version)) { $this->getPage($page->getContextId(), $pageId); throw new ConflictError(self::CHANGED_IN_BETWEEN); @@ -175,6 +175,7 @@ public function delete(int $contextId, int $pageId): array { } $widgets = $this->atomic(function () use ($contextId, $pageId): array { + $this->lockApplication($contextId); if (!$this->pageMapper->raiseVersion($pageId, null)) { throw new NotFoundError('Page ' . $pageId . ' does not belong to application ' . $contextId); } @@ -207,6 +208,19 @@ private function getPage(int $contextId, int $pageId): Page { return $page; } + /** + * Locks the application row until the transaction ends, the first statement of every + * write, so writers take application, page and relations in the same order. + * + * @throws NotFoundError + * @throws Exception + */ + private function lockApplication(int $contextId): void { + if (!$this->contextMapper->lock($contextId)) { + throw new NotFoundError('Application ' . $contextId . ' does not exist'); + } + } + /** * @param list $widgets * @return TablesPage diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index b0494da6a7..0a3a419190 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -172,6 +172,35 @@ public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { $service->create(7, 'Planning', null, null, null); } + public static function writesOfAPage(): array { + return [ + 'update of the fields' => [static fn (PageService $service): array => $service->update(7, self::GRID_PAGE, 'Planning', null, null, null, null, null)], + 'update of the widgets' => [static fn (PageService $service): array => $service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 4)], + 'delete' => [static fn (PageService $service): array => $service->delete(7, self::GRID_PAGE)], + ]; + } + + /** + * @dataProvider writesOfAPage + */ + public function testAWriteToAPageOfAnApplicationThatIsGoneStopsAtTheApplicationLock(\Closure $write): void { + $context = new Context(); + $context->id = 7; + $context->setNodes([]); + $contextMapper = $this->createMock(ContextMapper::class); + $contextMapper->method('findById')->willReturn($context); + $contextMapper->expects($this->once())->method('lock')->with(7)->willReturn(false); + $this->pageMapper->expects($this->never())->method('raiseVersion'); + $this->pageMapper->expects($this->never())->method('update'); + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + $this->widgetService->expects($this->never())->method($this->anything()); + $service = new PageService($contextMapper, $this->pageMapper, $this->pageContentMapper, $this->widgetService, new GridWidgetTypes($this->createMock(IL10N::class)), $this->createMock(IDBConnection::class)); + + $this->expectException(NotFoundError::class); + $this->expectExceptionMessage('Application 7 does not exist'); + $write($service); + } + public static function blankTitles(): array { return [ 'empty' => [''], From 522f12702c7e912dec5363c97f5f6ae2baeb90fc Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Thu, 19 Nov 2026 14:57:16 +0100 Subject: [PATCH 13/16] fix(api): refuse a widget of another page and answer with the stored version Once the version check of a save passed, a widget id that is not on the page, or a source that is not part of the application, cannot come from another save, so it is a 400 that names it instead of a 409. The version in the answer is read on the locked page row inside the transaction, so a save without a version no longer answers with a stale one. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Controller/ContextPageController.php | 2 +- lib/Db/PageMapper.php | 18 ++++++++++++++++++ lib/Service/PageService.php | 12 +++++++----- openapi.json | 2 +- src/types/openapi/openapi.ts | 2 +- .../unit/Service/ContextPagesRoundTripTest.php | 10 ++++++++++ tests/unit/Service/PageServiceTest.php | 15 ++++++++++++--- 7 files changed, 50 insertions(+), 11 deletions(-) diff --git a/lib/Controller/ContextPageController.php b/lib/Controller/ContextPageController.php index 6eb7e9858d..89029257f4 100644 --- a/lib/Controller/ContextPageController.php +++ b/lib/Controller/ContextPageController.php @@ -144,7 +144,7 @@ public function create(int $contextId, string $title, ?string $slug = null, ?str * @return DataResponse|DataResponse * * 200: Page updated - * 400: Invalid page field or widget, or too many widgets + * 400: Invalid page field or widget, a widget id that is not on the page, or too many widgets * 403: No permissions * 404: Not found * 409: The page was saved by someone else since the given version diff --git a/lib/Db/PageMapper.php b/lib/Db/PageMapper.php index 268819727c..fe3b09549d 100644 --- a/lib/Db/PageMapper.php +++ b/lib/Db/PageMapper.php @@ -87,6 +87,24 @@ public function raiseVersion(int $pageId, ?int $expected): bool { return $qb->executeStatement() === 1; } + /** + * @throws DoesNotExistException + * @throws Exception + */ + public function findVersion(int $pageId): int { + $qb = $this->db->getQueryBuilder(); + $qb->select('version') + ->from($this->table) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($pageId, IQueryBuilder::PARAM_INT))); + $result = $qb->executeQuery(); + $version = $result->fetchOne(); + $result->closeCursor(); + if ($version === false) { + throw new DoesNotExistException('Page ' . $pageId . ' does not exist'); + } + return (int)$version; + } + /** * @return int[] */ diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index fc90842d34..93f4a5e1b8 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -153,10 +153,11 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu throw new ConflictError(self::CHANGED_IN_BETWEEN); } $this->pageMapper->update($page); - return $inputs === null ? null : $this->widgetService->syncPage($pageId, $inputs); + $stored = $inputs === null ? null : $this->widgetService->syncPage($pageId, $inputs); + $page->setVersion($this->pageMapper->findVersion($pageId)); + return $stored; }, $this->dbc), $renamed ? (string)$page->getSlug() : null); - $page->setVersion($page->getVersion() + 1); return $this->response($page, $stored ?? $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); } @@ -261,8 +262,9 @@ private function readWidgets(array $widgets, int $contextId): array { /** * Runs a save. A unique index refusing a new slug means the name was - * taken; a widget the save lists that is not on the page means the list was built - * from another state of the page. + * taken. A widget the save lists that is not on the page, or a source that is not + * part of the application, is refused: the version check already ruled out a list + * built from another state of the page. * * @template T * @param callable(): T $save @@ -275,7 +277,7 @@ private function save(callable $save, ?string $newSlug): mixed { try { return $save(); } catch (\InvalidArgumentException $e) { - throw new ConflictError(self::CHANGED_IN_BETWEEN, 0, $e); + throw new BadRequestError($e->getMessage(), 0, $e); } catch (Exception $e) { if ($newSlug === null || $e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { throw $e; diff --git a/openapi.json b/openapi.json index 7cec594d37..eea802e4e8 100644 --- a/openapi.json +++ b/openapi.json @@ -15166,7 +15166,7 @@ } }, "400": { - "description": "Invalid page field or widget, or too many widgets", + "description": "Invalid page field or widget, a widget id that is not on the page, or too many widgets", "content": { "application/json": { "schema": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 22ac8cdef2..4982e44e78 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -8474,7 +8474,7 @@ export interface operations { }; }; }; - /** @description Invalid page field or widget, or too many widgets */ + /** @description Invalid page field or widget, a widget id that is not on the page, or too many widgets */ readonly 400: { headers: { readonly [name: string]: unknown; diff --git a/tests/unit/Service/ContextPagesRoundTripTest.php b/tests/unit/Service/ContextPagesRoundTripTest.php index 3d40dbb6f8..03536ef9f4 100644 --- a/tests/unit/Service/ContextPagesRoundTripTest.php +++ b/tests/unit/Service/ContextPagesRoundTripTest.php @@ -171,6 +171,16 @@ public function testRemovingTheNodeKeepsTheWidgetAndDeletingTheContextRemovesIt( $this->assertSame([], $this->pageMapper->getPageIdsForContext($context->getId())); } + public function testTheVersionOfAPageIsReadAfterEveryRaise(): void { + [, , $gridPageId] = $this->createContextWithGridPage(); + $initial = $this->pageMapper->findById($gridPageId)->getVersion(); + + $this->assertTrue($this->pageMapper->raiseVersion($gridPageId, null)); + $this->assertTrue($this->pageMapper->raiseVersion($gridPageId, null)); + + $this->assertSame($initial + 2, $this->pageMapper->findVersion($gridPageId)); + } + /** * @return array{0: Context, 1: ContextNodeRelation, 2: int} */ diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index 0a3a419190..0aedd750f0 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -243,6 +243,7 @@ public function testTheStartPageCanLoseItsTitleAgain(): void { public function testUpdateSyncsWidgetsAndAnswersWithWhatWasStored(): void { $this->pageMapper->expects($this->once())->method('raiseVersion')->with(self::GRID_PAGE, 4)->willReturn(true); + $this->pageMapper->method('findVersion')->willReturn(5); $stored = [['id' => 31, 'type' => 'text'], ['id' => 32, 'type' => 'data']]; $synced = null; $this->widgetService->expects($this->once())->method('syncPage')->willReturnCallback(function (int $pageId, array $widgets) use (&$synced, $stored): array { @@ -293,15 +294,23 @@ public function testASaveOfAPageDeletedInTheMeantimeIsNotFound(): void { $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 4); } - public function testAWidgetRemovedByAConcurrentSaveIsAConflict(): void { + public function testAWidgetThatIsNotOnThePageIsRefusedByName(): void { $this->pageMapper->method('raiseVersion')->willReturn(true); $this->widgetService->method('syncPage')->willThrowException(new \InvalidArgumentException('Widget 31 is not on page 2')); - $this->expectException(ConflictError::class); - $this->expectExceptionMessage('Load it again and retry'); + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('Widget 31 is not on page 2'); $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget(['id' => 31])], 4); } + public function testASaveAnswersWithTheVersionOfTheLockedRow(): void { + $this->pageMapper->expects($this->once())->method('raiseVersion')->with(self::GRID_PAGE, null)->willReturn(true); + $this->pageMapper->method('findVersion')->with(self::GRID_PAGE)->willReturn(9); + $this->widgetService->method('findByPageIds')->willReturn([]); + + $this->assertSame(9, $this->service->update(7, self::GRID_PAGE, 'Planning', null, null, null, null, null)['version']); + } + public function testUpdateChangesThePageFields(): void { $this->pageMapper->method('raiseVersion')->willReturn(true); $this->widgetService->method('findByPageIds')->willReturn([]); From 67448e4f8fc133f33b36393f5644a6b04a28c9d0 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 20 Nov 2026 10:20:42 +0100 Subject: [PATCH 14/16] fix(contexts): lock the applications first when a table or view leaves them Deleting a table or view, or removing one from an application, locks the rows of the applications that hold it before it touches widgets, page contents or node relations, in ascending id order. A page save and an application delete take the application first too, so they wait for each other instead of deadlocking. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Db/ContextNodeRelationMapper.php | 20 ++++++++ lib/Service/ContextService.php | 28 +++++++++-- tests/unit/Service/ContextServiceTest.php | 58 +++++++++++++++++++++-- 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/lib/Db/ContextNodeRelationMapper.php b/lib/Db/ContextNodeRelationMapper.php index 9817895c43..3dcf3360ba 100644 --- a/lib/Db/ContextNodeRelationMapper.php +++ b/lib/Db/ContextNodeRelationMapper.php @@ -34,6 +34,26 @@ public function deleteAllByContextId(int $contextId): void { $qb->executeStatement(); } + /** + * The ids of the applications that hold a node. + * + * @return list + * @throws Exception + */ + public function getContextIdsForNode(int $nodeId, int $nodeType): array { + $qb = $this->db->getQueryBuilder(); + $qb->selectDistinct('context_id')->from($this->table) + ->where($qb->expr()->eq('node_id', $qb->createNamedParameter($nodeId, IQueryBuilder::PARAM_INT))) + ->andWhere($qb->expr()->eq('node_type', $qb->createNamedParameter($nodeType, IQueryBuilder::PARAM_INT))); + $result = $qb->executeQuery(); + $contextIds = []; + while ($row = $result->fetchAssociative()) { + $contextIds[] = (int)$row['context_id']; + } + $result->closeCursor(); + return $contextIds; + } + public function getRelIdsForNode(int $nodeId, int $nodeType): array { $qb = $this->db->getQueryBuilder(); $qb->select('id')->from($this->table) diff --git a/lib/Service/ContextService.php b/lib/Service/ContextService.php index 368a6cbbd2..afb09a756c 100644 --- a/lib/Service/ContextService.php +++ b/lib/Service/ContextService.php @@ -380,8 +380,9 @@ public function delete(int $contextId, string $userId): Context { public function deleteNodeRel(int $nodeId, int $nodeType): void { try { - $nodeRelIds = $this->contextNodeRelMapper->getRelIdsForNode($nodeId, $nodeType); - $this->atomic(function () use ($nodeRelIds): void { + $this->atomic(function () use ($nodeId, $nodeType): void { + $this->lockContexts($this->contextNodeRelMapper->getContextIdsForNode($nodeId, $nodeType)); + $nodeRelIds = $this->contextNodeRelMapper->getRelIdsForNode($nodeId, $nodeType); $this->widgetService->deleteSourcesByNodeRelIds($nodeRelIds); $this->pageContentMapper->deleteByNodeRelIds($nodeRelIds); $this->contextNodeRelMapper->deleteByNodeRelIds($nodeRelIds); @@ -479,15 +480,34 @@ public function addNodeToContextAndStartpage(int $contextId, int $nodeId, int $n */ public function removeNodeFromContextAndPages(int $nodeRelationId): array { return $this->atomic(function () use ($nodeRelationId): array { - // the order of deleteNodeRel(): sources, contents, relation + // the order of deleteNodeRel(): application, sources, contents, relation + $nodeRelation = $this->contextNodeRelMapper->findById($nodeRelationId); + $this->lockContexts([$nodeRelation->getContextId()]); $this->widgetService->deleteSourcesByNodeRelIds([$nodeRelationId]); $contents = $this->pageContentMapper->findByNodeRelation($nodeRelationId); $this->pageContentMapper->deleteByNodeRelIds([$nodeRelationId]); - $nodeRelation = $this->removeNodeFromContextById($nodeRelationId); + $nodeRelation = $this->removeNodeFromContext($nodeRelation); return [$nodeRelation, $contents]; }, $this->dbc); } + /** + * Locks application rows until the transaction ends, in ascending id order. A write + * that removes tables or views from applications takes them before it touches widgets, + * contents or relations, the order of a page save and of an application delete, so + * neither waits for the other while holding what the other needs. + * + * @param list $contextIds + * @throws Exception + */ + private function lockContexts(array $contextIds): void { + $contextIds = array_values(array_unique($contextIds)); + sort($contextIds); + foreach ($contextIds as $contextId) { + $this->contextMapper->lock($contextId); + } + } + /** * @throws Exception */ diff --git a/tests/unit/Service/ContextServiceTest.php b/tests/unit/Service/ContextServiceTest.php index 1e2b89ecec..c195972bb6 100644 --- a/tests/unit/Service/ContextServiceTest.php +++ b/tests/unit/Service/ContextServiceTest.php @@ -46,6 +46,8 @@ final class ContextServiceTest extends TestCase { private MockObject $userManager; private MockObject $auditLogService; private bool $contextExists = true; + /** @var list the writes of a test in the order they ran */ + private array $calls = []; private MockObject $widgetService; private MockObject $dbConnection; @@ -53,7 +55,10 @@ protected function setUp(): void { parent::setUp(); $this->contextMapper = $this->createMock(ContextMapper::class); - $this->contextMapper->method('lock')->willReturnCallback(fn (): bool => $this->contextExists); + $this->contextMapper->method('lock')->willReturnCallback(function (int $contextId): bool { + $this->calls[] = 'lock ' . $contextId; + return $this->contextExists; + }); $this->contextNodeRelMapper = $this->createMock(ContextNodeRelationMapper::class); $this->pageMapper = $this->createMock(PageMapper::class); $this->pageContentMapper = $this->createMock(PageContentMapper::class); @@ -288,6 +293,7 @@ public function testUpdateLogsRemovedNodes(): void { $this->contextMapper->method('update')->willReturnArgument(0); $nodeRelation = new ContextNodeRelation(); $nodeRelation->id = 101; + $nodeRelation->setContextId(7); $this->contextNodeRelMapper->method('findById')->with(101)->willReturn($nodeRelation); $this->contextNodeRelMapper->method('delete')->willReturnArgument(0); $this->pageContentMapper->method('findByNodeRelation')->willReturn([]); @@ -509,13 +515,59 @@ public function testDeletingANodeUnlinksItsWidgets(): void { } public function testAFailedNodeRemovalRollsBackTheDeletedSources(): void { - $this->contextNodeRelMapper->method('findById')->willThrowException(new \OCP\AppFramework\Db\DoesNotExistException('gone')); + $nodeRelation = new ContextNodeRelation(); + $nodeRelation->id = 101; + $nodeRelation->setContextId(7); + $this->contextNodeRelMapper->method('findById')->willReturn($nodeRelation); + $this->contextNodeRelMapper->method('delete')->willThrowException(new Exception('gone')); $this->widgetService->expects($this->once())->method('deleteSourcesByNodeRelIds')->with([101]); $this->dbConnection->expects($this->once())->method('rollBack'); $this->dbConnection->expects($this->never())->method('commit'); - $this->expectException(\OCP\AppFramework\Db\DoesNotExistException::class); + $this->expectException(Exception::class); + $this->service->removeNodeFromContextAndPages(101); + } + + public function testDeletingANodeLocksItsApplicationsInAscendingOrderFirst(): void { + $this->contextNodeRelMapper->method('getContextIdsForNode')->with(11, 0)->willReturn([9, 3, 9]); + $this->contextNodeRelMapper->method('getRelIdsForNode')->willReturnCallback(function (): array { + $this->calls[] = 'read relations'; + return [101, 102]; + }); + $this->recordNodeRemoval(); + $this->contextNodeRelMapper->method('deleteByNodeRelIds')->willReturnCallback(function (): void { + $this->calls[] = 'relations'; + }); + + $this->service->deleteNodeRel(11, 0); + + $this->assertSame(['lock 3', 'lock 9', 'read relations', 'sources', 'contents', 'relations'], $this->calls); + } + + public function testRemovingANodeFromAnApplicationLocksTheApplicationFirst(): void { + $nodeRelation = new ContextNodeRelation(); + $nodeRelation->id = 101; + $nodeRelation->setContextId(7); + $this->contextNodeRelMapper->method('findById')->with(101)->willReturn($nodeRelation); + $this->pageContentMapper->method('findByNodeRelation')->willReturn([]); + $this->recordNodeRemoval(); + $this->contextNodeRelMapper->method('delete')->willReturnCallback(function (ContextNodeRelation $relation): ContextNodeRelation { + $this->calls[] = 'relations'; + return $relation; + }); + $this->service->removeNodeFromContextAndPages(101); + + $this->assertSame(['lock 7', 'sources', 'contents', 'relations'], $this->calls); + } + + private function recordNodeRemoval(): void { + $this->widgetService->method('deleteSourcesByNodeRelIds')->willReturnCallback(function (): void { + $this->calls[] = 'sources'; + }); + $this->pageContentMapper->method('deleteByNodeRelIds')->willReturnCallback(function (): void { + $this->calls[] = 'contents'; + }); } public function testImportContextRemapsSourcesAndSkipsInvalidWidgets(): void { From 0fe78d97ae4ecb792ccdd3bceb4232c3caeb904e Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 20 Nov 2026 10:21:49 +0100 Subject: [PATCH 15/16] fix(api): keep the slug of a page and add a grid page with createGridPage A page takes its slug when it is added and keeps it: a save that names another slug is refused with 400, the current slug is accepted. The create endpoint and service method are named createGridPage, as they add a grid page only; the route stays POST /pages. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- lib/Controller/ContextPageController.php | 10 +++---- lib/Service/PageService.php | 16 +++++----- .../Controller/ContextPageControllerTest.php | 4 +-- tests/unit/Service/PageServiceTest.php | 30 ++++++++++--------- 4 files changed, 31 insertions(+), 29 deletions(-) diff --git a/lib/Controller/ContextPageController.php b/lib/Controller/ContextPageController.php index 89029257f4..08bb027b13 100644 --- a/lib/Controller/ContextPageController.php +++ b/lib/Controller/ContextPageController.php @@ -95,7 +95,7 @@ public function showBySlug(int $contextId, string $slug): DataResponse { * * @param int $contextId ID of the application * @param string $title Title of the page - * @param string|null $slug Slug of the page, unique in the application; `page_` when left out, a form reserved for automatic names + * @param string|null $slug Slug of the page, unique in the application and never changed; `page_` when left out, a form reserved for automatic names * @param string|null $icon Name of the icon shown with the title * @param string|null $description Description of the page * @return DataResponse|DataResponse @@ -109,9 +109,9 @@ public function showBySlug(int $contextId, string $slug): DataResponse { #[UserRateLimit(limit: 20, period: 60)] #[RequirePermission(permission: Application::PERMISSION_MANAGE, typeParam: 'context', idParam: 'contextId')] #[ApiRoute(verb: 'POST', url: '/api/2/contexts/{contextId}/pages', requirements: ['contextId' => '\d+'])] - public function create(int $contextId, string $title, ?string $slug = null, ?string $icon = null, ?string $description = null): DataResponse { + public function createGridPage(int $contextId, string $title, ?string $slug = null, ?string $icon = null, ?string $description = null): DataResponse { try { - return new DataResponse($this->pageService->create($contextId, $title, $slug, $icon, $description)); + return new DataResponse($this->pageService->createGridPage($contextId, $title, $slug, $icon, $description)); } catch (BadRequestError $e) { return $this->handleBadRequestError($e); } catch (NotFoundError $e) { @@ -136,7 +136,7 @@ public function create(int $contextId, string $title, ?string $slug = null, ?str * @param int $contextId ID of the application * @param int $pageId ID of the page * @param string|null $title New title - * @param string|null $slug New slug + * @param string|null $slug Slug of the page; it never changes, so only the current slug is accepted * @param string|null $icon New icon name, empty to remove it * @param string|null $description New description, empty to remove it * @param list|null $widgets All widgets of the page @@ -144,7 +144,7 @@ public function create(int $contextId, string $title, ?string $slug = null, ?str * @return DataResponse|DataResponse * * 200: Page updated - * 400: Invalid page field or widget, a widget id that is not on the page, or too many widgets + * 400: Invalid page field or widget, a slug other than the one of the page, a widget id that is not on the page, or too many widgets * 403: No permissions * 404: Not found * 409: The page was saved by someone else since the given version diff --git a/lib/Service/PageService.php b/lib/Service/PageService.php index 93f4a5e1b8..29e7347ba8 100644 --- a/lib/Service/PageService.php +++ b/lib/Service/PageService.php @@ -79,14 +79,14 @@ public function findBySlug(int $contextId, string $slug): array { /** * Adds a grid page to an application. Without a slug the page is named - * `page_`; a given slug that is taken is refused. + * `page_`; a given slug that is taken is refused. The slug never changes. * * @return TablesPage * @throws BadRequestError * @throws NotFoundError * @throws Exception */ - public function create(int $contextId, string $title, ?string $slug, ?string $icon, ?string $description): array { + public function createGridPage(int $contextId, string $title, ?string $slug, ?string $icon, ?string $description): array { $page = new Page(); $page->setContextId($contextId); $page->setPageType(Page::TYPE_GRID); @@ -94,7 +94,7 @@ public function create(int $contextId, string $title, ?string $slug, ?string $ic $page->setIcon($this->validateIcon($icon)); $page->setDescription($this->validateDescription($description)); if ($slug !== null) { - $page->setSlug($this->validateSlug($slug, null)); + $page->setSlug($this->validateSlug($slug)); } $page = $this->save(fn (): Page => $this->atomic(function () use ($contextId, $page): Page { @@ -110,6 +110,7 @@ public function create(int $contextId, string $title, ?string $slug, ?string $ic * them in one transaction. A null argument keeps the current value; an empty icon * or description removes it, and so does an empty title of the start page. A * widget's `source` is `{nodeRelId}` of a table or view of this application, or null. + * A slug other than the one of the page is refused. * * A save with widgets names the version of the page it was based on, and is refused * when another save raised it since. @@ -128,7 +129,7 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu $page->setTitle($this->validateTitle($title, $page->getPageType())); } if ($slug !== null && $slug !== $page->getSlug()) { - $page->setSlug($this->validateSlug($slug, $pageId)); + throw new BadRequestError('The slug of a page cannot be changed.'); } if ($icon !== null) { $page->setIcon($this->validateIcon($icon)); @@ -145,7 +146,6 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu $inputs = $this->readWidgets($widgets, $contextId); } - $renamed = array_key_exists('slug', $page->getUpdatedFields()); $stored = $this->save(fn (): ?array => $this->atomic(function () use ($page, $contextId, $pageId, $version, $inputs): ?array { $this->lockApplication($contextId); if (!$this->pageMapper->raiseVersion($pageId, $version)) { @@ -156,7 +156,7 @@ public function update(int $contextId, int $pageId, ?string $title, ?string $slu $stored = $inputs === null ? null : $this->widgetService->syncPage($pageId, $inputs); $page->setVersion($this->pageMapper->findVersion($pageId)); return $stored; - }, $this->dbc), $renamed ? (string)$page->getSlug() : null); + }, $this->dbc), null); return $this->response($page, $stored ?? $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); } @@ -307,11 +307,11 @@ private function validateTitle(string $title, string $pageType): ?string { /** * @throws BadRequestError */ - private function validateSlug(string $slug, ?int $pageId): string { + private function validateSlug(string $slug): string { if (!TechnicalNameValidator::isValid($slug)) { throw new BadRequestError('A slug has 1 to ' . TechnicalNameValidator::MAX_LENGTH . ' lower case letters, digits and underscores and starts with a letter.'); } - if (Page::isDefaultSlug($slug) && $slug !== Page::DEFAULT_SLUG_PREFIX . $pageId) { + if (Page::isDefaultSlug($slug)) { throw new BadRequestError('The slug ' . $slug . ' is reserved for automatic names.'); } return $slug; diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php index 3bb241bc05..26246d3d6c 100644 --- a/tests/unit/Controller/ContextPageControllerTest.php +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -50,8 +50,8 @@ public static function endpoints(): array { return [ 'show' => ['find', [7, 2], static fn (ContextPageController $controller) => $controller->show(7, 2)], 'show by name' => ['findBySlug', [7, 'overview'], static fn (ContextPageController $controller) => $controller->showBySlug(7, 'overview')], - 'create' => ['create', [7, 'Overview', 'overview', 'star', 'At a glance'], static fn (ContextPageController $controller) => $controller->create(7, 'Overview', 'overview', 'star', 'At a glance')], - 'update' => ['update', [7, 2, null, 'planning', '', null, $widgets, 4], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'planning', '', null, $widgets, 4)], + 'create' => ['createGridPage', [7, 'Overview', 'overview', 'star', 'At a glance'], static fn (ContextPageController $controller) => $controller->createGridPage(7, 'Overview', 'overview', 'star', 'At a glance')], + 'update' => ['update', [7, 2, null, 'overview', '', null, $widgets, 4], static fn (ContextPageController $controller) => $controller->update(7, 2, null, 'overview', '', null, $widgets, 4)], 'destroy' => ['delete', [7, 2], static fn (ContextPageController $controller) => $controller->destroy(7, 2)], ]; } diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php index 0aedd750f0..ec897f9b71 100644 --- a/tests/unit/Service/PageServiceTest.php +++ b/tests/unit/Service/PageServiceTest.php @@ -139,7 +139,7 @@ public function testCreateInsertsAGridPageNamedByItsId(): void { return $page; }); - $page = $this->service->create(7, ' Planning ', null, 'star', ' Next steps '); + $page = $this->service->createGridPage(7, ' Planning ', null, 'star', ' Next steps '); $this->assertSame([9, Page::TYPE_GRID, 'page_9', 'Planning', 'star', 'Next steps', []], [ $page['id'], $page['pageType'], $page['slug'], $page['title'], $page['icon'], $page['description'], $page['widgets'], @@ -155,10 +155,10 @@ public function testCreateKeepsAGivenSlugAndReportsATakenOne(): void { return $page; }); - $this->assertSame('planning', $this->service->create(7, 'Planning', 'planning', null, null)['slug']); + $this->assertSame('planning', $this->service->createGridPage(7, 'Planning', 'planning', null, null)['slug']); $this->expectException(BadRequestError::class); $this->expectExceptionMessage('The slug taken is already used'); - $this->service->create(7, 'Planning', 'taken', null, null); + $this->service->createGridPage(7, 'Planning', 'taken', null, null); } public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { @@ -169,7 +169,7 @@ public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { $service = new PageService($contextMapper, $this->pageMapper, $this->pageContentMapper, $this->widgetService, new GridWidgetTypes($this->createMock(IL10N::class)), $this->createMock(IDBConnection::class)); $this->expectException(NotFoundError::class); - $service->create(7, 'Planning', null, null, null); + $service->createGridPage(7, 'Planning', null, null, null); } public static function writesOfAPage(): array { @@ -216,7 +216,7 @@ public static function blankTitles(): array { public function testAGridPageNeedsATitle(string $title): void { $this->pageMapper->expects($this->never())->method('raiseVersion'); try { - $this->service->create(7, $title, null, null, null); + $this->service->createGridPage(7, $title, null, null, null); $this->fail('A page was created without a title.'); } catch (BadRequestError $e) { $this->assertStringContainsString('A page title needs 1 to 200 characters', $e->getMessage()); @@ -320,18 +320,18 @@ public function testUpdateChangesThePageFields(): void { return $page; }); - $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', 'star', 'Next steps', null, null); + $this->service->update(7, self::GRID_PAGE, 'Planning', 'overview', 'star', 'Next steps', null, null); - $this->assertSame(['Planning', 'planning', 'star', 'Next steps'], $updated); + $this->assertSame(['Planning', 'overview', 'star', 'Next steps'], $updated); } - public function testARenameToANameAConcurrentSaveTookIsReported(): void { - $this->pageMapper->method('raiseVersion')->willReturn(true); - $this->pageMapper->method('update')->willThrowException(DbErrorStub::uniqueViolation()); + public function testTheSlugOfAPageCannotChange(): void { + $this->pageMapper->expects($this->never())->method('raiseVersion'); + $this->pageMapper->expects($this->never())->method('update'); $this->expectException(BadRequestError::class); - $this->expectExceptionMessage('The slug planning is already used'); - $this->service->update(7, self::GRID_PAGE, null, 'planning', null, null, null, null); + $this->expectExceptionMessage('The slug of a page cannot be changed.'); + $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', null, null, null, null); } public function testAUniqueViolationWithoutARenameIsNotTakenForOne(): void { @@ -345,7 +345,7 @@ public function testAUniqueViolationWithoutARenameIsNotTakenForOne(): void { public static function refusedSlugs(): array { return [ 'upper case' => ['Planning', 'A slug has 1 to 200 lower case letters'], - 'reserved for another page' => ['page_5', 'The slug page_5 is reserved'], + 'reserved for automatic names' => ['page_5', 'The slug page_5 is reserved'], ]; } @@ -353,9 +353,11 @@ public static function refusedSlugs(): array { * @dataProvider refusedSlugs */ public function testAnInvalidSlugIsRefused(string $slug, string $message): void { + $this->pageMapper->expects($this->never())->method('insert'); + $this->expectException(BadRequestError::class); $this->expectExceptionMessage($message); - $this->service->update(7, self::GRID_PAGE, null, $slug, null, null, null, null); + $this->service->createGridPage(7, 'Planning', $slug, null, null); } public function testAPageKeepsItsOwnAutomaticName(): void { From aa360a501c645710bf90240c47090c6c36df47fe Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 20 Nov 2026 10:21:49 +0100 Subject: [PATCH 16/16] chore(api): regenerate the OpenAPI spec and TypeScript types Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: Ruben van der Linde --- openapi.json | 31 +++++++++++++++++-------------- src/types/openapi/openapi.ts | 31 ++++++++++++++++--------------- 2 files changed, 33 insertions(+), 29 deletions(-) diff --git a/openapi.json b/openapi.json index eea802e4e8..9fcb2b17d7 100644 --- a/openapi.json +++ b/openapi.json @@ -469,7 +469,7 @@ "id", "contextId", "pageType", - "technicalName", + "slug", "title", "icon", "description", @@ -488,7 +488,7 @@ "pageType": { "type": "string" }, - "technicalName": { + "slug": { "type": "string" }, "title": { @@ -1541,6 +1541,9 @@ }, "required": { "type": "boolean" + }, + "hint": { + "type": "string" } } }, @@ -15063,11 +15066,11 @@ "default": null, "description": "New title" }, - "technicalName": { + "slug": { "type": "string", "nullable": true, "default": null, - "description": "New technical name" + "description": "Slug of the page; it never changes, so only the current slug is accepted" }, "icon": { "type": "string", @@ -15166,7 +15169,7 @@ } }, "400": { - "description": "Invalid page field or widget, a widget id that is not on the page, or too many widgets", + "description": "Invalid page field or widget, a slug other than the one of the page, a widget id that is not on the page, or too many widgets", "content": { "application/json": { "schema": { @@ -16265,10 +16268,10 @@ } } }, - "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{technicalName}": { + "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{slug}": { "get": { - "operationId": "context_page-show-by-technical-name", - "summary": "[api v2] Get a page of an application by its technical name", + "operationId": "context_page-show-by-slug", + "summary": "[api v2] Get a page of an application by its slug", "tags": [ "context_page" ], @@ -16292,9 +16295,9 @@ } }, { - "name": "technicalName", + "name": "slug", "in": "path", - "description": "Technical name of the page", + "description": "Slug of the page", "required": true, "schema": { "type": "string", @@ -16452,7 +16455,7 @@ }, "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages": { "post": { - "operationId": "context_page-create", + "operationId": "context_page-create-grid-page", "summary": "[api v2] Add a grid page to an application", "tags": [ "context_page" @@ -16479,11 +16482,11 @@ "type": "string", "description": "Title of the page" }, - "technicalName": { + "slug": { "type": "string", "nullable": true, "default": null, - "description": "Technical name of the page, unique in the application; `page_` when left out, a form reserved for automatic names" + "description": "Slug of the page, unique in the application and never changed; `page_` when left out, a form reserved for automatic names" }, "icon": { "type": "string", @@ -16556,7 +16559,7 @@ } }, "400": { - "description": "Invalid title, icon or description, or an invalid or taken technical name", + "description": "Invalid title, icon or description, or an invalid or taken slug", "content": { "application/json": { "schema": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 4982e44e78..feeea04136 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1031,15 +1031,15 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; - readonly "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{technicalName}": { + readonly "/ocs/v2.php/apps/tables/api/2/contexts/{contextId}/pages/{slug}": { readonly parameters: { readonly query?: never; readonly header?: never; readonly path?: never; readonly cookie?: never; }; - /** [api v2] Get a page of an application by its technical name */ - readonly get: operations["context_page-show-by-technical-name"]; + /** [api v2] Get a page of an application by its slug */ + readonly get: operations["context_page-show-by-slug"]; readonly put?: never; readonly post?: never; readonly delete?: never; @@ -1058,7 +1058,7 @@ export type paths = { readonly get?: never; readonly put?: never; /** [api v2] Add a grid page to an application */ - readonly post: operations["context_page-create"]; + readonly post: operations["context_page-create-grid-page"]; readonly delete?: never; readonly options?: never; readonly head?: never; @@ -1314,7 +1314,7 @@ export type components = { /** Format: int64 */ readonly contextId: number; readonly pageType: string; - readonly technicalName: string; + readonly slug: string; readonly title: string | null; readonly icon: string | null; readonly description: string | null; @@ -1611,6 +1611,7 @@ export type components = { readonly label: string; }[]; readonly required?: boolean; + readonly hint?: string; }; readonly WidgetType: { readonly type: string; @@ -8431,10 +8432,10 @@ export interface operations { */ readonly title?: string | null; /** - * @description New technical name + * @description Slug of the page; it never changes, so only the current slug is accepted * @default null */ - readonly technicalName?: string | null; + readonly slug?: string | null; /** * @description New icon name, empty to remove it * @default null @@ -8474,7 +8475,7 @@ export interface operations { }; }; }; - /** @description Invalid page field or widget, a widget id that is not on the page, or too many widgets */ + /** @description Invalid page field or widget, a slug other than the one of the page, a widget id that is not on the page, or too many widgets */ readonly 400: { headers: { readonly [name: string]: unknown; @@ -8838,7 +8839,7 @@ export interface operations { }; }; }; - readonly "context_page-show-by-technical-name": { + readonly "context_page-show-by-slug": { readonly parameters: { readonly query?: never; readonly header: { @@ -8848,8 +8849,8 @@ export interface operations { readonly path: { /** @description ID of the application */ readonly contextId: number; - /** @description Technical name of the page */ - readonly technicalName: string; + /** @description Slug of the page */ + readonly slug: string; }; readonly cookie?: never; }; @@ -8916,7 +8917,7 @@ export interface operations { }; }; }; - readonly "context_page-create": { + readonly "context_page-create-grid-page": { readonly parameters: { readonly query?: never; readonly header: { @@ -8935,10 +8936,10 @@ export interface operations { /** @description Title of the page */ readonly title: string; /** - * @description Technical name of the page, unique in the application; `page_` when left out, a form reserved for automatic names + * @description Slug of the page, unique in the application and never changed; `page_` when left out, a form reserved for automatic names * @default null */ - readonly technicalName?: string | null; + readonly slug?: string | null; /** * @description Name of the icon shown with the title * @default null @@ -8967,7 +8968,7 @@ export interface operations { }; }; }; - /** @description Invalid title, icon or description, or an invalid or taken technical name */ + /** @description Invalid title, icon or description, or an invalid or taken slug */ readonly 400: { headers: { readonly [name: string]: unknown;