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

Fix some page components recently added #1381

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
127 changes: 127 additions & 0 deletions frontend/src/pages/AliasEntryListPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* @jest-environment jsdom
*/

import { render, screen, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import React from "react";
import { createMemoryRouter, RouterProvider } from "react-router";

import { TestWrapperWithoutRoutes } from "TestWrapper";
import { AliasEntryListPage } from "pages/AliasEntryListPage";

// Setup mock location
const mockLocation = {
pathname: "/ui/entities/1/alias",
search: "",
hash: "",
state: null,
};

// Mock useLocation
jest.mock("react-use", () => ({
...jest.requireActual("react-use"),
useLocation: () => mockLocation,
}));

const server = setupServer(
// GET /entity/api/v2/:entityId/
http.get("http://localhost/entity/api/v2/1/", () => {
return HttpResponse.json({
id: 1,
name: "Entity1",
note: "Test Entity",
isToplevel: true,
hasOngoingChanges: false,
attrs: [],
webhooks: [],
});
}),

// GET /entity/api/v2/:entityId/entries/
http.get("http://localhost/entity/api/v2/1/entries/", ({ request }) => {
// Get query parameters (when isAlias is true)
const url = new URL(request.url);
const withAlias = url.searchParams.get("with_alias");

if (withAlias === "1") {
return HttpResponse.json({
count: 2,
next: null,
previous: null,
results: [
{
id: 1,
name: "entry1",
schema: 1,
created_at: "2023-01-01T00:00:00Z",
updated_at: "2023-01-01T00:00:00Z",
created_user: { id: 1, username: "user1" },
updated_user: { id: 1, username: "user1" },
attrs: [],
referrals: [],
aliases: [],
is_public: true,
status: 0,
},
{
id: 2,
name: "entry2",
schema: 1,
created_at: "2023-01-02T00:00:00Z",
updated_at: "2023-01-02T00:00:00Z",
created_user: { id: 1, username: "user1" },
updated_user: { id: 1, username: "user1" },
attrs: [],
referrals: [],
aliases: [],
is_public: true,
status: 0,
},
],
});
}

return HttpResponse.json({
count: 0,
next: null,
previous: null,
results: [],
});
})
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe("AliasEntryListPage", () => {
it("renders the alias entry list", async () => {
// Create memory router
const router = createMemoryRouter(
[
{
path: "/ui/entities/:entityId/alias",
element: <AliasEntryListPage />,
},
],
{
initialEntries: ["/ui/entities/1/alias"],
}
);

// Render component
render(
<TestWrapperWithoutRoutes>
<RouterProvider router={router} />
</TestWrapperWithoutRoutes>
);

// Wait for page title to be displayed
await waitFor(() => {
const titleElement = screen.getByRole("heading", { name: "Entity1" });
expect(titleElement).toBeInTheDocument();
});
});
});
197 changes: 197 additions & 0 deletions frontend/src/pages/AliasEntryListPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import { EntryBase } from "@dmm-com/airone-apiclient-typescript-fetch";
import AppsIcon from "@mui/icons-material/Apps";
import { Box, Container, Grid, IconButton } from "@mui/material";
import { useSnackbar } from "notistack";
import React, { FC, useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { useLocation } from "react-use";

import { useAsyncWithThrow } from "../hooks/useAsyncWithThrow";
import { useTypedParams } from "../hooks/useTypedParams";

import { PaginationFooter } from "components";
import { PageHeader } from "components/common/PageHeader";
import { SearchBox } from "components/common/SearchBox";
import { EntityBreadcrumbs } from "components/entity/EntityBreadcrumbs";
import { EntityControlMenu } from "components/entity/EntityControlMenu";
import { AliasEntryList } from "components/entry/AliasEntryList";
import { EntryImportModal } from "components/entry/EntryImportModal";
import { useFormNotification, usePage } from "hooks";
import { aironeApiClient } from "repository/AironeApiClient";
import {
EntryListParam,
extractAPIException,
isResponseError,
normalizeToMatch,
} from "services";

export const AliasEntryListPage: FC = ({}) => {
const { entityId } = useTypedParams<{
entityId: number;
}>();

const location = useLocation();
const params = new URLSearchParams(location.search);
const navigate = useNavigate();
const { enqueueSubmitResult } = useFormNotification("エイリアス", true);
const { enqueueSnackbar } = useSnackbar();
const [page, changePage] = usePage();
const [query, setQuery] = useState<string>(params.get("query") ?? "");

const [entityAnchorEl, setEntityAnchorEl] =
useState<HTMLButtonElement | null>(null);
const [openImportModal, setOpenImportModal] = React.useState(false);

const [entries, setEntries] = useState<EntryBase[]>([]);
const [totalCount, setTotalCount] = useState<number>(0);

const entity = useAsyncWithThrow(async () => {
return await aironeApiClient.getEntity(entityId);
}, [entityId]);

useEffect(() => {
aironeApiClient
.getEntries(entityId, true, page, query, true)
.then((res) => {
setEntries(res.results);
setTotalCount(res.count);
});
}, [page, query]);

const handleChangeQuery = (newQuery?: string) => {
changePage(1);
setQuery(newQuery ?? "");

navigate({
pathname: location.pathname,
search: newQuery ? `?query=${newQuery}` : "",
});
};

const handleCreate = (entryId: number, target: HTMLInputElement) => {
const name = target.value;
aironeApiClient
.createEntryAlias(entryId, name)
.then((resp) => {
setEntries(
entries.map((entry) => {
if (entry.id === entryId) {
return {
...entry,
aliases: [...entry.aliases, resp],
};
} else {
return entry;
}
})
);
target.value = "";
enqueueSubmitResult(true);
})
.catch((e) => {
if (e instanceof Error && isResponseError(e)) {
extractAPIException(
e,
(message) => enqueueSubmitResult(false, `詳細: "${message}"`),
(name, message) => enqueueSubmitResult(false, `詳細: "${message}"`)
);
} else {
enqueueSubmitResult(false);
}
});
};

const handleDelete = (id: number) => {
aironeApiClient
.deleteEntryAlias(id)
.then(() => {
setEntries(
entries.map((entry) => {
return {
...entry,
aliases: entry.aliases.filter((alias) => alias.id !== id),
};
})
);
enqueueSnackbar("エイリアスの削除が完了しました。", {
variant: "success",
});
})
.catch(() => {
enqueueSnackbar("エイリアスの削除が失敗しました。", {
variant: "error",
});
});
};

return (
<Box>
<EntityBreadcrumbs entity={entity.value} title="エイリアス設定" />

<PageHeader title={entity.value?.name ?? ""} description="エイリアス設定">
<Box width="50px">
<IconButton
id="entity_menu"
onClick={(e) => {
setEntityAnchorEl(e.currentTarget);
}}
>
<AppsIcon />
</IconButton>
<EntityControlMenu
entityId={entityId}
anchorElem={entityAnchorEl}
handleClose={() => setEntityAnchorEl(null)}
setOpenImportModal={setOpenImportModal}
/>
</Box>
</PageHeader>

<Container>
<Box width="600px" mb="16px">
<SearchBox
placeholder="アイテムを絞り込む"
onKeyPress={(e) => {
e.key === "Enter" &&
handleChangeQuery(
normalizeToMatch((e.target as HTMLInputElement).value ?? "")
);
}}
/>
</Box>
{/* show all Aliases that are associated with each Items */}
{entries.map((entry) => (
<Grid
key={entry.id}
container
my="4px"
display="flex"
alignItems="center"
>
<Grid item xs={4}>
{entry.name}
</Grid>
<Grid item xs={8}>
<AliasEntryList
entry={entry}
handleCreate={handleCreate}
handleDelete={handleDelete}
/>
</Grid>
</Grid>
))}
<PaginationFooter
count={totalCount}
maxRowCount={EntryListParam.MAX_ROW_COUNT}
page={page}
changePage={changePage}
/>
</Container>

<EntryImportModal
openImportModal={openImportModal}
closeImportModal={() => setOpenImportModal(false)}
/>
</Box>
);
};
Loading
Loading