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 new file mode 100644 index 0000000000..08bb027b13 --- /dev/null +++ b/lib/Controller/ContextPageController.php @@ -0,0 +1,218 @@ +|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)); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($e); + } catch (Exception $e) { + return $this->handleError($e); + } + } + + /** + * [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)); + } 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 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 + * + * 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 createGridPage(int $contextId, string $title, ?string $slug = null, ?string $icon = null, ?string $description = null): DataResponse { + try { + return new DataResponse($this->pageService->createGridPage($contextId, $title, $slug, $icon, $description)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($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 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 + * @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, 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 + */ + #[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, ?int $version = null): DataResponse { + try { + return new DataResponse($this->pageService->update($contextId, $pageId, $title, $slug, $icon, $description, $widgets, $version)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($e); + } catch (ConflictError $e) { + return $this->handleConflictError($e); + } catch (NotFoundError $e) { + return $this->handleNotFoundError($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] + #[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)); + } catch (BadRequestError $e) { + return $this->handleBadRequestError($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 { + // 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/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/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 a612e76130..fe3b09549d 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,72 @@ 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); + } + + /** + * @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; + } + + /** + * @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/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 @@ +, + * required?: bool, + * hint?: string, + * } + * + * @psalm-type TablesWidgetType = array{ + * type: string, + * title: string, + * defaultWidth: int, + * defaultHeight: int, + * hasSource: bool, + * 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{ + * 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, + * version: int, + * widgets: list, + * } + * * @psalm-type TablesContextNavigation = array{ * id: int, * shareId: int, diff --git a/lib/Service/ContextService.php b/lib/Service/ContextService.php index f54228335c..afb09a756c 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'); } @@ -379,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); @@ -478,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 */ @@ -871,7 +892,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..7006d12001 100644 --- a/lib/Service/GridWidgetTypes.php +++ b/lib/Service/GridWidgetTypes.php @@ -14,6 +14,7 @@ use OCA\Tables\Helper\IconHelper; use OCA\Tables\Helper\TextHelper; use OCA\Tables\Model\WidgetInput; +use OCA\Tables\ResponseDefinitions; use OCP\IL10N; /** @@ -21,23 +22,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 +119,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 +145,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..29e7347ba8 --- /dev/null +++ b/lib/Service/PageService.php @@ -0,0 +1,346 @@ +getPage($contextId, $pageId); + return $this->response($page, $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); + } + + /** + * @return TablesPage + * @throws NotFoundError + * @throws Exception + */ + 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); + } + return $this->response($page, $this->widgetService->findByPageIds([$page->getId()])[$page->getId()] ?? []); + } + + /** + * Adds a grid page to an application. Without a slug the page is named + * `page_`; a given slug that is taken is refused. The slug never changes. + * + * @return TablesPage + * @throws BadRequestError + * @throws NotFoundError + * @throws Exception + */ + 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); + $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)); + } + + $page = $this->save(fn (): Page => $this->atomic(function () use ($contextId, $page): Page { + $this->lockApplication($contextId); + 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, 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. + * + * @param list|null $widgets + * @return TablesPage + * @throws BadRequestError + * @throws ConflictError + * @throws NotFoundError + * @throws Exception + */ + 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->getPageType())); + } + if ($slug !== null && $slug !== $page->getSlug()) { + throw new BadRequestError('The slug of a page cannot be changed.'); + } + if ($icon !== null) { + $page->setIcon($this->validateIcon($icon)); + } + if ($description !== null) { + $page->setDescription($this->validateDescription($description)); + } + + $inputs = null; + if ($widgets !== null) { + if ($version === null) { + throw new BadRequestError('A save of the widgets of a page names the version of the page it is based on.'); + } + $inputs = $this->readWidgets($widgets, $contextId); + } + + $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); + } + $this->pageMapper->update($page); + $stored = $inputs === null ? null : $this->widgetService->syncPage($pageId, $inputs); + $page->setVersion($this->pageMapper->findVersion($pageId)); + return $stored; + }, $this->dbc), null); + + return $this->response($page, $stored ?? $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []); + } + + /** + * Deletes a page with its widgets. The start page cannot be deleted. + * + * @return TablesPage the deleted page + * @throws BadRequestError + * @throws NotFoundError + * @throws Exception + */ + 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.'); + } + + $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); + } + $widgets = $this->widgetService->findByPageIds([$pageId])[$pageId] ?? []; + $this->widgetService->deleteByPageIds([$pageId]); + $this->pageContentMapper->deleteByPageId($pageId); + $this->pageMapper->deleteByPageId($pageId); + return $widgets; + }, $this->dbc); + + return $this->response($page, $widgets); + } + + /** + * @throws NotFoundError + * @throws Exception + */ + 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 $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 + */ + 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, 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.'); + } + $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($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; + } + 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.'); + } + $inputs[] = $input; + } + return $inputs; + } + + /** + * 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, 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 + * @return T + * @throws BadRequestError + * @throws ConflictError + * @throws Exception + */ + private function save(callable $save, ?string $newSlug): mixed { + try { + return $save(); + } catch (\InvalidArgumentException $e) { + throw new BadRequestError($e->getMessage(), 0, $e); + } catch (Exception $e) { + if ($newSlug === null || $e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + throw $e; + } + throw new BadRequestError('The slug ' . $newSlug . ' is already used by a page of this application.', 0, $e); + } + } + + /** + * 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 + */ + private function validateTitle(string $title, string $pageType): ?string { + try { + $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): 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)) { + throw new BadRequestError('The slug ' . $slug . ' is reserved for automatic names.'); + } + return $slug; + } + + /** + * A named icon, or null for an empty one. + * + * @throws BadRequestError + */ + private function validateIcon(?string $icon): ?string { + $icon = trim((string)$icon); + if ($icon === '') { + return null; + } + if (!IconHelper::isValid($icon)) { + throw new BadRequestError('A page has an unknown icon: ' . $icon); + } + return $icon; + } + + /** + * @throws BadRequestError + */ + private function validateDescription(?string $description): ?string { + 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.'); + } + } +} diff --git a/lib/Service/WidgetService.php b/lib/Service/WidgetService.php index 22453bc32d..105c4b1fef 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 { @@ -54,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, ]; } @@ -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 @@ -95,13 +104,14 @@ private function insertWidget(int $pageId, WidgetInput $input): Widget { * 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; @@ -129,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 616e897e24..9fcb2b17d7 100644 --- a/openapi.json +++ b/openapi.json @@ -463,6 +463,58 @@ } } }, + "Page": { + "type": "object", + "required": [ + "id", + "contextId", + "pageType", + "slug", + "title", + "icon", + "description", + "version", + "widgets" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "contextId": { + "type": "integer", + "format": "int64" + }, + "pageType": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "title": { + "type": "string", + "nullable": true + }, + "icon": { + "type": "string", + "nullable": true + }, + "description": { + "type": "string", + "nullable": true + }, + "version": { + "type": "integer", + "format": "int64" + }, + "widgets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Widget" + } + } + } + }, "PublicColumn": { "type": "object", "required": [ @@ -1312,6 +1364,227 @@ "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" + } + } + } + } + }, + "WidgetInput": { + "type": "object", + "required": [ + "type", + "gridX", + "gridY", + "gridWidth", + "gridHeight" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "icon": { + "type": "string" + }, + "description": { + "type": "string" + }, + "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", + "required": [ + "nodeRelId" + ], + "properties": { + "nodeRelId": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "WidgetSettingSchema": { + "type": "object", + "required": [ + "type", + "title", + "default" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "text", + "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" + }, + "hint": { + "type": "string" + } + } + }, + "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": { + "type": "string" } } }, @@ -14581,14 +14854,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 +14871,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 +14903,7 @@ ], "responses": { "200": { - "description": "Table config returned", + "description": "Page returned", "content": { "application/json": { "schema": { @@ -14642,7 +14923,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/NotifyConfig" + "$ref": "#/components/schemas/Page" } } } @@ -14651,8 +14932,8 @@ } } }, - "401": { - "description": "Current user is not logged in", + "500": { + "description": "", "content": { "application/json": { "schema": { @@ -14671,57 +14952,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,7 +14991,15 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/NotifyConfig" + "type": "object", + "required": [ + "message" + ], + "properties": { + "message": { + "type": "string" + } + } } } } @@ -14779,14 +15037,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 +15054,51 @@ } ], "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" + }, + "slug": { + "type": "string", + "nullable": true, + "default": null, + "description": "Slug of the page; it never changes, so only the current slug is accepted" + }, + "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": { + "$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" } } } @@ -14817,12 +15107,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 +15139,7 @@ ], "responses": { "200": { - "description": "Config updated", + "description": "Page updated", "content": { "application/json": { "schema": { @@ -14858,7 +15159,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "type": "boolean" + "$ref": "#/components/schemas/Page" } } } @@ -14868,7 +15169,7 @@ } }, "400": { - "description": "bad request", + "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": { @@ -14943,6 +15244,120 @@ } } }, + "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" + } + } + } + } + } + } + } + } + } + }, + "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": { + "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 +15387,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 +15405,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 +15437,7 @@ ], "responses": { "200": { - "description": "Columns are returned", + "description": "Page deleted", "content": { "application/json": { "schema": { @@ -15035,10 +15457,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PublicColumn" - } + "$ref": "#/components/schemas/Page" } } } @@ -15047,8 +15466,8 @@ } } }, - "403": { - "description": "No permissions", + "400": { + "description": "The page is the start page", "content": { "application/json": { "schema": { @@ -15085,8 +15504,8 @@ } } }, - "400": { - "description": "Invalid request parameters", + "403": { + "description": "No permissions", "content": { "application/json": { "schema": { @@ -15162,7 +15581,7 @@ } }, "500": { - "description": "Internal error", + "description": "", "content": { "application/json": { "schema": { @@ -15198,6 +15617,1219 @@ } } } + }, + "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/{slug}": { + "get": { + "operationId": "context_page-show-by-slug", + "summary": "[api v2] Get a page of an application by its slug", + "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": "slug", + "in": "path", + "description": "Slug 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-grid-page", + "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" + }, + "slug": { + "type": "string", + "nullable": true, + "default": null, + "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", + "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 slug", + "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..feeea04136 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,60 @@ export type paths = { readonly patch?: never; readonly trace?: never; }; + 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 slug */ + readonly get: operations["context_page-show-by-slug"]; + 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; + 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-grid-page"]; + 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 +1308,20 @@ 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 slug: string; + 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: { /** Format: int64 */ readonly id: number; @@ -1477,6 +1555,77 @@ 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 WidgetInput: { + /** Format: int64 */ + readonly id?: number; + readonly type: string; + readonly title?: string; + readonly icon?: string; + readonly description?: string; + /** 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; + }; + }; + readonly WidgetSettingSchema: { + /** @enum {string} */ + readonly type: "string" | "text" | "enum"; + readonly title: string; + readonly default: components["schemas"]["WidgetValue"]; + readonly options?: readonly { + readonly value: string; + readonly label: string; + }[]; + readonly required?: boolean; + readonly hint?: string; + }; + 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; }; responses: never; parameters: never; @@ -7949,6 +8098,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 +8298,7 @@ export interface operations { }; }; }; - readonly "config-get-table-config": { + readonly "context_page-destroy": { readonly parameters: { readonly query?: never; readonly header: { @@ -8079,14 +8306,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,44 +8324,13 @@ export interface operations { 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 data: components["schemas"]["Page"]; }; }; }; }; - }; - }; - 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: { + /** @description The page is the start page */ + readonly 400: { headers: { readonly [name: string]: unknown; }; @@ -8140,7 +8338,9 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: components["schemas"]["NotifyConfig"]; + readonly data: { + readonly message: string; + }; }; }; }; @@ -8159,32 +8359,8 @@ export interface operations { }; }; }; - }; - }; - 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: { + /** @description No permissions */ + readonly 403: { headers: { readonly [name: string]: unknown; }; @@ -8192,13 +8368,15 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: boolean; + readonly data: { + readonly message: string; + }; }; }; }; }; - /** @description bad request */ - readonly 400: { + /** @description Not found */ + readonly 404: { headers: { readonly [name: string]: unknown; }; @@ -8213,8 +8391,7 @@ export interface operations { }; }; }; - /** @description Current user is not logged in */ - readonly 401: { + readonly 500: { headers: { readonly [name: string]: unknown; }; @@ -8222,16 +8399,338 @@ export interface operations { readonly "application/json": { readonly ocs: { readonly meta: components["schemas"]["OCSMeta"]; - readonly data: unknown; + readonly data: { + readonly message: string; + }; }; }; }; }; - /** @description No permissions */ - readonly 403: { - headers: { - readonly [name: string]: unknown; - }; + }; + }; + readonly "context_page-update": { + 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?: { + readonly content: { + readonly "application/json": { + /** + * @description New title + * @default null + */ + readonly title?: string | null; + /** + * @description Slug of the page; it never changes, so only the current slug is accepted + * @default null + */ + readonly slug?: 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 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; + }; + }; + }; + readonly responses: { + /** @description Page updated */ + 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 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; + }; + 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; + }; + }; + }; + }; + }; + /** @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; + }; + 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: { @@ -8340,6 +8839,256 @@ export interface operations { }; }; }; + readonly "context_page-show-by-slug": { + 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 Slug of the page */ + readonly slug: 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-grid-page": { + 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 Slug of the page, unique in the application and never changed; `page_` when left out, a form reserved for automatic names + * @default null + */ + readonly slug?: 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 slug */ + 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?: { diff --git a/tests/unit/Controller/ContextPageControllerTest.php b/tests/unit/Controller/ContextPageControllerTest.php new file mode 100644 index 0000000000..26246d3d6c --- /dev/null +++ b/tests/unit/Controller/ContextPageControllerTest.php @@ -0,0 +1,114 @@ +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], static fn (ContextPageController $controller) => $controller->show(7, 2)], + 'show by name' => ['findBySlug', [7, 'overview'], static fn (ContextPageController $controller) => $controller->showBySlug(7, 'overview')], + '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)], + ]; + } + + /** + * @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 . ', not found'] = [new NotFoundError('Context 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]]; + $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', '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']); + } +} 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 f088dd4e82..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()), ]); } 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/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/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 { diff --git a/tests/unit/Service/PageServiceTest.php b/tests/unit/Service/PageServiceTest.php new file mode 100644 index 0000000000..ec897f9b71 --- /dev/null +++ b/tests/unit/Service/PageServiceTest.php @@ -0,0 +1,418 @@ + stored pages by id */ + private array $pages = []; + private PageMapper&MockObject $pageMapper; + private PageContentMapper&MockObject $pageContentMapper; + private WidgetService&MockObject $widgetService; + + protected function setUp(): void { + parent::setUp(); + $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')->willReturn($context); + $contextMapper->method('lock')->willReturn(true); + + $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 clone $this->pages[$pageId]; + }); + $this->pageContentMapper = $this->createMock(PageContentMapper::class); + $this->widgetService = $this->createMock(WidgetService::class); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnArgument(0); + + $this->service = new PageService( + $contextMapper, + $this->pageMapper, + $this->pageContentMapper, + $this->widgetService, + new GridWidgetTypes($l10n), + $this->createMock(IDBConnection::class), + ); + } + + 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]]); + + $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 testFindBySlugAsksTheMapperAndAnUnknownNameIsNotFound(): void { + $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']); + $this->expectException(NotFoundError::class); + $this->service->findBySlug(7, 'missing'); + } + + public function testAPageOfAnotherApplicationIsNotFound(): void { + $this->pageMapper->expects($this->never())->method('raiseVersion'); + foreach ([ + '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->pageMapper->expects($this->once())->method('insertWithDefaultName')->willReturnCallback(static function (Page $page): Page { + $page->id = 9; + $page->setSlug('page_9'); + return $page; + }); + + $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'], + ]); + } + + 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->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->createGridPage(7, 'Planning', 'taken', null, null); + } + + public function testCreateInAnApplicationThatIsGoneIsNotFound(): void { + $contextMapper = $this->createMock(ContextMapper::class); + $contextMapper->method('lock')->willReturn(false); + $this->pageMapper = $this->createMock(PageMapper::class); + $this->pageMapper->expects($this->never())->method('insertWithDefaultName'); + $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->createGridPage(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' => [''], + '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->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()); + } + $this->expectException(BadRequestError::class); + $this->service->update(7, self::GRID_PAGE, $title, null, null, null, null, null); + } + + 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->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 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 { + $synced = $widgets; + return $stored; + }); + $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 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); + } + + 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 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->expectException(NotFoundError::class); + $this->service->update(7, self::GRID_PAGE, null, null, null, null, [self::widget()], 4); + } + + 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(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([]); + $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', 'overview', 'star', 'Next steps', null, null); + + $this->assertSame(['Planning', 'overview', 'star', 'Next steps'], $updated); + } + + 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 of a page cannot be changed.'); + $this->service->update(7, self::GRID_PAGE, 'Planning', 'planning', null, null, null, null); + } + + public function testAUniqueViolationWithoutARenameIsNotTakenForOne(): void { + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('syncPage')->willThrowException(DbErrorStub::uniqueViolation()); + + $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' => ['Planning', 'A slug has 1 to 200 lower case letters'], + 'reserved for automatic names' => ['page_5', 'The slug page_5 is reserved'], + ]; + } + + /** + * @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->createGridPage(7, 'Planning', $slug, null, null); + } + + public function testAPageKeepsItsOwnAutomaticName(): void { + $this->pages[self::GRID_PAGE]->setSlug('page_2'); + $this->pageMapper->method('raiseVersion')->willReturn(true); + $this->widgetService->method('findByPageIds')->willReturn([]); + + $this->assertSame('page_2', $this->service->update(7, self::GRID_PAGE, null, 'page_2', null, null, null, null)['slug']); + } + + public function testAnUnknownIconIsRefused(): void { + $this->expectException(BadRequestError::class); + $this->expectExceptionMessage('unknown icon'); + $this->service->update(7, self::GRID_PAGE, null, null, 'no-such-icon', null, null, null); + } + + public static function invalidWidgets(): array { + return [ + 'not an object' => [['x'], 'Widget 0 must be an object'], + '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 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, 4); + } + + public function testDeleteRemovesAGridPageWithItsWidgets(): void { + $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([['id' => 31]], $this->service->delete(7, self::GRID_PAGE)['widgets']); + } + + public function testTheStartPageCannotBeDeleted(): void { + $this->pageMapper->expects($this->never())->method('deleteByPageId'); + $this->expectException(BadRequestError::class); + $this->service->delete(7, self::START_PAGE); + } + + 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/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';