Skip to content

Commit

Permalink
feat: add new editor - error handling and enhancements (#3543)
Browse files Browse the repository at this point in the history
Co-authored-by: Dafydd Llŷr Pearson <[email protected]>
  • Loading branch information
jamdelion and DafyddLlyr authored Aug 28, 2024
1 parent 68a7ca9 commit 0b6b010
Show file tree
Hide file tree
Showing 11 changed files with 218 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import DialogContent from "@mui/material/DialogContent";
import Typography from "@mui/material/Typography";
import { FormikHelpers, useFormik } from "formik";
import { useStore } from "pages/FlowEditor/lib/store";
import React from "react";
import React, { useState } from "react";
import InputGroup from "ui/editor/InputGroup";
import InputLabel from "ui/editor/InputLabel";
import ErrorWrapper from "ui/shared/ErrorWrapper";
import Input from "ui/shared/Input";

import {
AddNewEditorErrors,
isUserAlreadyExistsError,
} from "../errors/addNewEditorErrors";
import { addNewEditorFormSchema } from "../formSchema";
import { createAndAddUserToTeam } from "../queries/createAndAddUserToTeam";
import { AddNewEditorFormValues, AddNewEditorModalProps } from "../types";
Expand All @@ -19,7 +24,15 @@ import { optimisticallyUpdateMembersTable } from "./lib/optimisticallyUpdateMemb
export const AddNewEditorModal = ({
showModal,
setShowModal,
setShowToast,
}: AddNewEditorModalProps) => {
const [showUserAlreadyExistsError, setShowUserAlreadyExistsError] =
useState<boolean>(false);

const clearErrors = () => {
setShowUserAlreadyExistsError(false);
};

const handleSubmit = async (
values: AddNewEditorFormValues,
{ resetForm }: FormikHelpers<AddNewEditorFormValues>,
Expand All @@ -32,11 +45,20 @@ export const AddNewEditorModal = ({
values.lastName,
teamId,
teamSlug,
);
).catch((err) => {
if (isUserAlreadyExistsError(err.message)) {
setShowUserAlreadyExistsError(true);
}
console.error(err);
});

if (!newUserId) {
return;
}
clearErrors();
optimisticallyUpdateMembersTable(values, newUserId);

setShowModal(false);
setShowToast(true);
resetForm({ values });
};

Expand All @@ -53,6 +75,7 @@ export const AddNewEditorModal = ({
return (
<Dialog
aria-labelledby="dialog-heading"
data-testid="dialog-create-user"
PaperProps={{
sx: (theme) => ({
width: "100%",
Expand Down Expand Up @@ -119,26 +142,36 @@ export const AddNewEditorModal = ({
padding: 2,
}}
>
<Box>
<Button
variant="contained"
color="prompt"
type="submit"
data-testid="modal-create-user-button"
>
Create user
</Button>
<Button
variant="contained"
color="secondary"
type="reset"
sx={{ ml: 1.5 }}
onClick={() => setShowModal(false)}
data-testid="modal-cancel-button"
>
Cancel
</Button>
</Box>
<ErrorWrapper
error={
showUserAlreadyExistsError
? AddNewEditorErrors.USER_ALREADY_EXISTS.errorMessage
: undefined
}
>
<Box>
<>
<Button
variant="contained"
color="prompt"
type="submit"
data-testid="modal-create-user-button"
>
Create user
</Button>
<Button
variant="contained"
color="secondary"
type="reset"
sx={{ ml: 1.5 }}
onClick={() => setShowModal(false)}
data-testid="modal-cancel-button"
>
Cancel
</Button>
</>
</Box>
</ErrorWrapper>
</DialogActions>
</form>
</Dialog>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Alert from "@mui/material/Alert";
import Chip from "@mui/material/Chip";
import Snackbar from "@mui/material/Snackbar";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
Expand All @@ -18,6 +20,18 @@ export const MembersTable = ({
showAddMemberButton,
}: MembersTableProps) => {
const [showModal, setShowModal] = useState(false);
const [showToast, setShowToast] = useState(false);

const handleCloseToast = (
_event?: React.SyntheticEvent | Event,
reason?: string,
) => {
if (reason === "clickaway") {
return;
}

setShowToast(false);
};

const roleLabels: Record<string, string> = {
platformAdmin: "Admin",
Expand Down Expand Up @@ -99,9 +113,28 @@ export const MembersTable = ({
)}
</TableBody>
</Table>
{showAddMemberButton && (
<Snackbar
open={showToast}
autoHideDuration={6000}
onClose={handleCloseToast}
>
<Alert
onClose={handleCloseToast}
severity="success"
sx={{ width: "100%" }}
>
Successfully added a user
</Alert>
</Snackbar>
)}
</TableContainer>
{showModal && (
<AddNewEditorModal showModal={showModal} setShowModal={setShowModal} />
<AddNewEditorModal
setShowToast={setShowToast}
showModal={showModal}
setShowModal={setShowModal}
/>
)}
</>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const AddNewEditorErrors = {
USER_ALREADY_EXISTS: {
regex: /violates unique constraint "users_email_key"/i,
errorMessage: "User already exists",
},
};
export const isUserAlreadyExistsError = (error: string) =>
AddNewEditorErrors.USER_ALREADY_EXISTS.regex.test(error);
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { screen, within } from "@testing-library/react";
import { FullStore, useStore } from "pages/FlowEditor/lib/store";
import { vi } from "vitest";

import { setupTeamMembersScreen } from "./helpers/setupTeamMembersScreen";
import { userTriesToAddNewEditor } from "./helpers/userTriesToAddNewEditor";
import { mockTeamMembersData } from "./mocks/mockTeamMembersData";
import { alreadyExistingUser } from "./mocks/mockUsers";

vi.mock("lib/featureFlags.ts", () => ({
hasFeatureFlag: vi.fn().mockReturnValue(true),
}));

vi.mock(
"pages/FlowEditor/components/Team/queries/createAndAddUserToTeam.tsx",
() => ({
createAndAddUserToTeam: vi.fn().mockRejectedValue({
message:
'Uniqueness violation. duplicate key value violates unique constraint "users_email_key"',
}),
}),
);

let initialState: FullStore;

describe("when a user fills in the 'add a new editor' form correctly but the user already exists", () => {
afterAll(() => useStore.setState(initialState));
beforeEach(async () => {
useStore.setState({
teamMembers: [...mockTeamMembersData, alreadyExistingUser],
});

const user = await setupTeamMembersScreen();
await userTriesToAddNewEditor(user);
});

it("shows an appropriate error message", async () => {
const addNewEditorModal = await screen.findByTestId("dialog-create-user");

expect(
await within(addNewEditorModal).findByText(/User already exists/),
).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { FullStore, useStore } from "pages/FlowEditor/lib/store";
import { vi } from "vitest";

import { setupTeamMembersScreen } from "./helpers/setupTeamMembersScreen";
import { userEntersInput } from "./helpers/userEntersInput";
import { userTriesToAddNewEditor } from "./helpers/userTriesToAddNewEditor";
import { mockTeamMembersData } from "./mocks/mockTeamMembersData";

vi.mock("lib/featureFlags.ts", () => ({
hasFeatureFlag: vi.fn().mockReturnValue(true),
Expand All @@ -23,6 +24,7 @@ let initialState: FullStore;

describe("when a user with the ADD_NEW_EDITOR feature flag enabled presses 'add a new editor'", () => {
beforeEach(async () => {
useStore.setState({ teamMembers: mockTeamMembersData });
const user = await setupTeamMembersScreen();

const teamEditorsTable = screen.getByTestId("team-editors");
Expand All @@ -41,26 +43,9 @@ describe("when a user with the ADD_NEW_EDITOR feature flag enabled presses 'add
describe("when a user fills in the 'add a new editor' form correctly", () => {
afterAll(() => useStore.setState(initialState));
beforeEach(async () => {
useStore.setState({ teamMembers: mockTeamMembersData });
const user = await setupTeamMembersScreen();
const teamEditorsTable = screen.getByTestId("team-editors");
const addEditorButton = await within(teamEditorsTable).findByText(
"Add a new editor",
);
user.click(addEditorButton);
const addNewEditorModal = await screen.findByTestId("modal-create-user");
await userEntersInput("First name", "Mickey", addNewEditorModal);
await userEntersInput("Last name", "Mouse", addNewEditorModal);
await userEntersInput(
"Email address",
"[email protected]",
addNewEditorModal,
);

const createUserButton = await screen.findByTestId(
"modal-create-user-button",
);

user.click(createUserButton);
await userTriesToAddNewEditor(user);
});

it("adds the new user row to the Team Editors table", async () => {
Expand All @@ -72,4 +57,16 @@ describe("when a user fills in the 'add a new editor' form correctly", () => {
).toBeInTheDocument();
});
});

it("closes the modal", async () => {
await waitFor(() => {
expect(screen.queryByTestId("modal-create-user")).not.toBeInTheDocument();
});
});

it("shows a success message", async () => {
expect(
await screen.findByText(/Successfully added a user/),
).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import { screen } from "@testing-library/react";
import { useStore } from "pages/FlowEditor/lib/store";
import React from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

import { setup } from "../../../../../../testUtils";
import { TeamMembers } from "../../TeamMembers";
import { exampleTeamMembersData } from "../exampleTeamMembersData";

export const setupTeamMembersScreen = async () => {
useStore.setState({ teamMembers: exampleTeamMembersData });

const { user } = setup(
<DndProvider backend={HTML5Backend}>
<TeamMembers />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { fireEvent, within } from "@testing-library/react";
import { within } from "@testing-library/react";
import { UserEvent } from "@testing-library/user-event/dist/types/setup/setup";

export const userEntersInput = async (
labelText: string,
inputString: string,
container: HTMLElement,
user: UserEvent,
) => {
const inputField = await within(container).findByLabelText(labelText);

fireEvent.change(inputField, {
target: { value: inputString },
});
await user.type(inputField, inputString);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { screen, within } from "@testing-library/react";
import { UserEvent } from "@testing-library/user-event/dist/types/setup/setup";

import { userEntersInput } from "./userEntersInput";

export const userTriesToAddNewEditor = async (user: UserEvent) => {
const teamEditorsTable = screen.getByTestId("team-editors");
const addEditorButton = await within(teamEditorsTable).findByText(
"Add a new editor",
);
user.click(addEditorButton);
const addNewEditorModal = await screen.findByTestId("modal-create-user");
await userEntersInput("First name", "Mickey", addNewEditorModal, user);
await userEntersInput("Last name", "Mouse", addNewEditorModal, user);
await userEntersInput(
"Email address",
"[email protected]",
addNewEditorModal,
user,
);

const createUserButton = await screen.findByTestId(
"modal-create-user-button",
);

user.click(createUserButton);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TeamMember } from "../../types";

export const mockTeamMembersData: TeamMember[] = [
{
firstName: "Donella",
lastName: "Meadows",
email: "[email protected]",
id: 1,
role: "platformAdmin",
},
{
firstName: "Bill",
lastName: "Sharpe",
email: "[email protected]",
id: 2,
role: "teamEditor",
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { TeamMember } from "../../types";

export const alreadyExistingUser: TeamMember = {
firstName: "Mickey",
lastName: "Mouse",
email: "[email protected]",
id: 3,
role: "teamEditor",
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface MembersTableProps {
export interface AddNewEditorModalProps {
showModal: boolean;
setShowModal: React.Dispatch<SetStateAction<boolean>>;
setShowToast: React.Dispatch<SetStateAction<boolean>>;
}

export interface AddNewEditorFormValues {
Expand Down

0 comments on commit 0b6b010

Please sign in to comment.