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: Edit a User #3664

Merged
merged 21 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,20 @@ import {
AddNewEditorErrors,
isUserAlreadyExistsError,
} from "../errors/addNewEditorErrors";
import { addNewEditorFormSchema } from "../formSchema";
import { editorFormSchema } 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";

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

Expand All @@ -39,12 +44,23 @@ export const AddNewEditorModal = ({
values: AddNewEditorFormValues,
{ resetForm }: FormikHelpers<AddNewEditorFormValues>,
) => {
switch (actionType) {
case "add":
handleNewSubmit();
break;
case "edit":
handleUpdateSubmit();
}
resetForm({ values });
};

const handleNewSubmit = 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,
).catch((err) => {
Expand All @@ -61,19 +77,41 @@ 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 handleUpdateSubmit = async () => {
const response = await useStore
.getState()
.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: editorFormSchema,
onSubmit: handleSubmit,
});

Expand Down Expand Up @@ -112,6 +150,7 @@ export const AddNewEditorModal = ({
? formik.errors.firstName
: undefined
}
value={formik.values.firstName}
/>
</InputLabel>
<InputLabel label="Last name" htmlFor="lastName">
Expand All @@ -124,6 +163,7 @@ export const AddNewEditorModal = ({
? formik.errors.lastName
: undefined
}
value={formik.values.lastName}
/>
</InputLabel>
<InputLabel label="Email address" htmlFor="email">
Expand All @@ -136,6 +176,7 @@ export const AddNewEditorModal = ({
? formik.errors.email
: undefined
}
value={formik.values.email}
/>
</InputLabel>
</InputGroup>
Expand All @@ -161,8 +202,9 @@ export const AddNewEditorModal = ({
color="prompt"
type="submit"
data-testid="modal-create-user-button"
disabled={!formik.dirty}
>
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 @@ -9,14 +11,33 @@ import { AddButton } from "pages/Team";
import React, { useState } from "react";

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

const TableButton = styled(Button)(({ theme }) => ({
RODO94 marked this conversation as resolved.
Show resolved Hide resolved
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(false);
const [showUpdateModal, setShowUpdateModal] = useState(false);
RODO94 marked this conversation as resolved.
Show resolved Hide resolved
const [initialValues, setInitialValues] = useState<TeamMember>({
firstName: "",
lastName: "",
email: "",
id: 0,
role: "platformAdmin",
});

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

{showModal && (
{showAddModal && (
<AddNewEditorModal
showModal={showModal}
setShowModal={setShowModal}
showModal={showAddModal}
setShowModal={setShowAddModal}
initialValues={initialValues}
actionType={"add"}
/>
)}
</>
Expand All @@ -74,7 +97,8 @@ export const MembersTable = ({
</TableCell>
<TableCell>
<strong>Email</strong>
</TableCell>
</TableCell>{" "}
<TableCell></TableCell>
</StyledTableRow>
</TableHead>
<TableBody
Expand Down Expand Up @@ -103,12 +127,22 @@ export const MembersTable = ({
/>
</TableCell>
<TableCell>{member.email}</TableCell>
<TableCell>
<TableButton
onClick={() => {
setShowUpdateModal(true);
setInitialValues(member);
}}
>
Edit
</TableButton>
</TableCell>
</StyledTableRow>
))}
{showAddMemberButton && (
<TableRow>
<TableCell colSpan={3}>
<AddButton onClick={() => setShowModal(true)}>
<AddButton onClick={() => setShowAddModal(true)}>
Add a new editor
</AddButton>
</TableCell>
Expand All @@ -117,8 +151,24 @@ export const MembersTable = ({
</TableBody>
</Table>
</TableContainer>
{showModal && (
<AddNewEditorModal showModal={showModal} setShowModal={setShowModal} />
{showAddModal && (
<AddNewEditorModal
showModal={showAddModal}
setShowModal={setShowAddModal}
initialValues={initialValues}
actionType={"add"}
/>
)}
{showUpdateModal && (
<AddNewEditorModal
showModal={showUpdateModal}
setShowModal={setShowUpdateModal}
RODO94 marked this conversation as resolved.
Show resolved Hide resolved
initialValues={
initialValues || { firstName: "", lastName: "", email: "" }
}
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
Expand Up @@ -5,3 +5,13 @@ export const addNewEditorFormSchema = Yup.object({
lastName: Yup.string().required("Required"),
email: Yup.string().email("Invalid email address").required("Required"),
});

export const editorFormSchema = Yup.object({
RODO94 marked this conversation as resolved.
Show resolved Hide resolved
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"),
});
20 changes: 20 additions & 0 deletions editor.planx.uk/src/pages/FlowEditor/components/Team/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,29 @@ export interface AddNewEditorModalProps {
showModal: boolean;
setShowModal: React.Dispatch<SetStateAction<boolean>>;
}
export interface UpdateEditorModalProps {
showUpdateModal: boolean;
setShowUpdateModal: React.Dispatch<SetStateAction<boolean>>;
initialValues: AddNewEditorFormValues;
userId: number;
}
export interface EditorModalProps {
showModal: boolean;
setShowModal: React.Dispatch<SetStateAction<boolean>>;
initialValues: TeamMember;
userId?: number;
actionType: "add" | "edit";
}

export interface AddNewEditorFormValues {
email: string;
firstName: string;
lastName: string;
}

export interface EditorFormValues {
RODO94 marked this conversation as resolved.
Show resolved Hide resolved
email: string;
firstName: string;
lastName: string;
id?: number;
}
Loading
Loading