Skip to content

Commit

Permalink
feat: Edit a User (#3664)
Browse files Browse the repository at this point in the history
Made final change from Jo and tested, all still working after renaming / repointing
  • Loading branch information
RODO94 authored Sep 17, 2024
1 parent 610df24 commit 3389060
Show file tree
Hide file tree
Showing 11 changed files with 436 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,21 @@ import {
AddNewEditorErrors,
isUserAlreadyExistsError,
} from "../errors/addNewEditorErrors";
import { addNewEditorFormSchema } from "../formSchema";
import { upsertEditorSchema } from "../formSchema";
import { createAndAddUserToTeam } from "../queries/createAndAddUserToTeam";
import { AddNewEditorFormValues, AddNewEditorModalProps } from "../types";
import { optimisticallyUpdateMembersTable } from "./lib/optimisticallyUpdateMembersTable";
import { AddNewEditorFormValues, EditorModalProps } from "../types";
import {
optimisticallyAddNewMember,
optimisticallyUpdateExistingMember,
} from "./lib/optimisticallyUpdateMembersTable";
import { updateTeamMember } from "../queries/updateUser";

export const AddNewEditorModal = ({
export const EditorUpsertModal = ({
showModal,
setShowModal,
}: AddNewEditorModalProps) => {
initialValues,
actionType,
}: EditorModalProps) => {
const [showUserAlreadyExistsError, setShowUserAlreadyExistsError] =
useState<boolean>(false);

Expand All @@ -37,16 +43,27 @@ export const AddNewEditorModal = ({

const handleSubmit = async (
values: AddNewEditorFormValues,
{ resetForm }: FormikHelpers<AddNewEditorFormValues>,
{ resetForm }: FormikHelpers<AddNewEditorFormValues>
) => {
switch (actionType) {
case "add":
handleSubmitToAddNewUser();
break;
case "edit":
handleSubmitToUpdateUser();
}
resetForm({ values });
};

const handleSubmitToAddNewUser = async () => {
const { teamId, teamSlug } = useStore.getState();

const createUserResult = await createAndAddUserToTeam(
values.email,
values.firstName,
values.lastName,
formik.values.email,
formik.values.firstName,
formik.values.lastName,
teamId,
teamSlug,
teamSlug
).catch((err) => {
if (isUserAlreadyExistsError(err.message)) {
setShowUserAlreadyExistsError(true);
Expand All @@ -61,26 +78,53 @@ export const AddNewEditorModal = ({
return;
}
clearErrors();
optimisticallyUpdateMembersTable(values, createUserResult.id);
optimisticallyAddNewMember(formik.values, createUserResult.id);
setShowModal(false);
toast.success("Successfully added a user");
resetForm({ values });
};
const handleSubmitToUpdateUser = async () => {
if (!initialValues) {
return;
}
const response = await updateTeamMember(
initialValues.id,
formik.values
).catch((err) => {
if (isUserAlreadyExistsError(err.message)) {
setShowUserAlreadyExistsError(true);
}
if (err.message === "Unable to update user") {
toast.error("Failed to update the user, please try again");
}
console.error(err);
});

if (!response) {
return;
}

clearErrors();
optimisticallyUpdateExistingMember(formik.values, initialValues.id);
setShowModal(false);
toast.success("Successfully updated a user");
};

const formik = useFormik<AddNewEditorFormValues>({
initialValues: {
firstName: "",
lastName: "",
email: "",
firstName: initialValues?.firstName || "",
lastName: initialValues?.lastName || "",
email: initialValues?.email || "",
},
validationSchema: addNewEditorFormSchema,
validationSchema: upsertEditorSchema,
onSubmit: handleSubmit,
});

return (
<Dialog
aria-labelledby="dialog-heading"
data-testid="dialog-create-user"
data-testid={
actionType === "add" ? "dialog-create-user" : "dialog-edit-user"
}
PaperProps={{
sx: (theme) => ({
width: "100%",
Expand All @@ -95,7 +139,11 @@ export const AddNewEditorModal = ({
onClose={() => setShowModal(false)}
>
<form onSubmit={formik.handleSubmit}>
<DialogContent data-testid="modal-create-user">
<DialogContent
data-testid={
actionType === "add" ? "modal-create-user" : "modal-edit-user"
}
>
<Box sx={{ mt: 1, mb: 4 }}>
<Typography variant="h3" component="h2" id="dialog-heading">
Add a new editor
Expand All @@ -112,6 +160,7 @@ export const AddNewEditorModal = ({
? formik.errors.firstName
: undefined
}
value={formik.values.firstName}
/>
</InputLabel>
<InputLabel label="Last name" htmlFor="lastName">
Expand All @@ -124,6 +173,7 @@ export const AddNewEditorModal = ({
? formik.errors.lastName
: undefined
}
value={formik.values.lastName}
/>
</InputLabel>
<InputLabel label="Email address" htmlFor="email">
Expand All @@ -136,6 +186,7 @@ export const AddNewEditorModal = ({
? formik.errors.email
: undefined
}
value={formik.values.email}
/>
</InputLabel>
</InputGroup>
Expand All @@ -160,9 +211,14 @@ export const AddNewEditorModal = ({
variant="contained"
color="prompt"
type="submit"
data-testid="modal-create-user-button"
data-testid={
actionType === "add"
? "modal-create-user-button"
: "modal-edit-user-button"
}
disabled={!formik.dirty || !formik.isValid}
>
Create user
{actionType === "add" ? "Create user" : "Update user"}
</Button>
<Button
variant="contained"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Button from "@mui/material/Button";
import Chip from "@mui/material/Chip";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
Expand All @@ -7,16 +9,30 @@ import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import { AddButton } from "pages/Team";
import React, { useState } from "react";
import Permission from "ui/editor/Permission";

import { StyledAvatar, StyledTableRow } from "./../styles";
import { MembersTableProps } from "./../types";
import { AddNewEditorModal } from "./AddNewEditorModal";
import { MembersTableProps, TeamMember } from "./../types";
import { EditorUpsertModal } from "./EditorUpsertModal";

const EditUserButton = styled(Button)(({ theme }) => ({
color: theme.palette.primary.main,
textDecoration: "underline",
boxShadow: "none",
"&:hover": {
boxShadow: "none",
color: theme.palette.primary.main,
textDecoration: "underline",
},
}));

export const MembersTable = ({
members,
showAddMemberButton,
}: MembersTableProps) => {
const [showModal, setShowModal] = useState(false);
const [showAddModal, setShowAddModal] = useState<boolean>(false);
const [showUpdateModal, setShowUpdateModal] = useState<boolean>(false);
const [initialValues, setInitialValues] = useState<TeamMember | undefined>();

const roleLabels: Record<string, string> = {
platformAdmin: "Admin",
Expand All @@ -42,18 +58,24 @@ export const MembersTable = ({
{showAddMemberButton && (
<TableRow>
<TableCell colSpan={3}>
<AddButton onClick={() => setShowModal(true)}>
<AddButton
onClick={() => {
setInitialValues(undefined);
setShowAddModal(true);
}}
>
Add a new editor
</AddButton>
</TableCell>
</TableRow>
)}
</Table>

{showModal && (
<AddNewEditorModal
showModal={showModal}
setShowModal={setShowModal}
{showAddModal && (
<EditorUpsertModal
showModal={showAddModal}
setShowModal={setShowAddModal}
initialValues={initialValues}
actionType={"add"}
/>
)}
</>
Expand All @@ -74,13 +96,14 @@ export const MembersTable = ({
</TableCell>
<TableCell>
<strong>Email</strong>
</TableCell>
</TableCell>{" "}
<TableCell></TableCell>
</StyledTableRow>
</TableHead>
<TableBody
data-testid={`members-table${showAddMemberButton && "-add-editor"}`}
>
{members.map((member) => (
{members.map((member, i) => (
<StyledTableRow key={member.id}>
<TableCell
sx={{
Expand All @@ -103,12 +126,30 @@ export const MembersTable = ({
/>
</TableCell>
<TableCell>{member.email}</TableCell>
<Permission.IsPlatformAdmin>
<TableCell>
<EditUserButton
onClick={() => {
setShowUpdateModal(true);
setInitialValues(member);
}}
data-testId={`edit-button-${i}`}
>
Edit
</EditUserButton>
</TableCell>
</Permission.IsPlatformAdmin>
</StyledTableRow>
))}
{showAddMemberButton && (
<TableRow>
<TableCell colSpan={3}>
<AddButton onClick={() => setShowModal(true)}>
<AddButton
onClick={() => {
setInitialValues(undefined);
setShowAddModal(true);
}}
>
Add a new editor
</AddButton>
</TableCell>
Expand All @@ -117,8 +158,22 @@ export const MembersTable = ({
</TableBody>
</Table>
</TableContainer>
{showModal && (
<AddNewEditorModal showModal={showModal} setShowModal={setShowModal} />
{showAddModal && (
<EditorUpsertModal
showModal={showAddModal}
setShowModal={setShowAddModal}
initialValues={initialValues}
actionType={"add"}
/>
)}
{showUpdateModal && (
<EditorUpsertModal
showModal={showUpdateModal}
setShowModal={setShowUpdateModal}
initialValues={initialValues}
userId={initialValues?.id || 1}
actionType={"edit"}
/>
)}
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,30 @@ import { useStore } from "pages/FlowEditor/lib/store";

import { AddNewEditorFormValues, TeamMember } from "../../types";

export const optimisticallyUpdateMembersTable = async (
export const optimisticallyAddNewMember = async (
values: AddNewEditorFormValues,
userId: number,
) => {
const existingMembers = useStore.getState().teamMembers;
const newMember: TeamMember = {
...values,
role: "teamEditor",
id: userId,
};

const existingMembers = useStore.getState().teamMembers;

await useStore.getState().setTeamMembers([...existingMembers, newMember]);
};

export const optimisticallyUpdateExistingMember = async (
values: AddNewEditorFormValues,
userId: number,
) => {
const existingMembers = useStore.getState().teamMembers;
const updatedMembers: TeamMember[] = existingMembers.map((member) => {
if (member.id === userId) {
return { ...values, id: userId, role: member.role };
}
return member;
});
await useStore.getState().setTeamMembers(updatedMembers);
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import * as Yup from "yup";

export const addNewEditorFormSchema = Yup.object({
firstName: Yup.string().required("Required"),
lastName: Yup.string().required("Required"),
email: Yup.string().email("Invalid email address").required("Required"),
export const upsertEditorSchema = Yup.object({
firstName: Yup.string().required("Enter a first name"),
lastName: Yup.string().required("Enter a last name"),
email: Yup.string()
.email(
"Enter an email address in the correct format, like [email protected]",
)
.required("Enter a valid email address"),
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const createAndAddUserToTeam = async (
firstName: string,
lastName: string,
teamId: number,
teamSlug: string,
teamSlug: string
) => {
// NB: the user is hard-coded with the 'teamEditor' role for now
const response: CreateAndAddUserResponse = await client.mutate({
Expand Down Expand Up @@ -45,6 +45,7 @@ export const createAndAddUserToTeam = async (
{ query: GET_USERS_FOR_TEAM_QUERY, variables: { teamSlug } },
],
});

if (response.data) {
return response.data.insert_users_one;
}
Expand Down
Loading

0 comments on commit 3389060

Please sign in to comment.