diff --git a/plugins/scaffolder/dev/index.tsx b/plugins/scaffolder/dev/index.tsx index 03632f434d..83496c719d 100644 --- a/plugins/scaffolder/dev/index.tsx +++ b/plugins/scaffolder/dev/index.tsx @@ -25,7 +25,11 @@ import { import React from 'react'; import { scaffolderApiRef, ScaffolderClient } from '../src'; import { ScaffolderPage } from '../src/plugin'; -import { discoveryApiRef, fetchApiRef } from '@backstage/core-plugin-api'; +import { + discoveryApiRef, + fetchApiRef, + identityApiRef, +} from '@backstage/core-plugin-api'; import { CatalogEntityPage } from '@backstage/plugin-catalog'; createDevApp() @@ -49,9 +53,15 @@ createDevApp() discoveryApi: discoveryApiRef, fetchApi: fetchApiRef, scmIntegrationsApi: scmIntegrationsApiRef, + identityApi: identityApiRef, }, - factory: ({ discoveryApi, fetchApi, scmIntegrationsApi }) => - new ScaffolderClient({ discoveryApi, fetchApi, scmIntegrationsApi }), + factory: ({ discoveryApi, fetchApi, scmIntegrationsApi, identityApi }) => + new ScaffolderClient({ + discoveryApi, + fetchApi, + scmIntegrationsApi, + identityApi, + }), }) .addPage({ path: '/create', diff --git a/plugins/scaffolder/src/api.test.ts b/plugins/scaffolder/src/api.test.ts index 4e47c7f239..a5a3a3c51e 100644 --- a/plugins/scaffolder/src/api.test.ts +++ b/plugins/scaffolder/src/api.test.ts @@ -33,6 +33,13 @@ describe('api', () => { const discoveryApi = { getBaseUrl: async () => mockBaseUrl }; const fetchApi = new MockFetchApi(); + const identityApi = { + getBackstageIdentity: jest.fn(), + getProfileInfo: jest.fn(), + getCredentials: jest.fn(), + signOut: jest.fn(), + }; + const scmIntegrationsApi = ScmIntegrations.fromConfig( new ConfigReader({ integrations: { @@ -51,6 +58,7 @@ describe('api', () => { scmIntegrationsApi, discoveryApi, fetchApi, + identityApi, }); }); @@ -129,6 +137,7 @@ describe('api', () => { scmIntegrationsApi, discoveryApi, fetchApi, + identityApi, useLongPollingLogs: true, }); }); @@ -305,4 +314,75 @@ describe('api', () => { }); }); }); + + describe('listTasks', () => { + it('should list all tasks', async () => { + server.use( + rest.get(`${mockBaseUrl}/v2/tasks`, (req, res, ctx) => { + const createdBy = req.url.searchParams.get('createdBy'); + + if (createdBy) { + return res( + ctx.json([ + { + createdBy, + }, + ]), + ); + } + + return res( + ctx.json([ + { + createdBy: null, + }, + { + createdBy: null, + }, + ]), + ); + }), + ); + + const result = await apiClient.listTasks('all'); + expect(identityApi.getBackstageIdentity).not.toBeCalled(); + expect(result).toHaveLength(2); + }); + it('should list task using the current user as owner', async () => { + server.use( + rest.get(`${mockBaseUrl}/v2/tasks`, (req, res, ctx) => { + const createdBy = req.url.searchParams.get('createdBy'); + + if (createdBy) { + return res( + ctx.json([ + { + createdBy, + }, + ]), + ); + } + + return res( + ctx.json([ + { + createdBy: null, + }, + { + createdBy: null, + }, + ]), + ); + }), + ); + + identityApi.getBackstageIdentity.mockResolvedValueOnce({ + userEntityRef: 'user:default/foo', + }); + + const result = await apiClient.listTasks('owned'); + expect(identityApi.getBackstageIdentity).toBeCalled(); + expect(result).toHaveLength(1); + }); + }); }); diff --git a/plugins/scaffolder/src/api.ts b/plugins/scaffolder/src/api.ts index 40c88ba68d..8f2319cb9d 100644 --- a/plugins/scaffolder/src/api.ts +++ b/plugins/scaffolder/src/api.ts @@ -19,6 +19,7 @@ import { createApiRef, DiscoveryApi, FetchApi, + IdentityApi, } from '@backstage/core-plugin-api'; import { ResponseError } from '@backstage/errors'; import { ScmIntegrationRegistry } from '@backstage/integration'; @@ -36,6 +37,7 @@ import { ScaffolderGetIntegrationsListOptions, ScaffolderGetIntegrationsListResponse, ScaffolderTask, + TasksOwnerFilterKind, } from './types'; /** @@ -56,11 +58,13 @@ export class ScaffolderClient implements ScaffolderApi { private readonly discoveryApi: DiscoveryApi; private readonly scmIntegrationsApi: ScmIntegrationRegistry; private readonly fetchApi: FetchApi; + private readonly identityApi: IdentityApi; private readonly useLongPollingLogs: boolean; constructor(options: { discoveryApi: DiscoveryApi; fetchApi: FetchApi; + identityApi: IdentityApi; scmIntegrationsApi: ScmIntegrationRegistry; useLongPollingLogs?: boolean; }) { @@ -68,11 +72,19 @@ export class ScaffolderClient implements ScaffolderApi { this.fetchApi = options.fetchApi ?? { fetch }; this.scmIntegrationsApi = options.scmIntegrationsApi; this.useLongPollingLogs = options.useLongPollingLogs ?? false; + this.identityApi = options.identityApi; } - async listTasks(): Promise { + async listTasks(createdBy: TasksOwnerFilterKind): Promise { const baseUrl = await this.discoveryApi.getBaseUrl('scaffolder'); - const url = `${baseUrl}/v2/tasks`; + + let query = ''; + if (createdBy === 'owned') { + const { userEntityRef } = await this.identityApi.getBackstageIdentity(); + query = `createdBy=${encodeURIComponent(userEntityRef)}`; + } + + const url = `${baseUrl}/v2/tasks?${query}`; const response = await this.fetchApi.fetch(url); if (!response.ok) { diff --git a/plugins/scaffolder/src/components/ActionsPage/ActionsPage.test.tsx b/plugins/scaffolder/src/components/ActionsPage/ActionsPage.test.tsx index aff6681037..40683f01ba 100644 --- a/plugins/scaffolder/src/components/ActionsPage/ActionsPage.test.tsx +++ b/plugins/scaffolder/src/components/ActionsPage/ActionsPage.test.tsx @@ -28,6 +28,7 @@ const scaffolderApiMock: jest.Mocked = { getTask: jest.fn(), streamLogs: jest.fn(), listActions: jest.fn(), + listTasks: jest.fn(), }; const apis = TestApiRegistry.from([scaffolderApiRef, scaffolderApiMock]); diff --git a/plugins/scaffolder/src/components/ListTasksPage/ListTaskPage.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/ListTaskPage.test.tsx new file mode 100644 index 0000000000..fced397ad3 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/ListTaskPage.test.tsx @@ -0,0 +1,226 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity } from '@backstage/catalog-model'; +import { renderInTestApp, TestApiProvider } from '@backstage/test-utils'; +import { + CatalogApi, + catalogApiRef, + entityRouteRef, +} from '@backstage/plugin-catalog-react'; +import React from 'react'; +import { identityApiRef } from '@backstage/core-plugin-api'; +import { ListTasksPage } from './ListTasksPage'; +import { ScaffolderApi } from '../../types'; +import { scaffolderApiRef } from '../../api'; +import { rootRouteRef } from '../../routes'; +import { act, fireEvent } from '@testing-library/react'; + +describe('', () => { + const catalogApi: jest.Mocked = { + getEntityByRef: jest.fn(), + } as any; + + const identityApi = { + getBackstageIdentity: jest.fn(), + getProfileInfo: jest.fn(), + getCredentials: jest.fn(), + signOut: jest.fn(), + }; + + const scaffolderApiMock: jest.Mocked = { + scaffold: jest.fn(), + getTemplateParameterSchema: jest.fn(), + listTasks: jest.fn(), + } as any; + + it('should render the page', async () => { + const entity: Entity = { + apiVersion: 'v1', + kind: 'service', + metadata: { + name: 'test', + }, + spec: { + profile: { + displayName: 'BackUser', + }, + }, + }; + catalogApi.getEntityByRef.mockResolvedValue(entity); + + scaffolderApiMock.listTasks.mockResolvedValue([]); + + const { getByText } = await renderInTestApp( + + + , + { + mountedRoutes: { + '/catalog/:namespace/:kind/:name': entityRouteRef, + '/root': rootRouteRef, + }, + }, + ); + + expect(getByText('List template tasks')).toBeInTheDocument(); + expect(getByText('All tasks that have been started')).toBeInTheDocument(); + expect(getByText('Tasks')).toBeInTheDocument(); + }); + + it('should render the task I am owner', async () => { + const entity: Entity = { + apiVersion: 'v1', + kind: 'User', + metadata: { + name: 'foo', + }, + spec: { + profile: { + displayName: 'BackUser', + }, + }, + }; + catalogApi.getEntityByRef.mockResolvedValue(entity); + scaffolderApiMock.listTasks.mockResolvedValue([ + { + id: 'a-random-id', + spec: { + createdBy: 'user:default/foo', + } as any, + status: 'completed', + createdAt: '', + lastHeartbeatAt: '', + }, + ]); + scaffolderApiMock.getTemplateParameterSchema.mockResolvedValue({ + title: 'One Template', + steps: [], + }); + + const { getByText } = await renderInTestApp( + + + , + { + mountedRoutes: { + '/catalog/:namespace/:kind/:name': entityRouteRef, + '/root': rootRouteRef, + }, + }, + ); + + expect(scaffolderApiMock.listTasks).toBeCalledWith('owned'); + expect(getByText('List template tasks')).toBeInTheDocument(); + expect(getByText('All tasks that have been started')).toBeInTheDocument(); + expect(getByText('Tasks')).toBeInTheDocument(); + expect(getByText('One Template')).toBeInTheDocument(); + expect(getByText('BackUser')).toBeInTheDocument(); + }); + + it('should render all tasks', async () => { + const entity: Entity = { + apiVersion: 'v1', + kind: 'User', + metadata: { + name: 'foo', + }, + spec: { + profile: { + displayName: 'BackUser', + }, + }, + }; + catalogApi.getEntityByRef + .mockResolvedValue(entity) + .mockResolvedValue(entity) + .mockResolvedValue({ + ...entity, + spec: { + profile: { + displayName: 'OtherUser', + }, + }, + }); + scaffolderApiMock.listTasks + .mockResolvedValue([ + { + id: 'a-random-id', + spec: { + createdBy: 'user:default/foo', + } as any, + status: 'completed', + createdAt: '', + lastHeartbeatAt: '', + }, + ]) + .mockResolvedValue([ + { + id: 'b-random-id', + spec: { + createdBy: 'user:default/boo', + } as any, + status: 'completed', + createdAt: '', + lastHeartbeatAt: '', + }, + ]); + + scaffolderApiMock.getTemplateParameterSchema.mockResolvedValue({ + title: 'One Template', + steps: [], + }); + + const { getByText } = await renderInTestApp( + + + , + { + mountedRoutes: { + '/catalog/:namespace/:kind/:name': entityRouteRef, + '/root': rootRouteRef, + }, + }, + ); + + await act(async () => { + const allButton = await getByText('All'); + fireEvent.click(allButton); + }); + + expect(scaffolderApiMock.listTasks).toBeCalledWith('all'); + expect(getByText('One Template')).toBeInTheDocument(); + expect(getByText('OtherUser')).toBeInTheDocument(); + }); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/ListTasksPage.tsx b/plugins/scaffolder/src/components/ListTasksPage/ListTasksPage.tsx new file mode 100644 index 0000000000..d66355b0a5 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/ListTasksPage.tsx @@ -0,0 +1,144 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + Content, + EmptyState, + ErrorPanel, + Header, + Lifecycle, + Link, + Page, + Progress, +} from '@backstage/core-components'; +import { useApi, useRouteRef } from '@backstage/core-plugin-api'; +import { CatalogFilterLayout } from '@backstage/plugin-catalog-react'; +import useAsync from 'react-use/lib/useAsync'; +import MaterialTable from '@material-table/core'; +import React, { useState } from 'react'; +import { scaffolderApiRef } from '../../api'; +import { rootRouteRef } from '../../routes'; +import { OwnerListPicker } from './OwnerListPicker'; +import { TasksOwnerFilterKind } from '../../types'; +import { + CreatedAtColumn, + OwnerEntityColumn, + TaskStatusColumn, + TemplateTitleColumn, +} from './columns'; + +export interface MyTaskPageProps { + initiallySelectedFilter?: TasksOwnerFilterKind; +} + +const ListTaskPageContent = (props: MyTaskPageProps) => { + const { initiallySelectedFilter = 'owned' } = props; + + const scaffolderApi = useApi(scaffolderApiRef); + const rootLink = useRouteRef(rootRouteRef); + + const [ownerFilter, setOwnerFilter] = useState(initiallySelectedFilter); + const { value, loading, error } = useAsync( + () => scaffolderApi.listTasks(ownerFilter), + [scaffolderApi, ownerFilter], + ); + + if (loading) { + return ; + } + + if (error) { + return ( + <> + + + + ); + } + + return ( + + + setOwnerFilter(id)} + /> + + + ( + {row.id} + ), + }, + { + title: 'Template', + render: row => ( + + ), + }, + { + title: 'Created', + field: 'createdAt', + render: row => , + }, + { + title: 'Owner', + field: 'createdBy', + render: row => ( + + ), + }, + { + title: 'Status', + field: 'status', + render: row => , + }, + ]} + /> + + + ); +}; + +export const ListTasksPage = (props: MyTaskPageProps) => { + return ( + +
+ List template tasks + + } + subtitle="All tasks that have been started" + /> + + + + + ); +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.test.tsx new file mode 100644 index 0000000000..bf0ae6d946 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.test.tsx @@ -0,0 +1,47 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderInTestApp } from '@backstage/test-utils'; + +import React from 'react'; +import { OwnerListPicker } from './OwnerListPicker'; +import { fireEvent } from '@testing-library/react'; + +describe('', () => { + it('should render the tasks owner filter', async () => { + const props = { + filter: 'owned', + onSelectOwner: jest.fn(), + }; + + const { getByText } = await renderInTestApp(); + + expect(await getByText('Owned')).toBeDefined(); + expect(await getByText('All')).toBeDefined(); + }); + + it('should call the function on select other item', async () => { + const props = { + filter: 'owned', + onSelectOwner: jest.fn(), + }; + + const { getByText } = await renderInTestApp(); + + fireEvent.click(await getByText('All')); + expect(props.onSelectOwner).toBeCalledWith('all'); + }); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.tsx b/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.tsx new file mode 100644 index 0000000000..e239938cb9 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/OwnerListPicker.tsx @@ -0,0 +1,135 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IconComponent } from '@backstage/core-plugin-api'; +import { + Card, + List, + ListItemIcon, + ListItemText, + makeStyles, + MenuItem, + Theme, + Typography, +} from '@material-ui/core'; +import SettingsIcon from '@material-ui/icons/Settings'; +import React, { Fragment } from 'react'; + +import AllIcon from '@material-ui/icons/FontDownload'; + +import { TasksOwnerFilterKind } from '../../types'; + +const useStyles = makeStyles( + theme => ({ + root: { + backgroundColor: 'rgba(0, 0, 0, .11)', + boxShadow: 'none', + margin: theme.spacing(1, 0, 1, 0), + }, + title: { + margin: theme.spacing(1, 0, 0, 1), + textTransform: 'uppercase', + fontSize: 12, + fontWeight: 'bold', + }, + listIcon: { + minWidth: 30, + color: theme.palette.text.primary, + }, + menuItem: { + minHeight: theme.spacing(6), + }, + groupWrapper: { + margin: theme.spacing(1, 1, 2, 1), + }, + }), + { + name: 'ScaffolderReactOwnerListPicker', + }, +); + +export type ButtonGroup = { + name: string; + items: { + id: 'owned' | 'starred' | 'all'; + label: string; + icon?: IconComponent; + }[]; +}; + +function getFilterGroups(): ButtonGroup[] { + return [ + { + name: 'Task Owner', + items: [ + { + id: 'owned', + label: 'Owned', + icon: SettingsIcon, + }, + { + id: 'all', + label: 'All', + icon: AllIcon, + }, + ], + }, + ]; +} + +export const OwnerListPicker = (props: { + filter: string; + onSelectOwner: (id: TasksOwnerFilterKind) => void; +}) => { + const { filter, onSelectOwner } = props; + const classes = useStyles(); + + const filterGroups = getFilterGroups(); + return ( + + {filterGroups.map(group => ( + + + {group.name} + + + + {group.items.map(item => ( + onSelectOwner(item.id as TasksOwnerFilterKind)} + selected={item.id === filter} + className={classes.menuItem} + data-testid={`owner-picker-${item.id}`} + > + {item.icon && ( + + + + )} + + {item.label} + + + ))} + + + + ))} + + ); +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.test.tsx new file mode 100644 index 0000000000..a30c1d370b --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.test.tsx @@ -0,0 +1,34 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderInTestApp } from '@backstage/test-utils'; + +import React from 'react'; +import { CreatedAtColumn } from './CreatedAtColumn'; +import { DateTime } from 'luxon'; + +describe('', () => { + it('should render the column with the time', async () => { + const props = { + createdAt: DateTime.now().toISO(), + }; + + const { getByText } = await renderInTestApp(); + + const text = getByText('0 seconds ago'); + expect(text).toBeDefined(); + }); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.tsx new file mode 100644 index 0000000000..8e48d4a561 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/CreatedAtColumn.tsx @@ -0,0 +1,27 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DateTime, Interval } from 'luxon'; +import humanizeDuration from 'humanize-duration'; +import React from 'react'; + +export const CreatedAtColumn = ({ createdAt }: { createdAt: string }) => { + const createdAtTime = DateTime.fromISO(createdAt); + const formatted = Interval.fromDateTimes(createdAtTime, DateTime.local()) + .toDuration() + .valueOf(); + + return

{humanizeDuration(formatted, { round: true })} ago

; +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.test.tsx new file mode 100644 index 0000000000..c2672e22bd --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.test.tsx @@ -0,0 +1,82 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity } from '@backstage/catalog-model'; +import { renderInTestApp, TestApiProvider } from '@backstage/test-utils'; +import { + CatalogApi, + catalogApiRef, + entityRouteRef, +} from '@backstage/plugin-catalog-react'; +import React from 'react'; +import { OwnerEntityColumn } from './OwnerEntityColumn'; +import { identityApiRef } from '@backstage/core-plugin-api'; + +describe('', () => { + const catalogApi: jest.Mocked = { + getEntityByRef: jest.fn(), + } as any; + + const identityApi = { + getBackstageIdentity: jest.fn(), + getProfileInfo: jest.fn(), + getCredentials: jest.fn(), + signOut: jest.fn(), + }; + + it('should render the column with the time', async () => { + const props = { + entityRef: 'user:default/foo', + }; + + const entity: Entity = { + apiVersion: 'v1', + kind: 'User', + metadata: { + name: 'test', + }, + spec: { + profile: { + displayName: 'BackUser', + }, + }, + }; + catalogApi.getEntityByRef.mockResolvedValue(entity); + + const { getByText, getByRole } = await renderInTestApp( + + + , + { + mountedRoutes: { + '/catalog/:namespace/:kind/:name': entityRouteRef, + }, + }, + ); + + expect(getByRole('link')).toHaveAttribute( + 'href', + '/catalog/default/user/foo', + ); + const text = getByText('BackUser'); + expect(text).toBeDefined(); + }); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.tsx new file mode 100644 index 0000000000..d2ca8f2620 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/OwnerEntityColumn.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Link } from '@backstage/core-components'; +import { useApi, useRouteRef } from '@backstage/core-plugin-api'; +import React from 'react'; + +import useAsync from 'react-use/lib/useAsync'; +import { ListItemText } from '@material-ui/core'; + +import { catalogApiRef, entityRouteRef } from '@backstage/plugin-catalog-react'; +import { parseEntityRef, UserEntity } from '@backstage/catalog-model'; + +export const OwnerEntityColumn = ({ + entityRef, +}: { + entityRef?: string | null; +}) => { + const catalogApi = useApi(catalogApiRef); + const catalogEntityRoute = useRouteRef(entityRouteRef); + + const { value, loading, error } = useAsync( + () => catalogApi.getEntityByRef(entityRef || ''), + [catalogApi, entityRef], + ); + + if (loading || error) { + return null; + } + + return ( + + + + ); +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.test.tsx new file mode 100644 index 0000000000..5eabcf72ff --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.test.tsx @@ -0,0 +1,38 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderInTestApp } from '@backstage/test-utils'; + +import React from 'react'; +import { TaskStatusColumn } from './TaskStatusColumn'; + +describe('', () => { + it.each(['processing', 'error', 'completed'])( + 'should render the column with the status %s', + async status => { + const props = { + status: status, + }; + + const { getByText } = await renderInTestApp( + , + ); + + const text = getByText(status); + expect(text).toBeDefined(); + }, + ); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.tsx new file mode 100644 index 0000000000..995e505c36 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/TaskStatusColumn.tsx @@ -0,0 +1,33 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + StatusError, + StatusOK, + StatusPending, +} from '@backstage/core-components'; +import React from 'react'; + +export const TaskStatusColumn = ({ status }: { status: string }) => { + switch (status) { + case 'processing': + return {status}; + case 'completed': + return {status}; + case 'error': + default: + return {status}; + } +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.test.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.test.tsx new file mode 100644 index 0000000000..5ce11da28a --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.test.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderInTestApp, TestApiProvider } from '@backstage/test-utils'; + +import React from 'react'; +import { TemplateTitleColumn } from './TemplateTitleColumn'; +import { scaffolderApiRef } from '../../../api'; +import { ScaffolderApi } from '../../../types'; + +describe('', () => { + const scaffolderApiMock: jest.Mocked = { + scaffold: jest.fn(), + getTemplateParameterSchema: jest.fn(), + } as any; + + it('should render the column with the time', async () => { + const props = { + entityRef: 'template:default/one-template', + }; + scaffolderApiMock.getTemplateParameterSchema.mockResolvedValue({ + title: 'One Template', + steps: [], + }); + + const { getByText } = await renderInTestApp( + + + , + ); + + const text = getByText('One Template'); + expect(text).toBeDefined(); + }); +}); diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.tsx b/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.tsx new file mode 100644 index 0000000000..8f86734809 --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/TemplateTitleColumn.tsx @@ -0,0 +1,33 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { useApi } from '@backstage/core-plugin-api'; +import React from 'react'; +import { scaffolderApiRef } from '../../../api'; +import useAsync from 'react-use/lib/useAsync'; + +export const TemplateTitleColumn = ({ entityRef }: { entityRef?: string }) => { + const scaffolder = useApi(scaffolderApiRef); + const { value, loading, error } = useAsync( + () => scaffolder.getTemplateParameterSchema(entityRef || ''), + [scaffolder, entityRef], + ); + + if (loading || error) { + return null; + } + + return

{value?.title}

; +}; diff --git a/plugins/scaffolder/src/components/ListTasksPage/columns/index.ts b/plugins/scaffolder/src/components/ListTasksPage/columns/index.ts new file mode 100644 index 0000000000..f6f356a3da --- /dev/null +++ b/plugins/scaffolder/src/components/ListTasksPage/columns/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2022 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { CreatedAtColumn } from './CreatedAtColumn'; +export { OwnerEntityColumn } from './OwnerEntityColumn'; +export { TaskStatusColumn } from './TaskStatusColumn'; +export { TemplateTitleColumn } from './TemplateTitleColumn'; diff --git a/plugins/scaffolder/src/components/MyTasksPage/index.tsx b/plugins/scaffolder/src/components/ListTasksPage/index.tsx similarity index 92% rename from plugins/scaffolder/src/components/MyTasksPage/index.tsx rename to plugins/scaffolder/src/components/ListTasksPage/index.tsx index 2535904349..56fc7d3d28 100644 --- a/plugins/scaffolder/src/components/MyTasksPage/index.tsx +++ b/plugins/scaffolder/src/components/ListTasksPage/index.tsx @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export { MyTaskPage } from './MyTaskPage'; +export { ListTasksPage } from './ListTasksPage'; diff --git a/plugins/scaffolder/src/components/MyTasksPage/MyTaskPage.tsx b/plugins/scaffolder/src/components/MyTasksPage/MyTaskPage.tsx deleted file mode 100644 index 36f7a68616..0000000000 --- a/plugins/scaffolder/src/components/MyTasksPage/MyTaskPage.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2022 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { - Content, - Header, - Lifecycle, - Link, - Page, - Progress, -} from '@backstage/core-components'; -import { useApi, useRouteRef } from '@backstage/core-plugin-api'; -import { Grid } from '@material-ui/core'; -import React from 'react'; -import { scaffolderApiRef } from '../../api'; -import useAsync from 'react-use/lib/useAsync'; -import MaterialTable, { Column } from '@material-table/core'; -import { rootRouteRef } from '../../routes'; -import { Duration, Interval, DateTime } from 'luxon'; -import humanizeDuration from 'humanize-duration'; -import { - StatusError, - StatusPending, - StatusOK, -} from '@backstage/core-components'; - -const CreatedAtColumn = ({ createdAt }: { createdAt: string }) => { - const createdAtTime = DateTime.fromISO(createdAt); - const formatted = Interval.fromDateTimes(createdAtTime, DateTime.local()) - .toDuration() - .valueOf(); - - return

{humanizeDuration(formatted, { round: true })} ago

; -}; - -const TemplateTitle = ({ templateName }: { templateName?: string }) => { - const scaffolder = useApi(scaffolderApiRef); - const { value, loading, error } = useAsync( - () => - scaffolder.getTemplateParameterSchema({ - kind: 'Template', - namespace: 'default', - name: templateName, - }), - [scaffolder, templateName], - ); - - if (loading) { - return null; - } - - return

{value?.title}

; -}; - -const Status = ({ status }) => { - switch (status) { - case 'processing': - return {status}; - case 'completed': - return {status}; - case 'error': - default: - return {status}; - } -}; -export const MyTaskPage = () => { - const scaffolderApi = useApi(scaffolderApiRef); - const { value, loading, error } = useAsync( - () => scaffolderApi.listTasks(), - [scaffolderApi], - ); - - const rootLink = useRouteRef(rootRouteRef); - - return ( - -
- All my tasks - - } - subtitle="All tasks that have been started by me" - /> - - {loading ? ( - - ) : ( - ( - {row.id} - ), - }, - { - title: 'Name', - render: row => ( - - ), - }, - { - title: 'Created', - field: 'createdAt', - render: row => , - }, - { - title: 'Status', - field: 'status', - render: row => , - }, - ]} - /> - )} - - - ); -}; diff --git a/plugins/scaffolder/src/components/Router.tsx b/plugins/scaffolder/src/components/Router.tsx index d7158f81cb..6beaa3419a 100644 --- a/plugins/scaffolder/src/components/Router.tsx +++ b/plugins/scaffolder/src/components/Router.tsx @@ -35,10 +35,11 @@ import { useElementFilter } from '@backstage/core-plugin-api'; import { actionsRouteRef, editRouteRef, + scaffolderListTaskRouteRef, scaffolderTaskRouteRef, selectedTemplateRouteRef, } from '../routes'; -import { MyTaskPage } from './MyTasksPage'; +import { ListTasksPage } from './ListTasksPage'; /** * The props for the entrypoint `ScaffolderPage` component the plugin. @@ -119,7 +120,10 @@ export const Router = (props: RouterProps) => { } /> - } /> + } + /> } /> } /> = { getTask: jest.fn(), streamLogs: jest.fn(), listActions: jest.fn(), + listTasks: jest.fn(), }; const featureFlagsApiMock: jest.Mocked = { diff --git a/plugins/scaffolder/src/plugin.ts b/plugins/scaffolder/src/plugin.ts index 9bbb52a71f..5ea4ae49a4 100644 --- a/plugins/scaffolder/src/plugin.ts +++ b/plugins/scaffolder/src/plugin.ts @@ -30,6 +30,7 @@ import { createRoutableExtension, discoveryApiRef, fetchApiRef, + identityApiRef, } from '@backstage/core-plugin-api'; import { OwnedEntityPicker } from './components/fields/OwnedEntityPicker/OwnedEntityPicker'; import { EntityTagsPicker } from './components/fields/EntityTagsPicker/EntityTagsPicker'; @@ -47,12 +48,14 @@ export const scaffolderPlugin = createPlugin({ discoveryApi: discoveryApiRef, scmIntegrationsApi: scmIntegrationsApiRef, fetchApi: fetchApiRef, + identityApi: identityApiRef, }, - factory: ({ discoveryApi, scmIntegrationsApi, fetchApi }) => + factory: ({ discoveryApi, scmIntegrationsApi, fetchApi, identityApi }) => new ScaffolderClient({ discoveryApi, scmIntegrationsApi, fetchApi, + identityApi, }), }), ], diff --git a/plugins/scaffolder/src/routes.ts b/plugins/scaffolder/src/routes.ts index 8ec9f9b68a..be0d69135a 100644 --- a/plugins/scaffolder/src/routes.ts +++ b/plugins/scaffolder/src/routes.ts @@ -40,6 +40,12 @@ export const scaffolderTaskRouteRef = createSubRouteRef({ path: '/tasks/:taskId', }); +export const scaffolderListTaskRouteRef = createSubRouteRef({ + id: 'scaffolder/list-tasks', + parent: rootRouteRef, + path: '/tasks', +}); + export const actionsRouteRef = createSubRouteRef({ id: 'scaffolder/actions', parent: rootRouteRef, diff --git a/plugins/scaffolder/src/types.ts b/plugins/scaffolder/src/types.ts index bddd6a7b70..acd686019c 100644 --- a/plugins/scaffolder/src/types.ts +++ b/plugins/scaffolder/src/types.ts @@ -102,6 +102,13 @@ export type LogEvent = { taskId: string; }; +/** + * The status of each task you can filter from `ScaffolderClient` + * + * @public + */ +export type TasksOwnerFilterKind = 'owned' | 'all'; + /** * The input options to the `scaffold` method of the `ScaffolderClient`. * @@ -171,6 +178,8 @@ export interface ScaffolderApi { getTask(taskId: string): Promise; + listTasks(createdBy: TasksOwnerFilterKind): Promise; + getIntegrationsList( options: ScaffolderGetIntegrationsListOptions, ): Promise;