|
| 1 | +import type { FC } from "react"; |
| 2 | +import { Helmet } from "react-helmet-async"; |
| 3 | +import { useMutation, useQuery, useQueryClient } from "react-query"; |
| 4 | +import { useNavigate, useParams } from "react-router-dom"; |
| 5 | +import { getErrorMessage } from "api/errors"; |
| 6 | +import { organizationPermissions } from "api/queries/organizations"; |
| 7 | +import { patchOrganizationRole, organizationRoles } from "api/queries/roles"; |
| 8 | +import type { PatchRoleRequest } from "api/typesGenerated"; |
| 9 | +import { displayError } from "components/GlobalSnackbar/utils"; |
| 10 | +import { Loader } from "components/Loader/Loader"; |
| 11 | +import { pageTitle } from "utils/page"; |
| 12 | +import { useOrganizationSettings } from "../ManagementSettingsLayout"; |
| 13 | +import CreateEditRolePageView from "./CreateEditRolePageView"; |
| 14 | + |
| 15 | +export const CreateEditRolePage: FC = () => { |
| 16 | + const queryClient = useQueryClient(); |
| 17 | + const navigate = useNavigate(); |
| 18 | + const { organization: organizationName, roleName } = useParams() as { |
| 19 | + organization: string; |
| 20 | + roleName: string; |
| 21 | + }; |
| 22 | + const { organizations } = useOrganizationSettings(); |
| 23 | + const organization = organizations?.find((o) => o.name === organizationName); |
| 24 | + const permissionsQuery = useQuery(organizationPermissions(organization?.id)); |
| 25 | + const patchOrganizationRoleMutation = useMutation( |
| 26 | + patchOrganizationRole(queryClient, organizationName), |
| 27 | + ); |
| 28 | + const { data: roleData, isLoading } = useQuery( |
| 29 | + organizationRoles(organizationName), |
| 30 | + ); |
| 31 | + const role = roleData?.find((role) => role.name === roleName); |
| 32 | + const permissions = permissionsQuery.data; |
| 33 | + |
| 34 | + if (isLoading || !permissions) { |
| 35 | + return <Loader />; |
| 36 | + } |
| 37 | + |
| 38 | + return ( |
| 39 | + <> |
| 40 | + <Helmet> |
| 41 | + <title> |
| 42 | + {pageTitle( |
| 43 | + role !== undefined ? "Edit Custom Role" : "Create Custom Role", |
| 44 | + )} |
| 45 | + </title> |
| 46 | + </Helmet> |
| 47 | + |
| 48 | + <CreateEditRolePageView |
| 49 | + role={role} |
| 50 | + onSubmit={async (data: PatchRoleRequest) => { |
| 51 | + try { |
| 52 | + await patchOrganizationRoleMutation.mutateAsync(data); |
| 53 | + navigate(`/organizations/${organizationName}/roles`); |
| 54 | + } catch (error) { |
| 55 | + displayError( |
| 56 | + getErrorMessage(error, "Failed to update custom role"), |
| 57 | + ); |
| 58 | + } |
| 59 | + }} |
| 60 | + error={patchOrganizationRoleMutation.error} |
| 61 | + isLoading={patchOrganizationRoleMutation.isLoading} |
| 62 | + organizationName={organizationName} |
| 63 | + canAssignOrgRole={permissions.assignOrgRole} |
| 64 | + /> |
| 65 | + </> |
| 66 | + ); |
| 67 | +}; |
| 68 | + |
| 69 | +export default CreateEditRolePage; |
0 commit comments