add promocode datagrid pagination
This commit is contained in:
parent
5021f260b0
commit
8978081198
@ -5,9 +5,7 @@ import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
|
||||
|
||||
const getPromocodeList = async (
|
||||
body: GetPromocodeListBody
|
||||
): Promise<Promocode[]> => {
|
||||
const getPromocodeList = async (body: GetPromocodeListBody) => {
|
||||
try {
|
||||
const promocodeListResponse = await makeRequest<
|
||||
GetPromocodeListBody,
|
||||
@ -19,16 +17,14 @@ const getPromocodeList = async (
|
||||
useToken: false,
|
||||
});
|
||||
|
||||
return promocodeListResponse.items;
|
||||
return promocodeListResponse;
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
const createPromocode = async (
|
||||
body: CreatePromocodeBody
|
||||
): Promise<Promocode> => {
|
||||
const createPromocode = async (body: CreatePromocodeBody) => {
|
||||
try {
|
||||
const createPromocodeResponse = await makeRequest<
|
||||
CreatePromocodeBody,
|
||||
|
@ -1,69 +1,81 @@
|
||||
import { CreatePromocodeBody, Promocode } from "@root/model/promocodes";
|
||||
import { CreatePromocodeBody, PromocodeList } from "@root/model/promocodes";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { useCallback, useRef } from "react";
|
||||
import useSwr, { mutate } from "swr";
|
||||
import { promocodeApi } from "./requests";
|
||||
|
||||
export function usePromocodes() {
|
||||
return useSwr(
|
||||
"promocodes",
|
||||
() => promocodeApi.getPromocodeList({
|
||||
limit: 100,
|
||||
filter: {
|
||||
active: true,
|
||||
},
|
||||
page: 0,
|
||||
}),
|
||||
|
||||
export function usePromocodes(page: number, pageSize: number) {
|
||||
const promocodesCountRef = useRef<number>(0);
|
||||
const swrResponse = useSwr(
|
||||
["promocodes", page, pageSize],
|
||||
async (key) => {
|
||||
const result = await promocodeApi.getPromocodeList({
|
||||
limit: key[2],
|
||||
filter: {
|
||||
active: true,
|
||||
},
|
||||
page: key[1],
|
||||
});
|
||||
|
||||
promocodesCountRef.current = result.count;
|
||||
return result;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.log("Error fetching promocodes", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function createPromocode(body: CreatePromocodeBody) {
|
||||
try {
|
||||
await mutate<Promocode[] | undefined, Promocode>(
|
||||
"promocodes",
|
||||
promocodeApi.createPromocode(body),
|
||||
{
|
||||
populateCache(result, currentData) {
|
||||
if (!currentData) return;
|
||||
const createPromocode = useCallback(async function (body: CreatePromocodeBody) {
|
||||
try {
|
||||
await promocodeApi.createPromocode(body);
|
||||
mutate(["promocodes", page, pageSize]);
|
||||
} catch (error) {
|
||||
console.log("Error creating promocode", error);
|
||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
}, [page, pageSize]);
|
||||
|
||||
return [...currentData, result];
|
||||
},
|
||||
revalidate: false,
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.log("Error creating promocode", error);
|
||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
}
|
||||
const deletePromocode = useCallback(async function (id: string) {
|
||||
try {
|
||||
await mutate<PromocodeList | undefined, void>(
|
||||
["promocodes", page, pageSize],
|
||||
promocodeApi.deletePromocode(id),
|
||||
{
|
||||
optimisticData(currentData, displayedData) {
|
||||
if (!displayedData) return;
|
||||
|
||||
export async function deletePromocode(id: string) {
|
||||
try {
|
||||
await mutate<Promocode[] | undefined, void>(
|
||||
"promocodes",
|
||||
promocodeApi.deletePromocode(id),
|
||||
{
|
||||
optimisticData(currentData, displayedData) {
|
||||
if (!displayedData) return;
|
||||
return {
|
||||
count: displayedData.count - 1,
|
||||
items: displayedData.items.filter((item) => item.id !== id),
|
||||
};
|
||||
},
|
||||
rollbackOnError: true,
|
||||
populateCache(result, currentData) {
|
||||
if (!currentData) return;
|
||||
|
||||
return displayedData.filter((item) => item.id !== id);
|
||||
},
|
||||
rollbackOnError: true,
|
||||
populateCache(result, currentData) {
|
||||
if (!currentData) return;
|
||||
return {
|
||||
count: currentData.count - 1,
|
||||
items: currentData.items.filter((item) => item.id !== id),
|
||||
};
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.log("Error deleting promocode", error);
|
||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
}, [page, pageSize]);
|
||||
|
||||
return currentData.filter((item) => item.id !== id);
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.log("Error deleting promocode", error);
|
||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
}
|
||||
return {
|
||||
...swrResponse,
|
||||
createPromocode,
|
||||
deletePromocode,
|
||||
promocodesCount: promocodesCountRef.current,
|
||||
};
|
||||
}
|
||||
|
@ -36,6 +36,6 @@ export type Promocode = CreatePromocodeBody & {
|
||||
};
|
||||
|
||||
export type PromocodeList = {
|
||||
count: 0;
|
||||
count: number;
|
||||
items: Promocode[];
|
||||
};
|
||||
|
@ -20,7 +20,7 @@ import { SERVICE_LIST } from "@root/model/privilege";
|
||||
import theme from "@root/theme";
|
||||
|
||||
import type { TextFieldProps } from "@mui/material";
|
||||
import { createPromocode } from "@root/api/promocode/swr";
|
||||
import { CreatePromocodeBody } from "@root/model/promocodes";
|
||||
import type { ChangeEvent } from "react";
|
||||
|
||||
type BonusType = "discount" | "privilege";
|
||||
@ -53,7 +53,11 @@ const initialValues: FormValues = {
|
||||
threshold: 0,
|
||||
};
|
||||
|
||||
export const CreatePromocodeForm = () => {
|
||||
type Props = {
|
||||
createPromocode: (body: CreatePromocodeBody) => Promise<void>;
|
||||
};
|
||||
|
||||
export const CreatePromocodeForm = ({ createPromocode }: Props) => {
|
||||
const [bonusType, setBonusType] = useState<BonusType>("discount");
|
||||
const { privileges } = usePrivilegeStore();
|
||||
|
||||
|
@ -1,93 +0,0 @@
|
||||
import { Box, IconButton } from "@mui/material";
|
||||
import { DataGrid, GridColDef, GridToolbar } from "@mui/x-data-grid";
|
||||
import { Promocode } from "@root/model/promocodes";
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
|
||||
import theme from "@root/theme";
|
||||
import { deletePromocode } from "@root/api/promocode/swr";
|
||||
|
||||
const columns: GridColDef<Promocode, string | number>[] = [
|
||||
{
|
||||
field: "id",
|
||||
headerName: "ID",
|
||||
width: 30,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.id,
|
||||
},
|
||||
{
|
||||
field: "codeword",
|
||||
headerName: "Кодовое слово",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.codeword,
|
||||
},
|
||||
{
|
||||
field: "factor",
|
||||
headerName: "Коэф. скидки",
|
||||
width: 140,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.bonus.discount.factor,
|
||||
},
|
||||
{
|
||||
field: "activationCount",
|
||||
headerName: "Кол-во активаций",
|
||||
width: 140,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.activationCount,
|
||||
},
|
||||
{
|
||||
field: "dueTo",
|
||||
headerName: "Истекает",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => new Date(row.dueTo * 1000).toLocaleString(),
|
||||
},
|
||||
{
|
||||
field: "delete",
|
||||
headerName: "",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton onClick={() => deletePromocode(row.id)}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
type Props = {
|
||||
promocodes: Promocode[];
|
||||
};
|
||||
|
||||
export const PromocodesList = ({ promocodes }: Props) => {
|
||||
|
||||
return (
|
||||
<Box style={{ width: "80%", marginTop: "55px" }}>
|
||||
<Box style={{ height: 400 }}>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
checkboxSelection={true}
|
||||
rows={promocodes}
|
||||
columns={columns}
|
||||
sx={{
|
||||
minHeight: "1000px",
|
||||
color: theme.palette.secondary.main,
|
||||
"& .MuiDataGrid-iconSeparator": { display: "none" },
|
||||
"& .css-levciy-MuiTablePagination-displayedRows": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiTablePagination-selectLabel": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiButton-text": { color: theme.palette.secondary.main },
|
||||
}}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
onSelectionModelChange={(ids) => console.log("datagrid select")}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
@ -1,19 +1,22 @@
|
||||
import { CircularProgress, Typography } from "@mui/material";
|
||||
import { Box, Typography, useTheme } from "@mui/material";
|
||||
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
|
||||
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
||||
import { PromocodesList } from "./PromocodesList";
|
||||
|
||||
import { usePromocodes } from "@root/api/promocode/swr";
|
||||
import theme from "@root/theme";
|
||||
import { fadeIn } from "@root/utils/style/keyframes";
|
||||
import { useState } from "react";
|
||||
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
||||
import { usePromocodeGridColDef } from "./usePromocodeGridColDef";
|
||||
|
||||
|
||||
export const PromocodeManagement = () => {
|
||||
const { data, error, isLoading } = usePromocodes();
|
||||
const theme = useTheme();
|
||||
const [page, setPage] = useState<number>(0);
|
||||
const [pageSize, setPageSize] = useState<number>(10);
|
||||
const { data, error, isValidating, promocodesCount, deletePromocode, createPromocode } = usePromocodes(page, pageSize);
|
||||
const columns = usePromocodeGridColDef(deletePromocode);
|
||||
|
||||
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
|
||||
if (isLoading) return <CircularProgress />;
|
||||
if (!data) return null;
|
||||
|
||||
return (
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
@ -32,8 +35,44 @@ export const PromocodeManagement = () => {
|
||||
>
|
||||
Создание промокода
|
||||
</Typography>
|
||||
<CreatePromocodeForm />
|
||||
<PromocodesList promocodes={data} />
|
||||
<CreatePromocodeForm createPromocode={createPromocode} />
|
||||
<Box style={{ width: "80%", marginTop: "55px" }}>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
rows={data?.items ?? []}
|
||||
columns={columns}
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"& .MuiDataGrid-iconSeparator": { display: "none" },
|
||||
"& .css-levciy-MuiTablePagination-displayedRows": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiTablePagination-selectLabel": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiButton-text": { color: theme.palette.secondary.main },
|
||||
"& .MuiDataGrid-overlay": {
|
||||
backgroundColor: "rgba(255, 255, 255, 0.1)",
|
||||
animation: `${fadeIn} 0.5s ease-out`,
|
||||
},
|
||||
}}
|
||||
components={{
|
||||
Toolbar: GridToolbar,
|
||||
LoadingOverlay: GridLoadingOverlay,
|
||||
}}
|
||||
loading={isValidating}
|
||||
paginationMode="server"
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
rowCount={promocodesCount}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
rowsPerPageOptions={[10, 25, 50, 100]}
|
||||
autoHeight
|
||||
/>
|
||||
</Box>
|
||||
</LocalizationProvider>
|
||||
);
|
||||
};
|
||||
|
@ -0,0 +1,59 @@
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import { IconButton } from "@mui/material";
|
||||
import { GridColDef } from "@mui/x-data-grid";
|
||||
import { Promocode } from "@root/model/promocodes";
|
||||
import { useMemo } from "react";
|
||||
|
||||
export function usePromocodeGridColDef(deletePromocode: (id: string) => void) {
|
||||
return useMemo<GridColDef<Promocode, string | number, string>[]>(() => [
|
||||
{
|
||||
field: "id",
|
||||
headerName: "ID",
|
||||
width: 30,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.id,
|
||||
},
|
||||
{
|
||||
field: "codeword",
|
||||
headerName: "Кодовое слово",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.codeword,
|
||||
},
|
||||
{
|
||||
field: "factor",
|
||||
headerName: "Коэф. скидки",
|
||||
width: 120,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.bonus.discount.factor,
|
||||
},
|
||||
{
|
||||
field: "activationCount",
|
||||
headerName: "Кол-во активаций",
|
||||
width: 140,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.activationCount,
|
||||
},
|
||||
{
|
||||
field: "dueTo",
|
||||
headerName: "Истекает",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.dueTo * 1000,
|
||||
valueFormatter: ({ value }) => new Date(value).toLocaleString(),
|
||||
},
|
||||
{
|
||||
field: "delete",
|
||||
headerName: "",
|
||||
width: 60,
|
||||
sortable: false,
|
||||
renderCell: (params) => {
|
||||
return (
|
||||
<IconButton onClick={() => deletePromocode(params.row.id)}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
], [deletePromocode]);
|
||||
}
|
11
src/utils/style/keyframes.ts
Normal file
11
src/utils/style/keyframes.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { keyframes } from "@emotion/react";
|
||||
|
||||
|
||||
export const fadeIn = keyframes`
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
Loading…
Reference in New Issue
Block a user