Merge branch '14452-my-account'
authorPawel Kromplewski <pawel.kromplewski@contractors.roche.com>
Fri, 7 Dec 2018 11:27:34 +0000 (12:27 +0100)
committerPawel Kromplewski <pawel.kromplewski@contractors.roche.com>
Fri, 7 Dec 2018 11:27:34 +0000 (12:27 +0100)
refs #14452

Arvados-DCO-1.1-Signed-off-by: Pawel Kromplewski <pawel.kromplewski@contractors.roche.com>

89 files changed:
package.json
src/common/formatters.ts
src/common/objects.ts [new file with mode: 0644]
src/components/autocomplete/autocomplete.tsx
src/components/data-explorer/data-explorer.tsx
src/index.tsx
src/models/api-client-authorization.ts [new file with mode: 0644]
src/models/resource.ts
src/models/search-bar.ts
src/models/user.ts
src/routes/route-change-handlers.ts
src/routes/routes.ts
src/services/api-client-authorization-service/api-client-authorization-service.ts [new file with mode: 0644]
src/services/api/filter-builder.ts
src/services/common-service/common-resource-service.ts
src/services/common-service/common-service.ts [new file with mode: 0644]
src/services/favorite-service/favorite-service.ts
src/services/groups-service/groups-service.ts
src/services/permission-service/permission-service.ts
src/services/project-service/project-service.ts
src/services/search-service/search-service.ts
src/services/services.ts
src/store/advanced-tab/advanced-tab.ts
src/store/api-client-authorizations/api-client-authorizations-actions.ts [new file with mode: 0644]
src/store/api-client-authorizations/api-client-authorizations-reducer.ts [new file with mode: 0644]
src/store/auth/auth-action.ts
src/store/collection-panel/collection-panel-files/collection-panel-files-actions.ts
src/store/collections/collection-copy-actions.ts
src/store/collections/collection-create-actions.ts
src/store/collections/collection-move-actions.ts
src/store/collections/collection-partial-copy-actions.ts
src/store/collections/collection-update-actions.ts
src/store/context-menu/context-menu-actions.ts
src/store/data-explorer/data-explorer-middleware-service.ts
src/store/navigation/navigation-action.ts
src/store/processes/process-move-actions.ts
src/store/processes/process-update-actions.ts
src/store/project-panel/project-panel-middleware-service.ts
src/store/projects/project-create-actions.ts
src/store/projects/project-move-actions.ts
src/store/projects/project-update-actions.ts
src/store/repositories/repositories-actions.ts
src/store/search-bar/search-bar-actions.test.ts [new file with mode: 0644]
src/store/search-bar/search-bar-actions.ts
src/store/search-bar/search-bar-reducer.ts
src/store/search-bar/search-bar-tree-actions.ts [new file with mode: 0644]
src/store/search-results-panel/search-results-middleware-service.ts
src/store/shared-with-me-panel/shared-with-me-middleware-service.ts
src/store/store.ts
src/store/trash-panel/trash-panel-action.ts
src/store/users/user-panel-middleware-service.ts [new file with mode: 0644]
src/store/users/users-actions.ts [new file with mode: 0644]
src/store/virtual-machines/virtual-machines-actions.ts
src/store/virtual-machines/virtual-machines-reducer.ts
src/store/workbench/workbench-actions.ts
src/store/workflow-panel/workflow-middleware-service.ts
src/validators/validators.tsx
src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx [new file with mode: 0644]
src/views-components/api-client-authorizations-dialog/help-dialog.tsx [new file with mode: 0644]
src/views-components/api-client-authorizations-dialog/remove-dialog.tsx [new file with mode: 0644]
src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts [new file with mode: 0644]
src/views-components/context-menu/action-sets/user-action-set.ts [new file with mode: 0644]
src/views-components/context-menu/context-menu.tsx
src/views-components/data-explorer/renderers.tsx
src/views-components/dialog-create/dialog-user-create.tsx [new file with mode: 0644]
src/views-components/dialog-forms/create-user-dialog.ts [new file with mode: 0644]
src/views-components/form-fields/collection-form-fields.tsx
src/views-components/form-fields/process-form-fields.tsx
src/views-components/form-fields/search-bar-form-fields.tsx
src/views-components/form-fields/user-form-fields.tsx [new file with mode: 0644]
src/views-components/main-app-bar/account-menu.tsx
src/views-components/main-content-bar/main-content-bar.tsx
src/views-components/search-bar/search-bar-advanced-properties-view.tsx
src/views-components/search-bar/search-bar-advanced-view.tsx
src/views-components/search-bar/search-bar-basic-view.tsx
src/views-components/search-bar/search-bar-save-queries.tsx
src/views-components/search-bar/search-bar-view.tsx
src/views-components/search-bar/search-bar.tsx
src/views-components/sharing-dialog/sharing-management-form-component.tsx
src/views-components/user-dialog/attributes-dialog.tsx [new file with mode: 0644]
src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx [new file with mode: 0644]
src/views/api-client-authorization-panel/api-client-authorization-panel.tsx [new file with mode: 0644]
src/views/compute-node-panel/compute-node-panel-root.tsx
src/views/search-results-panel/search-results-panel-view.tsx
src/views/trash-panel/trash-panel.tsx
src/views/user-panel/user-panel.tsx [new file with mode: 0644]
src/views/virtual-machine-panel/virtual-machine-panel.tsx
src/views/workbench/workbench.tsx
yarn.lock

index 623b86d3a58d659bae2105ae06aa0629db71b22f..1332630471dccf4c6baf093905c74cd525880bfc 100644 (file)
@@ -12,7 +12,7 @@
     "@types/react-dnd": "3.0.2",
     "@types/react-dropzone": "4.2.2",
     "@types/react-highlight-words": "0.12.0",
-    "@types/redux-form": "7.4.5",
+    "@types/redux-form": "7.4.12",
     "@types/reselect": "2.2.0",
     "@types/shell-quote": "1.6.0",
     "axios": "0.18.0",
index e2097878a9f98276ffe1d78cf49ac6ca4468d894..5383c66e949f59ee1b2d1258f0d2d1402f485bdb 100644 (file)
@@ -2,6 +2,8 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
+import { PropertyValue } from "~/models/search-bar";
+
 export const formatDate = (isoDate?: string) => {
     if (isoDate) {
         const date = new Date(isoDate);
@@ -67,3 +69,12 @@ const FILE_SIZES = [
         unit: "B"
     }
 ];
+
+export const formatPropertyValue = (pv: PropertyValue) => {
+    if (pv.key) {
+        return pv.value
+            ? `${pv.key}: ${pv.value}`
+            : pv.key;
+    }
+    return "";
+};
diff --git a/src/common/objects.ts b/src/common/objects.ts
new file mode 100644 (file)
index 0000000..0a01ed6
--- /dev/null
@@ -0,0 +1,18 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+import * as _ from "lodash";
+
+export function getModifiedKeys(a: any, b: any) {
+    const keys = _.union(_.keys(a), _.keys(b));
+    return _.filter(keys, key => a[key] !== b[key]);
+}
+
+export function getModifiedKeysValues(a: any, b: any) {
+    const keys = getModifiedKeys(a, b);
+    const obj = {};
+    keys.forEach(k => {
+        obj[k] = a[k];
+    });
+    return obj;
+}
index 7da4ba4a30845a85713439624c8f70fcb052c99a..c5811bb6ea716b44692752c68d7f630d61208e7f 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as React from 'react';
-import { Input as MuiInput, Chip as MuiChip, Popper as MuiPopper, Paper, FormControl, InputLabel, StyleRulesCallback, withStyles, RootRef, ListItemText, ListItem, List, FormHelperText } from '@material-ui/core';
+import { Input as MuiInput, Chip as MuiChip, Popper as MuiPopper, Paper as MuiPaper, FormControl, InputLabel, StyleRulesCallback, withStyles, RootRef, ListItemText, ListItem, List, FormHelperText } from '@material-ui/core';
 import { PopperProps } from '@material-ui/core/Popper';
 import { WithStyles } from '@material-ui/core/styles';
 import { noop } from 'lodash';
@@ -27,11 +27,13 @@ export interface AutocompleteProps<Item, Suggestion> {
 
 export interface AutocompleteState {
     suggestionsOpen: boolean;
+    selectedSuggestionIndex: number;
 }
 export class Autocomplete<Value, Suggestion> extends React.Component<AutocompleteProps<Value, Suggestion>, AutocompleteState> {
 
     state = {
         suggestionsOpen: false,
+        selectedSuggestionIndex: 0,
     };
 
     containerRef = React.createRef<HTMLDivElement>();
@@ -64,10 +66,11 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
             onBlur={this.handleBlur}
             onChange={this.props.onChange}
             onKeyPress={this.handleKeyPress}
+            onKeyDown={this.handleNavigationKeyPress}
         />;
     }
 
-    renderHelperText(){
+    renderHelperText() {
         return <FormHelperText>{this.props.helperText}</FormHelperText>;
     }
 
@@ -75,13 +78,18 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         const { suggestions = [] } = this.props;
         return (
             <Popper
-                open={this.state.suggestionsOpen && suggestions.length > 0}
-                anchorEl={this.inputRef.current}>
+                open={this.isSuggestionBoxOpen()}
+                anchorEl={this.inputRef.current}
+                key={suggestions.length}>
                 <Paper onMouseDown={this.preventBlur}>
                     <List dense style={{ width: this.getSuggestionsWidth() }}>
                         {suggestions.map(
                             (suggestion, index) =>
-                                <ListItem button key={index} onClick={this.handleSelect(suggestion)}>
+                                <ListItem
+                                    button
+                                    key={index}
+                                    onClick={this.handleSelect(suggestion)}
+                                    selected={index === this.state.selectedSuggestionIndex}>
                                     {this.renderSuggestion(suggestion)}
                                 </ListItem>
                         )}
@@ -91,6 +99,11 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         );
     }
 
+    isSuggestionBoxOpen() {
+        const { suggestions = [] } = this.props;
+        return this.state.suggestionsOpen && suggestions.length > 0;
+    }
+
     handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
         const { onFocus = noop } = this.props;
         this.setState({ suggestionsOpen: true });
@@ -105,13 +118,35 @@ export class Autocomplete<Value, Suggestion> extends React.Component<Autocomplet
         });
     }
 
-    handleKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
-        const { onCreate = noop } = this.props;
-        if (key === 'Enter' && this.props.value.length > 0) {
-            onCreate();
+    handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
+        const { onCreate = noop, onSelect = noop, suggestions = [] } = this.props;
+        const { selectedSuggestionIndex } = this.state;
+        if (event.key === 'Enter') {
+            if (this.isSuggestionBoxOpen() && selectedSuggestionIndex < suggestions.length) {
+                // prevent form submissions when selecting a suggestion
+                event.preventDefault(); 
+                onSelect(suggestions[selectedSuggestionIndex]);
+            } else if (this.props.value.length > 0) {
+                onCreate();
+            }
+        }
+    }
+
+    handleNavigationKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
+        if (key === 'ArrowUp') {
+            this.updateSelectedSuggestionIndex(-1);
+        } else if (key === 'ArrowDown') {
+            this.updateSelectedSuggestionIndex(1);
         }
     }
 
+    updateSelectedSuggestionIndex(value: -1 | 1) {
+        const { suggestions = [] } = this.props;
+        this.setState(({ selectedSuggestionIndex }) => ({
+            selectedSuggestionIndex: (selectedSuggestionIndex + value) % suggestions.length
+        }));
+    }
+
     renderChips() {
         const { items, onDelete } = this.props;
         return items.map(
@@ -199,3 +234,10 @@ const inputStyles: StyleRulesCallback<InputClasses> = () => ({
 });
 
 const Input = withStyles(inputStyles)(MuiInput);
+
+const Paper = withStyles({
+    root: {
+        maxHeight: '80vh',
+        overflowY: 'auto',
+    }
+})(MuiPaper);
index cb979c7bd216b31d7e7d6760c08da9471a159472..d906a32cbf7b5bab7f41dbed0062de63fa2d252c 100644 (file)
@@ -4,16 +4,16 @@
 
 import * as React from 'react';
 import { Grid, Paper, Toolbar, StyleRulesCallback, withStyles, WithStyles, TablePagination, IconButton, Tooltip } from '@material-ui/core';
-import { ColumnSelector } from "../column-selector/column-selector";
-import { DataTable, DataColumns } from "../data-table/data-table";
-import { DataColumn, SortDirection } from "../data-table/data-column";
-import { SearchInput } from '../search-input/search-input';
+import { ColumnSelector } from "~/components/column-selector/column-selector";
+import { DataTable, DataColumns } from "~/components/data-table/data-table";
+import { DataColumn, SortDirection } from "~/components/data-table/data-column";
+import { SearchInput } from '~/components/search-input/search-input';
 import { ArvadosTheme } from "~/common/custom-theme";
 import { createTree } from '~/models/tree';
-import { DataTableFilters } from '../data-table-filters/data-table-filters-tree';
+import { DataTableFilters } from '~/components/data-table-filters/data-table-filters-tree';
 import { MoreOptionsIcon } from '~/components/icon/icon';
 
-type CssRules = 'searchBox' | "toolbar" | "footer" | "root" | 'moreOptionsButton';
+type CssRules = 'searchBox' | "toolbar" | "footer" | "root" | 'moreOptionsButton' | 'rootUserPanel';
 
 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
     searchBox: {
@@ -28,6 +28,10 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
     root: {
         height: '100%'
     },
+    rootUserPanel: {
+        height: '100%',
+        boxShadow: 'none'
+    },
     moreOptionsButton: {
         padding: 0
     }
@@ -44,6 +48,7 @@ interface DataExplorerDataProps<T> {
     contextMenuColumn: boolean;
     dataTableDefaultView?: React.ReactNode;
     working?: boolean;
+    isUserPanel?: boolean;
 }
 
 interface DataExplorerActionProps<T> {
@@ -74,19 +79,19 @@ export const DataExplorer = withStyles(styles)(
                 columns, onContextMenu, onFiltersChange, onSortToggle, working, extractKey,
                 rowsPerPage, rowsPerPageOptions, onColumnToggle, searchValue, onSearch,
                 items, itemsAvailable, onRowClick, onRowDoubleClick, classes,
-                dataTableDefaultView
+                dataTableDefaultView, isUserPanel
             } = this.props;
-            return <Paper className={classes.root}>
-                <Toolbar className={classes.toolbar}>
+            return <Paper className={!isUserPanel ? classes.root : classes.rootUserPanel}>
+                <Toolbar className={!isUserPanel ? classes.toolbar : ''}>
                     <Grid container justify="space-between" wrap="nowrap" alignItems="center">
                         <div className={classes.searchBox}>
                             <SearchInput
                                 value={searchValue}
                                 onSearch={onSearch} />
                         </div>
-                        <ColumnSelector
+                        {!isUserPanel && <ColumnSelector
                             columns={columns}
-                            onColumnToggle={onColumnToggle} />
+                            onColumnToggle={onColumnToggle} />}
                     </Grid>
                 </Toolbar>
                 <DataTable
index fbd6c9a88e1bb8ac18d66bd3ff4c681f38ab89ee..8f702af164bdabc1945ca99d42f9bb7742c0af5c 100644 (file)
@@ -5,31 +5,31 @@
 import * as React from 'react';
 import * as ReactDOM from 'react-dom';
 import { Provider } from "react-redux";
-import { MainPanel } from './views/main-panel/main-panel';
-import './index.css';
+import { MainPanel } from '~/views/main-panel/main-panel';
+import '~/index.css';
 import { Route, Switch } from 'react-router';
 import createBrowserHistory from "history/createBrowserHistory";
 import { History } from "history";
-import { configureStore, RootStore } from './store/store';
+import { configureStore, RootStore } from '~/store/store';
 import { ConnectedRouter } from "react-router-redux";
-import { ApiToken } from "./views-components/api-token/api-token";
-import { initAuth } from "./store/auth/auth-action";
-import { createServices } from "./services/services";
+import { ApiToken } from "~/views-components/api-token/api-token";
+import { initAuth } from "~/store/auth/auth-action";
+import { createServices } from "~/services/services";
 import { MuiThemeProvider } from '@material-ui/core/styles';
-import { CustomTheme } from './common/custom-theme';
-import { fetchConfig } from './common/config';
-import { addMenuActionSet, ContextMenuKind } from './views-components/context-menu/context-menu';
-import { rootProjectActionSet } from "./views-components/context-menu/action-sets/root-project-action-set";
-import { projectActionSet } from "./views-components/context-menu/action-sets/project-action-set";
-import { resourceActionSet } from './views-components/context-menu/action-sets/resource-action-set';
-import { favoriteActionSet } from "./views-components/context-menu/action-sets/favorite-action-set";
-import { collectionFilesActionSet } from './views-components/context-menu/action-sets/collection-files-action-set';
-import { collectionFilesItemActionSet } from './views-components/context-menu/action-sets/collection-files-item-action-set';
-import { collectionFilesNotSelectedActionSet } from './views-components/context-menu/action-sets/collection-files-not-selected-action-set';
-import { collectionActionSet } from './views-components/context-menu/action-sets/collection-action-set';
-import { collectionResourceActionSet } from './views-components/context-menu/action-sets/collection-resource-action-set';
-import { processActionSet } from './views-components/context-menu/action-sets/process-action-set';
-import { loadWorkbench } from './store/workbench/workbench-actions';
+import { CustomTheme } from '~/common/custom-theme';
+import { fetchConfig } from '~/common/config';
+import { addMenuActionSet, ContextMenuKind } from '~/views-components/context-menu/context-menu';
+import { rootProjectActionSet } from "~/views-components/context-menu/action-sets/root-project-action-set";
+import { projectActionSet } from "~/views-components/context-menu/action-sets/project-action-set";
+import { resourceActionSet } from '~/views-components/context-menu/action-sets/resource-action-set';
+import { favoriteActionSet } from "~/views-components/context-menu/action-sets/favorite-action-set";
+import { collectionFilesActionSet } from '~/views-components/context-menu/action-sets/collection-files-action-set';
+import { collectionFilesItemActionSet } from '~/views-components/context-menu/action-sets/collection-files-item-action-set';
+import { collectionFilesNotSelectedActionSet } from '~/views-components/context-menu/action-sets/collection-files-not-selected-action-set';
+import { collectionActionSet } from '~/views-components/context-menu/action-sets/collection-action-set';
+import { collectionResourceActionSet } from '~/views-components/context-menu/action-sets/collection-resource-action-set';
+import { processActionSet } from '~/views-components/context-menu/action-sets/process-action-set';
+import { loadWorkbench } from '~/store/workbench/workbench-actions';
 import { Routes } from '~/routes/routes';
 import { trashActionSet } from "~/views-components/context-menu/action-sets/trash-action-set";
 import { ServiceRepository } from '~/services/services';
@@ -53,7 +53,9 @@ import { sshKeyActionSet } from '~/views-components/context-menu/action-sets/ssh
 import { keepServiceActionSet } from '~/views-components/context-menu/action-sets/keep-service-action-set';
 import { loadVocabulary } from '~/store/vocabulary/vocabulary-actions';
 import { virtualMachineActionSet } from '~/views-components/context-menu/action-sets/virtual-machine-action-set';
+import { userActionSet } from '~/views-components/context-menu/action-sets/user-action-set';
 import { computeNodeActionSet } from '~/views-components/context-menu/action-sets/compute-node-action-set';
+import { apiClientAuthorizationActionSet } from '~/views-components/context-menu/action-sets/api-client-authorization-action-set';
 
 console.log(`Starting arvados [${getBuildInfo()}]`);
 
@@ -74,7 +76,9 @@ addMenuActionSet(ContextMenuKind.REPOSITORY, repositoryActionSet);
 addMenuActionSet(ContextMenuKind.SSH_KEY, sshKeyActionSet);
 addMenuActionSet(ContextMenuKind.VIRTUAL_MACHINE, virtualMachineActionSet);
 addMenuActionSet(ContextMenuKind.KEEP_SERVICE, keepServiceActionSet);
+addMenuActionSet(ContextMenuKind.USER, userActionSet);
 addMenuActionSet(ContextMenuKind.NODE, computeNodeActionSet);
+addMenuActionSet(ContextMenuKind.API_CLIENT_AUTHORIZATION, apiClientAuthorizationActionSet);
 
 fetchConfig()
     .then(({ config, apiHost }) => {
diff --git a/src/models/api-client-authorization.ts b/src/models/api-client-authorization.ts
new file mode 100644 (file)
index 0000000..aff50be
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+export interface ApiClientAuthorization {
+    uuid: string;
+    apiToken: string;
+    apiClientId: number;
+    userId: number;
+    createdByIpAddress: string;
+    lastUsedByIpAddress: string;
+    lastUsedAt: string;
+    expiresAt: string;
+    createdAt: string;
+    updatedAt: string;
+    ownerUuid: string;
+    defaultOwnerUuid: string;
+    scopes: string[];
+}
\ No newline at end of file
index 4d2d92e0155b183763b1445865420ffe84a558bf..eddcd5a05db44d536d736dce47e28ec27e8df0c1 100644 (file)
@@ -21,6 +21,7 @@ export interface TrashableResource extends Resource {
 }
 
 export enum ResourceKind {
+    API_CLIENT_AUTHORIZATION = "arvados#apiClientAuthorization",
     COLLECTION = "arvados#collection",
     CONTAINER = "arvados#container",
     CONTAINER_REQUEST = "arvados#containerRequest",
@@ -39,6 +40,7 @@ export enum ResourceKind {
 }
 
 export enum ResourceObjectType {
+    API_CLIENT_AUTHORIZATION = 'gj3su',
     COLLECTION = '4zz18',
     CONTAINER = 'dz642',
     CONTAINER_REQUEST = 'xvhdp',
@@ -93,6 +95,8 @@ export const extractUuidKind = (uuid: string = '') => {
             return ResourceKind.KEEP_SERVICE;
         case ResourceObjectType.NODE:
             return ResourceKind.NODE;
+        case ResourceObjectType.API_CLIENT_AUTHORIZATION:
+            return ResourceKind.API_CLIENT_AUTHORIZATION;
         default:
             return undefined;
     }
index 4df5c38f2527278babfa187210681d89310685cb..798f9c8f27bd84d1aeb6fbb06aaa244771ff840b 100644 (file)
@@ -12,11 +12,12 @@ export type SearchBarAdvanceFormData = {
     dateFrom: string;
     dateTo: string;
     saveQuery: boolean;
-    searchQuery: string;
-    properties: PropertyValues[];
-} & PropertyValues;
+    queryName: string;
+    searchValue: string;
+    properties: PropertyValue[];
+};
 
-export interface PropertyValues {
+export interface PropertyValue {
     key: string;
     value: string;
 }
@@ -25,4 +26,4 @@ export enum ClusterObjectType {
     INDIANAPOLIS = "indianapolis",
     KAISERAUGST = "kaiseraugst",
     PENZBERG = "penzberg"
-}
\ No newline at end of file
+}
index 60d598d57bd637c0728476f6b6b5f18a77909270..a7b8458bf81fb37eb6480d33ea19c6e484b67180 100644 (file)
@@ -37,7 +37,7 @@ export interface UserResource extends Resource {
     lastName: string;
     identityUrl: string;
     isAdmin: boolean;
-    prefs: string;
+    prefs: UserPrefs;
     defaultOwnerUuid: string;
     isActive: boolean;
     writableBy: string[];
index 68de3107f1a82bb219fb49e883c27682c486902f..e2454d63ac1aea6eaa6d1ac0fcba9dc0e384dd4e 100644 (file)
@@ -31,7 +31,9 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
     const sshKeysMatch = Routes.matchSshKeysRoute(pathname);
     const keepServicesMatch = Routes.matchKeepServicesRoute(pathname);
     const computeNodesMatch = Routes.matchComputeNodesRoute(pathname);
+    const apiClientAuthorizationsMatch = Routes.matchApiClientAuthorizationsRoute(pathname);
     const myAccountMatch = Routes.matchMyAccountRoute(pathname);
+    const userMatch = Routes.matchUsersRoute(pathname);
 
     if (projectMatch) {
         store.dispatch(WorkbenchActions.loadProject(projectMatch.params.id));
@@ -65,7 +67,11 @@ const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
         store.dispatch(WorkbenchActions.loadKeepServices);
     } else if (computeNodesMatch) {
         store.dispatch(WorkbenchActions.loadComputeNodes);
+    } else if (apiClientAuthorizationsMatch) {
+        store.dispatch(WorkbenchActions.loadApiClientAuthorizations);
     } else if (myAccountMatch) {
         store.dispatch(WorkbenchActions.loadMyAccount);
+    }else if (userMatch) {
+        store.dispatch(WorkbenchActions.loadUsers);
     }
 };
index 71d920ab3e4d984dcf126a5aaf6b439431dde9d7..88dfd46951945928336079381035e70e1733ae07 100644 (file)
@@ -25,7 +25,9 @@ export const Routes = {
     SSH_KEYS: `/ssh-keys`,
     MY_ACCOUNT: '/my-account',
     KEEP_SERVICES: `/keep-services`,
-    COMPUTE_NODES: `/nodes`
+    COMPUTE_NODES: `/nodes`,
+    USERS: '/users',
+    API_CLIENT_AUTHORIZATIONS: `/api_client_authorizations`
 };
 
 export const getResourceUrl = (uuid: string) => {
@@ -85,10 +87,10 @@ export const matchSearchResultsRoute = (route: string) =>
 
 export const matchVirtualMachineRoute = (route: string) =>
     matchPath<ResourceRouteParams>(route, { path: Routes.VIRTUAL_MACHINES });
-    
+
 export const matchRepositoriesRoute = (route: string) =>
     matchPath<ResourceRouteParams>(route, { path: Routes.REPOSITORIES });
-    
+
 export const matchSshKeysRoute = (route: string) =>
     matchPath(route, { path: Routes.SSH_KEYS });
 
@@ -98,5 +100,11 @@ export const matchMyAccountRoute = (route: string) =>
 export const matchKeepServicesRoute = (route: string) =>
     matchPath(route, { path: Routes.KEEP_SERVICES });
 
+export const matchUsersRoute = (route: string) =>
+    matchPath(route, { path: Routes.USERS });
+
 export const matchComputeNodesRoute = (route: string) =>
-    matchPath(route, { path: Routes.COMPUTE_NODES });
\ No newline at end of file
+    matchPath(route, { path: Routes.COMPUTE_NODES });
+
+export const matchApiClientAuthorizationsRoute = (route: string) =>
+    matchPath(route, { path: Routes.API_CLIENT_AUTHORIZATIONS });
diff --git a/src/services/api-client-authorization-service/api-client-authorization-service.ts b/src/services/api-client-authorization-service/api-client-authorization-service.ts
new file mode 100644 (file)
index 0000000..3bf4ae8
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { AxiosInstance } from "axios";
+import { ApiActions } from '~/services/api/api-actions';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { CommonService } from '~/services/common-service/common-service';
+
+export class ApiClientAuthorizationService extends CommonService<ApiClientAuthorization> {
+    constructor(serverApi: AxiosInstance, actions: ApiActions) {
+        super(serverApi, "api_client_authorizations", actions);
+    }
+} 
\ No newline at end of file
index 1ebf488636115c7dfb2cd9bcbf420d79ee82fa1b..08746c81b9ee1d91736b4e9e09eb79b820bd916f 100644 (file)
@@ -51,6 +51,10 @@ export class FilterBuilder {
         return this.addCondition(field, "<=", value, "", "", resourcePrefix);
     }
 
+    public addExists(value?: string, resourcePrefix?: string) {
+        return this.addCondition("properties", "exists", value, "", "", resourcePrefix);
+    }
+
     public getFilters() {
         return this.filters;
     }
@@ -69,7 +73,9 @@ export class FilterBuilder {
                 ? resourcePrefix + "."
                 : "";
 
-            this.filters += `${this.filters ? "," : ""}["${resPrefix}${_.snakeCase(field)}","${cond}",${value}]`;
+            const fld = field.indexOf('properties.') < 0 ? _.snakeCase(field) : field;
+
+            this.filters += `${this.filters ? "," : ""}["${resPrefix}${fld}","${cond}",${value}]`;
         }
         return this;
     }
index 6114c560526e7b598c033b0a9c6ae4435bd10047..471c32fa21020e8b9eb1db9ae248ad3c6aa30f8f 100644 (file)
@@ -3,33 +3,10 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as _ from "lodash";
-import { AxiosInstance, AxiosPromise } from "axios";
+import { AxiosInstance } from "axios";
 import { Resource } from "src/models/resource";
-import * as uuid from "uuid/v4";
 import { ApiActions } from "~/services/api/api-actions";
-
-export interface ListArguments {
-    limit?: number;
-    offset?: number;
-    filters?: string;
-    order?: string;
-    select?: string[];
-    distinct?: boolean;
-    count?: string;
-}
-
-export interface ListResults<T> {
-    kind: string;
-    offset: number;
-    limit: number;
-    items: T[];
-    itemsAvailable: number;
-}
-
-export interface Errors {
-    errors: string[];
-    errorToken: string;
-}
+import { CommonService } from "~/services/common-service/common-service";
 
 export enum CommonResourceServiceError {
     UNIQUE_VIOLATION = 'UniqueViolation',
@@ -40,105 +17,12 @@ export enum CommonResourceServiceError {
     NONE = 'None'
 }
 
-export class CommonResourceService<T extends Resource> {
-
-    static mapResponseKeys = (response: { data: any }) =>
-        CommonResourceService.mapKeys(_.camelCase)(response.data)
-
-    static mapKeys = (mapFn: (key: string) => string) =>
-        (value: any): any => {
-            switch (true) {
-                case _.isPlainObject(value):
-                    return Object
-                        .keys(value)
-                        .map(key => [key, mapFn(key)])
-                        .reduce((newValue, [key, newKey]) => ({
-                            ...newValue,
-                            [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
-                        }), {});
-                case _.isArray(value):
-                    return value.map(CommonResourceService.mapKeys(mapFn));
-                default:
-                    return value;
-            }
-        }
-
-    static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true): Promise<R> {
-        const reqId = uuid();
-        actions.progressFn(reqId, true);
-        return promise
-            .then(data => {
-                actions.progressFn(reqId, false);
-                return data;
-            })
-            .then((response: { data: any }) => {
-                return mapKeys ? CommonResourceService.mapResponseKeys(response) : response.data;
-            })
-            .catch(({ response }) => {
-                actions.progressFn(reqId, false);
-                const errors = CommonResourceService.mapResponseKeys(response) as Errors;
-                actions.errorFn(reqId, errors);
-                throw errors;
-            });
-    }
-
-    protected serverApi: AxiosInstance;
-    protected resourceType: string;
-    protected actions: ApiActions;
+export class CommonResourceService<T extends Resource> extends CommonService<T> {
 
     constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
-        this.serverApi = serverApi;
-        this.resourceType = '/' + resourceType + '/';
-        this.actions = actions;
-    }
-
-    create(data?: Partial<T>) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
-            this.actions
-        );
-    }
-
-    delete(uuid: string): Promise<T> {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .delete(this.resourceType + uuid),
-            this.actions
-        );
-    }
-
-    get(uuid: string) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .get<T>(this.resourceType + uuid),
-            this.actions
-        );
-    }
-
-    list(args: ListArguments = {}): Promise<ListResults<T>> {
-        const { filters, order, ...other } = args;
-        const params = {
-            ...other,
-            filters: filters ? `[${filters}]` : undefined,
-            order: order ? order : undefined
-        };
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .get(this.resourceType, {
-                    params: CommonResourceService.mapKeys(_.snakeCase)(params)
-                }),
-            this.actions
-        );
-    }
-
-    update(uuid: string, data: Partial<T>) {
-        return CommonResourceService.defaultResponse(
-            this.serverApi
-                .put<T>(this.resourceType + uuid, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
-            this.actions
-        );
+        super(serverApi, resourceType, actions);
     }
+    
 }
 
 export const getCommonResourceServiceError = (errorResponse: any) => {
diff --git a/src/services/common-service/common-service.ts b/src/services/common-service/common-service.ts
new file mode 100644 (file)
index 0000000..b301a72
--- /dev/null
@@ -0,0 +1,131 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as _ from "lodash";
+import { AxiosInstance, AxiosPromise } from "axios";
+import * as uuid from "uuid/v4";
+import { ApiActions } from "~/services/api/api-actions";
+
+interface Errors {
+    errors: string[];
+    errorToken: string;
+}
+
+export interface ListArguments {
+    limit?: number;
+    offset?: number;
+    filters?: string;
+    order?: string;
+    select?: string[];
+    distinct?: boolean;
+    count?: string;
+}
+
+export interface ListResults<T> {
+    kind: string;
+    offset: number;
+    limit: number;
+    items: T[];
+    itemsAvailable: number;
+}
+
+export class CommonService<T> {
+    protected serverApi: AxiosInstance;
+    protected resourceType: string;
+    protected actions: ApiActions;
+
+    constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
+        this.serverApi = serverApi;
+        this.resourceType = '/' + resourceType + '/';
+        this.actions = actions;
+    }
+
+    static mapResponseKeys = (response: { data: any }) =>
+        CommonService.mapKeys(_.camelCase)(response.data)
+
+    static mapKeys = (mapFn: (key: string) => string) =>
+        (value: any): any => {
+            switch (true) {
+                case _.isPlainObject(value):
+                    return Object
+                        .keys(value)
+                        .map(key => [key, mapFn(key)])
+                        .reduce((newValue, [key, newKey]) => ({
+                            ...newValue,
+                            [newKey]: CommonService.mapKeys(mapFn)(value[key])
+                        }), {});
+                case _.isArray(value):
+                    return value.map(CommonService.mapKeys(mapFn));
+                default:
+                    return value;
+            }
+        }
+
+    static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true): Promise<R> {
+        const reqId = uuid();
+        actions.progressFn(reqId, true);
+        return promise
+            .then(data => {
+                actions.progressFn(reqId, false);
+                return data;
+            })
+            .then((response: { data: any }) => {
+                return mapKeys ? CommonService.mapResponseKeys(response) : response.data;
+            })
+            .catch(({ response }) => {
+                actions.progressFn(reqId, false);
+                const errors = CommonService.mapResponseKeys(response) as Errors;
+                actions.errorFn(reqId, errors);
+                throw errors;
+            });
+    }
+
+    create(data?: Partial<T>) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .post<T>(this.resourceType, data && CommonService.mapKeys(_.snakeCase)(data)),
+            this.actions
+        );
+    }
+
+    delete(uuid: string): Promise<T> {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .delete(this.resourceType + uuid),
+            this.actions
+        );
+    }
+
+    get(uuid: string) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .get<T>(this.resourceType + uuid),
+            this.actions
+        );
+    }
+
+    list(args: ListArguments = {}): Promise<ListResults<T>> {
+        const { filters, order, ...other } = args;
+        const params = {
+            ...other,
+            filters: filters ? `[${filters}]` : undefined,
+            order: order ? order : undefined
+        };
+        return CommonService.defaultResponse(
+            this.serverApi
+                .get(this.resourceType, {
+                    params: CommonService.mapKeys(_.snakeCase)(params)
+                }),
+            this.actions
+        );
+    }
+
+    update(uuid: string, data: Partial<T>) {
+        return CommonService.defaultResponse(
+            this.serverApi
+                .put<T>(this.resourceType + uuid, data && CommonService.mapKeys(_.snakeCase)(data)),
+            this.actions
+        );
+    }
+}
\ No newline at end of file
index 92b0713dbcc6ee2ce8b0eb0939d4cb928710676b..c41b2b992e10aafd33f07353f17087834ecf8a68 100644 (file)
@@ -6,7 +6,7 @@ import { LinkService } from "../link-service/link-service";
 import { GroupsService, GroupContentsResource } from "../groups-service/groups-service";
 import { LinkClass } from "~/models/link";
 import { FilterBuilder, joinFilters } from "~/services/api/filter-builder";
-import { ListResults } from "~/services/common-service/common-resource-service";
+import { ListResults } from '~/services/common-service/common-service';
 
 export interface FavoriteListArguments {
     limit?: number;
index d1e2eff2791c101ef7fd21b2b52ff6e6fb0ed438..d8b33f601f94c553e79e8be078f0dc2c9c4ee62f 100644 (file)
@@ -3,7 +3,8 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as _ from "lodash";
-import { CommonResourceService, ListResults, ListArguments } from '~/services/common-service/common-resource-service';
+import { CommonResourceService } from '~/services/common-service/common-resource-service';
+import { ListResults, ListArguments } from '~/services/common-service/common-service';
 import { AxiosInstance } from "axios";
 import { CollectionResource } from "~/models/collection";
 import { ProjectResource } from "~/models/project";
index 4bb0fe0934eecde90c1d2621745b43477b0dd6db..763844e0663552448cfd0f75ebe0a2ed987e2e04 100644 (file)
@@ -4,8 +4,9 @@
 
 import { LinkService } from "~/services/link-service/link-service";
 import { PermissionResource } from "~/models/permission";
-import { ListArguments, ListResults, CommonResourceService } from '~/services/common-service/common-resource-service';
+import { CommonResourceService } from '~/services/common-service/common-resource-service';
 import { LinkClass } from '../../models/link';
+import { ListArguments, ListResults } from '~/services/common-service/common-service';
 
 export class PermissionService extends LinkService<PermissionResource> {
 
index d60034711ed8402e654c3fa43494c963952a0a4a..5c686aae67fd5db06251071bacbc591b5c5f0f51 100644 (file)
@@ -5,7 +5,7 @@
 import { GroupsService } from "../groups-service/groups-service";
 import { ProjectResource } from "~/models/project";
 import { GroupClass } from "~/models/group";
-import { ListArguments } from "~/services/common-service/common-resource-service";
+import { ListArguments } from "~/services/common-service/common-service";
 import { FilterBuilder, joinFilters } from "~/services/api/filter-builder";
 import { TrashableResourceService } from '~/services/common-service/trashable-resource-service';
 import { snakeCase } from 'lodash';
index a8e91c39633b6007ad89cb2aa354a9fbe58fc1f4..84d120a89c52dacc835256b8f39e6f56ac0f8212 100644 (file)
@@ -26,7 +26,7 @@ export class SearchService {
     }
 
     editSavedQueries(data: SearchBarAdvanceFormData) {
-        const itemIndex = this.savedQueries.findIndex(item => item.searchQuery === data.searchQuery);
+        const itemIndex = this.savedQueries.findIndex(item => item.queryName === data.queryName);
         this.savedQueries[itemIndex] = {...data};
         localStorage.setItem('savedQueries', JSON.stringify(this.savedQueries));
     }
index d524405fe62000a889d980520e00ef0b9e771e79..59fe2d4704ee194e6a5f0cf684c09b3629342ada 100644 (file)
@@ -3,6 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import Axios from "axios";
+import { ApiClientAuthorizationService } from '~/services/api-client-authorization-service/api-client-authorization-service';
 import { AuthService } from "./auth-service/auth-service";
 import { GroupsService } from "./groups-service/groups-service";
 import { ProjectService } from "./project-service/project-service";
@@ -39,6 +40,7 @@ export const createServices = (config: Config, actions: ApiActions) => {
     const webdavClient = new WebDAV();
     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
 
+    const apiClientAuthorizationService = new ApiClientAuthorizationService(apiClient, actions);
     const authorizedKeysService = new AuthorizedKeysService(apiClient, actions);
     const containerRequestService = new ContainerRequestService(apiClient, actions);
     const containerService = new ContainerService(apiClient, actions);
@@ -66,6 +68,7 @@ export const createServices = (config: Config, actions: ApiActions) => {
     return {
         ancestorsService,
         apiClient,
+        apiClientAuthorizationService,
         authService,
         authorizedKeysService,
         collectionFilesService,
index 6b20f8b328a2ac555552031d5732834a6912fdc8..851eb949a9a7036ce5e5231fd8aa280e7bbab61d 100644 (file)
@@ -14,14 +14,15 @@ import { CollectionResource } from '~/models/collection';
 import { ProjectResource } from '~/models/project';
 import { ServiceRepository } from '~/services/services';
 import { FilterBuilder } from '~/services/api/filter-builder';
+import { ListResults } from '~/services/common-service/common-service';
 import { RepositoryResource } from '~/models/repositories';
 import { SshKeyResource } from '~/models/ssh-key';
 import { VirtualMachinesResource } from '~/models/virtual-machines';
 import { UserResource } from '~/models/user';
-import { ListResults } from '~/services/common-service/common-resource-service';
 import { LinkResource } from '~/models/link';
 import { KeepServiceResource } from '~/models/keep-services';
 import { NodeResource } from '~/models/node';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
 
 export const ADVANCED_TAB_DIALOG = 'advancedTabDialog';
 
@@ -74,7 +75,9 @@ enum ResourcePrefix {
     AUTORIZED_KEYS = 'authorized_keys',
     VIRTUAL_MACHINES = 'virtual_machines',
     KEEP_SERVICES = 'keep_services',
-    COMPUTE_NODES = 'nodes'
+    COMPUTE_NODES = 'nodes',
+    USERS = 'users',
+    API_CLIENT_AUTHORIZATIONS = 'api_client_authorizations'
 }
 
 enum KeepServiceData {
@@ -82,14 +85,24 @@ enum KeepServiceData {
     CREATED_AT = 'created_at'
 }
 
+enum UserData {
+    USER = 'user',
+    USERNAME = 'username'
+}
+
 enum ComputeNodeData {
     COMPUTE_NODE = 'node',
     PROPERTIES = 'properties'
 }
 
-type AdvanceResourceKind = CollectionData | ProcessData | ProjectData | RepositoryData | SshKeyData | VirtualMachineData | KeepServiceData | ComputeNodeData;
+enum ApiClientAuthorizationsData {
+    API_CLIENT_AUTHORIZATION = 'api_client_authorization',
+    DEFAULT_OWNER_UUID = 'default_owner_uuid'
+}
+
+type AdvanceResourceKind = CollectionData | ProcessData | ProjectData | RepositoryData | SshKeyData | VirtualMachineData | KeepServiceData | ComputeNodeData | ApiClientAuthorizationsData | UserData;
 type AdvanceResourcePrefix = GroupContentsResourcePrefix | ResourcePrefix;
-type AdvanceResponseData = ContainerRequestResource | ProjectResource | CollectionResource | RepositoryResource | SshKeyResource | VirtualMachinesResource | KeepServiceResource | NodeResource | undefined;
+type AdvanceResponseData = ContainerRequestResource | ProjectResource | CollectionResource | RepositoryResource | SshKeyResource | VirtualMachinesResource | KeepServiceResource | NodeResource | ApiClientAuthorization | UserResource | undefined;
 
 export const openAdvancedTabDialog = (uuid: string) =>
     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
@@ -200,6 +213,27 @@ export const openAdvancedTabDialog = (uuid: string) =>
                 });
                 dispatch<any>(initAdvancedTabDialog(advanceDataKeepService));
                 break;
+            case ResourceKind.USER:
+                const { resources } = getState();
+                const data = getResource<UserResource>(uuid)(resources);
+                const metadata = await services.linkService.list({
+                    filters: new FilterBuilder()
+                        .addEqual('headUuid', uuid)
+                        .getFilters()
+                });
+                const advanceDataUser = advancedTabData({
+                    uuid,
+                    metadata,
+                    user: '',
+                    apiResponseKind: userApiResponse,
+                    data,
+                    resourceKind: UserData.USER,
+                    resourcePrefix: ResourcePrefix.USERS,
+                    resourceKindProperty: UserData.USERNAME,
+                    property: data!.username
+                });
+                dispatch<any>(initAdvancedTabDialog(advanceDataUser));
+                break;
             case ResourceKind.NODE:
                 const dataComputeNode = getState().computeNodes.find(node => node.uuid === uuid);
                 const advanceDataComputeNode = advancedTabData({
@@ -215,6 +249,21 @@ export const openAdvancedTabDialog = (uuid: string) =>
                 });
                 dispatch<any>(initAdvancedTabDialog(advanceDataComputeNode));
                 break;
+            case ResourceKind.API_CLIENT_AUTHORIZATION:
+                const dataApiClientAuthorization = getState().apiClientAuthorizations.find(item => item.uuid === uuid);
+                const advanceDataApiClientAuthorization = advancedTabData({
+                    uuid,
+                    metadata: '',
+                    user: '',
+                    apiResponseKind: apiClientAuthorizationApiResponse,
+                    data: dataApiClientAuthorization,
+                    resourceKind: ApiClientAuthorizationsData.API_CLIENT_AUTHORIZATION,
+                    resourcePrefix: ResourcePrefix.API_CLIENT_AUTHORIZATIONS,
+                    resourceKindProperty: ApiClientAuthorizationsData.DEFAULT_OWNER_UUID,
+                    property: dataApiClientAuthorization!.defaultOwnerUuid
+                });
+                dispatch<any>(initAdvancedTabDialog(advanceDataApiClientAuthorization));
+                break;
             default:
                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Could not open advanced tab for this resource.", hideDuration: 2000, kind: SnackbarKind.ERROR }));
         }
@@ -465,6 +514,30 @@ const keepServiceApiResponse = (apiResponse: KeepServiceResource) => {
     return response;
 };
 
+const userApiResponse = (apiResponse: UserResource) => {
+    const {
+        uuid, ownerUuid, createdAt, modifiedAt, modifiedByClientUuid, modifiedByUserUuid,
+        email, firstName, lastName, identityUrl, isActive, isAdmin, prefs, defaultOwnerUuid, username
+    } = apiResponse;
+    const response = `"uuid": "${uuid}",
+"owner_uuid": "${ownerUuid}",
+"created_at": "${createdAt}",
+"modified_by_client_uuid": ${stringify(modifiedByClientUuid)},
+"modified_by_user_uuid": ${stringify(modifiedByUserUuid)},
+"modified_at": ${stringify(modifiedAt)},
+"email": "${email}",
+"first_name": "${firstName}",
+"last_name": "${stringify(lastName)}",
+"identity_url": "${identityUrl}",
+"is_active": "${isActive},
+"is_admin": "${isAdmin},
+"prefs": "${stringifyObject(prefs)},
+"default_owner_uuid": "${defaultOwnerUuid},
+"username": "${username}"`;
+
+    return response;
+};
+
 const computeNodeApiResponse = (apiResponse: NodeResource) => {
     const {
         uuid, slotNumber, hostname, domain, ipAddress, firstPingAt, lastPingAt, jobUuid,
@@ -487,5 +560,27 @@ const computeNodeApiResponse = (apiResponse: NodeResource) => {
 "properties": "${JSON.stringify(properties, null, 4)}",
 "info": "${JSON.stringify(info, null, 4)}"`;
 
+    return response;
+};
+
+const apiClientAuthorizationApiResponse = (apiResponse: ApiClientAuthorization) => {
+    const {
+        uuid, ownerUuid, apiToken, apiClientId, userId, createdByIpAddress, lastUsedByIpAddress,
+        lastUsedAt, expiresAt, defaultOwnerUuid, scopes, updatedAt, createdAt
+    } = apiResponse;
+    const response = `"uuid": "${uuid}",
+"owner_uuid": "${ownerUuid}",
+"api_token": "${stringify(apiToken)}",
+"api_client_id": "${stringify(apiClientId)}",
+"user_id": "${stringify(userId)}",
+"created_by_ip_address": "${stringify(createdByIpAddress)}",
+"last_used_by_ip_address": "${stringify(lastUsedByIpAddress)}",
+"last_used_at": "${stringify(lastUsedAt)}",
+"expires_at": "${stringify(expiresAt)}",
+"created_at": "${stringify(createdAt)}",
+"updated_at": "${stringify(updatedAt)}",
+"default_owner_uuid": "${stringify(defaultOwnerUuid)}",
+"scopes": "${JSON.stringify(scopes, null, 4)}"`;
+
     return response;
 };
\ No newline at end of file
diff --git a/src/store/api-client-authorizations/api-client-authorizations-actions.ts b/src/store/api-client-authorizations/api-client-authorizations-actions.ts
new file mode 100644 (file)
index 0000000..8ed8a38
--- /dev/null
@@ -0,0 +1,82 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { Dispatch } from "redux";
+import { unionize, ofType, UnionOf } from "~/common/unionize";
+import { RootState } from '~/store/store';
+import { setBreadcrumbs } from '~/store/breadcrumbs/breadcrumbs-actions';
+import { ServiceRepository } from "~/services/services";
+import { dialogActions } from '~/store/dialog/dialog-actions';
+import { snackbarActions } from '~/store/snackbar/snackbar-actions';
+import { navigateToRootProject } from '~/store/navigation/navigation-action';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+
+export const apiClientAuthorizationsActions = unionize({
+    SET_API_CLIENT_AUTHORIZATIONS: ofType<ApiClientAuthorization[]>(),
+    REMOVE_API_CLIENT_AUTHORIZATION: ofType<string>()
+});
+
+export type ApiClientAuthorizationsActions = UnionOf<typeof apiClientAuthorizationsActions>;
+
+export const API_CLIENT_AUTHORIZATION_REMOVE_DIALOG = 'apiClientAuthorizationRemoveDialog';
+export const API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG = 'apiClientAuthorizationAttributesDialog';
+export const API_CLIENT_AUTHORIZATION_HELP_DIALOG = 'apiClientAuthorizationHelpDialog';
+
+export const loadApiClientAuthorizationsPanel = () =>
+    async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+        const user = getState().auth.user;
+        if (user && user.isAdmin) {
+            try {
+                dispatch(setBreadcrumbs([{ label: 'Api client authorizations' }]));
+                const response = await services.apiClientAuthorizationService.list();
+                dispatch(apiClientAuthorizationsActions.SET_API_CLIENT_AUTHORIZATIONS(response.items));
+            } catch (e) {
+                dispatch(snackbarActions.OPEN_SNACKBAR({ message: "You don't have permissions to view this page", hideDuration: 2000 }));
+                return;
+            }
+        } else {
+            dispatch(navigateToRootProject);
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "You don't have permissions to view this page", hideDuration: 2000 }));
+        }
+    };
+
+export const openApiClientAuthorizationAttributesDialog = (uuid: string) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const apiClientAuthorization = getState().apiClientAuthorizations.find(node => node.uuid === uuid);
+        dispatch(dialogActions.OPEN_DIALOG({ id: API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG, data: { apiClientAuthorization } }));
+    };
+
+export const openApiClientAuthorizationRemoveDialog = (uuid: string) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        dispatch(dialogActions.OPEN_DIALOG({
+            id: API_CLIENT_AUTHORIZATION_REMOVE_DIALOG,
+            data: {
+                title: 'Remove api client authorization',
+                text: 'Are you sure you want to remove this api client authorization?',
+                confirmButtonLabel: 'Remove',
+                uuid
+            }
+        }));
+    };
+
+export const removeApiClientAuthorization = (uuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...' }));
+        try {
+            await services.apiClientAuthorizationService.delete(uuid);
+            dispatch(apiClientAuthorizationsActions.REMOVE_API_CLIENT_AUTHORIZATION(uuid));
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Api client authorization has been successfully removed.', hideDuration: 2000 }));
+        } catch (e) {
+            return;
+        }
+    };
+
+export const openApiClientAuthorizationsHelpDialog = () =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const apiHost = getState().properties.apiHost;
+        const user = getState().auth.user;
+        const email = user ? user.email : '';
+        const apiToken = getState().auth.apiToken;
+        dispatch(dialogActions.OPEN_DIALOG({ id: API_CLIENT_AUTHORIZATION_HELP_DIALOG, data: { apiHost, apiToken, email } }));
+    };
\ No newline at end of file
diff --git a/src/store/api-client-authorizations/api-client-authorizations-reducer.ts b/src/store/api-client-authorizations/api-client-authorizations-reducer.ts
new file mode 100644 (file)
index 0000000..7084dea
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { 
+    apiClientAuthorizationsActions, 
+    ApiClientAuthorizationsActions 
+} from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+
+export type ApiClientAuthorizationsState = ApiClientAuthorization[];
+
+const initialState: ApiClientAuthorizationsState = [];
+
+export const apiClientAuthorizationsReducer = 
+    (state: ApiClientAuthorizationsState = initialState, action: ApiClientAuthorizationsActions): ApiClientAuthorizationsState =>
+        apiClientAuthorizationsActions.match(action, {
+            SET_API_CLIENT_AUTHORIZATIONS: apiClientAuthorizations => apiClientAuthorizations,
+            REMOVE_API_CLIENT_AUTHORIZATION: (uuid: string) => 
+                state.filter((apiClientAuthorization) => apiClientAuthorization.uuid !== uuid),
+            default: () => state
+        });
\ No newline at end of file
index 0ec39ebc8d7cf475e04099176d733a37589f859d..1e2620e48c790838e87d76ee0ab45317170e3a5f 100644 (file)
@@ -4,7 +4,7 @@
 
 import { ofType, unionize, UnionOf } from '~/common/unionize';
 import { Dispatch } from "redux";
-import { reset, stopSubmit, startSubmit } from 'redux-form';
+import { reset, stopSubmit, startSubmit, FormErrors } from 'redux-form';
 import { AxiosInstance } from "axios";
 import { RootState } from "../store";
 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
@@ -143,9 +143,9 @@ export const createSshKey = (data: SshKeyCreateFormDialogData) =>
         } catch (e) {
             const error = getAuthorizedKeysServiceError(e);
             if (error === AuthorizedKeysServiceError.UNIQUE_PUBLIC_KEY) {
-                dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' }));
+                dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key already exists.' } as FormErrors));
             } else if (error === AuthorizedKeysServiceError.INVALID_PUBLIC_KEY) {
-                dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' }));
+                dispatch(stopSubmit(SSH_KEY_CREATE_FORM_NAME, { publicKey: 'Public key is invalid' } as FormErrors));
             }
         }
     };
index 3f82d29e921e670fdf4f3b453290c9ec32de5c01..11cdd6226fa264d3ac98770438290e372c211138 100644 (file)
@@ -11,7 +11,7 @@ import { snackbarActions, SnackbarKind } from "../../snackbar/snackbar-actions";
 import { dialogActions } from '../../dialog/dialog-actions';
 import { getNodeValue } from "~/models/tree";
 import { filterCollectionFilesBySelection } from './collection-panel-files-state';
-import { startSubmit, stopSubmit, reset, initialize } from 'redux-form';
+import { startSubmit, stopSubmit, reset, initialize, FormErrors } from 'redux-form';
 import { getDialog } from "~/store/dialog/dialog-reducer";
 import { getFileFullPath } from "~/services/collection-service/collection-service-files-response";
 import { resourcesDataActions } from "~/store/resources-data/resources-data-actions";
@@ -130,7 +130,10 @@ export const renameFile = (newName: string) =>
                     dispatch(dialogActions.CLOSE_DIALOG({ id: RENAME_FILE_DIALOG }));
                     dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'File name changed.', hideDuration: 2000 }));
                 } catch (e) {
-                    dispatch(stopSubmit(RENAME_FILE_DIALOG, { name: 'Could not rename the file' }));
+                    const errors: FormErrors<RenameFileDialogData, string> = {
+                        name: 'Could not rename the file'
+                    };
+                    dispatch(stopSubmit(RENAME_FILE_DIALOG, errors));
                 }
             }
         }
index e5a6676c6b4dbc789199f589e3a5315ebe2ed199..0ce92dfabcecbdc86a3c4cd087b97d4bcee2fddd 100644 (file)
@@ -4,7 +4,7 @@
 
 import { Dispatch } from "redux";
 import { dialogActions } from "~/store/dialog/dialog-actions";
-import { initialize, startSubmit, stopSubmit } from 'redux-form';
+import { FormErrors, initialize, startSubmit, stopSubmit } from 'redux-form';
 import { resetPickerProjectTree } from '~/store/project-tree-picker/project-tree-picker-actions';
 import { RootState } from '~/store/store';
 import { ServiceRepository } from '~/services/services';
@@ -39,7 +39,10 @@ export const copyCollection = (resource: CopyFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(COLLECTION_COPY_FORM_NAME, { ownerUuid: 'A collection with the same name already exists in the target project.' }));
+                dispatch(stopSubmit(
+                    COLLECTION_COPY_FORM_NAME,
+                    { ownerUuid: 'A collection with the same name already exists in the target project.' } as FormErrors
+                ));
             } else {
                 dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_COPY_FORM_NAME }));
                 throw new Error('Could not copy the collection.');
index f4375688141cdc5eb3873321eaac01c22c895024..8d1e9ba5f247be426fc0b2faabb6d4ec60f858fb 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { Dispatch } from "redux";
-import { reset, startSubmit, stopSubmit, initialize } from 'redux-form';
+import { reset, startSubmit, stopSubmit, initialize, FormErrors } from 'redux-form';
 import { RootState } from '~/store/store';
 import { dialogActions } from "~/store/dialog/dialog-actions";
 import { ServiceRepository } from '~/services/services';
@@ -40,7 +40,7 @@ export const openCollectionCreateDialog = (ownerUuid: string) =>
 export const createCollection = (data: CollectionCreateFormDialogData) =>
     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         dispatch(startSubmit(COLLECTION_CREATE_FORM_NAME));
-        let newCollection: CollectionResource | null = null;
+        let newCollection: CollectionResource;
         try {
             dispatch(progressIndicatorActions.START_WORKING(COLLECTION_CREATE_FORM_NAME));
             newCollection = await services.collectionService.create(data);
@@ -52,7 +52,7 @@ export const createCollection = (data: CollectionCreateFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME, { name: 'Collection with the same name already exists.' }));
+                dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME, { name: 'Collection with the same name already exists.' } as FormErrors));
             } else if (error === CommonResourceServiceError.NONE) {
                 dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME));
                 dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_CREATE_FORM_NAME }));
index 770eed1a7872f9f3c30ec65f5f091f4ad2a329fb..aacaf4e66d88cd6e2c8e9eab9e0b8f85173afb75 100644 (file)
@@ -4,7 +4,7 @@
 
 import { Dispatch } from "redux";
 import { dialogActions } from "~/store/dialog/dialog-actions";
-import { startSubmit, stopSubmit, initialize } from 'redux-form';
+import { startSubmit, stopSubmit, initialize, FormErrors } from 'redux-form';
 import { ServiceRepository } from '~/services/services';
 import { RootState } from '~/store/store';
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
@@ -39,7 +39,7 @@ export const moveCollection = (resource: MoveToFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(COLLECTION_MOVE_FORM_NAME, { ownerUuid: 'A collection with the same name already exists in the target project.' }));
+                dispatch(stopSubmit(COLLECTION_MOVE_FORM_NAME, { ownerUuid: 'A collection with the same name already exists in the target project.' } as FormErrors));
             } else {
                 dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_MOVE_FORM_NAME }));
                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not move the collection.', hideDuration: 2000 }));
index b9ada5ee01fa1014bc1ef2fc5605c0c94ade9ec9..ef2c1284fd6ba49d9866d8f3ea3bcdc6f6852387 100644 (file)
@@ -4,7 +4,7 @@
 
 import { Dispatch } from 'redux';
 import { RootState } from '~/store/store';
-import { initialize, startSubmit, stopSubmit } from 'redux-form';
+import { FormErrors, initialize, startSubmit, stopSubmit } from 'redux-form';
 import { resetPickerProjectTree } from '~/store/project-tree-picker/project-tree-picker-actions';
 import { dialogActions } from '~/store/dialog/dialog-actions';
 import { ServiceRepository } from '~/services/services';
@@ -67,7 +67,7 @@ export const copyCollectionPartial = ({ name, description, projectUuid }: Collec
             } catch (e) {
                 const error = getCommonResourceServiceError(e);
                 if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                    dispatch(stopSubmit(COLLECTION_PARTIAL_COPY_FORM_NAME, { name: 'Collection with this name already exists.' }));
+                    dispatch(stopSubmit(COLLECTION_PARTIAL_COPY_FORM_NAME, { name: 'Collection with this name already exists.' } as FormErrors));
                 } else if (error === CommonResourceServiceError.UNKNOWN) {
                     dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_PARTIAL_COPY_FORM_NAME }));
                     dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not create a copy of collection', hideDuration: 2000 }));
index 9c859234f3a3911e755e9840fa6b554a6e7d83a0..02ec8bb5824920879691a7ae7935ac64263ab30e 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { Dispatch } from "redux";
-import { initialize, startSubmit, stopSubmit } from 'redux-form';
+import { FormErrors, initialize, startSubmit, stopSubmit } from 'redux-form';
 import { RootState } from "~/store/store";
 import { collectionPanelActions } from "~/store/collection-panel/collection-panel-action";
 import { dialogActions } from "~/store/dialog/dialog-actions";
@@ -41,7 +41,7 @@ export const updateCollection = (collection: Partial<CollectionResource>) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(COLLECTION_UPDATE_FORM_NAME, { name: 'Collection with the same name already exists.' }));
+                dispatch(stopSubmit(COLLECTION_UPDATE_FORM_NAME, { name: 'Collection with the same name already exists.' } as FormErrors));
             }
             dispatch(progressIndicatorActions.STOP_WORKING(COLLECTION_UPDATE_FORM_NAME));
             return;
index 65ddcff2c7f1b360baa0e4ea98587cdb9bbbc179..b7d6cb260c7b7be319648e48c787ee231aba7052 100644 (file)
@@ -18,6 +18,7 @@ import { SshKeyResource } from '~/models/ssh-key';
 import { VirtualMachinesResource } from '~/models/virtual-machines';
 import { KeepServiceResource } from '~/models/keep-services';
 import { NodeResource } from '~/models/node';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
 
 export const contextMenuActions = unionize({
     OPEN_CONTEXT_MENU: ofType<{ position: ContextMenuPosition, resource: ContextMenuResource }>(),
@@ -121,6 +122,18 @@ export const openComputeNodeContextMenu = (event: React.MouseEvent<HTMLElement>,
         }));
     };
 
+export const openApiClientAuthorizationContextMenu = 
+    (event: React.MouseEvent<HTMLElement>, apiClientAuthorization: ApiClientAuthorization) =>
+        (dispatch: Dispatch) => {
+            dispatch<any>(openContextMenu(event, {
+                name: '',
+                uuid: apiClientAuthorization.uuid,
+                ownerUuid: apiClientAuthorization.ownerUuid,
+                kind: ResourceKind.API_CLIENT_AUTHORIZATION,
+                menuKind: ContextMenuKind.API_CLIENT_AUTHORIZATION
+            }));
+        };
+
 export const openRootProjectContextMenu = (event: React.MouseEvent<HTMLElement>, projectUuid: string) =>
     (dispatch: Dispatch, getState: () => RootState) => {
         const res = getResource<UserResource>(projectUuid)(getState().resources);
index 80ab514cb41440b9a3356f62ed6379a4ec08896c..82ba5b4b8e517e9ad6541f228e53213e9ab3f81b 100644 (file)
@@ -6,7 +6,7 @@ import { Dispatch, MiddlewareAPI } from "redux";
 import { RootState } from "../store";
 import { DataColumns } from "~/components/data-table/data-table";
 import { DataExplorer } from './data-explorer-reducer';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { createTree } from "~/models/tree";
 import { DataTableFilters } from "~/components/data-table-filters/data-table-filters-tree";
 
index a3652726f1d2dfda5b51d8c1f5200ebf1bbd6b71..8d68a4b6856e4179260a95315eac5158f4c8a95f 100644 (file)
@@ -72,4 +72,8 @@ export const navigateToMyAccount = push(Routes.MY_ACCOUNT);
 
 export const navigateToKeepServices = push(Routes.KEEP_SERVICES);
 
-export const navigateToComputeNodes = push(Routes.COMPUTE_NODES);
\ No newline at end of file
+export const navigateToComputeNodes = push(Routes.COMPUTE_NODES);
+
+export const navigateToUsers = push(Routes.USERS);
+
+export const navigateToApiClientAuthorizations = push(Routes.API_CLIENT_AUTHORIZATIONS);
index 7e65bcca0bd221c8eea7bd293b77f42895ee26f5..dcf97185c3a1ebca03bfaccfdbfbde16db80d83f 100644 (file)
@@ -4,7 +4,7 @@
 
 import { Dispatch } from "redux";
 import { dialogActions } from "~/store/dialog/dialog-actions";
-import { startSubmit, stopSubmit, initialize } from 'redux-form';
+import { startSubmit, stopSubmit, initialize, FormErrors } from 'redux-form';
 import { ServiceRepository } from '~/services/services';
 import { RootState } from '~/store/store';
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
@@ -42,11 +42,11 @@ export const moveProcess = (resource: MoveToFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(PROCESS_MOVE_FORM_NAME, { ownerUuid: 'A process with the same name already exists in the target project.' }));
+                dispatch(stopSubmit(PROCESS_MOVE_FORM_NAME, { ownerUuid: 'A process with the same name already exists in the target project.' } as FormErrors));
             } else {
                 dispatch(dialogActions.CLOSE_DIALOG({ id: PROCESS_MOVE_FORM_NAME }));
                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not move the process.', hideDuration: 2000 }));
             }
             return;
         }
-    };
\ No newline at end of file
+    };
index 2063f11362ced7bb2b04e0327dc3743432bc9b48..372e18829d222745fe487adc395d979fb83557ce 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { Dispatch } from "redux";
-import { initialize, startSubmit, stopSubmit } from 'redux-form';
+import { FormErrors, initialize, startSubmit, stopSubmit } from 'redux-form';
 import { RootState } from "~/store/store";
 import { dialogActions } from "~/store/dialog/dialog-actions";
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
@@ -41,11 +41,11 @@ export const updateProcess = (resource: ProcessUpdateFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(PROCESS_UPDATE_FORM_NAME, { name: 'Process with the same name already exists.' }));
+                dispatch(stopSubmit(PROCESS_UPDATE_FORM_NAME, { name: 'Process with the same name already exists.' } as FormErrors));
             } else {
                 dispatch(dialogActions.CLOSE_DIALOG({ id: PROCESS_UPDATE_FORM_NAME }));
                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not update the process.', hideDuration: 2000 }));
             }
             return;
         }
-    };
\ No newline at end of file
+    };
index 36672e99ac19003ede9f9ade9240d870de496d14..58f158772240019b1b3a9873546cfd7b61e39ed6 100644 (file)
@@ -7,32 +7,32 @@ import {
     dataExplorerToListParams,
     getDataExplorerColumnFilters,
     listResultsToDataExplorerItemsMeta
-} from '../data-explorer/data-explorer-middleware-service';
-import { ProjectPanelColumnNames, ProjectPanelFilter } from "~/views/project-panel/project-panel";
-import { RootState } from "../store";
+} from '~/store/data-explorer/data-explorer-middleware-service';
+import { ProjectPanelColumnNames } from "~/views/project-panel/project-panel";
+import { RootState } from "~/store/store";
 import { DataColumns } from "~/components/data-table/data-table";
 import { ServiceRepository } from "~/services/services";
 import { SortDirection } from "~/components/data-table/data-column";
 import { OrderBuilder, OrderDirection } from "~/services/api/order-builder";
 import { FilterBuilder, joinFilters } from "~/services/api/filter-builder";
 import { GroupContentsResource, GroupContentsResourcePrefix } from "~/services/groups-service/groups-service";
-import { updateFavorites } from "../favorites/favorites-actions";
-import { PROJECT_PANEL_CURRENT_UUID, IS_PROJECT_PANEL_TRASHED, projectPanelActions } from './project-panel-action';
+import { updateFavorites } from "~/store/favorites/favorites-actions";
+import { PROJECT_PANEL_CURRENT_UUID, IS_PROJECT_PANEL_TRASHED, projectPanelActions } from '~/store/project-panel/project-panel-action';
 import { Dispatch, MiddlewareAPI } from "redux";
 import { ProjectResource } from "~/models/project";
 import { updateResources } from "~/store/resources/resources-actions";
 import { getProperty } from "~/store/properties/properties";
-import { snackbarActions, SnackbarKind } from '../snackbar/snackbar-actions';
+import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions.ts';
-import { DataExplorer, getDataExplorer } from '../data-explorer/data-explorer-reducer';
-import { ListResults } from '~/services/common-service/common-resource-service';
-import { loadContainers } from '../processes/processes-actions';
+import { DataExplorer, getDataExplorer } from '~/store/data-explorer/data-explorer-reducer';
+import { ListResults } from '~/services/common-service/common-service';
+import { loadContainers } from '~/store/processes/processes-actions';
 import { ResourceKind } from '~/models/resource';
 import { getResource } from "~/store/resources/resources";
 import { CollectionResource } from "~/models/collection";
 import { resourcesDataActions } from "~/store/resources-data/resources-data-actions";
 import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
-import { serializeResourceTypeFilters } from '../resource-type-filters/resource-type-filters';
+import { serializeResourceTypeFilters } from '~/store/resource-type-filters/resource-type-filters';
 
 export class ProjectPanelMiddlewareService extends DataExplorerMiddlewareService {
     constructor(private services: ServiceRepository, id: string) {
index 1fd1be0c23cf9258f404c769a783760a7c6dfdbb..d226048b08c06b4e1fd9ca868bf63ea2ddd92beb 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { Dispatch } from "redux";
-import { reset, startSubmit, stopSubmit, initialize } from 'redux-form';
+import { reset, startSubmit, stopSubmit, initialize, FormErrors } from 'redux-form';
 import { RootState } from '~/store/store';
 import { dialogActions } from "~/store/dialog/dialog-actions";
 import { getCommonResourceServiceError, CommonResourceServiceError } from '~/services/common-service/common-resource-service';
@@ -43,7 +43,7 @@ export const openProjectCreateDialog = (ownerUuid: string) =>
             dispatch(initialize(PROJECT_CREATE_FORM_NAME, { userUuid }));
         } else {
             dispatch(initialize(PROJECT_CREATE_FORM_NAME, { ownerUuid }));
-        }        
+        }
         dispatch(dialogActions.OPEN_DIALOG({ id: PROJECT_CREATE_FORM_NAME, data: {} }));
     };
 
@@ -58,7 +58,7 @@ export const createProject = (project: Partial<ProjectResource>) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(PROJECT_CREATE_FORM_NAME, { name: 'Project with the same name already exists.' }));
+                dispatch(stopSubmit(PROJECT_CREATE_FORM_NAME, { name: 'Project with the same name already exists.' } as FormErrors));
             }
             return undefined;
         }
index cacd49e68f8f8d5699d807bf1c2df286863719c6..365e07aab61cd662e427d5bb6e05c1998ca693ee 100644 (file)
@@ -4,7 +4,7 @@
 
 import { Dispatch } from "redux";
 import { dialogActions } from "~/store/dialog/dialog-actions";
-import { startSubmit, stopSubmit, initialize } from 'redux-form';
+import { startSubmit, stopSubmit, initialize, FormErrors } from 'redux-form';
 import { ServiceRepository } from '~/services/services';
 import { RootState } from '~/store/store';
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
@@ -33,9 +33,9 @@ export const moveProject = (resource: MoveToFormDialogData) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(PROJECT_MOVE_FORM_NAME, { ownerUuid: 'A project with the same name already exists in the target project.' }));
+                dispatch(stopSubmit(PROJECT_MOVE_FORM_NAME, { ownerUuid: 'A project with the same name already exists in the target project.' } as FormErrors));
             } else if (error === CommonResourceServiceError.OWNERSHIP_CYCLE) {
-                dispatch(stopSubmit(PROJECT_MOVE_FORM_NAME, { ownerUuid: 'Cannot move a project into itself.' }));
+                dispatch(stopSubmit(PROJECT_MOVE_FORM_NAME, { ownerUuid: 'Cannot move a project into itself.' } as FormErrors));
             } else {
                 dispatch(dialogActions.CLOSE_DIALOG({ id: PROJECT_MOVE_FORM_NAME }));
                 throw new Error('Could not move the project.');
index 34ea42f59bd93796bb355da70d3291cc91133906..321b85548610298005299b3f64b5911d11437113 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { Dispatch } from "redux";
-import { initialize, startSubmit, stopSubmit } from 'redux-form';
+import { FormErrors, initialize, startSubmit, stopSubmit } from 'redux-form';
 import { RootState } from "~/store/store";
 import { dialogActions } from "~/store/dialog/dialog-actions";
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
@@ -38,7 +38,7 @@ export const updateProject = (project: Partial<ProjectResource>) =>
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
-                dispatch(stopSubmit(PROJECT_UPDATE_FORM_NAME, { name: 'Project with the same name already exists.' }));
+                dispatch(stopSubmit(PROJECT_UPDATE_FORM_NAME, { name: 'Project with the same name already exists.' } as FormErrors));
             }
             return ;
         }
index 61caa769f1ea32746608f3a4f570a86ddbb4db38..f2f06e805def51d0843fdecf2d91f39c785779e0 100644 (file)
@@ -10,7 +10,7 @@ import { navigateToRepositories } from "~/store/navigation/navigation-action";
 import { unionize, ofType, UnionOf } from "~/common/unionize";
 import { dialogActions } from '~/store/dialog/dialog-actions';
 import { RepositoryResource } from "~/models/repositories";
-import { startSubmit, reset, stopSubmit } from "redux-form";
+import { startSubmit, reset, stopSubmit, FormErrors } from "redux-form";
 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
 
@@ -55,13 +55,13 @@ export const createRepository = (repository: RepositoryResource) =>
             const newRepository = await services.repositoriesService.create({ name: `${user.username}/${repository.name}` });
             dispatch(dialogActions.CLOSE_DIALOG({ id: REPOSITORY_CREATE_FORM_NAME }));
             dispatch(reset(REPOSITORY_CREATE_FORM_NAME));
-            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Repository has been successfully created.", hideDuration: 2000, kind: SnackbarKind.SUCCESS })); 
-            dispatch<any>(loadRepositoriesData());     
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Repository has been successfully created.", hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
+            dispatch<any>(loadRepositoriesData());
             return newRepository;
         } catch (e) {
             const error = getCommonResourceServiceError(e);
             if (error === CommonResourceServiceError.NAME_HAS_ALREADY_BEEN_TAKEN) {
-                dispatch(stopSubmit(REPOSITORY_CREATE_FORM_NAME, { name: 'Repository with the same name already exists.' }));
+                dispatch(stopSubmit(REPOSITORY_CREATE_FORM_NAME, { name: 'Repository with the same name already exists.' } as FormErrors));
             }
             return undefined;
         }
@@ -91,7 +91,7 @@ export const removeRepository = (uuid: string) =>
 const repositoriesBindedActions = bindDataExplorerActions(REPOSITORIES_PANEL);
 
 export const openRepositoriesPanel = () =>
-    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         dispatch<any>(navigateToRepositories);
     };
 
@@ -104,4 +104,4 @@ export const loadRepositoriesData = () =>
 export const loadRepositoriesPanel = () =>
     (dispatch: Dispatch) => {
         dispatch(repositoriesBindedActions.REQUEST_ITEMS());
-    };
\ No newline at end of file
+    };
diff --git a/src/store/search-bar/search-bar-actions.test.ts b/src/store/search-bar/search-bar-actions.test.ts
new file mode 100644 (file)
index 0000000..aa6e475
--- /dev/null
@@ -0,0 +1,137 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { getAdvancedDataFromQuery, getQueryFromAdvancedData, parseSearchQuery } from "~/store/search-bar/search-bar-actions";
+import { ResourceKind } from "~/models/resource";
+import { ClusterObjectType } from "~/models/search-bar";
+
+describe('search-bar-actions', () => {
+    describe('parseSearchQuery', () => {
+        it('should correctly parse query #1', () => {
+            const q = 'val0 is:trashed val1';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val1']);
+            expect(r.properties).toEqual({
+                is: ['trashed']
+            });
+        });
+
+        it('should correctly parse query #2 (value with keyword should be ignored)', () => {
+            const q = 'val0 is:from:trashed val1';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val1']);
+            expect(r.properties).toEqual({
+                from: ['trashed']
+            });
+        });
+
+        it('should correctly parse query #3 (many keywords)', () => {
+            const q = 'val0 is:trashed val2 from:2017-04-01 val1';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val2', 'val1']);
+            expect(r.properties).toEqual({
+                is: ['trashed'],
+                from: ['2017-04-01']
+            });
+        });
+
+        it('should correctly parse query #4 (no duplicated values)', () => {
+            const q = 'val0 is:trashed val2 val2 val0';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val2']);
+            expect(r.properties).toEqual({
+                is: ['trashed']
+            });
+        });
+
+        it('should correctly parse query #5 (properties)', () => {
+            const q = 'val0 has:filesize:100mb val2 val2 val0';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val2']);
+            expect(r.properties).toEqual({
+                'has': ['filesize:100mb']
+            });
+        });
+
+        it('should correctly parse query #6 (multiple properties, multiple is)', () => {
+            const q = 'val0 has:filesize:100mb val2 has:user:daniel is:starred val2 val0 is:trashed';
+            const r = parseSearchQuery(q);
+            expect(r.hasKeywords).toBeTruthy();
+            expect(r.values).toEqual(['val0', 'val2']);
+            expect(r.properties).toEqual({
+                'has': ['filesize:100mb', 'user:daniel'],
+                'is': ['starred', 'trashed']
+            });
+        });
+    });
+
+    describe('getAdvancedDataFromQuery', () => {
+        it('should correctly build advanced data record from query #1', () => {
+            const r = getAdvancedDataFromQuery('val0 has:filesize:100mb val2 has:user:daniel is:starred val2 val0 is:trashed');
+            expect(r).toEqual({
+                searchValue: 'val0 val2',
+                type: undefined,
+                cluster: undefined,
+                projectUuid: undefined,
+                inTrash: true,
+                dateFrom: undefined,
+                dateTo: undefined,
+                properties: [{
+                    key: 'filesize',
+                    value: '100mb'
+                }, {
+                    key: 'user',
+                    value: 'daniel'
+                }],
+                saveQuery: false,
+                queryName: ''
+            });
+        });
+
+        it('should correctly build advanced data record from query #2', () => {
+            const r = getAdvancedDataFromQuery('document from:2017-08-01 pdf has:filesize:101mb is:trashed type:arvados#collection cluster:indianapolis');
+            expect(r).toEqual({
+                searchValue: 'document pdf',
+                type: ResourceKind.COLLECTION,
+                cluster: ClusterObjectType.INDIANAPOLIS,
+                projectUuid: undefined,
+                inTrash: true,
+                dateFrom: '2017-08-01',
+                dateTo: undefined,
+                properties: [{
+                    key: 'filesize',
+                    value: '101mb'
+                }],
+                saveQuery: false,
+                queryName: ''
+            });
+        });
+    });
+
+    describe('getQueryFromAdvancedData', () => {
+        it('should build query from advanced data', () => {
+            const q = getQueryFromAdvancedData({
+                searchValue: 'document pdf',
+                type: ResourceKind.COLLECTION,
+                cluster: ClusterObjectType.INDIANAPOLIS,
+                projectUuid: undefined,
+                inTrash: true,
+                dateFrom: '2017-08-01',
+                dateTo: '',
+                properties: [{
+                    key: 'filesize',
+                    value: '101mb'
+                }],
+                saveQuery: false,
+                queryName: ''
+            });
+            expect(q).toBe('document pdf type:arvados#collection cluster:indianapolis is:trashed from:2017-08-01 has:filesize:101mb');
+        });
+    });
+});
index 165392c6c20ef0dc9fef9bdbfe559608529a623a..199ec3f95788c9f131e373862e52c07ddb9703bd 100644 (file)
@@ -2,22 +2,24 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { unionize, ofType, UnionOf } from "~/common/unionize";
+import { ofType, unionize, UnionOf } from "~/common/unionize";
 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
 import { Dispatch } from 'redux';
-import { change, arrayPush } from 'redux-form';
+import { arrayPush, change, initialize } from 'redux-form';
 import { RootState } from '~/store/store';
-import { initUserProject } from '~/store/tree-picker/tree-picker-actions';
+import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions';
 import { ServiceRepository } from '~/services/services';
 import { FilterBuilder } from "~/services/api/filter-builder";
 import { ResourceKind } from '~/models/resource';
 import { GroupClass } from '~/models/group';
 import { SearchView } from '~/store/search-bar/search-bar-reducer';
-import { navigateToSearchResults, navigateTo } from '~/store/navigation/navigation-action';
+import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
-import { initialize } from 'redux-form';
-import { SearchBarAdvanceFormData, PropertyValues } from '~/models/search-bar';
+import { ClusterObjectType, PropertyValue, SearchBarAdvanceFormData } from '~/models/search-bar';
 import { debounce } from 'debounce';
+import * as _ from "lodash";
+import { getModifiedKeysValues } from "~/common/objects";
+import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
 
 export const searchBarActions = unionize({
     SET_CURRENT_VIEW: ofType<string>(),
@@ -61,7 +63,7 @@ export const searchData = (searchValue: string) =>
         const currentView = getState().searchBar.currentView;
         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
         if (searchValue.length > 0) {
-            dispatch<any>(searchGroups(searchValue, 5, {}));
+            dispatch<any>(searchGroups(searchValue, 5));
             if (currentView === SearchView.BASIC) {
                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
                 dispatch(navigateToSearchResults);
@@ -77,11 +79,32 @@ export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
         dispatch(navigateToSearchResults);
     };
 
+export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const searchValue = getState().searchBar.searchValue;
+        const value = getQueryFromAdvancedData({
+            ...data,
+            searchValue
+        }, prevData);
+        dispatch(searchBarActions.SET_SEARCH_VALUE(value));
+    };
+
+export const setAdvancedDataFromSearchValue = (search: string) =>
+    async (dispatch: Dispatch) => {
+        const data = getAdvancedDataFromQuery(search);
+        dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
+        if (data.projectUuid) {
+            await dispatch<any>(activateSearchBarProject(data.projectUuid));
+            dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
+        }
+    };
+
 const saveQuery = (data: SearchBarAdvanceFormData) =>
     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
         const savedQueries = services.searchService.getSavedQueries();
-        if (data.saveQuery && data.searchQuery) {
-            const filteredQuery = savedQueries.find(query => query.searchQuery === data.searchQuery);
+        if (data.saveQuery && data.queryName) {
+            const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
+            data.searchValue = getState().searchBar.searchValue;
             if (filteredQuery) {
                 services.searchService.editSavedQueries(data);
                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
@@ -105,7 +128,7 @@ export const deleteSavedQuery = (id: number) =>
 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
     (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
-        dispatch(searchBarActions.SET_SEARCH_VALUE(data.searchQuery));
+        dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
     };
 
@@ -127,6 +150,7 @@ export const closeSearchView = () =>
 export const closeAdvanceView = () =>
     (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
+        dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
     };
 
@@ -144,7 +168,7 @@ export const changeData = (searchValue: string) =>
         const searchValuePresent = searchValue.length > 0;
 
         if (currentView === SearchView.ADVANCED) {
-
+            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
         } else if (searchValuePresent) {
             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
@@ -176,12 +200,12 @@ const startSearch = () =>
         dispatch<any>(searchData(searchValue));
     };
 
-const searchGroups = (searchValue: string, limit: number, {...props}) =>
+const searchGroups = (searchValue: string, limit: number) =>
     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         const currentView = getState().searchBar.currentView;
 
         if (searchValue || currentView === SearchView.ADVANCED) {
-            const filters = getFilters('name', searchValue, props);
+            const filters = getFilters('name', searchValue);
             const { items } = await services.groupsService.contents('', {
                 filters,
                 limit,
@@ -191,16 +215,241 @@ const searchGroups = (searchValue: string, limit: number, {...props}) =>
         }
     };
 
-export const getFilters = (filterName: string, searchValue: string, props: any): string => {
-    const { resourceKind, dateTo, dateFrom } = props;
-    return new FilterBuilder()
-        .addIsA("uuid", buildUuidFilter(resourceKind))
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
-        .addLte('modified_at', buildDateFilter(dateTo))
-        .addGte('modified_at', buildDateFilter(dateFrom))
+const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
+    let value = data.searchValue;
+
+    const addRem = (field: string, key: string) => {
+        const v = data[key];
+
+        if (data.hasOwnProperty(key)) {
+            const pattern = v === false
+                ? `${field.replace(':', '\\:\\s*')}\\s*`
+                : `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
+            value = value.replace(new RegExp(pattern), '');
+        }
+
+        if (v) {
+            const nv = v === true
+                ? `${field}`
+                : `${field}:${v}`;
+
+            if (mode === 'rebuild') {
+                value = value + ' ' + nv;
+            } else {
+                value = nv + ' ' + value;
+            }
+        }
+    };
+
+    keyMap.forEach(km => addRem(km[0], km[1]));
+
+    return value;
+};
+
+export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
+    let value = '';
+
+    const flatData = (data: SearchBarAdvanceFormData) => {
+        const fo = {
+            searchValue: data.searchValue,
+            type: data.type,
+            cluster: data.cluster,
+            projectUuid: data.projectUuid,
+            inTrash: data.inTrash,
+            dateFrom: data.dateFrom,
+            dateTo: data.dateTo,
+        };
+        (data.properties || []).forEach(p => fo[`prop-${p.key}`] = p.value);
+        return fo;
+    };
+
+    const keyMap = [
+        ['type', 'type'],
+        ['cluster', 'cluster'],
+        ['project', 'projectUuid'],
+        ['is:trashed', 'inTrash'],
+        ['from', 'dateFrom'],
+        ['to', 'dateTo']
+    ];
+    _.union(data.properties, prevData ? prevData.properties : [])
+        .forEach(p => keyMap.push([`has:${p.key}`, `prop-${p.key}`]));
+
+    if (prevData) {
+        const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
+        value = buildQueryFromKeyMap({
+            searchValue: data.searchValue,
+            ...obj
+        } as SearchBarAdvanceFormData, keyMap, "reuse");
+    } else {
+        value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
+    }
+
+    value = value.trim();
+    return value;
+};
+
+export interface ParseSearchQuery {
+    hasKeywords: boolean;
+    values: string[];
+    properties: {
+        [key: string]: string[]
+    };
+}
+
+export const parseSearchQuery: (query: string) => ParseSearchQuery = (searchValue: string) => {
+    const keywords = [
+        'type:',
+        'cluster:',
+        'project:',
+        'is:',
+        'from:',
+        'to:',
+        'has:'
+    ];
+
+    const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + (search.includes(keyword) ? 1 : 0), 0);
+    let keywordsCnt = 0;
+
+    const properties = {};
+
+    keywords.forEach(k => {
+        let p = searchValue.indexOf(k);
+        const key = k.substr(0, k.length - 1);
+
+        while (p >= 0) {
+            const l = searchValue.length;
+            keywordsCnt += 1;
+
+            let v = '';
+            let i = p + k.length;
+            while (i < l && searchValue[i] === ' ') {
+                ++i;
+            }
+            const vp = i;
+            while (i < l && searchValue[i] !== ' ') {
+                v += searchValue[i];
+                ++i;
+            }
+
+            if (hasKeywords(v)) {
+                searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
+            } else {
+                if (v !== '') {
+                    if (!properties[key]) {
+                        properties[key] = [];
+                    }
+                    properties[key].push(v);
+                }
+                searchValue = searchValue.substr(0, p) + searchValue.substr(i);
+            }
+            p = searchValue.indexOf(k);
+        }
+    });
+
+    const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
+
+    return { hasKeywords: keywordsCnt > 0, values, properties };
+};
+
+const getFirstProp = (sq: ParseSearchQuery, name: string) => sq.properties[name] && sq.properties[name][0];
+const getPropValue = (sq: ParseSearchQuery, name: string, value: string) => sq.properties[name] && sq.properties[name].find((v: string) => v === value);
+const getProperties = (sq: ParseSearchQuery): PropertyValue[] => {
+    if (sq.properties.has) {
+        return sq.properties.has.map((value: string) => {
+            const v = value.split(':');
+            return {
+                key: v[0],
+                value: v[1]
+            };
+        });
+    }
+    return [];
+};
+
+export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
+    const sq = parseSearchQuery(query);
+
+    return {
+        searchValue: sq.values.join(' '),
+        type: getFirstProp(sq, 'type') as ResourceKind,
+        cluster: getFirstProp(sq, 'cluster') as ClusterObjectType,
+        projectUuid: getFirstProp(sq, 'project'),
+        inTrash: getPropValue(sq, 'is', 'trashed') !== undefined,
+        dateFrom: getFirstProp(sq, 'from'),
+        dateTo: getFirstProp(sq, 'to'),
+        properties: getProperties(sq),
+        saveQuery: false,
+        queryName: ''
+    };
+};
+
+export const getFilters = (filterName: string, searchValue: string): string => {
+    const filter = new FilterBuilder();
+    const sq = parseSearchQuery(searchValue);
+
+    const resourceKind = getFirstProp(sq, 'type') as ResourceKind;
+
+    let prefix = '';
+    switch (resourceKind) {
+        case ResourceKind.COLLECTION:
+            prefix = GroupContentsResourcePrefix.COLLECTION;
+            break;
+        case ResourceKind.PROCESS:
+            prefix = GroupContentsResourcePrefix.PROCESS;
+            break;
+        default:
+            prefix = GroupContentsResourcePrefix.PROJECT;
+            break;
+    }
+
+    if (!sq.hasKeywords) {
+        filter
+            .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
+            .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
+            .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
+    } else {
+        if (prefix) {
+            sq.values.forEach(v =>
+                filter.addILike(filterName, v, prefix)
+            );
+        } else {
+            sq.values.forEach(v => {
+                filter
+                    .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
+                    .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
+                    .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
+            });
+        }
+
+        if (getPropValue(sq, 'is', 'trashed')) {
+            filter.addEqual("is_trashed", true);
+        }
+
+        const projectUuid = getFirstProp(sq, 'project');
+        if (projectUuid) {
+            filter.addEqual('uuid', projectUuid, prefix);
+        }
+
+        const dateFrom = getFirstProp(sq, 'from');
+        if (dateFrom) {
+            filter.addGte('modified_at', buildDateFilter(dateFrom));
+        }
+
+        const dateTo = getFirstProp(sq, 'to');
+        if (dateTo) {
+            filter.addLte('modified_at', buildDateFilter(dateTo));
+        }
+
+        const props = getProperties(sq);
+        props.forEach(p => {
+            // filter.addILike(`properties.${p.key}`, p.value);
+            filter.addExists(p.key);
+        });
+    }
+
+    return filter
         .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
+        .addIsA("uuid", buildUuidFilter(resourceKind))
         .getFilters();
 };
 
@@ -217,12 +466,12 @@ export const initAdvanceFormProjectsTree = () =>
         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
     };
 
-export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
+export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
     (dispatch: Dispatch) => {
         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
     };
 
-export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
+export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
     (dispatch: Dispatch) => {
         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
     };
index 8508c05d044cee1668ad04272f69fb427342b828..4f663eeb393f6f1ea115ca43d42152bcce5ca0cc 100644 (file)
@@ -2,7 +2,11 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { searchBarActions, SearchBarActions } from '~/store/search-bar/search-bar-actions';
+import {
+    getQueryFromAdvancedData,
+    searchBarActions,
+    SearchBarActions
+} from '~/store/search-bar/search-bar-actions';
 import { GroupContentsResource } from '~/services/groups-service/groups-service';
 import { SearchBarAdvanceFormData } from '~/models/search-bar';
 
@@ -45,7 +49,7 @@ const makeSelectedItem = (id: string, query?: string): SearchBarSelectedItem =>
 
 const makeQueryList = (recentQueries: string[], savedQueries: SearchBarAdvanceFormData[]) => {
     const recentIds = recentQueries.map((q, idx) => makeSelectedItem(`RQ-${idx}-${q}`, q));
-    const savedIds = savedQueries.map((q, idx) => makeSelectedItem(`SQ-${idx}-${q.searchQuery}`, q.searchQuery));
+    const savedIds = savedQueries.map((q, idx) => makeSelectedItem(`SQ-${idx}-${q.queryName}`, getQueryFromAdvancedData(q)));
     return recentIds.concat(savedIds);
 };
 
diff --git a/src/store/search-bar/search-bar-tree-actions.ts b/src/store/search-bar/search-bar-tree-actions.ts
new file mode 100644 (file)
index 0000000..5101055
--- /dev/null
@@ -0,0 +1,101 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { getTreePicker, TreePicker } from "~/store/tree-picker/tree-picker";
+import { getNode, getNodeAncestorsIds, initTreeNode, TreeNodeStatus } from "~/models/tree";
+import { Dispatch } from "redux";
+import { RootState } from "~/store/store";
+import { ServiceRepository } from "~/services/services";
+import { treePickerActions } from "~/store/tree-picker/tree-picker-actions";
+import { FilterBuilder } from "~/services/api/filter-builder";
+import { OrderBuilder } from "~/services/api/order-builder";
+import { ProjectResource } from "~/models/project";
+import { resourcesActions } from "~/store/resources/resources-actions";
+import { SEARCH_BAR_ADVANCE_FORM_PICKER_ID } from "~/store/search-bar/search-bar-actions";
+
+const getSearchBarTreeNode = (id: string) => (treePicker: TreePicker) => {
+    const searchTree = getTreePicker(SEARCH_BAR_ADVANCE_FORM_PICKER_ID)(treePicker);
+    return searchTree
+        ? getNode(id)(searchTree)
+        : undefined;
+};
+
+export const loadSearchBarTreeProjects = (projectUuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState) => {
+        const treePicker = getTreePicker(SEARCH_BAR_ADVANCE_FORM_PICKER_ID)(getState().treePicker);
+        const node = treePicker ? getNode(projectUuid)(treePicker) : undefined;
+        if (node || projectUuid === '') {
+            await dispatch<any>(loadSearchBarProject(projectUuid));
+        }
+    };
+
+export const getSearchBarTreeNodeAncestorsIds = (id: string) => (treePicker: TreePicker) => {
+    const searchTree = getTreePicker(SEARCH_BAR_ADVANCE_FORM_PICKER_ID)(treePicker);
+    return searchTree
+        ? getNodeAncestorsIds(id)(searchTree)
+        : [];
+};
+
+export const activateSearchBarTreeBranch = (id: string) =>
+    async (dispatch: Dispatch, _: void, services: ServiceRepository) => {
+        const ancestors = await services.ancestorsService.ancestors(id, services.authService.getUuid() || '');
+
+        for (const ancestor of ancestors) {
+            await dispatch<any>(loadSearchBarTreeProjects(ancestor.uuid));
+        }
+        dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
+            ids: [
+                ...[],
+                ...ancestors.map(ancestor => ancestor.uuid)
+            ],
+            pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID
+        }));
+        dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id, pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
+    };
+
+export const expandSearchBarTreeItem = (id: string) =>
+    async (dispatch: Dispatch, getState: () => RootState) => {
+        const node = getSearchBarTreeNode(id)(getState().treePicker);
+        if (node && !node.expanded) {
+            dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
+        }
+    };
+
+export const activateSearchBarProject = (id: string) =>
+    async (dispatch: Dispatch, getState: () => RootState) => {
+        const { treePicker } = getState();
+        const node = getSearchBarTreeNode(id)(treePicker);
+        if (node && node.status !== TreeNodeStatus.LOADED) {
+            await dispatch<any>(loadSearchBarTreeProjects(id));
+        } else if (node === undefined) {
+            await dispatch<any>(activateSearchBarTreeBranch(id));
+        }
+        dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
+            ids: getSearchBarTreeNodeAncestorsIds(id)(treePicker),
+            pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID
+        }));
+        dispatch<any>(expandSearchBarTreeItem(id));
+    };
+
+
+const loadSearchBarProject = (projectUuid: string) =>
+    async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
+        dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: projectUuid, pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
+        const params = {
+            filters: new FilterBuilder()
+                .addEqual('ownerUuid', projectUuid)
+                .getFilters(),
+            order: new OrderBuilder<ProjectResource>()
+                .addAsc('name')
+                .getOrder()
+        };
+        const { items } = await services.projectService.list(params);
+        dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
+            id: projectUuid,
+            pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID,
+            nodes: items.map(item => initTreeNode({ id: item.uuid, value: item })),
+        }));
+        dispatch(resourcesActions.SET_RESOURCES(items));
+    };
+
index b7607e319073e6ba727808eaba321794cff331bb..d8b4d7e76f7e6c6616f6b69b1d7779fd9cbd2238 100644 (file)
@@ -13,7 +13,7 @@ import { SortDirection } from '~/components/data-table/data-column';
 import { SearchResultsPanelColumnNames } from '~/views/search-results-panel/search-results-panel-view';
 import { OrderDirection, OrderBuilder } from '~/services/api/order-builder';
 import { GroupContentsResource, GroupContentsResourcePrefix } from "~/services/groups-service/groups-service";
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { searchResultsPanelActions } from '~/store/search-results-panel/search-results-panel-actions';
 import { getFilters } from '~/store/search-bar/search-bar-actions';
 import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
@@ -40,7 +40,7 @@ export class SearchResultsMiddlewareService extends DataExplorerMiddlewareServic
 
 export const getParams = (dataExplorer: DataExplorer, searchValue: string) => ({
     ...dataExplorerToListParams(dataExplorer),
-    filters: getFilters('name', searchValue, {}),
+    filters: getFilters('name', searchValue),
     order: getOrder(dataExplorer)
 });
 
index c139b429da435b734cfac187543b923d2e0818b2..9e76d46da7a30ef8f0b782b8bf701fbb1e47487e 100644 (file)
@@ -12,7 +12,7 @@ import { updateResources } from '~/store/resources/resources-actions';
 import { loadMissingProcessesInformation, getFilters } from '~/store/project-panel/project-panel-middleware-service';
 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
 import { sharedWithMePanelActions } from './shared-with-me-panel-actions';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
 import { SortDirection } from '~/components/data-table/data-column';
 import { OrderBuilder, OrderDirection } from '~/services/api/order-builder';
index 321a19b6f25182072d405e29e8b308457b4162df..2b0ada81afec1a8869a7629ccf89546a20982172 100644 (file)
@@ -46,7 +46,10 @@ import { resourcesDataReducer } from "~/store/resources-data/resources-data-redu
 import { virtualMachinesReducer } from "~/store/virtual-machines/virtual-machines-reducer";
 import { repositoriesReducer } from '~/store/repositories/repositories-reducer';
 import { keepServicesReducer } from '~/store/keep-services/keep-services-reducer';
+import { UserMiddlewareService } from '~/store/users/user-panel-middleware-service';
+import { USERS_PANEL_ID } from '~/store/users/users-actions';
 import { computeNodesReducer } from '~/store/compute-nodes/compute-nodes-reducer';
+import { apiClientAuthorizationsReducer } from '~/store/api-client-authorizations/api-client-authorizations-reducer';
 
 const composeEnhancers =
     (process.env.NODE_ENV === 'development' &&
@@ -78,6 +81,9 @@ export function configureStore(history: History, services: ServiceRepository): R
     const workflowPanelMiddleware = dataExplorerMiddleware(
         new WorkflowMiddlewareService(services, WORKFLOW_PANEL_ID)
     );
+    const userPanelMiddleware = dataExplorerMiddleware(
+        new UserMiddlewareService(services, USERS_PANEL_ID)
+    );
 
     const middlewares: Middleware[] = [
         routerMiddleware(history),
@@ -87,7 +93,8 @@ export function configureStore(history: History, services: ServiceRepository): R
         trashPanelMiddleware,
         searchResultsPanelMiddleware,
         sharedWithMePanelMiddleware,
-        workflowPanelMiddleware
+        workflowPanelMiddleware,
+        userPanelMiddleware
     ];
     const enhancer = composeEnhancers(applyMiddleware(...middlewares));
     return createStore(rootReducer, enhancer);
@@ -119,5 +126,6 @@ const createRootReducer = (services: ServiceRepository) => combineReducers({
     virtualMachines: virtualMachinesReducer,
     repositories: repositoriesReducer,
     keepServices: keepServicesReducer,
-    computeNodes: computeNodesReducer
+    computeNodes: computeNodesReducer,
+    apiClientAuthorizations: apiClientAuthorizationsReducer
 });
index 6be93228be73d438d5b2c8c0f00dd0ba5c46c1ec..e17d9faea5d0e35febddca034fd39b8d950e3afa 100644 (file)
@@ -2,8 +2,7 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { bindDataExplorerActions } from "../data-explorer/data-explorer-action";
-import { favoritePanelActions } from "~/store/favorite-panel/favorite-panel-action";
+import { bindDataExplorerActions } from "~/store/data-explorer/data-explorer-action";
 
 export const TRASH_PANEL_ID = "trashPanel";
 export const trashPanelActions = bindDataExplorerActions(TRASH_PANEL_ID);
diff --git a/src/store/users/user-panel-middleware-service.ts b/src/store/users/user-panel-middleware-service.ts
new file mode 100644 (file)
index 0000000..bc4bb13
--- /dev/null
@@ -0,0 +1,78 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { ServiceRepository } from '~/services/services';
+import { MiddlewareAPI, Dispatch } from 'redux';
+import { DataExplorerMiddlewareService, dataExplorerToListParams, listResultsToDataExplorerItemsMeta } from '~/store/data-explorer/data-explorer-middleware-service';
+import { RootState } from '~/store/store';
+import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
+import { DataExplorer, getDataExplorer } from '~/store/data-explorer/data-explorer-reducer';
+import { updateResources } from '~/store/resources/resources-actions';
+import { FilterBuilder } from '~/services/api/filter-builder';
+import { SortDirection } from '~/components/data-table/data-column';
+import { OrderDirection, OrderBuilder } from '~/services/api/order-builder';
+import { ListResults } from '~/services/common-service/common-service';
+import { userBindedActions } from '~/store/users/users-actions';
+import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
+import { UserResource } from '~/models/user';
+import { UserPanelColumnNames } from '~/views/user-panel/user-panel';
+
+export class UserMiddlewareService extends DataExplorerMiddlewareService {
+    constructor(private services: ServiceRepository, id: string) {
+        super(id);
+    }
+
+    async requestItems(api: MiddlewareAPI<Dispatch, RootState>) {
+        const state = api.getState();
+        const dataExplorer = getDataExplorer(state.dataExplorer, this.getId());
+        try {
+            const response = await this.services.userService.list(getParams(dataExplorer));
+            api.dispatch(updateResources(response.items));
+            api.dispatch(setItems(response));
+        } catch {
+            api.dispatch(couldNotFetchUsers());
+        }
+    }
+}
+
+export const getParams = (dataExplorer: DataExplorer) => ({
+    ...dataExplorerToListParams(dataExplorer),
+    order: getOrder(dataExplorer),
+    filters: getFilters(dataExplorer)
+});
+
+export const getFilters = (dataExplorer: DataExplorer) => {
+    const filters = new FilterBuilder()
+        .addILike("username", dataExplorer.searchValue)
+        .getFilters();
+    return filters;
+};
+
+export const getOrder = (dataExplorer: DataExplorer) => {
+    const sortColumn = getSortColumn(dataExplorer);
+    const order = new OrderBuilder<UserResource>();
+    if (sortColumn) {
+        const sortDirection = sortColumn && sortColumn.sortDirection === SortDirection.ASC
+            ? OrderDirection.ASC
+            : OrderDirection.DESC;
+        const columnName = sortColumn && sortColumn.name === UserPanelColumnNames.LAST_NAME ? "lastName" : "firstName";
+        return order
+            .addOrder(sortDirection, columnName)
+            .getOrder();
+    } else {
+        return order.getOrder();
+    }
+};
+
+export const setItems = (listResults: ListResults<UserResource>) =>
+    userBindedActions.SET_ITEMS({
+        ...listResultsToDataExplorerItemsMeta(listResults),
+        items: listResults.items.map(resource => resource.uuid),
+    });
+
+const couldNotFetchUsers = () =>
+    snackbarActions.OPEN_SNACKBAR({
+        message: 'Could not fetch users.',
+        kind: SnackbarKind.ERROR
+    });
\ No newline at end of file
diff --git a/src/store/users/users-actions.ts b/src/store/users/users-actions.ts
new file mode 100644 (file)
index 0000000..64c3646
--- /dev/null
@@ -0,0 +1,96 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { Dispatch } from "redux";
+import { bindDataExplorerActions } from '~/store/data-explorer/data-explorer-action';
+import { RootState } from '~/store/store';
+import { ServiceRepository } from "~/services/services";
+import { dialogActions } from '~/store/dialog/dialog-actions';
+import { startSubmit, reset, stopSubmit } from "redux-form";
+import { getCommonResourceServiceError, CommonResourceServiceError } from "~/services/common-service/common-resource-service";
+import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
+import { UserResource } from "~/models/user";
+import { getResource } from '~/store/resources/resources';
+import { navigateToProject } from "~/store/navigation/navigation-action";
+
+export const USERS_PANEL_ID = 'usersPanel';
+export const USER_ATTRIBUTES_DIALOG = 'userAttributesDialog';
+export const USER_CREATE_FORM_NAME = 'repositoryCreateFormName';
+
+export interface UserCreateFormDialogData {
+    email: string;
+    identityUrl: string;
+    virtualMachineName: string;
+    groupVirtualMachine: string;
+}
+
+export const openUserAttributes = (uuid: string) =>
+    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        const { resources } = getState();
+        const data = getResource<UserResource>(uuid)(resources);
+        dispatch(dialogActions.OPEN_DIALOG({ id: USER_ATTRIBUTES_DIALOG, data }));
+    };
+
+export const openUserCreateDialog = () =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        const userUuid = await services.authService.getUuid();
+        const user = await services.userService.get(userUuid!);
+        const virtualMachines = await services.virtualMachineService.list();
+        dispatch(reset(USER_CREATE_FORM_NAME));
+        dispatch(dialogActions.OPEN_DIALOG({ id: USER_CREATE_FORM_NAME, data: { user, ...virtualMachines } }));
+    };
+
+export const openUserProjects = (uuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        dispatch<any>(navigateToProject(uuid));
+    };
+
+
+export const createUser = (user: UserCreateFormDialogData) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        dispatch(startSubmit(USER_CREATE_FORM_NAME));
+        try {
+            const newUser = await services.userService.create({ ...user });
+            dispatch(dialogActions.CLOSE_DIALOG({ id: USER_CREATE_FORM_NAME }));
+            dispatch(reset(USER_CREATE_FORM_NAME));
+            dispatch(snackbarActions.OPEN_SNACKBAR({ message: "User has been successfully created.", hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
+            dispatch<any>(loadUsersPanel());
+            dispatch(userBindedActions.REQUEST_ITEMS());
+            return newUser;
+        } catch (e) {
+            return ;
+        }
+    };
+
+export const toggleIsActive = (uuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        const { resources } = getState();
+        const data = getResource<UserResource>(uuid)(resources);
+        const isActive = data!.isActive;
+        const newActivity = await services.userService.update(uuid, { ...data, isActive: !isActive });
+        dispatch<any>(loadUsersPanel());
+        return newActivity;
+    };
+
+export const toggleIsAdmin = (uuid: string) =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        const { resources } = getState();
+        const data = getResource<UserResource>(uuid)(resources);
+        const isAdmin = data!.isAdmin;
+        const newActivity = await services.userService.update(uuid, { ...data, isAdmin: !isAdmin });
+        dispatch<any>(loadUsersPanel());
+        return newActivity;
+    };
+
+export const userBindedActions = bindDataExplorerActions(USERS_PANEL_ID);
+
+export const loadUsersData = () =>
+    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+        await services.userService.list();
+    };
+
+export const loadUsersPanel = () =>
+    (dispatch: Dispatch) => {
+        dispatch(userBindedActions.REQUEST_ITEMS());
+    };
\ No newline at end of file
index c95277b3a4c412149d4d2f3606a21f0bf3fc699f..0aaa9050d7276cd4eef159b53166d5a34032182b 100644 (file)
@@ -11,7 +11,7 @@ import { formatDate } from "~/common/formatters";
 import { unionize, ofType, UnionOf } from "~/common/unionize";
 import { VirtualMachineLogins } from '~/models/virtual-machines';
 import { FilterBuilder } from "~/services/api/filter-builder";
-import { ListResults } from "~/services/common-service/common-resource-service";
+import { ListResults } from "~/services/common-service/common-service";
 import { dialogActions } from '~/store/dialog/dialog-actions';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
 
index 475ad7523896eeb2f63bd96efe92bfa3ce44ea8a..3ee90d57d60a7fbe9280ca89d0027a47a0619917 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import { virtualMachinesActions, VirtualMachineActions } from '~/store/virtual-machines/virtual-machines-actions';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { VirtualMachineLogins } from '~/models/virtual-machines';
 
 interface VirtualMachines {
index 49c50f288982c2140243948b2ccc17dcda46aa3b..bc5eac6c8bcaa41ea74ea96ab4de5aeb8163837a 100644 (file)
@@ -58,7 +58,10 @@ import { searchResultsPanelColumns } from '~/views/search-results-panel/search-r
 import { loadVirtualMachinesPanel } from '~/store/virtual-machines/virtual-machines-actions';
 import { loadRepositoriesPanel } from '~/store/repositories/repositories-actions';
 import { loadKeepServicesPanel } from '~/store/keep-services/keep-services-actions';
+import { loadUsersPanel, userBindedActions } from '~/store/users/users-actions';
+import { userPanelColumns } from '~/views/user-panel/user-panel';
 import { loadComputeNodesPanel } from '~/store/compute-nodes/compute-nodes-actions';
+import { loadApiClientAuthorizationsPanel } from '~/store/api-client-authorizations/api-client-authorizations-actions';
 
 export const WORKBENCH_LOADING_SCREEN = 'workbenchLoadingScreen';
 
@@ -78,7 +81,6 @@ const handleFirstTimeLoad = (action: any) =>
         }
     };
 
-
 export const loadWorkbench = () =>
     async (dispatch: Dispatch, getState: () => RootState) => {
         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
@@ -93,6 +95,7 @@ export const loadWorkbench = () =>
                 dispatch(sharedWithMePanelActions.SET_COLUMNS({ columns: projectPanelColumns }));
                 dispatch(workflowPanelActions.SET_COLUMNS({ columns: workflowPanelColumns }));
                 dispatch(searchResultsPanelActions.SET_COLUMNS({ columns: searchResultsPanelColumns }));
+                dispatch(userBindedActions.SET_COLUMNS({ columns: userPanelColumns }));
                 dispatch<any>(initSidePanelTree());
                 if (router.location) {
                     const match = matchRootRoute(router.location.pathname);
@@ -130,7 +133,10 @@ export const loadProject = (uuid: string) =>
             const userUuid = services.authService.getUuid();
             dispatch(setIsProjectPanelTrashed(false));
             if (userUuid) {
-                if (userUuid !== uuid) {
+                if (extractUuidKind(uuid) === ResourceKind.USER && userUuid !== uuid) {
+                    // Load another users home projects
+                    dispatch(finishLoadingProject(uuid));
+                } else if (userUuid !== uuid) {
                     const match = await loadGroupContentsResource({ uuid, userUuid, services });
                     match({
                         OWNED: async project => {
@@ -401,7 +407,7 @@ export const loadVirtualMachines = handleFirstTimeLoad(
         await dispatch(loadVirtualMachinesPanel());
         dispatch(setBreadcrumbs([{ label: 'Virtual Machines' }]));
     });
-    
+
 export const loadRepositories = handleFirstTimeLoad(
     async (dispatch: Dispatch<any>) => {
         await dispatch(loadRepositoriesPanel());
@@ -423,11 +429,22 @@ export const loadKeepServices = handleFirstTimeLoad(
         await dispatch(loadKeepServicesPanel());
     });
 
+export const loadUsers = handleFirstTimeLoad(
+    async (dispatch: Dispatch<any>) => {
+        await dispatch(loadUsersPanel());
+        dispatch(setBreadcrumbs([{ label: 'Users' }]));
+    });
+
 export const loadComputeNodes = handleFirstTimeLoad(
     async (dispatch: Dispatch<any>) => {
         await dispatch(loadComputeNodesPanel());
     });
 
+export const loadApiClientAuthorizations = handleFirstTimeLoad(
+    async (dispatch: Dispatch<any>) => {
+        await dispatch(loadApiClientAuthorizationsPanel());
+    });
+
 const finishLoadingProject = (project: GroupContentsResource | string) =>
     async (dispatch: Dispatch<any>) => {
         const uuid = typeof project === 'string' ? project : project.uuid;
index fefcb325e24dc8fe406c2b92545309e5e33db11d..6dbcf6ac8df1d5f6e28552b16a6c63451f9fc0c4 100644 (file)
@@ -14,8 +14,8 @@ import { SortDirection } from '~/components/data-table/data-column';
 import { WorkflowPanelColumnNames } from '~/views/workflow-panel/workflow-panel-view';
 import { OrderDirection, OrderBuilder } from '~/services/api/order-builder';
 import { WorkflowResource } from '~/models/workflow';
-import { ListResults } from '~/services/common-service/common-resource-service';
-import { workflowPanelActions } from './workflow-panel-actions';
+import { ListResults } from '~/services/common-service/common-service';
+import { workflowPanelActions } from '~/store/workflow-panel/workflow-panel-actions';
 import { getSortColumn } from "~/store/data-explorer/data-explorer-reducer";
 
 export class WorkflowMiddlewareService extends DataExplorerMiddlewareService {
index a3f5df2e22d24df4f0c5eb7892298994451432c4..30fa36bfeb9ece62a3ee3a46f19764bf9487a357 100644 (file)
@@ -24,6 +24,9 @@ export const PROCESS_NAME_VALIDATION = [require, maxLength(255)];
 
 export const REPOSITORY_NAME_VALIDATION = [require, maxLength(255)];
 
+export const USER_EMAIL_VALIDATION = [require, maxLength(255)];
+export const USER_LENGTH_VALIDATION = [maxLength(255)];
+
 export const SSH_KEY_PUBLIC_VALIDATION = [require, isRsaKey, maxLength(1024)];
 export const SSH_KEY_NAME_VALIDATION = [require, maxLength(255)];
 
diff --git a/src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx b/src/views-components/api-client-authorizations-dialog/attributes-dialog.tsx
new file mode 100644 (file)
index 0000000..e7defd6
--- /dev/null
@@ -0,0 +1,78 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { compose } from 'redux';
+import {
+    withStyles, Dialog, DialogTitle, DialogContent, DialogActions,
+    Button, StyleRulesCallback, WithStyles, Grid
+} from '@material-ui/core';
+import { WithDialogProps, withDialog } from "~/store/dialog/with-dialog";
+import { API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { formatDate } from '~/common/formatters';
+
+type CssRules = 'root';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    root: {
+        fontSize: '0.875rem',
+        '& div:nth-child(odd)': {
+            textAlign: 'right',
+            color: theme.palette.grey["500"]
+        }
+    }
+});
+
+interface AttributesKeepServiceDialogDataProps {
+    apiClientAuthorization: ApiClientAuthorization;
+}
+
+export const AttributesApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_ATTRIBUTES_DIALOG),
+    withStyles(styles))(
+        ({ open, closeDialog, data, classes }: WithDialogProps<AttributesKeepServiceDialogDataProps> & WithStyles<CssRules>) =>
+            <Dialog open={open} onClose={closeDialog} fullWidth maxWidth='sm'>
+                <DialogTitle>Attributes</DialogTitle>
+                <DialogContent>
+                    {data.apiClientAuthorization && <Grid container direction="row" spacing={16} className={classes.root}>
+                        <Grid item xs={5}>UUID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.uuid}</Grid>
+                        <Grid item xs={5}>Owner uuid</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.ownerUuid}</Grid>
+                        <Grid item xs={5}>API Client ID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.apiClientId}</Grid>
+                        <Grid item xs={5}>API Token</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.apiToken}</Grid>
+                        <Grid item xs={5}>Created by IP address</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.createdByIpAddress || '(none)'}</Grid>
+                        <Grid item xs={5}>Default owner</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.defaultOwnerUuid || '(none)'}</Grid>
+                        <Grid item xs={5}>Expires at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.expiresAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Last used at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.lastUsedAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Last used by IP address</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.lastUsedByIpAddress || '(none)'}</Grid>
+                        <Grid item xs={5}>Scopes</Grid>
+                        <Grid item xs={7}>{JSON.stringify(data.apiClientAuthorization.scopes || '(none)')}</Grid>
+                        <Grid item xs={5}>User ID</Grid>
+                        <Grid item xs={7}>{data.apiClientAuthorization.userId || '(none)'}</Grid>
+                        <Grid item xs={5}>Created at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.createdAt) || '(none)'}</Grid>
+                        <Grid item xs={5}>Updated at</Grid>
+                        <Grid item xs={7}>{formatDate(data.apiClientAuthorization.updatedAt) || '(none)'}</Grid>
+                    </Grid>}
+                </DialogContent>
+                <DialogActions>
+                    <Button
+                        variant='flat'
+                        color='primary'
+                        onClick={closeDialog}>
+                        Close
+                    </Button>
+                </DialogActions>
+            </Dialog>
+    );
\ No newline at end of file
diff --git a/src/views-components/api-client-authorizations-dialog/help-dialog.tsx b/src/views-components/api-client-authorizations-dialog/help-dialog.tsx
new file mode 100644 (file)
index 0000000..d2802fa
--- /dev/null
@@ -0,0 +1,66 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Typography } from "@material-ui/core";
+import { WithDialogProps } from "~/store/dialog/with-dialog";
+import { withDialog } from '~/store/dialog/with-dialog';
+import { DefaultCodeSnippet } from '~/components/default-code-snippet/default-code-snippet';
+import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core/styles';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { compose } from "redux";
+import { API_CLIENT_AUTHORIZATION_HELP_DIALOG } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+type CssRules = 'codeSnippet';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    codeSnippet: {
+        borderRadius: theme.spacing.unit * 0.5,
+        border: `1px solid ${theme.palette.grey["400"]}`,
+        '& pre': {
+            fontSize: '0.815rem'
+        }
+    }
+});
+
+interface HelpApiClientAuthorizationDataProps {
+    apiHost: string;
+    apiToken: string;
+    email: string;
+}
+
+export const HelpApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_HELP_DIALOG),
+    withStyles(styles))(
+        (props: WithDialogProps<HelpApiClientAuthorizationDataProps> & WithStyles<CssRules>) =>
+            <Dialog open={props.open}
+                onClose={props.closeDialog}
+                fullWidth
+                maxWidth='md'>
+                <DialogTitle>HELP:</DialogTitle>
+                <DialogContent>
+                    <DefaultCodeSnippet
+                        className={props.classes.codeSnippet}
+                        lines={[snippetText(props.data)]} />
+                        {/* // lines={snippetText2(props.data)} /> */}
+                </DialogContent>
+                <DialogActions>
+                    <Button
+                        variant='flat'
+                        color='primary'
+                        onClick={props.closeDialog}>
+                        Close
+                </Button>
+                </DialogActions>
+            </Dialog>
+    );
+
+const snippetText = (data: HelpApiClientAuthorizationDataProps) => `### Pasting the following lines at a shell prompt will allow Arvados SDKs
+### to authenticate to your account, ${data.email}
+
+read ARVADOS_API_TOKEN <<EOF
+${data.apiToken}
+EOF
+export ARVADOS_API_TOKEN ARVADOS_API_HOST=${data.apiHost}
+unset ARVADOS_API_HOST_INSECURE`;
diff --git a/src/views-components/api-client-authorizations-dialog/remove-dialog.tsx b/src/views-components/api-client-authorizations-dialog/remove-dialog.tsx
new file mode 100644 (file)
index 0000000..47b6adc
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+import { Dispatch, compose } from 'redux';
+import { connect } from "react-redux";
+import { ConfirmationDialog } from "~/components/confirmation-dialog/confirmation-dialog";
+import { withDialog, WithDialogProps } from "~/store/dialog/with-dialog";
+import { API_CLIENT_AUTHORIZATION_REMOVE_DIALOG, removeApiClientAuthorization } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+const mapDispatchToProps = (dispatch: Dispatch, props: WithDialogProps<any>) => ({
+    onConfirm: () => {
+        props.closeDialog();
+        dispatch<any>(removeApiClientAuthorization(props.data.uuid));
+    }
+});
+
+export const RemoveApiClientAuthorizationDialog = compose(
+    withDialog(API_CLIENT_AUTHORIZATION_REMOVE_DIALOG),
+    connect(null, mapDispatchToProps)
+)(ConfirmationDialog);
\ No newline at end of file
diff --git a/src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts b/src/views-components/context-menu/action-sets/api-client-authorization-action-set.ts
new file mode 100644 (file)
index 0000000..b6f089a
--- /dev/null
@@ -0,0 +1,31 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import {
+    openApiClientAuthorizationAttributesDialog,
+    openApiClientAuthorizationRemoveDialog
+} from '~/store/api-client-authorizations/api-client-authorizations-actions';
+import { openAdvancedTabDialog } from '~/store/advanced-tab/advanced-tab';
+import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set";
+import { AdvancedIcon, RemoveIcon, AttributesIcon } from "~/components/icon/icon";
+
+export const apiClientAuthorizationActionSet: ContextMenuActionSet = [[{
+    name: "Attributes",
+    icon: AttributesIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openApiClientAuthorizationAttributesDialog(uuid));
+    }
+}, {
+    name: "Advanced",
+    icon: AdvancedIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openAdvancedTabDialog(uuid));
+    }
+}, {
+    name: "Remove",
+    icon: RemoveIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openApiClientAuthorizationRemoveDialog(uuid));
+    }
+}]];
diff --git a/src/views-components/context-menu/action-sets/user-action-set.ts b/src/views-components/context-menu/action-sets/user-action-set.ts
new file mode 100644 (file)
index 0000000..7b0884e
--- /dev/null
@@ -0,0 +1,35 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { ContextMenuActionSet } from "~/views-components/context-menu/context-menu-action-set";
+import { AdvancedIcon, ProjectIcon, AttributesIcon, UserPanelIcon } from "~/components/icon/icon";
+import { openAdvancedTabDialog } from '~/store/advanced-tab/advanced-tab';
+import { openUserAttributes, openUserProjects } from "~/store/users/users-actions";
+
+export const userActionSet: ContextMenuActionSet = [[{
+    name: "Attributes",
+    icon: AttributesIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openUserAttributes(uuid));
+    }
+}, {
+    name: "Project",
+    icon: ProjectIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openUserProjects(uuid));
+    }
+}, {
+    name: "Advanced",
+    icon: AdvancedIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openAdvancedTabDialog(uuid));
+    }
+},
+{
+    name: "Manage",
+    icon: UserPanelIcon,
+    execute: (dispatch, { uuid }) => {
+        dispatch<any>(openAdvancedTabDialog(uuid));
+    }
+}]];
index 3fa1ab30d83d5d994e7b94bbe49b356deee74009..95a4a83f8c2cb8fa8073392348b7f32112a31d05 100644 (file)
@@ -55,6 +55,7 @@ const getMenuActionSet = (resource?: ContextMenuResource): ContextMenuActionSet
 };
 
 export enum ContextMenuKind {
+    API_CLIENT_AUTHORIZATION = "ApiClientAuthorization",
     ROOT_PROJECT = "RootProject",
     PROJECT = "Project",
     RESOURCE = "Resource",
@@ -73,5 +74,6 @@ export enum ContextMenuKind {
     SSH_KEY = "SshKey",
     VIRTUAL_MACHINE = "VirtualMachine",
     KEEP_SERVICE = "KeepService",
+    USER = "User",
     NODE = "Node"
 }
index a032b3ed5a22945e952d20767afd924fb931d4bd..16ea7a995ec451b1fba9fdd5f0e9e23b60d0bfb1 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as React from 'react';
-import { Grid, Typography, withStyles, Tooltip, IconButton } from '@material-ui/core';
+import { Grid, Typography, withStyles, Tooltip, IconButton, Checkbox } from '@material-ui/core';
 import { FavoriteStar } from '../favorite-star/favorite-star';
 import { ResourceKind, TrashableResource } from '~/models/resource';
 import { ProjectIcon, CollectionIcon, ProcessIcon, DefaultIcon, WorkflowIcon, ShareIcon } from '~/components/icon/icon';
@@ -21,8 +21,10 @@ import { ResourceStatus } from '~/views/workflow-panel/workflow-panel-view';
 import { getUuidPrefix, openRunProcess } from '~/store/workflow-panel/workflow-panel-actions';
 import { getResourceData } from "~/store/resources-data/resources-data";
 import { openSharingDialog } from '~/store/sharing-dialog/sharing-dialog-actions';
+import { UserResource } from '~/models/user';
+import { toggleIsActive, toggleIsAdmin } from '~/store/users/users-actions';
 
-export const renderName = (item: { name: string; uuid: string, kind: string }) =>
+const renderName = (item: { name: string; uuid: string, kind: string }) =>
     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
         <Grid item>
             {renderIcon(item)}
@@ -45,7 +47,7 @@ export const ResourceName = connect(
         return resource || { name: '', uuid: '', kind: '' };
     })(renderName);
 
-export const renderIcon = (item: { kind: string }) => {
+const renderIcon = (item: { kind: string }) => {
     switch (item.kind) {
         case ResourceKind.PROJECT:
             return <ProjectIcon />;
@@ -60,11 +62,11 @@ export const renderIcon = (item: { kind: string }) => {
     }
 };
 
-export const renderDate = (date?: string) => {
+const renderDate = (date?: string) => {
     return <Typography noWrap style={{ minWidth: '100px' }}>{formatDate(date)}</Typography>;
 };
 
-export const renderWorkflowName = (item: { name: string; uuid: string, kind: string, ownerUuid: string }) =>
+const renderWorkflowName = (item: { name: string; uuid: string, kind: string, ownerUuid: string }) =>
     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
         <Grid item>
             {renderIcon(item)}
@@ -86,7 +88,7 @@ const getPublicUuid = (uuidPrefix: string) => {
     return `${uuidPrefix}-tpzed-anonymouspublic`;
 };
 
-export const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
+const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
     const isPublic = ownerUuid === getPublicUuid(uuidPrefix);
     return (
         <div>
@@ -113,7 +115,79 @@ export const ResourceShare = connect(
     })((props: { ownerUuid?: string, uuidPrefix: string, uuid?: string } & DispatchProp<any>) =>
         resourceShare(props.dispatch, props.uuidPrefix, props.ownerUuid, props.uuid));
 
-export const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
+const renderFirstName = (item: { firstName: string }) => {
+    return <Typography noWrap>{item.firstName}</Typography>;
+};
+
+export const ResourceFirstName = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { firstName: '' };
+    })(renderFirstName);
+
+const renderLastName = (item: { lastName: string }) =>
+    <Typography noWrap>{item.lastName}</Typography>;
+
+export const ResourceLastName = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { lastName: '' };
+    })(renderLastName);
+
+const renderUuid = (item: { uuid: string }) =>
+    <Typography noWrap>{item.uuid}</Typography>;
+
+export const ResourceUuid = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { uuid: '' };
+    })(renderUuid);
+
+const renderEmail = (item: { email: string }) =>
+    <Typography noWrap>{item.email}</Typography>;
+
+export const ResourceEmail = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { email: '' };
+    })(renderEmail);
+
+const renderIsActive = (props: { uuid: string, isActive: boolean, toggleIsActive: (uuid: string) => void }) =>
+    <Checkbox
+        color="primary"
+        checked={props.isActive}
+        onClick={() => props.toggleIsActive(props.uuid)} />;
+
+export const ResourceIsActive = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { isActive: false };
+    }, { toggleIsActive }
+)(renderIsActive);
+
+const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
+    <Checkbox
+        color="primary"
+        checked={props.isAdmin}
+        onClick={() => props.toggleIsAdmin(props.uuid)} />;
+
+export const ResourceIsAdmin = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { isAdmin: false };
+    }, { toggleIsAdmin }
+)(renderIsAdmin);
+
+const renderUsername = (item: { username: string }) =>
+    <Typography noWrap>{item.username}</Typography>;
+
+export const ResourceUsername = connect(
+    (state: RootState, props: { uuid: string }) => {
+        const resource = getResource<UserResource>(props.uuid)(state.resources);
+        return resource || { username: '' };
+    })(renderUsername);
+
+const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
     return (
         <div>
             {uuid &&
@@ -135,7 +209,7 @@ export const ResourceRunProcess = connect(
     })((props: { uuid: string } & DispatchProp<any>) =>
         resourceRunProcess(props.dispatch, props.uuid));
 
-export const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
+const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
     if (ownerUuid === getPublicUuid(uuidPrefix)) {
         return renderStatus(ResourceStatus.PUBLIC);
     } else {
@@ -185,7 +259,7 @@ export const ResourceFileSize = connect(
         return { fileSize: resource ? resource.fileSize : 0 };
     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
 
-export const renderOwner = (owner: string) =>
+const renderOwner = (owner: string) =>
     <Typography noWrap color="primary" >
         {owner}
     </Typography>;
@@ -196,7 +270,7 @@ export const ResourceOwner = connect(
         return { owner: resource ? resource.ownerUuid : '' };
     })((props: { owner: string }) => renderOwner(props.owner));
 
-export const renderType = (type: string) =>
+const renderType = (type: string) =>
     <Typography noWrap>
         {resourceLabel(type)}
     </Typography>;
diff --git a/src/views-components/dialog-create/dialog-user-create.tsx b/src/views-components/dialog-create/dialog-user-create.tsx
new file mode 100644 (file)
index 0000000..14365af
--- /dev/null
@@ -0,0 +1,26 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from 'react';
+import { InjectedFormProps } from 'redux-form';
+import { WithDialogProps } from '~/store/dialog/with-dialog';
+import { FormDialog } from '~/components/form-dialog/form-dialog';
+import { UserEmailField, UserIdentityUrlField, UserVirtualMachineField, UserGroupsVirtualMachineField } from '~/views-components/form-fields/user-form-fields';
+
+export type DialogUserProps = WithDialogProps<{}> & InjectedFormProps<any>;
+
+export const UserRepositoryCreate = (props: DialogUserProps) =>
+    <FormDialog
+        dialogTitle='New user'
+        formFields={UserAddFields}
+        submitLabel='ADD NEW USER'
+        {...props}
+    />;
+
+const UserAddFields = (props: DialogUserProps) => <span>
+    <UserEmailField />
+    <UserIdentityUrlField />
+    <UserVirtualMachineField data={props.data}/>
+    <UserGroupsVirtualMachineField />
+</span>;
diff --git a/src/views-components/dialog-forms/create-user-dialog.ts b/src/views-components/dialog-forms/create-user-dialog.ts
new file mode 100644 (file)
index 0000000..cb46204
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { compose } from "redux";
+import { reduxForm } from 'redux-form';
+import { withDialog } from "~/store/dialog/with-dialog";
+import { USER_CREATE_FORM_NAME, createUser, UserCreateFormDialogData } from "~/store/users/users-actions";
+import { UserRepositoryCreate } from "~/views-components/dialog-create/dialog-user-create";
+
+export const CreateUserDialog = compose(
+    withDialog(USER_CREATE_FORM_NAME),
+    reduxForm<UserCreateFormDialogData>({
+        form: USER_CREATE_FORM_NAME,
+        onSubmit: (data, dispatch) => {
+            dispatch(createUser(data));
+        }
+    })
+)(UserRepositoryCreate);
\ No newline at end of file
index 2d2a7c80880b0fef31e428c46150fd504d506f95..c02996d81cb21b148708d0cac1a2a9a398a1ee65 100644 (file)
@@ -3,11 +3,11 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as React from "react";
-import { Field, WrappedFieldProps } from "redux-form";
+import { Field } from "redux-form";
 import { TextField } from "~/components/text-field/text-field";
 import { COLLECTION_NAME_VALIDATION, COLLECTION_DESCRIPTION_VALIDATION, COLLECTION_PROJECT_VALIDATION } from "~/validators/validators";
-import { ProjectTreePicker, ProjectTreePickerField } from "~/views-components/project-tree-picker/project-tree-picker";
-import { PickerIdProp } from '../../store/tree-picker/picker-id';
+import { ProjectTreePickerField } from "~/views-components/project-tree-picker/project-tree-picker";
+import { PickerIdProp } from '~/store/tree-picker/picker-id';
 
 export const CollectionNameField = () =>
     <Field
index cf471b67d1f16323abd551f69342782c11e068f0..8f55e08456258fa3a0f87f259cfd8afa66e8c5d5 100644 (file)
@@ -3,7 +3,7 @@
 // SPDX-License-Identifier: AGPL-3.0
 
 import * as React from "react";
-import { Field, WrappedFieldProps } from "redux-form";
+import { Field } from "redux-form";
 import { TextField } from "~/components/text-field/text-field";
 import { PROCESS_NAME_VALIDATION } from "~/validators/validators";
 
index 7a5703fecfc6b9e4d5202df5ac8827d5ae8f6e0a..da0b12b55311fc045819c8f5d4b7641f0c6df045 100644 (file)
@@ -12,6 +12,8 @@ import { ClusterObjectType } from '~/models/search-bar';
 import { HomeTreePicker } from '~/views-components/projects-tree-picker/home-tree-picker';
 import { SEARCH_BAR_ADVANCE_FORM_PICKER_ID } from '~/store/search-bar/search-bar-actions';
 import { SearchBarAdvancedPropertiesView } from '~/views-components/search-bar/search-bar-advanced-properties-view';
+import { TreeItem } from "~/components/tree/tree";
+import { ProjectsTreePickerItem } from "~/views-components/projects-tree-picker/generic-projects-tree-picker";
 
 export const SearchBarTypeField = () =>
     <Field
@@ -42,7 +44,13 @@ export const SearchBarProjectField = () =>
 
 const ProjectsPicker = (props: WrappedFieldProps) =>
     <div style={{ height: '100px', display: 'flex', flexDirection: 'column', overflow: 'overlay' }}>
-        <HomeTreePicker pickerId={SEARCH_BAR_ADVANCE_FORM_PICKER_ID} />
+        <HomeTreePicker
+            pickerId={SEARCH_BAR_ADVANCE_FORM_PICKER_ID}
+            toggleItemActive={
+                (_: any, { id }: TreeItem<ProjectsTreePickerItem>) => {
+                    props.input.onChange(id);
+                }
+            }/>
     </div>;
 
 export const SearchBarTrashField = () =>
@@ -82,10 +90,10 @@ export const SearchBarSaveSearchField = () =>
     <Field
         name='saveQuery'
         component={CheckboxField}
-        label="Save search query" />;
+        label="Save query" />;
 
 export const SearchBarQuerySearchField = () =>
     <Field
-        name='searchQuery'
+        name='queryName'
         component={TextField}
-        label="Search query name" />;
\ No newline at end of file
+        label="Query name" />;
diff --git a/src/views-components/form-fields/user-form-fields.tsx b/src/views-components/form-fields/user-form-fields.tsx
new file mode 100644 (file)
index 0000000..8563444
--- /dev/null
@@ -0,0 +1,48 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { Field } from "redux-form";
+import { TextField } from "~/components/text-field/text-field";
+import { USER_EMAIL_VALIDATION, USER_LENGTH_VALIDATION } from "~/validators/validators";
+import { NativeSelectField } from "~/components/select-field/select-field";
+import { InputLabel } from "@material-ui/core";
+import { VirtualMachinesResource } from "~/models/virtual-machines";
+
+export const UserEmailField = () =>
+    <Field
+        name='email'
+        component={TextField}
+        validate={USER_EMAIL_VALIDATION}
+        autoFocus={true}
+        label="Email" />;
+
+export const UserIdentityUrlField = () =>
+    <Field
+        name='identityUrl'
+        component={TextField}
+        validate={USER_LENGTH_VALIDATION}
+        label="Identity URL Prefix" />;
+
+export const UserVirtualMachineField = ({ data }: any) =>
+    <div style={{ marginBottom: '21px' }}>
+        <InputLabel>Virtual Machine</InputLabel>
+        <Field
+            name='virtualMachine'
+            component={NativeSelectField}
+            validate={USER_LENGTH_VALIDATION}
+            items={getVirtualMachinesList(data.items)} />
+    </div>;
+
+export const UserGroupsVirtualMachineField = () =>
+    <Field
+        name='groups'
+        component={TextField}
+        validate={USER_LENGTH_VALIDATION}
+        label="Groups for virtual machine (comma separated list)" />;
+
+const getVirtualMachinesList = (virtualMachines: VirtualMachinesResource[]) => {
+    const mappedVirtualMachines = virtualMachines.map(it => ({ key: it.hostname, value: it.hostname }));
+    return mappedVirtualMachines;
+};
index ee726f3d75ec5a603acbf80c0708be9085b59316..44b113df39e6b33a347bd661680d4af3312dae04 100644 (file)
@@ -12,8 +12,12 @@ import { logout } from '~/store/auth/auth-action';
 import { RootState } from "~/store/store";
 import { openCurrentTokenDialog } from '~/store/current-token-dialog/current-token-dialog-actions';
 import { openRepositoriesPanel } from "~/store/repositories/repositories-actions";
-import { navigateToSshKeys, navigateToKeepServices, navigateToComputeNodes, navigateToMyAccount } from '~/store/navigation/navigation-action';
+import { 
+    navigateToSshKeys, navigateToKeepServices, navigateToComputeNodes,
+    navigateToApiClientAuthorizations, navigateToMyAccount
+} from '~/store/navigation/navigation-action';
 import { openVirtualMachines } from "~/store/virtual-machines/virtual-machines-actions";
+import { navigateToUsers } from '~/store/navigation/navigation-action';
 
 interface AccountMenuProps {
     user?: User;
@@ -37,6 +41,8 @@ export const AccountMenu = connect(mapStateToProps)(
                 <MenuItem onClick={() => dispatch(openRepositoriesPanel())}>Repositories</MenuItem>
                 <MenuItem onClick={() => dispatch(openCurrentTokenDialog)}>Current token</MenuItem>
                 <MenuItem onClick={() => dispatch(navigateToSshKeys)}>Ssh Keys</MenuItem>
+                <MenuItem onClick={() => dispatch(navigateToUsers)}>Users</MenuItem>
+                { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToApiClientAuthorizations)}>Api Tokens</MenuItem> }
                 { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToKeepServices)}>Keep Services</MenuItem> }
                 { user.isAdmin && <MenuItem onClick={() => dispatch(navigateToComputeNodes)}>Compute Nodes</MenuItem> }
                 <MenuItem onClick={() => dispatch(navigateToMyAccount)}>My account</MenuItem>
index 78b79a8ed46bf0f70737fa412178d421fa0562fb..8c2e4ceda26a8f029b78492747942f86b92c1a17 100644 (file)
@@ -20,7 +20,8 @@ const isButtonVisible = ({ router }: RootState) => {
     const pathname = router.location ? router.location.pathname : '';
     return !Routes.matchWorkflowRoute(pathname) && !Routes.matchVirtualMachineRoute(pathname) &&
         !Routes.matchRepositoriesRoute(pathname) && !Routes.matchSshKeysRoute(pathname) &&
-        !Routes.matchKeepServicesRoute(pathname) && !Routes.matchComputeNodesRoute(pathname);
+        !Routes.matchKeepServicesRoute(pathname) && !Routes.matchComputeNodesRoute(pathname) &&
+        !Routes.matchApiClientAuthorizationsRoute(pathname) && !Routes.matchUsersRoute(pathname);
 };
 
 export const MainContentBar = connect((state: RootState) => ({
index 0384de223d083fa73379460b1ff0652f78e8f597..d4044f958d55b0d1c270232b32469c0c74fe3559 100644 (file)
@@ -13,10 +13,11 @@ import {
     changeAdvanceFormProperty,
     updateAdvanceFormProperties
 } from '~/store/search-bar/search-bar-actions';
-import { PropertyValues } from '~/models/search-bar';
+import { PropertyValue } from '~/models/search-bar';
 import { ArvadosTheme } from '~/common/custom-theme';
 import { SearchBarKeyField, SearchBarValueField } from '~/views-components/form-fields/search-bar-form-fields';
 import { Chips } from '~/components/chips/chips';
+import { formatPropertyValue } from "~/common/formatters";
 
 type CssRules = 'label' | 'button';
 
@@ -35,14 +36,14 @@ interface SearchBarAdvancedPropertiesViewDataProps {
     submitting: boolean;
     invalid: boolean;
     pristine: boolean;
-    propertyValues: PropertyValues;
-    fields: PropertyValues[];
+    propertyValues: PropertyValue;
+    fields: PropertyValue[];
 }
 
 interface SearchBarAdvancedPropertiesViewActionProps {
     setProps: () => void;
-    addProp: (propertyValues: PropertyValues) => void;
-    getAllFields: (propertyValues: PropertyValues[]) => PropertyValues[] | [];
+    addProp: (propertyValues: PropertyValue) => void;
+    getAllFields: (propertyValues: PropertyValue[]) => PropertyValue[] | [];
 }
 
 type SearchBarAdvancedPropertiesViewProps = SearchBarAdvancedPropertiesViewDataProps
@@ -57,10 +58,10 @@ const mapStateToProps = (state: RootState) => {
 };
 
 const mapDispatchToProps = (dispatch: Dispatch) => ({
-    setProps: (propertyValues: PropertyValues[]) => {
+    setProps: (propertyValues: PropertyValue[]) => {
         dispatch<any>(changeAdvanceFormProperty('properties', propertyValues));
     },
-    addProp: (propertyValues: PropertyValues) => {
+    addProp: (propertyValues: PropertyValue) => {
         dispatch<any>(updateAdvanceFormProperties(propertyValues));
         dispatch<any>(changeAdvanceFormProperty('key'));
         dispatch<any>(changeAdvanceFormProperty('value'));
@@ -95,8 +96,8 @@ export const SearchBarAdvancedPropertiesView = connect(mapStateToProps, mapDispa
                     <Chips values={getAllFields(fields)}
                         deletable
                         onChange={setProps}
-                        getLabel={(field: PropertyValues) => `${field.key}: ${field.value}`} />
+                        getLabel={(field: PropertyValue) => formatPropertyValue(field)} />
                 </Grid>
             </Grid>
     )
-);
\ No newline at end of file
+);
index c75735010bcbba439d8709908585e3e263ed2647..05bdb9706301daa2f7f2f94c95fa80cdb7db73d1 100644 (file)
@@ -6,7 +6,11 @@ import * as React from 'react';
 import { reduxForm, InjectedFormProps, reset } from 'redux-form';
 import { compose, Dispatch } from 'redux';
 import { Paper, StyleRulesCallback, withStyles, WithStyles, Button, Grid, IconButton, CircularProgress } from '@material-ui/core';
-import { SEARCH_BAR_ADVANCE_FORM_NAME, searchAdvanceData } from '~/store/search-bar/search-bar-actions';
+import {
+    SEARCH_BAR_ADVANCE_FORM_NAME, SEARCH_BAR_ADVANCE_FORM_PICKER_ID,
+    searchAdvanceData,
+    setSearchValueFromAdvancedData
+} from '~/store/search-bar/search-bar-actions';
 import { ArvadosTheme } from '~/common/custom-theme';
 import { CloseIcon } from '~/components/icon/icon';
 import { SearchBarAdvanceFormData } from '~/models/search-bar';
@@ -15,6 +19,7 @@ import {
     SearchBarDateFromField, SearchBarDateToField, SearchBarPropertiesField,
     SearchBarSaveSearchField, SearchBarQuerySearchField
 } from '~/views-components/form-fields/search-bar-form-fields';
+import { treePickerActions } from "~/store/tree-picker/tree-picker-actions";
 
 type CssRules = 'container' | 'closeIcon' | 'label' | 'buttonWrapper'
     | 'button' | 'circularProgress' | 'searchView' | 'selectGrid';
@@ -69,6 +74,7 @@ interface SearchBarAdvancedViewFormDataProps {
 // ToDo: maybe we should remove tags
 export interface SearchBarAdvancedViewDataProps {
     tags: any;
+    saveQuery: boolean;
 }
 
 export interface SearchBarAdvancedViewActionProps {
@@ -99,10 +105,14 @@ export const SearchBarAdvancedView = compose(
         onSubmit: (data: SearchBarAdvanceFormData, dispatch: Dispatch) => {
             dispatch<any>(searchAdvanceData(data));
             dispatch(reset(SEARCH_BAR_ADVANCE_FORM_NAME));
-        }
+            dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
+        },
+        onChange: (data: SearchBarAdvanceFormData, dispatch: Dispatch, props: any, prevData: SearchBarAdvanceFormData) => {
+            dispatch<any>(setSearchValueFromAdvancedData(data, prevData));
+        },
     }),
     withStyles(styles))(
-        ({ classes, closeAdvanceView, handleSubmit, submitting, invalid, pristine, tags }: SearchBarAdvancedViewFormProps) =>
+        ({ classes, closeAdvanceView, handleSubmit, submitting, invalid, pristine, tags, saveQuery }: SearchBarAdvancedViewFormProps) =>
             <Paper className={classes.searchView}>
                 <form onSubmit={handleSubmit}>
                     <Grid container direction="column" justify="flex-start" alignItems="flex-start">
@@ -121,7 +131,7 @@ export const SearchBarAdvancedView = compose(
                             </Grid>
                             <Grid item container xs={12}>
                                 <Grid item xs={2} className={classes.label}>Project</Grid>
-                                <Grid item xs={5}>
+                                <Grid item xs={10}>
                                     <SearchBarProjectField />
                                 </Grid>
                             </Grid>
@@ -152,7 +162,7 @@ export const SearchBarAdvancedView = compose(
                                     <SearchBarSaveSearchField />
                                 </Grid>
                                 <Grid item xs={4}>
-                                    <SearchBarQuerySearchField />
+                                    {saveQuery && <SearchBarQuerySearchField />}
                                 </Grid>
                             </Grid>
                             <Grid container item xs={12} justify='flex-end'>
index 76d46b3662573cd78a0541090aaa4b3ec00fbe7a..b23a96a089e4c26099c6dbeb6cc3460d63c9c657 100644 (file)
@@ -32,10 +32,12 @@ const styles: StyleRulesCallback<CssRules> = theme => {
             color: theme.palette.primary.main
         },
         label: {
-            fontSize: '0.875rem',
+            fontSize: '0.775rem',
             padding: `${theme.spacing.unit}px ${theme.spacing.unit}px `,
             color: theme.palette.grey["900"],
-            background: theme.palette.grey["200"]
+            background: 'white',
+            textAlign: 'right',
+            fontWeight: 'bold'
         }
     };
 };
@@ -52,18 +54,17 @@ type SearchBarBasicViewProps = SearchBarBasicViewDataProps & SearchBarBasicViewA
 export const SearchBarBasicView = withStyles(styles)(
     ({ classes, onSetView, loadRecentQueries, deleteSavedQuery, savedQueries, onSearch, editSavedQuery, selectedItem }: SearchBarBasicViewProps) =>
         <Paper className={classes.root}>
-            <div className={classes.label}>Recent search queries</div>
+            <div className={classes.label}>{"Recent queries"}</div>
             <SearchBarRecentQueries
                 onSearch={onSearch}
                 loadRecentQueries={loadRecentQueries}
                 selectedItem={selectedItem} />
-            <div className={classes.label}>Saved search queries</div>
+            <div className={classes.label}>{"Saved queries"}</div>
             <SearchBarSavedQueries
                 onSearch={onSearch}
                 savedQueries={savedQueries}
                 editSavedQuery={editSavedQuery}
                 deleteSavedQuery={deleteSavedQuery}
                 selectedItem={selectedItem} />
-            <div className={classes.advanced} onClick={() => onSetView(SearchView.ADVANCED)}>Advanced search</div>
         </Paper>
 );
index aa62c58f97214918cfc1bbf06be3c20ae93808bf..5234c214cb9050d950781bf9224c36c030d9279d 100644 (file)
@@ -8,6 +8,7 @@ import { ArvadosTheme } from '~/common/custom-theme';
 import { RemoveIcon, EditSavedQueryIcon } from '~/components/icon/icon';
 import { SearchBarAdvanceFormData } from '~/models/search-bar';
 import { SearchBarSelectedItem } from "~/store/search-bar/search-bar-reducer";
+import { getQueryFromAdvancedData } from "~/store/search-bar/search-bar-actions";
 
 type CssRules = 'root' | 'listItem' | 'listItemText' | 'button';
 
@@ -48,10 +49,10 @@ export const SearchBarSavedQueries = withStyles(styles)(
     ({ classes, savedQueries, onSearch, editSavedQuery, deleteSavedQuery, selectedItem }: SearchBarSavedQueriesProps) =>
         <List component="nav" className={classes.root}>
             {savedQueries.map((query, index) =>
-                <ListItem button key={index} className={classes.listItem} selected={`SQ-${index}-${query.searchQuery}` === selectedItem.id}>
+                <ListItem button key={index} className={classes.listItem} selected={`SQ-${index}-${query.queryName}` === selectedItem.id}>
                     <ListItemText disableTypography
-                        secondary={query.searchQuery}
-                        onClick={() => onSearch(query.searchQuery)}
+                        secondary={query.queryName}
+                        onClick={() => onSearch(getQueryFromAdvancedData(query))}
                         className={classes.listItemText} />
                     <ListItemSecondaryAction>
                         <Tooltip title="Edit">
index 1a19b47d67dccbac6cc643f7caeb13006c9ee3a2..51ea3fa14793fe9ff3fe19b939b867c3db52a497 100644 (file)
@@ -14,6 +14,7 @@ import {
     ClickAwayListener
 } from '@material-ui/core';
 import SearchIcon from '@material-ui/icons/Search';
+import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
 import { ArvadosTheme } from '~/common/custom-theme';
 import { SearchView } from '~/store/search-bar/search-bar-reducer';
 import {
@@ -49,7 +50,7 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => {
         },
         input: {
             border: 'none',
-            padding: `0px ${theme.spacing.unit}px`
+            padding: `0`
         },
         view: {
             position: 'absolute',
@@ -85,6 +86,7 @@ interface SearchBarViewActionProps {
     loadRecentQueries: () => string[];
     moveUp: () => void;
     moveDown: () => void;
+    setAdvancedDataFromSearchValue: (search: string) => void;
 }
 
 type SearchBarViewProps = SearchBarDataProps & SearchBarActionProps & WithStyles<CssRules>;
@@ -93,6 +95,7 @@ const handleKeyDown = (e: React.KeyboardEvent, props: SearchBarViewProps) => {
     if (e.keyCode === KEY_CODE_DOWN) {
         e.preventDefault();
         if (!props.isPopoverOpen) {
+            props.onSetView(SearchView.AUTOCOMPLETE);
             props.openSearchView();
         } else {
             props.moveDown();
@@ -116,6 +119,30 @@ const handleKeyDown = (e: React.KeyboardEvent, props: SearchBarViewProps) => {
     }
 };
 
+const handleInputClick = (e: React.MouseEvent, props: SearchBarViewProps) => {
+    if (props.searchValue) {
+        props.onSetView(SearchView.AUTOCOMPLETE);
+        props.openSearchView();
+    } else {
+        props.closeView();
+    }
+};
+
+const handleDropdownClick = (e: React.MouseEvent, props: SearchBarViewProps) => {
+    e.stopPropagation();
+    if (props.isPopoverOpen) {
+        if (props.currentView === SearchView.ADVANCED) {
+            props.closeView();
+        } else {
+            props.setAdvancedDataFromSearchValue(props.searchValue);
+            props.onSetView(SearchView.ADVANCED);
+        }
+    } else {
+        props.setAdvancedDataFromSearchValue(props.searchValue);
+        props.onSetView(SearchView.ADVANCED);
+    }
+};
+
 export const SearchBarView = withStyles(styles)(
     (props : SearchBarViewProps) => {
         const { classes, isPopoverOpen } = props;
@@ -130,16 +157,25 @@ export const SearchBarView = withStyles(styles)(
                             value={props.searchValue}
                             fullWidth={true}
                             disableUnderline={true}
-                            onClick={props.openSearchView}
+                            onClick={e => handleInputClick(e, props)}
                             onKeyDown={e => handleKeyDown(e, props)}
-                            endAdornment={
-                                <InputAdornment position="end">
+                            startAdornment={
+                                <InputAdornment position="start">
                                     <Tooltip title='Search'>
                                         <IconButton type="submit">
                                             <SearchIcon />
                                         </IconButton>
                                     </Tooltip>
                                 </InputAdornment>
+                            }
+                            endAdornment={
+                                <InputAdornment position="end">
+                                    <Tooltip title='Advanced search'>
+                                        <IconButton onClick={e => handleDropdownClick(e, props)}>
+                                            <ArrowDropDownIcon />
+                                        </IconButton>
+                                    </Tooltip>
+                                </InputAdornment>
                             } />
                     </form>
                     <div className={classes.view}>
@@ -162,7 +198,8 @@ const getView = (props: SearchBarViewProps) => {
         case SearchView.ADVANCED:
             return <SearchBarAdvancedView
                 closeAdvanceView={props.closeAdvanceView}
-                tags={props.tags} />;
+                tags={props.tags}
+                saveQuery={props.saveQuery} />;
         default:
             return <SearchBarBasicView
                 onSetView={props.onSetView}
index e60b214121351d23e47ea36a13e2a707c406c869..41cf291688dc2d53ef7534ee8048a2d9b2629f99 100644 (file)
@@ -16,7 +16,7 @@ import {
     navigateToItem,
     editSavedQuery,
     changeData,
-    submitData, moveUp, moveDown
+    submitData, moveUp, moveDown, setAdvancedDataFromSearchValue
 } from '~/store/search-bar/search-bar-actions';
 import { SearchBarView, SearchBarActionProps, SearchBarDataProps } from '~/views-components/search-bar/search-bar-view';
 import { SearchBarAdvanceFormData } from '~/models/search-bar';
@@ -29,7 +29,10 @@ const mapStateToProps = ({ searchBar, form }: RootState): SearchBarDataProps =>
         searchResults: searchBar.searchResults,
         selectedItem: searchBar.selectedItem,
         savedQueries: searchBar.savedQueries,
-        tags: form.searchBarAdvanceFormName
+        tags: form.searchBarAdvanceFormName,
+        saveQuery: form.searchBarAdvanceFormName &&
+            form.searchBarAdvanceFormName.values &&
+            form.searchBarAdvanceFormName.values.saveQuery
     };
 };
 
@@ -46,7 +49,8 @@ const mapDispatchToProps = (dispatch: Dispatch): SearchBarActionProps => ({
     navigateTo: (uuid: string) => dispatch<any>(navigateToItem(uuid)),
     editSavedQuery: (data: SearchBarAdvanceFormData) => dispatch<any>(editSavedQuery(data)),
     moveUp: () => dispatch<any>(moveUp()),
-    moveDown: () => dispatch<any>(moveDown())
+    moveDown: () => dispatch<any>(moveDown()),
+    setAdvancedDataFromSearchValue: (search: string) => dispatch<any>(setAdvancedDataFromSearchValue(search))
 });
 
 export const SearchBar = connect(mapStateToProps, mapDispatchToProps)(SearchBarView);
index ad8f65fbe104fa05fa4a30f7a9a46f25aeed516c..5e374042b32438cd0ed5045097dd8ca61b1bf66c 100644 (file)
@@ -4,7 +4,13 @@
 
 import * as React from 'react';
 import { Grid, StyleRulesCallback, Divider, IconButton, Typography } from '@material-ui/core';
-import { Field, WrappedFieldProps, WrappedFieldArrayProps, FieldArray, FieldsProps } from 'redux-form';
+import {
+    Field,
+    WrappedFieldProps,
+    WrappedFieldArrayProps,
+    FieldArray,
+    FieldArrayFieldsProps
+} from 'redux-form';
 import { PermissionSelect, formatPermissionLevel, parsePermissionLevel } from './permission-select';
 import { WithStyles } from '@material-ui/core/styles';
 import withStyles from '@material-ui/core/styles/withStyles';
@@ -29,7 +35,7 @@ const permissionManagementRowStyles: StyleRulesCallback<'root'> = theme => ({
     }
 });
 const PermissionManagementRow = withStyles(permissionManagementRowStyles)(
-    ({ field, index, fields, classes }: { field: string, index: number, fields: FieldsProps<{ email: string }> } & WithStyles<'root'>) =>
+    ({ field, index, fields, classes }: { field: string, index: number, fields: FieldArrayFieldsProps<{ email: string }> } & WithStyles<'root'>) =>
         <>
             <Divider />
             <Grid container alignItems='center' spacing={8} wrap='nowrap' className={classes.root}>
diff --git a/src/views-components/user-dialog/attributes-dialog.tsx b/src/views-components/user-dialog/attributes-dialog.tsx
new file mode 100644 (file)
index 0000000..66a4881
--- /dev/null
@@ -0,0 +1,97 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from "react";
+import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Typography, Grid } from "@material-ui/core";
+import { WithDialogProps } from "~/store/dialog/with-dialog";
+import { withDialog } from '~/store/dialog/with-dialog';
+import { WithStyles, withStyles } from '@material-ui/core/styles';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { compose } from "redux";
+import { USER_ATTRIBUTES_DIALOG } from "~/store/users/users-actions";
+import { UserResource } from "~/models/user";
+
+type CssRules = 'rightContainer' | 'leftContainer' | 'spacing';
+
+const styles = withStyles<CssRules>((theme: ArvadosTheme) => ({
+    rightContainer: {
+        textAlign: 'right',
+        paddingRight: theme.spacing.unit * 2,
+        color: theme.palette.grey["500"]
+    },
+    leftContainer: {
+        textAlign: 'left',
+        paddingLeft: theme.spacing.unit * 2
+    },
+    spacing: {
+        paddingTop: theme.spacing.unit * 2
+    },
+}));
+
+interface UserAttributesDataProps {
+    data: UserResource;
+}
+
+type UserAttributesProps = UserAttributesDataProps & WithStyles<CssRules>;
+
+export const UserAttributesDialog = compose(
+    withDialog(USER_ATTRIBUTES_DIALOG),
+    styles)(
+        (props: WithDialogProps<UserAttributesProps> & UserAttributesProps) =>
+            <Dialog open={props.open}
+                onClose={props.closeDialog}
+                fullWidth
+                maxWidth="sm">
+                <DialogTitle>Attributes</DialogTitle>
+                <DialogContent>
+                    <Typography variant="body2" className={props.classes.spacing}>
+                        {props.data && attributes(props.data, props.classes)}
+                    </Typography>
+                </DialogContent>
+                <DialogActions>
+                    <Button
+                        variant='flat'
+                        color='primary'
+                        onClick={props.closeDialog}>
+                        Close
+                </Button>
+                </DialogActions>
+            </Dialog>
+    );
+
+const attributes = (user: UserResource, classes: any) => {
+    const { uuid, ownerUuid, createdAt, modifiedAt, modifiedByClientUuid, modifiedByUserUuid, firstName, lastName, href, identityUrl, username } = user;
+    return (
+        <span>
+            <Grid container direction="row">
+                <Grid item xs={5} className={classes.rightContainer}>
+                    {firstName && <Grid item>First name</Grid>}
+                    {lastName && <Grid item>Last name</Grid>}
+                    {ownerUuid && <Grid item>Owner uuid</Grid>}
+                    {createdAt && <Grid item>Created at</Grid>}
+                    {modifiedAt && <Grid item>Modified at</Grid>}
+                    {modifiedByUserUuid && <Grid item>Modified by user uuid</Grid>}
+                    {modifiedByClientUuid && <Grid item>Modified by client uuid</Grid>}
+                    {uuid && <Grid item>uuid</Grid>}
+                    {href && <Grid item>Href</Grid>}
+                    {identityUrl && <Grid item>Identity url</Grid>}
+                    {username && <Grid item>Username</Grid>}
+                </Grid>
+                <Grid item xs={7} className={classes.leftContainer}>
+                    <Grid item>{firstName}</Grid>
+                    <Grid item>{lastName}</Grid>
+                    <Grid item>{ownerUuid}</Grid>
+                    <Grid item>{createdAt}</Grid>
+                    <Grid item>{modifiedAt}</Grid>
+                    <Grid item>{modifiedByUserUuid}</Grid>
+                    <Grid item>{modifiedByClientUuid}</Grid>
+                    <Grid item>{uuid}</Grid>
+                    <Grid item>{href}</Grid>
+                    <Grid item>{identityUrl}</Grid>
+                    <Grid item>{username}</Grid>
+                </Grid>
+            </Grid>
+        </span>
+    );
+};
diff --git a/src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx b/src/views/api-client-authorization-panel/api-client-authorization-panel-root.tsx
new file mode 100644 (file)
index 0000000..52921b3
--- /dev/null
@@ -0,0 +1,104 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from 'react';
+import { 
+    StyleRulesCallback, WithStyles, withStyles, Card, CardContent, Grid, 
+    Table, TableHead, TableRow, TableCell, TableBody, Tooltip, IconButton
+} from '@material-ui/core';
+import { ArvadosTheme } from '~/common/custom-theme';
+import { MoreOptionsIcon, HelpIcon } from '~/components/icon/icon';
+import { ApiClientAuthorization } from '~/models/api-client-authorization';
+import { formatDate } from '~/common/formatters';
+
+type CssRules = 'root' | 'tableRow' | 'helpIconGrid' | 'tableGrid';
+
+const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
+    root: {
+        width: '100%',
+        overflow: 'auto'
+    },
+    helpIconGrid: {
+        textAlign: 'right'
+    },
+    tableGrid: {
+        marginTop: theme.spacing.unit
+    },
+    tableRow: {
+        '& td, th': {
+            whiteSpace: 'nowrap'
+        }
+    }
+});
+
+export interface ApiClientAuthorizationPanelRootActionProps {
+    openRowOptions: (event: React.MouseEvent<HTMLElement>, keepService: ApiClientAuthorization) => void;
+    openHelpDialog: () => void;
+}
+
+export interface ApiClientAuthorizationPanelRootDataProps {
+    apiClientAuthorizations: ApiClientAuthorization[];
+    hasApiClientAuthorizations: boolean;
+}
+
+type ApiClientAuthorizationPanelRootProps = ApiClientAuthorizationPanelRootActionProps 
+    & ApiClientAuthorizationPanelRootDataProps & WithStyles<CssRules>;
+
+export const ApiClientAuthorizationPanelRoot = withStyles(styles)(
+    ({ classes, hasApiClientAuthorizations, apiClientAuthorizations, openRowOptions, openHelpDialog }: ApiClientAuthorizationPanelRootProps) =>
+        <Card className={classes.root}>
+            <CardContent>
+                {hasApiClientAuthorizations && <Grid container direction="row" justify="flex-end">
+                    <Grid item xs={12} className={classes.helpIconGrid}>
+                        <Tooltip title="Api token - help">
+                            <IconButton onClick={openHelpDialog}>
+                                <HelpIcon />
+                            </IconButton>
+                        </Tooltip>
+                    </Grid>
+                    <Grid item xs={12}>
+                        <Table>
+                            <TableHead>
+                                <TableRow className={classes.tableRow}>
+                                    <TableCell>UUID</TableCell>
+                                    <TableCell>API Client ID</TableCell>
+                                    <TableCell>API Token</TableCell>
+                                    <TableCell>Created by IP address</TableCell>
+                                    <TableCell>Default owner</TableCell>
+                                    <TableCell>Expires at</TableCell>
+                                    <TableCell>Last used at</TableCell>
+                                    <TableCell>Last used by IP address</TableCell>
+                                    <TableCell>Scopes</TableCell>
+                                    <TableCell>User ID</TableCell>
+                                    <TableCell />
+                                </TableRow>
+                            </TableHead>
+                            <TableBody>
+                                {apiClientAuthorizations.map((apiClientAuthorizatio, index) =>
+                                    <TableRow key={index} className={classes.tableRow}>
+                                        <TableCell>{apiClientAuthorizatio.uuid}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.apiClientId}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.apiToken}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.createdByIpAddress || '(none)'}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.defaultOwnerUuid || '(none)'}</TableCell>
+                                        <TableCell>{formatDate(apiClientAuthorizatio.expiresAt) || '(none)'}</TableCell>
+                                        <TableCell>{formatDate(apiClientAuthorizatio.lastUsedAt) || '(none)'}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.lastUsedByIpAddress || '(none)'}</TableCell>
+                                        <TableCell>{JSON.stringify(apiClientAuthorizatio.scopes)}</TableCell>
+                                        <TableCell>{apiClientAuthorizatio.userId}</TableCell>
+                                        <TableCell>
+                                            <Tooltip title="More options" disableFocusListener>
+                                                <IconButton onClick={event => openRowOptions(event, apiClientAuthorizatio)}>
+                                                    <MoreOptionsIcon />
+                                                </IconButton>
+                                            </Tooltip>
+                                        </TableCell>
+                                    </TableRow>)}
+                            </TableBody>
+                        </Table>
+                    </Grid>
+                </Grid>}
+            </CardContent>
+        </Card>
+);
\ No newline at end of file
diff --git a/src/views/api-client-authorization-panel/api-client-authorization-panel.tsx b/src/views/api-client-authorization-panel/api-client-authorization-panel.tsx
new file mode 100644 (file)
index 0000000..75b79ab
--- /dev/null
@@ -0,0 +1,32 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import { RootState } from '~/store/store';
+import { Dispatch } from 'redux';
+import { connect } from 'react-redux';
+import {
+    ApiClientAuthorizationPanelRoot,
+    ApiClientAuthorizationPanelRootDataProps,
+    ApiClientAuthorizationPanelRootActionProps
+} from '~/views/api-client-authorization-panel/api-client-authorization-panel-root';
+import { openApiClientAuthorizationContextMenu } from '~/store/context-menu/context-menu-actions';
+import { openApiClientAuthorizationsHelpDialog } from '~/store/api-client-authorizations/api-client-authorizations-actions';
+
+const mapStateToProps = (state: RootState): ApiClientAuthorizationPanelRootDataProps => {
+    return {
+        apiClientAuthorizations: state.apiClientAuthorizations,
+        hasApiClientAuthorizations: state.apiClientAuthorizations.length > 0
+    };
+};
+
+const mapDispatchToProps = (dispatch: Dispatch): ApiClientAuthorizationPanelRootActionProps => ({
+    openRowOptions: (event, apiClientAuthorization) => {
+        dispatch<any>(openApiClientAuthorizationContextMenu(event, apiClientAuthorization));
+    },
+    openHelpDialog: () => {
+        dispatch<any>(openApiClientAuthorizationsHelpDialog());
+    }
+});
+
+export const ApiClientAuthorizationPanel = connect(mapStateToProps, mapDispatchToProps)(ApiClientAuthorizationPanelRoot);
\ No newline at end of file
index be3627b8782748354f00baea1708c6d81b78450c..2d325b514a8bb20897d3f4ca5959b4b5496af14e 100644 (file)
@@ -20,7 +20,7 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
         overflow: 'auto'
     },
     tableRow: {
-        '& td, th': {
+        '& th': {
             whiteSpace: 'nowrap'
         }
     }
@@ -60,7 +60,7 @@ export const ComputeNodePanelRoot = withStyles(styles)(
                             <TableBody>
                                 {computeNodes.map((computeNode, index) =>
                                     <TableRow key={index} className={classes.tableRow}>
-                                        <TableCell>{computeNode.uuid}</TableCell>
+                                        <TableCell>{JSON.stringify(computeNode.info, null, 4)}</TableCell>
                                         <TableCell>{computeNode.uuid}</TableCell>
                                         <TableCell>{computeNode.domain}</TableCell>
                                         <TableCell>{formatDate(computeNode.firstPingAt) || '(none)'}</TableCell>
index ea658ee72573c1e6554a6053b4e75ae96c474295..7bfc2bfef6caa70aa952f654a8d15423dd234d8a 100644 (file)
@@ -8,7 +8,6 @@ import { DataColumns } from '~/components/data-table/data-table';
 import { DataTableFilterItem } from '~/components/data-table-filters/data-table-filters';
 import { ResourceKind } from '~/models/resource';
 import { ContainerRequestState } from '~/models/container-request';
-import { resourceLabel } from '~/common/labels';
 import { SearchBarAdvanceFormData } from '~/models/search-bar';
 import { SEARCH_RESULTS_PANEL_ID } from '~/store/search-results-panel/search-results-panel-actions';
 import { DataExplorer } from '~/views-components/data-explorer/data-explorer';
@@ -21,8 +20,8 @@ import {
     ResourceType
 } from '~/views-components/data-explorer/renderers';
 import { createTree } from '~/models/tree';
-import { getInitialResourceTypeFilters } from '../../store/resource-type-filters/resource-type-filters';
-// TODO: code clean up
+import { getInitialResourceTypeFilters } from '~/store/resource-type-filters/resource-type-filters';
+
 export enum SearchResultsPanelColumnNames {
     NAME = "Name",
     PROJECT = "Project",
index ae12425e1516a1dde5e05b31624a2537b97c5704..bcc661144fe64f0f0aee9faf0499a7d2c3ff06b4 100644 (file)
@@ -11,7 +11,6 @@ import { RootState } from '~/store/store';
 import { DataTableFilterItem } from '~/components/data-table-filters/data-table-filters';
 import { SortDirection } from '~/components/data-table/data-column';
 import { ResourceKind, TrashableResource } from '~/models/resource';
-import { resourceLabel } from '~/common/labels';
 import { ArvadosTheme } from '~/common/custom-theme';
 import { RestoreFromTrashIcon, TrashIcon } from '~/components/icon/icon';
 import { TRASH_PANEL_ID } from "~/store/trash-panel/trash-panel-action";
@@ -31,11 +30,10 @@ import { loadDetailsPanel } from "~/store/details-panel/details-panel-action";
 import { toggleTrashed } from "~/store/trash/trash-actions";
 import { ContextMenuKind } from "~/views-components/context-menu/context-menu";
 import { Dispatch } from "redux";
-import { PanelDefaultView } from '~/components/panel-default-view/panel-default-view';
 import { DataTableDefaultView } from '~/components/data-table-default-view/data-table-default-view';
 import { createTree } from '~/models/tree';
-import { getInitialResourceTypeFilters } from '../../store/resource-type-filters/resource-type-filters';
-// TODO: code clean up
+import { getInitialResourceTypeFilters } from '~/store/resource-type-filters/resource-type-filters';
+
 type CssRules = "toolbar" | "button";
 
 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
diff --git a/src/views/user-panel/user-panel.tsx b/src/views/user-panel/user-panel.tsx
new file mode 100644 (file)
index 0000000..f28cca3
--- /dev/null
@@ -0,0 +1,212 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+import * as React from 'react';
+import { WithStyles, withStyles, Typography, Tabs, Tab, Paper, Button } from '@material-ui/core';
+import { DataExplorer } from "~/views-components/data-explorer/data-explorer";
+import { connect, DispatchProp } from 'react-redux';
+import { DataColumns } from '~/components/data-table/data-table';
+import { RootState } from '~/store/store';
+import { SortDirection } from '~/components/data-table/data-column';
+import { openContextMenu } from "~/store/context-menu/context-menu-actions";
+import { getResource, ResourcesState } from "~/store/resources/resources";
+import {
+    ResourceFirstName,
+    ResourceLastName,
+    ResourceUuid,
+    ResourceEmail,
+    ResourceIsActive,
+    ResourceIsAdmin,
+    ResourceUsername
+} from "~/views-components/data-explorer/renderers";
+import { navigateTo } from "~/store/navigation/navigation-action";
+import { ContextMenuKind } from "~/views-components/context-menu/context-menu";
+import { DataTableDefaultView } from '~/components/data-table-default-view/data-table-default-view';
+import { createTree } from '~/models/tree';
+import { compose, Dispatch } from 'redux';
+import { UserResource } from '~/models/user';
+import { ShareMeIcon, AddIcon } from '~/components/icon/icon';
+import { USERS_PANEL_ID, openUserCreateDialog } from '~/store/users/users-actions';
+
+type UserPanelRules = "button";
+
+const styles = withStyles<UserPanelRules>(theme => ({
+    button: {
+        marginTop: theme.spacing.unit,
+        marginRight: theme.spacing.unit * 2,
+        textAlign: 'right',
+        alignSelf: 'center'
+    },
+}));
+
+export enum UserPanelColumnNames {
+    FIRST_NAME = "First Name",
+    LAST_NAME = "Last Name",
+    UUID = "Uuid",
+    EMAIL = "Email",
+    ACTIVE = "Active",
+    ADMIN = "Admin",
+    REDIRECT_TO_USER = "Redirect to user",
+    USERNAME = "Username"
+}
+
+export const userPanelColumns: DataColumns<string> = [
+    {
+        name: UserPanelColumnNames.FIRST_NAME,
+        selected: true,
+        configurable: true,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceFirstName uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.LAST_NAME,
+        selected: true,
+        configurable: true,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceLastName uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.UUID,
+        selected: true,
+        configurable: true,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceUuid uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.EMAIL,
+        selected: true,
+        configurable: true,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceEmail uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.ACTIVE,
+        selected: true,
+        configurable: true,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceIsActive uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.ADMIN,
+        selected: true,
+        configurable: false,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceIsAdmin uuid={uuid} />
+    },
+    {
+        name: UserPanelColumnNames.REDIRECT_TO_USER,
+        selected: true,
+        configurable: false,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: () => <Typography noWrap>(none)</Typography>
+    },
+    {
+        name: UserPanelColumnNames.USERNAME,
+        selected: true,
+        configurable: false,
+        sortDirection: SortDirection.NONE,
+        filters: createTree(),
+        render: uuid => <ResourceUsername uuid={uuid} />
+    }
+];
+
+interface UserPanelDataProps {
+    resources: ResourcesState;
+}
+
+interface UserPanelActionProps {
+    openUserCreateDialog: () => void;
+    handleRowDoubleClick: (uuid: string) => void;
+    onContextMenu: (event: React.MouseEvent<HTMLElement>, item: any) => void;
+}
+
+const mapStateToProps = (state: RootState) => {
+    return {
+        resources: state.resources
+    };
+};
+
+const mapDispatchToProps = (dispatch: Dispatch) => ({
+    openUserCreateDialog: () => dispatch<any>(openUserCreateDialog()),
+    handleRowDoubleClick: (uuid: string) => dispatch<any>(navigateTo(uuid)),
+    onContextMenu: (event: React.MouseEvent<HTMLElement>, item: any) => dispatch<any>(openContextMenu(event, item))
+});
+
+type UserPanelProps = UserPanelDataProps & UserPanelActionProps & DispatchProp & WithStyles<UserPanelRules>;
+
+export const UserPanel = compose(
+    styles,
+    connect(mapStateToProps, mapDispatchToProps))(
+        class extends React.Component<UserPanelProps> {
+            state = {
+                value: 0,
+            };
+
+            componentDidMount() {
+                this.setState({ value: 0 });
+            }
+
+            render() {
+                const { value } = this.state;
+                return <Paper>
+                    <Tabs value={value} onChange={this.handleChange} fullWidth>
+                        <Tab label="USERS" />
+                        <Tab label="ACTIVITY" disabled />
+                    </Tabs>
+                    {value === 0 &&
+                        <span>
+                            <div className={this.props.classes.button}>
+                                <Button variant="contained" color="primary" onClick={this.props.openUserCreateDialog}>
+                                    <AddIcon /> NEW USER
+                                </Button>
+                            </div>
+                            <DataExplorer
+                                id={USERS_PANEL_ID}
+                                onRowClick={this.handleRowClick}
+                                onRowDoubleClick={this.handleRowDoubleClick}
+                                onContextMenu={this.handleContextMenu}
+                                contextMenuColumn={true}
+                                isUserPanel={true}
+                                dataTableDefaultView={
+                                    <DataTableDefaultView
+                                        icon={ShareMeIcon}
+                                        messages={['Your user list is empty.']} />
+                                } />
+                        </span>}
+                </Paper>;
+            }
+
+            handleChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
+                this.setState({ value });
+            }
+
+            handleContextMenu = (event: React.MouseEvent<HTMLElement>, resourceUuid: string) => {
+                const resource = getResource<UserResource>(resourceUuid)(this.props.resources);
+                if (resource) {
+                    this.props.onContextMenu(event, {
+                        name: '',
+                        uuid: resource.uuid,
+                        ownerUuid: resource.ownerUuid,
+                        kind: resource.kind,
+                        menuKind: ContextMenuKind.USER
+                    });
+                }
+            }
+
+            handleRowDoubleClick = (uuid: string) => {
+                this.props.handleRowDoubleClick(uuid);
+            }
+
+            handleRowClick = () => {
+                return;
+            }
+        }
+    );
index 5dbd3f0965aa6336d2893fd7faf48ecba75e43e7..d5d345551c41a680a26c6b62247f2109980567ce 100644 (file)
@@ -12,7 +12,7 @@ import { Link } from 'react-router-dom';
 import { compose, Dispatch } from 'redux';
 import { saveRequestedDate, loadVirtualMachinesData } from '~/store/virtual-machines/virtual-machines-actions';
 import { RootState } from '~/store/store';
-import { ListResults } from '~/services/common-service/common-resource-service';
+import { ListResults } from '~/services/common-service/common-service';
 import { HelpIcon, MoreOptionsIcon } from '~/components/icon/icon';
 import { VirtualMachineLogins, VirtualMachinesResource } from '~/models/virtual-machines';
 import { Routes } from '~/routes/routes';
index 5efffa19ac26b705233cd24c3fb4e08578a6c32f..70f2a2ddd207a7303851d542e999d589be24b175 100644 (file)
@@ -54,20 +54,27 @@ import { ProjectPropertiesDialog } from '~/views-components/project-properties-d
 import { RepositoriesPanel } from '~/views/repositories-panel/repositories-panel';
 import { KeepServicePanel } from '~/views/keep-service-panel/keep-service-panel';
 import { ComputeNodePanel } from '~/views/compute-node-panel/compute-node-panel';
+import { ApiClientAuthorizationPanel } from '~/views/api-client-authorization-panel/api-client-authorization-panel';
 import { RepositoriesSampleGitDialog } from '~/views-components/repositories-sample-git-dialog/repositories-sample-git-dialog';
 import { RepositoryAttributesDialog } from '~/views-components/repository-attributes-dialog/repository-attributes-dialog';
 import { CreateRepositoryDialog } from '~/views-components/dialog-forms/create-repository-dialog';
 import { RemoveRepositoryDialog } from '~/views-components/repository-remove-dialog/repository-remove-dialog';
 import { CreateSshKeyDialog } from '~/views-components/dialog-forms/create-ssh-key-dialog';
 import { PublicKeyDialog } from '~/views-components/ssh-keys-dialog/public-key-dialog';
+import { RemoveApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/remove-dialog';
 import { RemoveComputeNodeDialog } from '~/views-components/compute-nodes-dialog/remove-dialog';
 import { RemoveKeepServiceDialog } from '~/views-components/keep-services-dialog/remove-dialog';
 import { RemoveSshKeyDialog } from '~/views-components/ssh-keys-dialog/remove-dialog';
 import { RemoveVirtualMachineDialog } from '~/views-components/virtual-machines-dialog/remove-dialog';
+import { AttributesApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/attributes-dialog';
 import { AttributesComputeNodeDialog } from '~/views-components/compute-nodes-dialog/attributes-dialog';
 import { AttributesKeepServiceDialog } from '~/views-components/keep-services-dialog/attributes-dialog';
 import { AttributesSshKeyDialog } from '~/views-components/ssh-keys-dialog/attributes-dialog';
 import { VirtualMachineAttributesDialog } from '~/views-components/virtual-machines-dialog/attributes-dialog';
+import { UserPanel } from '~/views/user-panel/user-panel';
+import { UserAttributesDialog } from '~/views-components/user-dialog/attributes-dialog';
+import { CreateUserDialog } from '~/views-components/dialog-forms/create-user-dialog';
+import { HelpApiClientAuthorizationDialog } from '~/views-components/api-client-authorizations-dialog/help-dialog';
 
 type CssRules = 'root' | 'container' | 'splitter' | 'asidePanel' | 'contentWrapper' | 'content';
 
@@ -141,7 +148,9 @@ export const WorkbenchPanel =
                                 <Route path={Routes.REPOSITORIES} component={RepositoriesPanel} />
                                 <Route path={Routes.SSH_KEYS} component={SshKeyPanel} />
                                 <Route path={Routes.KEEP_SERVICES} component={KeepServicePanel} />
+                                <Route path={Routes.USERS} component={UserPanel} />
                                 <Route path={Routes.COMPUTE_NODES} component={ComputeNodePanel} />
+                                <Route path={Routes.API_CLIENT_AUTHORIZATIONS} component={ApiClientAuthorizationPanel} />
                                 <Route path={Routes.MY_ACCOUNT} component={MyAccountPanel} />
                             </Switch>
                         </Grid>
@@ -152,6 +161,7 @@ export const WorkbenchPanel =
                 <DetailsPanel />
             </Grid>
             <AdvancedTabDialog />
+            <AttributesApiClientAuthorizationDialog />
             <AttributesComputeNodeDialog />
             <AttributesKeepServiceDialog />
             <AttributesSshKeyDialog />
@@ -163,9 +173,11 @@ export const WorkbenchPanel =
             <CreateProjectDialog />
             <CreateRepositoryDialog />
             <CreateSshKeyDialog />
+            <CreateUserDialog />
             <CurrentTokenDialog />
             <FileRemoveDialog />
             <FilesUploadCollectionDialog />
+            <HelpApiClientAuthorizationDialog />
             <MoveCollectionDialog />
             <MoveProcessDialog />
             <MoveProjectDialog />
@@ -175,6 +187,7 @@ export const WorkbenchPanel =
             <ProcessCommandDialog />
             <ProcessInputDialog />
             <ProjectPropertiesDialog />
+            <RemoveApiClientAuthorizationDialog />
             <RemoveComputeNodeDialog />
             <RemoveKeepServiceDialog />
             <RemoveProcessDialog />
@@ -190,6 +203,7 @@ export const WorkbenchPanel =
             <UpdateCollectionDialog />
             <UpdateProcessDialog />
             <UpdateProjectDialog />
+            <UserAttributesDialog />
             <VirtualMachineAttributesDialog />
         </Grid>
     );
\ No newline at end of file
index f08c370f5d3fb8121d01411f0519fda30590e7ba..d3d6396d479953c17c56aa7ebbfca727d5cc2661 100644 (file)
--- a/yarn.lock
+++ b/yarn.lock
     "@types/react" "*"
     redux "^3.6.0"
 
-"@types/redux-form@7.4.5":
-  version "7.4.5"
-  resolved "https://registry.yarnpkg.com/@types/redux-form/-/redux-form-7.4.5.tgz#fae0fa6cfbc613867093d1e0f6a84db17177305e"
-  integrity sha512-PY74tuDamNhStB+87TQJXAKoa7uf5Ue/MJvnIrQowgjyRUo2Ky/THUfDec9U7IKRGzLnX7vWVTsoN1EvLnwAEQ==
+"@types/redux-form@7.4.12":
+  version "7.4.12"
+  resolved "https://registry.yarnpkg.com/@types/redux-form/-/redux-form-7.4.12.tgz#2afb0615e3b7417d460ab14a4802ede4a98f9c79"
+  integrity sha512-qHRkJcgdc5MntQHrkYCg5o6oySh+OdVKA90yELTdi9XlNvSGRxd6K230aTckVrwdUjdxtwZ31UqFgLoU5SiWYQ==
   dependencies:
     "@types/react" "*"
     redux "^3.6.0 || ^4.0.0"