From e09ddc04963c41f6399aea6749b019f18ce0d2c1 Mon Sep 17 00:00:00 2001 From: Stefan Dietrich Date: Wed, 25 Nov 2026 13:50:22 +0100 Subject: [PATCH 1/3] feat(dashboard): add team dashboard with ITeamWidget support Add ITeamManager::isMemberOfTeam, reusing the member-only Circles probe, and authorize team membership before resolving team-capable widgets while preserving the personal dashboard paths. Isolate applicability, metadata and item failures per provider: log a warning and omit only the broken widget from the response. Move the team dashboard UI into the dashboard app as an embeddable `dashboard-team` widget. It shares widget loading, headings, picker tiles and item rendering with the personal dashboard. Assisted-by: Copilot:gpt-6.1-sol Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Stefan Dietrich --- .../lib/Controller/DashboardApiController.php | 165 +++++++--- apps/dashboard/openapi.json | 132 ++++++++ apps/dashboard/src/DashboardApp.spec.ts | 84 ++++- apps/dashboard/src/DashboardApp.vue | 183 +++-------- .../components/DashboardWidgetChoice.spec.ts | 31 ++ .../src/components/DashboardWidgetChoice.vue | 88 ++++++ .../src/components/DashboardWidgetHeading.vue | 30 ++ .../src/components/TeamDashboard.spec.ts | 289 ++++++++++++++++++ .../src/components/TeamDashboard.vue | 237 ++++++++++++++ apps/dashboard/src/dashboardApi.ts | 89 ++++++ apps/dashboard/src/team-dashboard.ts | 42 +++ apps/dashboard/src/useDashboardWidgets.ts | 168 ++++++++++ .../tests/DashboardApiControllerTest.php | 282 +++++++++++++++++ lib/composer/composer/autoload_classmap.php | 1 + lib/composer/composer/autoload_static.php | 1 + lib/private/Teams/TeamManager.php | 11 +- lib/public/Dashboard/ITeamWidget.php | 42 +++ lib/public/Teams/ITeamManager.php | 7 + openapi.json | 132 ++++++++ tests/lib/Teams/TeamManagerTest.php | 75 +++++ vite.config.ts | 1 + 21 files changed, 1911 insertions(+), 179 deletions(-) create mode 100644 apps/dashboard/src/components/DashboardWidgetChoice.spec.ts create mode 100644 apps/dashboard/src/components/DashboardWidgetChoice.vue create mode 100644 apps/dashboard/src/components/DashboardWidgetHeading.vue create mode 100644 apps/dashboard/src/components/TeamDashboard.spec.ts create mode 100644 apps/dashboard/src/components/TeamDashboard.vue create mode 100644 apps/dashboard/src/dashboardApi.ts create mode 100644 apps/dashboard/src/team-dashboard.ts create mode 100644 apps/dashboard/src/useDashboardWidgets.ts create mode 100644 apps/dashboard/tests/DashboardApiControllerTest.php create mode 100644 lib/public/Dashboard/ITeamWidget.php diff --git a/apps/dashboard/lib/Controller/DashboardApiController.php b/apps/dashboard/lib/Controller/DashboardApiController.php index 8a4599a7ec0fa..bad64796b0804 100644 --- a/apps/dashboard/lib/Controller/DashboardApiController.php +++ b/apps/dashboard/lib/Controller/DashboardApiController.php @@ -16,6 +16,8 @@ use OCP\AppFramework\Http\Attribute\NoAdminRequired; use OCP\AppFramework\Http\Attribute\NoCSRFRequired; use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCS\OCSBadRequestException; +use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\AppFramework\OCSController; use OCP\AppFramework\Services\IAppConfig; use OCP\Config\IUserConfig; @@ -26,11 +28,14 @@ use OCP\Dashboard\IManager; use OCP\Dashboard\IOptionWidget; use OCP\Dashboard\IReloadableWidget; +use OCP\Dashboard\ITeamWidget; use OCP\Dashboard\IWidget; use OCP\Dashboard\Model\WidgetButton; use OCP\Dashboard\Model\WidgetItem; use OCP\Dashboard\Model\WidgetOptions; use OCP\IRequest; +use OCP\Teams\ITeamManager; +use Psr\Log\LoggerInterface; /** * @psalm-import-type DashboardWidget from ResponseDefinitions @@ -47,6 +52,8 @@ public function __construct( private IUserConfig $userConfig, private ?string $userId, private DashboardService $service, + private ITeamManager $teamManager, + private LoggerInterface $logger, ) { parent::__construct($appName, $request); } @@ -69,6 +76,44 @@ static function (IWidget $widget) use ($widgetIds) { ); } + private function validateTeamAccess(?string $teamId): ?string { + if ($teamId === null) { + return null; + } + if ($teamId === '') { + throw new OCSBadRequestException('Empty team ID'); + } + if ($this->userId === null || !$this->teamManager->isMemberOfTeam($teamId, $this->userId)) { + throw new OCSNotFoundException('Team not found'); + } + return $teamId; + } + + /** + * @param list $widgetIds + * @return array + */ + private function getTeamWidgets(string $teamId, array $widgetIds): array { + $widgets = []; + foreach ($this->dashboardManager->getWidgets() as $id => $widget) { + if (!$widget instanceof ITeamWidget || ($widgetIds !== [] && !in_array($id, $widgetIds, true))) { + continue; + } + try { + if ($widget->isEnabledForTeam($teamId, $this->userId)) { + $widgets[$id] = $widget; + } + } catch (\Throwable $e) { + $this->logger->warning('Failed to check dashboard widget applicability for team', [ + 'widget' => $id, + 'team' => $teamId, + 'exception' => $e, + ]); + } + } + return $widgets; + } + /** * Get the items for the widgets * @@ -104,15 +149,34 @@ public function getWidgetItems(array $sinceIds = [], int $limit = 7, array $widg * @param int $limit Limit number of result items per widget, not more than 30 are allowed * @psalm-param int<1, 30> $limit * @param list $widgets Limit results to specific widgets + * @param ?string $teamId Team to show widgets for; omit for the personal dashboard * @return DataResponse, array{}> + * @throws OCSNotFoundException Team not found + * @throws OCSBadRequestException Empty team ID * * 200: Widget items returned */ #[NoAdminRequired] #[NoCSRFRequired] #[ApiRoute(verb: 'GET', url: '/api/v2/widget-items')] - public function getWidgetItemsV2(array $sinceIds = [], int $limit = 7, array $widgets = []): DataResponse { + public function getWidgetItemsV2(array $sinceIds = [], int $limit = 7, array $widgets = [], ?string $teamId = null): DataResponse { + $teamId = $this->validateTeamAccess($teamId); $items = []; + if ($teamId !== null) { + foreach ($this->getTeamWidgets($teamId, $widgets) as $id => $widget) { + try { + $items[$id] = $widget->getTeamItems($teamId, $this->userId, $sinceIds[$id] ?? null, $limit)->jsonSerialize(); + } catch (\Throwable $e) { + $this->logger->warning('Failed to get dashboard widget items for team', [ + 'widget' => $id, + 'team' => $teamId, + 'exception' => $e, + ]); + } + } + return new DataResponse($items); + } + $widgets = $this->getShownWidgets($widgets); foreach ($widgets as $widget) { if ($widget instanceof IAPIWidgetV2) { @@ -128,55 +192,80 @@ public function getWidgetItemsV2(array $sinceIds = [], int $limit = 7, array $wi /** * Get the widgets * + * @param ?string $teamId Team to show widgets for; omit for the personal dashboard * @return DataResponse, array{}> + * @throws OCSNotFoundException Team not found + * @throws OCSBadRequestException Empty team ID * * 200: Widgets returned */ #[NoAdminRequired] #[NoCSRFRequired] #[ApiRoute(verb: 'GET', url: '/api/v1/widgets')] - public function getWidgets(): DataResponse { - $widgets = $this->dashboardManager->getWidgets(); - - $items = array_map(function (IWidget $widget) { - $options = ($widget instanceof IOptionWidget) ? $widget->getWidgetOptions() : WidgetOptions::getDefault(); - $data = [ - 'id' => $widget->getId(), - 'title' => $widget->getTitle(), - 'order' => $widget->getOrder(), - 'icon_class' => $widget->getIconClass(), - 'icon_url' => ($widget instanceof IIconWidget) ? $widget->getIconUrl() : '', - 'widget_url' => $widget->getUrl(), - 'item_icons_round' => $options->withRoundItemIcons(), - 'item_api_versions' => [], - 'reload_interval' => 0, - ]; - if ($widget instanceof IButtonWidget) { - $data += [ - 'buttons' => array_map(function (WidgetButton $button) { - return [ - 'type' => $button->getType(), - 'text' => $button->getText(), - 'link' => $button->getLink(), - ]; - }, $widget->getWidgetButtons($this->userId)), - ]; + public function getWidgets(?string $teamId = null): DataResponse { + $teamId = $this->validateTeamAccess($teamId); + if ($teamId !== null) { + $items = []; + foreach ($this->getTeamWidgets($teamId, []) as $id => $widget) { + try { + $items[$id] = $this->serializeWidget($widget, $widget->getTeamUrl($teamId, $this->userId) ?? $widget->getUrl()); + } catch (\Throwable $e) { + $this->logger->warning('Failed to get dashboard widget metadata for team', [ + 'widget' => $id, + 'team' => $teamId, + 'exception' => $e, + ]); + } } - if ($widget instanceof IReloadableWidget) { - $data['reload_interval'] = $widget->getReloadInterval(); - } - if ($widget instanceof IAPIWidget) { - $data['item_api_versions'][] = 1; - } - if ($widget instanceof IAPIWidgetV2) { - $data['item_api_versions'][] = 2; - } - return $data; - }, $widgets); + } else { + $items = array_map( + fn (IWidget $widget) => $this->serializeWidget($widget, $widget->getUrl()), + $this->dashboardManager->getWidgets(), + ); + } return new DataResponse($items); } + /** + * @return DashboardWidget + */ + private function serializeWidget(IWidget $widget, ?string $url): array { + $options = ($widget instanceof IOptionWidget) ? $widget->getWidgetOptions() : WidgetOptions::getDefault(); + $data = [ + 'id' => $widget->getId(), + 'title' => $widget->getTitle(), + 'order' => $widget->getOrder(), + 'icon_class' => $widget->getIconClass(), + 'icon_url' => ($widget instanceof IIconWidget) ? $widget->getIconUrl() : '', + 'widget_url' => $url, + 'item_icons_round' => $options->withRoundItemIcons(), + 'item_api_versions' => [], + 'reload_interval' => 0, + ]; + if ($widget instanceof IButtonWidget) { + $data += [ + 'buttons' => array_map(function (WidgetButton $button) { + return [ + 'type' => $button->getType(), + 'text' => $button->getText(), + 'link' => $button->getLink(), + ]; + }, $widget->getWidgetButtons($this->userId)), + ]; + } + if ($widget instanceof IReloadableWidget) { + $data['reload_interval'] = $widget->getReloadInterval(); + } + if ($widget instanceof IAPIWidget) { + $data['item_api_versions'][] = 1; + } + if ($widget instanceof IAPIWidgetV2) { + $data['item_api_versions'][] = 2; + } + return $data; + } + /** * Get the layout * diff --git a/apps/dashboard/openapi.json b/apps/dashboard/openapi.json index 1960328b6c2ae..410b2276ba469 100644 --- a/apps/dashboard/openapi.json +++ b/apps/dashboard/openapi.json @@ -347,6 +347,16 @@ } } }, + { + "name": "teamId", + "in": "query", + "description": "Team to show widgets for; omit for the personal dashboard", + "schema": { + "type": "string", + "nullable": true, + "default": null + } + }, { "name": "OCS-APIRequest", "in": "header", @@ -392,6 +402,62 @@ } } }, + "404": { + "description": "Team not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "400": { + "description": "Empty team ID", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { @@ -439,6 +505,16 @@ } ], "parameters": [ + { + "name": "teamId", + "in": "query", + "description": "Team to show widgets for; omit for the personal dashboard", + "schema": { + "type": "string", + "nullable": true, + "default": null + } + }, { "name": "OCS-APIRequest", "in": "header", @@ -484,6 +560,62 @@ } } }, + "404": { + "description": "Team not found", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, + "400": { + "description": "Empty team ID", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { diff --git a/apps/dashboard/src/DashboardApp.spec.ts b/apps/dashboard/src/DashboardApp.spec.ts index 21cf3ccba13af..7b2ceeef49afb 100644 --- a/apps/dashboard/src/DashboardApp.spec.ts +++ b/apps/dashboard/src/DashboardApp.spec.ts @@ -9,7 +9,7 @@ import type { Ref } from 'vue' import axios from '@nextcloud/axios' import { cleanup, fireEvent, render, screen } from '@testing-library/vue' -import { flushPromises } from '@vue/test-utils' +import { flushPromises, mount } from '@vue/test-utils' import { moveArrayElement } from '@vueuse/integrations/useSortable' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -140,4 +140,86 @@ describe('DashboardApp.vue', () => { layout: ['third', 'first', 'second'], }) }) + + it('auto-saves changes from the shared picker on the personal dashboard', async () => { + render(DashboardApp) + await flushPromises() + await fireEvent.click(screen.getByRole('button', { name: 'Customize' })) + await fireEvent.click(await screen.findByRole('checkbox', { name: 'Second widget' })) + + expect(axios.post).toHaveBeenCalledOnce() + expect(axios.post).toHaveBeenCalledWith(expect.stringContaining('/apps/dashboard/api/v3/layout'), { + layout: ['first', 'third'], + }) + }) + + it('toggles statuses from the shared picker and shows the user status icon', async () => { + const wrapper = mount(DashboardApp, { attachTo: document.body }) + await flushPromises() + const vm = wrapper.vm as unknown as { registerStatus: (app: string, callback: () => void) => void } + vm.registerStatus('weather', vi.fn()) + vm.registerStatus('status', vi.fn()) + await fireEvent.click(screen.getByRole('button', { name: 'Customize' })) + await fireEvent.click(await screen.findByRole('checkbox', { name: 'Weather' })) + + expect(axios.post).toHaveBeenCalledWith(expect.stringContaining('/apps/dashboard/api/v3/statuses'), { + statuses: ['weather'], + }) + expect(document.querySelector('label[for="status-checkbox-status"] .widget-choice__icon--custom')).not.toBeNull() + expect(document.querySelector('label[for="status-checkbox-weather"] .widget-choice__icon--custom')).toBeNull() + wrapper.unmount() + }) + + it('batches personal API widgets and refreshes only the ones that are due', async () => { + vi.useFakeTimers() + const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + try { + vi.mocked(axios.get).mockResolvedValueOnce({ data: { ocs: { data: { + first: { id: 'first', title: 'First widget', item_api_versions: [2], reload_interval: 5 }, + second: { id: 'second', title: 'Second widget', item_api_versions: [2], reload_interval: 0 }, + third: { id: 'third', title: 'Third widget', item_api_versions: [1], reload_interval: 5 }, + } } } }) + const { unmount } = render(DashboardApp) + await flushPromises() + expect(axios.get).toHaveBeenNthCalledWith(2, expect.stringContaining('/apps/dashboard/api/v2/widget-items'), { + params: { widgets: ['first', 'second'] }, + signal: expect.any(AbortSignal), + }) + + await vi.advanceTimersByTimeAsync(5000) + expect(axios.get).toHaveBeenNthCalledWith(3, expect.stringContaining('/apps/dashboard/api/v2/widget-items'), { + params: { widgets: ['first'] }, + signal: expect.any(AbortSignal), + }) + unmount() + await vi.advanceTimersByTimeAsync(5000) + expect(axios.get).toHaveBeenCalledTimes(3) + } finally { + hidden.mockRestore() + vi.useRealTimers() + } + }) + + it.each([401, 403, 404])('keeps personal API widgets after a %s refresh response', async (status) => { + vi.useFakeTimers() + const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + try { + vi.mocked(axios.get) + .mockResolvedValueOnce({ data: { ocs: { data: { + first: { id: 'first', title: 'First API widget', item_api_versions: [2], reload_interval: 5 }, + } } } }) + .mockResolvedValueOnce({ data: { ocs: { data: { first: { items: [], emptyContentMessage: '', halfEmptyContentMessage: '' } } } } }) + .mockRejectedValueOnce({ response: { status } }) + render(DashboardApp) + await flushPromises() + expect(screen.getByText('First API widget')).toBeTruthy() + + await vi.advanceTimersByTimeAsync(5000) + expect(axios.get).toHaveBeenCalledTimes(3) + expect(screen.getByText('First API widget')).toBeTruthy() + } finally { + hidden.mockRestore() + vi.useRealTimers() + } + }) }) diff --git a/apps/dashboard/src/DashboardApp.vue b/apps/dashboard/src/DashboardApp.vue index 3e07018eab609..ca8104f2e2e48 100644 --- a/apps/dashboard/src/DashboardApp.vue +++ b/apps/dashboard/src/DashboardApp.vue @@ -18,11 +18,10 @@