Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create edit user group page #1732

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cypress/e2e/users-and-user-groups.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,12 @@ describe('Users and User Groups page', () => {
cy.get('[data-ouia-component-id="iam-user-groups-table-actions-dropdown-action-0"]').click();
cy.get('[data-ouia-component-id="add-group-wizard"]').should('exist');
});

it('should be able to open Edit User Group page from row actions', () => {
cy.get('[data-ouia-component-id="user-groups-tab-button"]').click();
cy.get('[data-ouia-component-id^="iam-user-groups-table-table-td-0-7"]').click();
cy.get('[data-ouia-component-id^="iam-user-groups-table-table-td-0-7"] button').contains('Edit user group').click();
cy.url().should('include', '/iam/access-management/users-and-user-groups/edit-group');
cy.get('[data-ouia-component-id="edit-user-group-form"]').should('be.visible');
});
});
5 changes: 5 additions & 0 deletions src/Messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2528,4 +2528,9 @@ export default defineMessages({
description: 'create user group button label',
defaultMessage: 'Create user group',
},
selectUsersAndOrServiceAccounts: {
id: 'selectUsersAndOrServiceAccounts',
description: 'select users and/or service accounts label',
defaultMessage: 'Select users and/or service accounts',
},
});
5 changes: 5 additions & 0 deletions src/Routing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const QuickstartsTest = lazy(() => import('./smart-components/quickstarts/quicks
const UsersAndUserGroups = lazy(() => import('./smart-components/access-management/users-and-user-groups/users-and-user-groups'));
const UsersView = lazy(() => import('./smart-components/access-management/users-and-user-groups/users/UsersView'));
const UserGroupsView = lazy(() => import('./smart-components/access-management/users-and-user-groups/user-groups/UserGroupsView'));
const EditUserGroup = lazy(() => import('./smart-components/access-management/users-and-user-groups/user-groups/edit-user-group/EditUserGroup'));

const getRoutes = ({ enableServiceAccounts, isITLess, isWorkspacesFlag, isCommonAuthModel }: Record<string, boolean>) => [
{
Expand Down Expand Up @@ -75,6 +76,10 @@ const getRoutes = ({ enableServiceAccounts, isITLess, isWorkspacesFlag, isCommon
},
],
},
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be a child route

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
Rendering this as a child route adds the Users and Users Groups header above - is there a way to avoid this?

path: pathnames['users-and-user-groups-edit-group'].path,
element: EditUserGroup,
},
{
path: pathnames.overview.path,
element: isWorkspacesFlag ? WorkspacesOverview : Overview,
Expand Down
2 changes: 1 addition & 1 deletion src/redux/reducers/group-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface GroupStore {
filters: any;
pagination: { count: number };
};
selectedGroup: {
selectedGroup: Group & {
addRoles: any;
members: { meta: PaginationDefaultI; data?: any[] };
serviceAccounts: { meta: PaginationDefaultI; data?: any[] };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ const UserGroupsTable: React.FunctionComponent<UserGroupsTableProps> = ({
items={[
{
title: intl.formatMessage(messages['usersAndUserGroupsEditUserGroup']),
onClick: () => console.log('EDIT USER GROUP'),
onClick: () => navigate(pathnames['users-and-user-groups-edit-group'].link.replace(':groupId', group.uuid)),
},
{
title: intl.formatMessage(messages['usersAndUserGroupsDeleteUserGroup']),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import ContentHeader from '@patternfly/react-component-groups/dist/esm/ContentHeader';
import { PageSection, PageSectionVariants, Spinner } from '@patternfly/react-core';
import React, { useEffect, useMemo, useState } from 'react';
import { useIntl } from 'react-intl';
import Messages from '../../../../../Messages';
import { FormRenderer, componentTypes, validatorTypes } from '@data-driven-forms/react-form-renderer';
import componentMapper from '@data-driven-forms/pf4-component-mapper/component-mapper';
import { FormTemplate } from '@data-driven-forms/pf4-component-mapper';
import { useDispatch, useSelector } from 'react-redux';
import { fetchGroup, fetchGroups, updateGroup } from '../../../../../redux/actions/group-actions';
import { RBACStore } from '../../../../../redux/store';
import { useNavigate, useParams } from 'react-router-dom';
import { EditGroupUsersAndServiceAccounts } from './EditUserGroupUsersAndServiceAccounts';
import RbacBreadcrumbs from '../../../../../presentational-components/shared/breadcrumbs';
import { mergeToBasename } from '../../../../../presentational-components/shared/AppLink';
import pathnames from '../../../../../utilities/pathnames';

export const EditUserGroup: React.FunctionComponent = () => {
const intl = useIntl();
const dispatch = useDispatch();
const params = useParams();
const groupId = params.groupId;
const navigate = useNavigate();

const [isLoading, setIsLoading] = useState(true);
const [initialFormData, setInitialFormData] = useState<{
name?: string;
description?: string;
users?: string[];
serviceAccounts?: string[];
} | null>(null);

const group = useSelector((state: RBACStore) => state.groupReducer?.selectedGroup);
const allGroups = useSelector((state: RBACStore) => state.groupReducer?.groups?.data || []);
const groupUsers = useSelector((state: RBACStore) => state.groupReducer?.selectedGroup?.members?.data || []);
const groupServiceAccounts = useSelector((state: RBACStore) => state.groupReducer?.selectedGroup?.serviceAccounts?.data || []);

const breadcrumbsList = useMemo(
() => [
{
title: intl.formatMessage(Messages.userGroups),
to: mergeToBasename(pathnames['users-and-user-groups'].link),
},
{
title: intl.formatMessage(Messages.usersAndUserGroupsEditUserGroup),
isActive: true,
},
],
[intl]
);

useEffect(() => {
const fetchData = async () => {
try {
await Promise.all([
dispatch(fetchGroups({ limit: 1000, offset: 0, orderBy: 'name', usesMetaInURL: true })),
groupId ? dispatch(fetchGroup(groupId)) : Promise.resolve(),
]);
} finally {
if (group) {
setInitialFormData({
name: group.name,
description: group.description,
users: groupUsers.map((user) => user.username),
serviceAccounts: groupServiceAccounts.map((sa) => sa.clientId),
});
}
setIsLoading(false);
}
};
fetchData();
}, [dispatch, groupId, group?.uuid]);

const schema = useMemo(
() => ({
fields: [
{
name: 'name',
label: intl.formatMessage(Messages.name),
component: componentTypes.TEXT_FIELD,
validate: [
{ type: validatorTypes.REQUIRED },
(value: string) => {
if (value === initialFormData?.name) {
return undefined;
}

const isDuplicate = allGroups.some(
(existingGroup) => existingGroup.name.toLowerCase() === value?.toLowerCase() && existingGroup.uuid !== groupId
);

return isDuplicate ? intl.formatMessage(Messages.groupNameTakenTitle) : undefined;
},
],
initialValue: initialFormData?.name,
isRequired: true,
},
{
name: 'description',
label: intl.formatMessage(Messages.description),
component: componentTypes.TEXTAREA,
initialValue: initialFormData?.description,
isRequired: true,
},
{
name: 'users-and-service-accounts',
component: 'users-and-service-accounts',
groupId: groupId,
initialUsers: initialFormData?.users || [],
initialServiceAccounts: initialFormData?.serviceAccounts || [],
initialValue: {
users: {
initial: initialFormData?.users || [],
updated: initialFormData?.users || [],
},
serviceAccounts: {
initial: initialFormData?.serviceAccounts || [],
updated: initialFormData?.serviceAccounts || [],
},
},
},
],
}),
[initialFormData, allGroups, groupId, intl]
);

const returnToPreviousPage = () => {
navigate(-1);
};

const handleSubmit = async (values: Record<string, any>) => {
if (values.name !== group?.name || values.description !== group?.description) {
dispatch(updateGroup({ uuid: groupId, name: values.name, description: values.description }));
}

if (values['users-and-service-accounts']) {
const { users, serviceAccounts } = values['users-and-service-accounts'];
if (users.updated.length > 0) {
const addedUsers = users.updated.filter((user: string) => !users.initial.includes(user));
const removedUsers = users.initial.filter((user: string) => !users.updated.includes(user));
console.log(`Users added: ${addedUsers} and removed: ${removedUsers}`);
}
if (serviceAccounts.updated.length > 0) {
const addedServiceAccounts = serviceAccounts.updated.filter((serviceAccount: string) => !serviceAccounts.initial.includes(serviceAccount));
const removedServiceAccounts = serviceAccounts.initial.filter((serviceAccount: string) => !serviceAccounts.updated.includes(serviceAccount));
console.log(`Service accounts added: ${addedServiceAccounts} and removed: ${removedServiceAccounts}`);
}
returnToPreviousPage();
}
};

return (
<React.Fragment>
<section className="pf-v5-c-page__main-breadcrumb">
<RbacBreadcrumbs {...breadcrumbsList} />
</section>
<ContentHeader title={intl.formatMessage(Messages.usersAndUserGroupsEditUserGroup)} subtitle={''} />
<PageSection data-ouia-component-id="edit-user-group-form" className="pf-v5-u-m-lg-on-lg" variant={PageSectionVariants.light} isWidthLimited>
{isLoading || !initialFormData ? (
<div style={{ textAlign: 'center' }}>
<Spinner />
</div>
) : (
<FormRenderer
schema={schema}
componentMapper={{
...componentMapper,
'users-and-service-accounts': EditGroupUsersAndServiceAccounts,
}}
onSubmit={handleSubmit}
onCancel={returnToPreviousPage}
FormTemplate={FormTemplate}
FormTemplateProps={{
disableSubmit: ['pristine', 'invalid'],
}}
debug={(values) => {
console.log('values:', values);
}}
/>
)}
</PageSection>
</React.Fragment>
);
};

export default EditUserGroup;
Loading
Loading