Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 63 additions & 1 deletion client/src/app/features/user/components/UserProfileView.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import TextField from "@shared/uis/TextField.tsx";
import { Button } from "@shared/uis/Button.tsx";
import { ErrorPanel } from "@shared/uis/ErrorPanel.tsx";
Expand All @@ -12,6 +16,9 @@ type Props = {
onUpdate: (values: UpdateUserFormValues) => void;
isUpdating: boolean;
updateError: unknown;
onDelete: () => void;
isDeleting: boolean;
deleteError: unknown;
};

type EditableField = keyof UpdateUserFormValues;
Expand All @@ -25,11 +32,21 @@ const toFormValues = (profile: UserProfile): UpdateUserFormValues => ({
email: profile.email,
});

export function UserProfileView({ profile, onUpdate, isUpdating, updateError }: Props) {
export function UserProfileView({
profile,
onUpdate,
isUpdating,
updateError,
onDelete,
isDeleting,
deleteError,
}: Props) {
const text = useText();
const [editingField, setEditingField] = useState<EditableField | null>(null);
const [fieldValue, setFieldValue] = useState("");
const [isConfirmingDelete, setIsConfirmingDelete] = useState(false);
const wasUpdatingRef = useRef(false);
const wasDeletingRef = useRef(false);

useEffect(() => {
if (wasUpdatingRef.current && !isUpdating && updateError == null) {
Expand All @@ -38,6 +55,13 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
wasUpdatingRef.current = isUpdating;
}, [isUpdating, updateError]);

useEffect(() => {
if (wasDeletingRef.current && !isDeleting && deleteError != null) {
setIsConfirmingDelete(false);
}
wasDeletingRef.current = isDeleting;
}, [isDeleting, deleteError]);

const startEditing = (field: EditableField) => {
setFieldValue(profile[field]);
setEditingField(field);
Expand All @@ -53,6 +77,10 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
onUpdate({ ...toFormValues(profile), [editingField]: fieldValue });
};

const handleConfirmDelete = () => {
onDelete();
};

return (
<div className="mx-auto flex max-w-xl flex-col items-center gap-6 px-4 py-12">
<div className="flex h-24 w-24 items-center justify-center rounded-full bg-indigo-600 text-3xl font-semibold text-white">
Expand Down Expand Up @@ -118,6 +146,40 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
<ProfileRow label={text.userAgeRange} value={profile.ageRange} />
<ProfileRow label={text.userSubscriptionTier} value={profile.subscriptionTier} />
</div>

{deleteError != null && <ErrorPanel message={text.userDeleteError} />}

<Button
type="button"
variant="destructive"
onClick={() => setIsConfirmingDelete(true)}
disabled={isDeleting}
>
{text.userDeleteButton}
</Button>

<Dialog open={isConfirmingDelete} onClose={() => setIsConfirmingDelete(false)}>
<DialogTitle>{text.userDeleteConfirmTitle}</DialogTitle>
<DialogContent>{text.userDeleteConfirmMessage}</DialogContent>
<DialogActions>
<Button
type="button"
variant="secondary"
onClick={() => setIsConfirmingDelete(false)}
disabled={isDeleting}
>
{text.userUpdateCancel}
</Button>
<Button
type="button"
variant="destructive"
onClick={handleConfirmDelete}
isLoading={isDeleting}
>
{text.userDeleteButton}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @jest-environment jsdom */

import { render, screen, fireEvent } from "@testing-library/react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { LocaleProvider } from "@shared/locale/LocaleProvider.tsx";
import { UserProfileView } from "../UserProfileView";
Expand All @@ -22,6 +22,9 @@ const renderView = (props: Partial<React.ComponentProps<typeof UserProfileView>>
onUpdate: jest.fn(),
isUpdating: false,
updateError: null,
onDelete: jest.fn(),
isDeleting: false,
deleteError: null,
...props,
};

Expand Down Expand Up @@ -125,7 +128,14 @@ describe("UserProfileView", () => {
rerender(
<MemoryRouter>
<LocaleProvider>
<UserProfileView profile={profile} onUpdate={jest.fn()} {...props} />
<UserProfileView
profile={profile}
onUpdate={jest.fn()}
onDelete={jest.fn()}
isDeleting={false}
deleteError={null}
{...props}
/>
</LocaleProvider>
</MemoryRouter>,
);
Expand All @@ -150,4 +160,45 @@ describe("UserProfileView", () => {
expect(screen.queryByLabelText(/^First Name/)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Edit First Name" })).toBeInTheDocument();
});

it("opens a confirmation dialog when Delete User is clicked", () => {
renderView();

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(
screen.getByText("Are you sure you want to delete this user?", { exact: false }),
).toBeInTheDocument();
});

it("closes the dialog without calling onDelete when Cancel is clicked", async () => {
const onDelete = jest.fn();
renderView({ onDelete });

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));

expect(onDelete).not.toHaveBeenCalled();
await waitFor(() => {
expect(
screen.queryByText("Are you sure you want to delete this user?", { exact: false }),
).not.toBeInTheDocument();
});
});

it("calls onDelete when the dialog's Delete User button is confirmed", () => {
const onDelete = jest.fn();
renderView({ onDelete });

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(onDelete).toHaveBeenCalledTimes(1);
});

it("shows an error panel when deleteError is present", () => {
renderView({ deleteError: new Error("boom") });

expect(screen.getByText("Failed to delete user.")).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { UserProfile } from "../../types";

const useGetUserMock = jest.fn();
const useUpdateUserMock = jest.fn();
const useDeleteUserMock = jest.fn();

jest.mock("../../hooks/use-get-user", () => ({
useGetUser: (id: number) => useGetUserMock(id),
Expand All @@ -13,6 +14,10 @@ jest.mock("../../hooks/use-update-user", () => ({
useUpdateUser: () => useUpdateUserMock(),
}));

jest.mock("../../hooks/use-delete-user", () => ({
useDeleteUser: () => useDeleteUserMock(),
}));

import { render, screen, fireEvent } from "@testing-library/react";
import { MemoryRouter, Routes, Route } from "react-router-dom";
import { LocaleProvider } from "@shared/locale/LocaleProvider.tsx";
Expand All @@ -34,22 +39,30 @@ const renderContainer = (id = "1") =>
<LocaleProvider>
<Routes>
<Route path="/users/:id" element={<UserGetContainer />} />
<Route path="/heritages" element={<div>Heritages Home</div>} />
</Routes>
</LocaleProvider>
</MemoryRouter>,
);

describe("UserGetContainer", () => {
const submitMock = jest.fn();
const submitUpdateMock = jest.fn();
const submitDeleteMock = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
useUpdateUserMock.mockReturnValue({
submit: submitMock,
submit: submitUpdateMock,
data: null,
isLoading: false,
error: null,
});
useDeleteUserMock.mockReturnValue({
submit: submitDeleteMock,
done: false,
isLoading: false,
error: null,
});
});

it("shows a spinner while loading", () => {
Expand Down Expand Up @@ -102,7 +115,7 @@ describe("UserGetContainer", () => {
fireEvent.change(screen.getByLabelText(/^First Name/), { target: { value: "Jiro" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));

expect(submitMock).toHaveBeenCalledWith(
expect(submitUpdateMock).toHaveBeenCalledWith(
42,
expect.objectContaining({ firstName: "Jiro", lastName: "Yamada", email: "taro@example.com" }),
);
Expand All @@ -111,7 +124,7 @@ describe("UserGetContainer", () => {
it("reflects the updated profile immediately once useUpdateUser returns data", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });
useUpdateUserMock.mockReturnValue({
submit: submitMock,
submit: submitUpdateMock,
data: { ...profile, firstName: "Jiro" },
isLoading: false,
error: null,
Expand All @@ -121,4 +134,29 @@ describe("UserGetContainer", () => {

expect(screen.getByText("Jiro Yamada")).toBeInTheDocument();
});

it("calls useDeleteUser's submit with the numeric id after confirming deletion", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });

renderContainer("42");

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(submitDeleteMock).toHaveBeenCalledWith(42);
});

it("navigates to /heritages once useDeleteUser reports done", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });
useDeleteUserMock.mockReturnValue({
submit: submitDeleteMock,
done: true,
isLoading: false,
error: null,
});

renderContainer();

expect(screen.getByText("Heritages Home")).toBeInTheDocument();
});
});
17 changes: 16 additions & 1 deletion client/src/app/features/user/containers/user-get-container.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import { useGetUser } from "../hooks/use-get-user";
import { useUpdateUser } from "../hooks/use-update-user";
import { useDeleteUser } from "../hooks/use-delete-user";
import { UserProfileView } from "../components/UserProfileView";
import { ErrorPanel } from "@shared/uis/ErrorPanel.tsx";
import { Spinner } from "@shared/uis/Spinner.tsx";
Expand All @@ -11,13 +12,20 @@ import type { UserProfile } from "../types";
export function UserGetContainer() {
const { id } = useParams<{ id: string }>();
const numericId = Number(id);
const navigate = useNavigate();
const { data, isLoading, error } = useGetUser(numericId);
const {
submit: submitUpdate,
data: updated,
isLoading: isUpdating,
error: updateError,
} = useUpdateUser();
const {
submit: submitDelete,
done: isDeleted,
isLoading: isDeleting,
error: deleteError,
} = useDeleteUser();
const [profile, setProfile] = useState<UserProfile | null>(null);
const text = useText();

Expand All @@ -29,6 +37,10 @@ export function UserGetContainer() {
if (updated) setProfile(updated);
}, [updated]);

useEffect(() => {
if (isDeleted) navigate("/heritages");
}, [isDeleted, navigate]);

if (isLoading) return <Spinner />;
if (error || !profile) return <ErrorPanel message={text.userGetError} />;

Expand All @@ -38,6 +50,9 @@ export function UserGetContainer() {
onUpdate={(values) => submitUpdate(numericId, values)}
isUpdating={isUpdating}
updateError={updateError}
onDelete={() => submitDelete(numericId)}
isDeleting={isDeleting}
deleteError={deleteError}
/>
);
}
6 changes: 5 additions & 1 deletion client/src/locals/en/ui.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,9 @@
"userUpdateEdit": "Edit",
"userUpdateSubmit": "Save",
"userUpdateCancel": "Cancel",
"userUpdateError": "Failed to update user."
"userUpdateError": "Failed to update user.",
"userDeleteButton": "Delete User",
"userDeleteConfirmTitle": "Delete User",
"userDeleteConfirmMessage": "Are you sure you want to delete this user? This action cannot be undone.",
"userDeleteError": "Failed to delete user."
}
6 changes: 5 additions & 1 deletion client/src/locals/ja/ui.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,9 @@
"userUpdateEdit": "編集",
"userUpdateSubmit": "保存",
"userUpdateCancel": "キャンセル",
"userUpdateError": "ユーザー情報の更新に失敗しました。"
"userUpdateError": "ユーザー情報の更新に失敗しました。",
"userDeleteButton": "ユーザーを削除",
"userDeleteConfirmTitle": "ユーザーの削除",
"userDeleteConfirmMessage": "このユーザーを削除してもよろしいですか?この操作は取り消せません。",
"userDeleteError": "ユーザーの削除に失敗しました。"
}
Loading