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

Add inline form validation for duplicates & convert identities to queries #78

Merged
merged 2 commits into from
Apr 8, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkg/client/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@
"group(s)": "Group(s)",
"groupCount": "Group count",
"highRisk": "High risk",
"identity": "Identity",
"identifiedRisks": "Identified risks",
"impactfulButMigratable": "Impactful but migratable",
"impactfulButNotAdvisableToMove": "Impactful but not advisable to move",
Expand Down Expand Up @@ -268,7 +269,7 @@
},
"toastr": {
"success": {
"added": "Success! {{what}} was added as a {{type}}.",
"added": "Success! {{what}} was added as a(n) {{type}}.",
"assessmentAndReviewCopied": "Success! Assessment and review copied to selected applications",
"assessmentCopied": "Success! Assessment copied to selected applications",
"assessmentDiscarded": "Success! Assessment discarded for {{application}}.",
Expand Down
70 changes: 58 additions & 12 deletions pkg/client/src/app/pages/identities/components/identity-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { FieldValues, useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";

import { OptionWithValue, SimpleSelect } from "@app/shared/components";
import { createIdentity, updateIdentity } from "@app/api/rest";
import { Identity } from "@app/api/models";
import {
getAxiosErrorMessage,
Expand All @@ -29,6 +28,14 @@ const xmllint = require("xmllint");
const { XMLValidator } = require("fast-xml-parser");

import "./identity-form.css";
import { useQueryClient } from "react-query";
import {
IdentitiesQueryKey,
useCreateIdentityMutation,
useUpdateIdentityMutation,
} from "@app/queries/identities";
import { useDispatch } from "react-redux";
import { alertActions } from "@app/store/alert";

export interface IdentityFormProps {
identity?: Identity;
Expand All @@ -46,6 +53,10 @@ export const IdentityForm: React.FC<IdentityFormProps> = ({
const [axiosError, setAxiosError] = useState<AxiosError>();
const [isLoading, setIsLoading] = useState(false);
const [identity, setIdentity] = useState(initialIdentity);
const dispatch = useDispatch();

const queryClient = useQueryClient();

useEffect(() => {
setIdentity(initialIdentity);
return () => {
Expand All @@ -62,6 +73,23 @@ export const IdentityForm: React.FC<IdentityFormProps> = ({
return "";
}
};
const onCreateUpdateIdentitySuccess = (response: any) => {
onSaved(response);
};

const onCreateUpdateIdentityError = (error: AxiosError) => {
setAxiosError(error);
};

const { mutate: createIdentity } = useCreateIdentityMutation(
onCreateUpdateIdentitySuccess,
onCreateUpdateIdentityError
);

const { mutate: updateIdentity } = useUpdateIdentityMutation(
onCreateUpdateIdentitySuccess,
onCreateUpdateIdentityError
);

const onSubmit = (formValues: FieldValues) => {
const payload: Identity = {
Expand Down Expand Up @@ -101,29 +129,42 @@ export const IdentityForm: React.FC<IdentityFormProps> = ({
}),
};

let promise: AxiosPromise<Identity>;
if (identity) {
promise = updateIdentity({
updateIdentity({
...payload,
});
} else {
promise = createIdentity(payload);
createIdentity(payload);
}
promise
.then((response) => {
onSaved(response);
})
.catch((error) => {
setAxiosError(error);
});
};

const validationSchema = object().shape({
name: string()
.trim()
.required(t("validation.required"))
.min(3, t("validation.minLength", { length: 3 }))
.max(120, t("validation.maxLength", { length: 120 })),
.max(120, t("validation.maxLength", { length: 120 }))
.test(
"Duplicate name",
"An identity with this name already exists. Please use a different name.",
(value) => {
const identities: Identity[] =
queryClient.getQueryData(IdentitiesQueryKey) || [];
let duplicateList = [...identities];
if (identity) {
const index = duplicateList.findIndex(
(id) => id.name === identity.name
);
if (index > -1) {
duplicateList.splice(index, 1);
}
}
const hasDuplicate = duplicateList.some(
(identity) => identity.name === value
);
return !hasDuplicate;
}
),
description: string()
.trim()
.max(250, t("validation.maxLength", { length: 250 })),
Expand Down Expand Up @@ -169,6 +210,10 @@ export const IdentityForm: React.FC<IdentityFormProps> = ({
},
}),
}),
userCredentials: string().when("kind", {
is: "source",
then: string().required(),
}),
user: string()
.when("kind", {
is: "proxy",
Expand Down Expand Up @@ -248,6 +293,7 @@ export const IdentityForm: React.FC<IdentityFormProps> = ({
resolver: yupResolver(validationSchema),
mode: "onChange",
});

const values = getValues();

const [isFileRejected, setIsFileRejected] = useState(false);
Expand Down
46 changes: 19 additions & 27 deletions pkg/client/src/app/pages/identities/identities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,23 @@ import { useFilterState } from "@app/shared/hooks/useFilterState";
import { usePaginationState } from "@app/shared/hooks/usePaginationState";
import { useSortState } from "@app/shared/hooks/useSortState";
import { useEntityModal } from "@app/shared/hooks/useEntityModal";
import { AxiosResponse } from "axios";
import { AxiosError, AxiosResponse } from "axios";
import { useDispatch } from "react-redux";
import { alertActions } from "@app/store/alert";
import { useDelete, useTableControls } from "@app/shared/hooks";
import { confirmDialogActions } from "@app/store/confirmDialog";
import { NewIdentityModal } from "./components/new-identity-modal";
import { UpdateIdentityModal } from "./components/update-identity-modal";
import { getAxiosErrorMessage } from "@app/utils/utils";
import { useFetchIdentities } from "@app/shared/hooks/useFetchIdentities";
import {
FilterCategory,
FilterToolbar,
FilterType,
} from "@app/shared/components/FilterToolbar";
import {
useDeleteIdentityMutation,
useFetchIdentities,
} from "@app/queries/identities";

const ENTITY_FIELD = "entity";

Expand All @@ -52,6 +55,19 @@ export const Identities: React.FunctionComponent = () => {
const dispatch = useDispatch();

const [rowToUpdate, setRowToUpdate] = useState<Identity>();
const onDeleteIdentitySuccess = (response: any) => {
dispatch(confirmDialogActions.closeDialog());
};

const onDeleteIdentityError = (error: AxiosError) => {
dispatch(confirmDialogActions.closeDialog());
dispatch(alertActions.addDanger(getAxiosErrorMessage(error)));
};

const { mutate: deleteIdentity } = useDeleteIdentityMutation(
onDeleteIdentitySuccess,
onDeleteIdentityError
);

// Create and update modal
const {
Expand All @@ -66,16 +82,8 @@ export const Identities: React.FunctionComponent = () => {
identities,
isFetching,
fetchError: fetchErrorIdentities,
fetchIdentities,
} = useFetchIdentities();

useEffect(() => {
fetchIdentities();
}, [fetchIdentities]);

const { requestDelete: requestDeleteIdentity } = useDelete<Identity>({
onDelete: (t: Identity) => deleteIdentity(t.id!),
});
interface ITypeOptions {
key: string;
value: string;
Expand Down Expand Up @@ -136,10 +144,6 @@ export const Identities: React.FunctionComponent = () => {
const { currentPageItems, setPageNumber, paginationProps } =
usePaginationState(sortedItems, 10);

useEffect(() => {
fetchIdentities();
}, [fetchIdentities]);

const columns: ICell[] = [
{
title: "Name",
Expand Down Expand Up @@ -176,17 +180,7 @@ export const Identities: React.FunctionComponent = () => {
cancelBtnLabel: t("actions.cancel"),
onConfirm: () => {
dispatch(confirmDialogActions.processing());
requestDeleteIdentity(
row,
() => {
dispatch(confirmDialogActions.closeDialog());
fetchIdentities();
},
(error) => {
dispatch(confirmDialogActions.closeDialog());
dispatch(alertActions.addDanger(getAxiosErrorMessage(error)));
}
);
deleteIdentity(row.id);
},
})
);
Expand All @@ -205,12 +199,10 @@ export const Identities: React.FunctionComponent = () => {
}

closeIdentityModal();
fetchIdentities();
};

const handleOnIdentityUpdated = () => {
setRowToUpdate(undefined);
fetchIdentities();
};

const handleOnClearAllFilters = () => {
Expand Down
87 changes: 84 additions & 3 deletions pkg/client/src/app/queries/identities.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,82 @@
import React from "react";
import { useQuery } from "react-query";
import { useMutation, useQuery, useQueryClient } from "react-query";

import { getIdentities } from "@app/api/rest";
import {
createIdentity,
deleteIdentity,
getIdentities,
updateIdentity,
} from "@app/api/rest";
import { Identity } from "@app/api/models";
import { AxiosError } from "axios";

export interface IIdentityFetchState {
identities: Identity[];
isFetching: boolean;
fetchError: any;
}

export interface IIdentityMutateState {
mutate: any;
isLoading: boolean;
error: any;
}

export const IdentitiesQueryKey = "identities";

export const useUpdateIdentityMutation = (
onSuccess: (res: any) => void,
onError: (err: AxiosError) => void
): IIdentityMutateState => {
const queryClient = useQueryClient();
const { isLoading, mutate, error } = useMutation(updateIdentity, {
onSuccess: (res) => {
onSuccess(res);
queryClient.invalidateQueries("identities");
},
onError: (err: AxiosError) => {
onError(err);
},
});
return {
mutate,
isLoading,
error,
};
};

export const useCreateIdentityMutation = (
onSuccess: (res: any) => void,
onError: (err: AxiosError) => void
): IIdentityMutateState => {
const queryClient = useQueryClient();
const { isLoading, mutate, error } = useMutation(createIdentity, {
onSuccess: (res) => {
onSuccess(res);
queryClient.invalidateQueries("identities");
},
onError: (err: AxiosError) => {
onError(err);
},
});
return {
mutate,
isLoading,
error,
};
};

export const useFetchIdentities = (): IIdentityFetchState => {
const [identities, setIdentities] = React.useState<Identity[]>([]);
const { isLoading, error } = useQuery("identities", () =>
const { isLoading, error } = useQuery(IdentitiesQueryKey, () =>
getIdentities()
.then(({ data }) => {
setIdentities(data);
return data;
})
.catch((error) => {
console.log("error, ", error);
return error;
})
);
return {
Expand All @@ -27,3 +85,26 @@ export const useFetchIdentities = (): IIdentityFetchState => {
fetchError: error,
};
};

export const useDeleteIdentityMutation = (
onSuccess: (res: any) => void,
onError: (err: AxiosError) => void
): IIdentityMutateState => {
const queryClient = useQueryClient();

const { isLoading, mutate, error } = useMutation(deleteIdentity, {
onSuccess: (res) => {
onSuccess(res);
queryClient.invalidateQueries("identities");
},
onError: (err: AxiosError) => {
onError(err);
queryClient.invalidateQueries("identities");
},
});
return {
mutate,
isLoading,
error,
};
};