Implement basic group submission
[arvados-workbench2.git] / src / store / groups-panel / groups-panel-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from 'redux';
6 import { reset, startSubmit, stopSubmit, FormErrors } from 'redux-form';
7 import { bindDataExplorerActions } from "~/store/data-explorer/data-explorer-action";
8 import { dialogActions } from '~/store/dialog/dialog-actions';
9 import { Person } from '~/views-components/sharing-dialog/people-select';
10 import { ServiceRepository } from '~/services/services';
11 import { getCommonResourceServiceError, CommonResourceServiceError } from '~/services/common-service/common-resource-service';
12 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
13
14 export const GROUPS_PANEL_ID = "groupsPanel";
15 export const CREATE_GROUP_DIALOG = "createGroupDialog";
16 export const CREATE_GROUP_FORM = "createGroupForm";
17 export const CREATE_GROUP_NAME_FIELD_NAME = 'name';
18 export const CREATE_GROUP_USERS_FIELD_NAME = 'users';
19
20 export const GroupsPanelActions = bindDataExplorerActions(GROUPS_PANEL_ID);
21
22 export const loadGroupsPanel = () => GroupsPanelActions.REQUEST_ITEMS();
23
24 export const openCreateGroupDialog = () =>
25     (dispatch: Dispatch) => {
26         dispatch(dialogActions.OPEN_DIALOG({ id: CREATE_GROUP_DIALOG, data: {} }));
27         dispatch(reset(CREATE_GROUP_FORM));
28     };
29
30 export interface CreateGroupFormData {
31     [CREATE_GROUP_NAME_FIELD_NAME]: string;
32     [CREATE_GROUP_USERS_FIELD_NAME]?: Person[];
33 }
34
35 export const createGroup = ({ name }: CreateGroupFormData) =>
36     async (dispatch: Dispatch, _: {}, { groupsService }: ServiceRepository) => {
37
38         dispatch(startSubmit(CREATE_GROUP_FORM));
39
40         try {
41
42             const newGroup = await groupsService.create({ name });
43
44             dispatch(dialogActions.CLOSE_DIALOG({ id: CREATE_GROUP_DIALOG }));
45             dispatch(reset(CREATE_GROUP_FORM));
46             dispatch(loadGroupsPanel());
47             dispatch(snackbarActions.OPEN_SNACKBAR({
48                 message: `${newGroup.name} group has been created`,
49                 kind: SnackbarKind.SUCCESS
50             }));
51
52             return newGroup;
53
54         } catch (e) {
55
56             const error = getCommonResourceServiceError(e);
57             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
58                 dispatch(stopSubmit(CREATE_GROUP_FORM, { name: 'Group with the same name already exists.' } as FormErrors));
59             }
60
61             return;
62
63         }
64     };