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 baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
|
||||||
|
|
||||||
const getPromocodeList = async (
|
const getPromocodeList = async (body: GetPromocodeListBody) => {
|
||||||
body: GetPromocodeListBody
|
|
||||||
): Promise<Promocode[]> => {
|
|
||||||
try {
|
try {
|
||||||
const promocodeListResponse = await makeRequest<
|
const promocodeListResponse = await makeRequest<
|
||||||
GetPromocodeListBody,
|
GetPromocodeListBody,
|
||||||
@ -19,16 +17,14 @@ const getPromocodeList = async (
|
|||||||
useToken: false,
|
useToken: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
return promocodeListResponse.items;
|
return promocodeListResponse;
|
||||||
} catch (nativeError) {
|
} catch (nativeError) {
|
||||||
const [error] = parseAxiosError(nativeError);
|
const [error] = parseAxiosError(nativeError);
|
||||||
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const createPromocode = async (
|
const createPromocode = async (body: CreatePromocodeBody) => {
|
||||||
body: CreatePromocodeBody
|
|
||||||
): Promise<Promocode> => {
|
|
||||||
try {
|
try {
|
||||||
const createPromocodeResponse = await makeRequest<
|
const createPromocodeResponse = await makeRequest<
|
||||||
CreatePromocodeBody,
|
CreatePromocodeBody,
|
||||||
|
@ -1,69 +1,81 @@
|
|||||||
import { CreatePromocodeBody, Promocode } from "@root/model/promocodes";
|
import { CreatePromocodeBody, PromocodeList } from "@root/model/promocodes";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
import { useCallback, useRef } from "react";
|
||||||
import useSwr, { mutate } from "swr";
|
import useSwr, { mutate } from "swr";
|
||||||
import { promocodeApi } from "./requests";
|
import { promocodeApi } from "./requests";
|
||||||
|
|
||||||
export function usePromocodes() {
|
|
||||||
return useSwr(
|
export function usePromocodes(page: number, pageSize: number) {
|
||||||
"promocodes",
|
const promocodesCountRef = useRef<number>(0);
|
||||||
() => promocodeApi.getPromocodeList({
|
const swrResponse = useSwr(
|
||||||
limit: 100,
|
["promocodes", page, pageSize],
|
||||||
filter: {
|
async (key) => {
|
||||||
active: true,
|
const result = await promocodeApi.getPromocodeList({
|
||||||
},
|
limit: key[2],
|
||||||
page: 0,
|
filter: {
|
||||||
}),
|
active: true,
|
||||||
|
},
|
||||||
|
page: key[1],
|
||||||
|
});
|
||||||
|
|
||||||
|
promocodesCountRef.current = result.count;
|
||||||
|
return result;
|
||||||
|
},
|
||||||
{
|
{
|
||||||
onError(err) {
|
onError(err) {
|
||||||
console.log("Error fetching promocodes", err);
|
console.log("Error fetching promocodes", err);
|
||||||
enqueueSnackbar(err.message, { variant: "error" });
|
enqueueSnackbar(err.message, { variant: "error" });
|
||||||
},
|
},
|
||||||
focusThrottleInterval: 60e3,
|
focusThrottleInterval: 60e3,
|
||||||
|
keepPreviousData: true,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
export async function createPromocode(body: CreatePromocodeBody) {
|
const createPromocode = useCallback(async function (body: CreatePromocodeBody) {
|
||||||
try {
|
try {
|
||||||
await mutate<Promocode[] | undefined, Promocode>(
|
await promocodeApi.createPromocode(body);
|
||||||
"promocodes",
|
mutate(["promocodes", page, pageSize]);
|
||||||
promocodeApi.createPromocode(body),
|
} catch (error) {
|
||||||
{
|
console.log("Error creating promocode", error);
|
||||||
populateCache(result, currentData) {
|
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
||||||
if (!currentData) return;
|
}
|
||||||
|
}, [page, pageSize]);
|
||||||
|
|
||||||
return [...currentData, result];
|
const deletePromocode = useCallback(async function (id: string) {
|
||||||
},
|
try {
|
||||||
revalidate: false,
|
await mutate<PromocodeList | undefined, void>(
|
||||||
}
|
["promocodes", page, pageSize],
|
||||||
);
|
promocodeApi.deletePromocode(id),
|
||||||
} catch (error) {
|
{
|
||||||
console.log("Error creating promocode", error);
|
optimisticData(currentData, displayedData) {
|
||||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
if (!displayedData) return;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deletePromocode(id: string) {
|
return {
|
||||||
try {
|
count: displayedData.count - 1,
|
||||||
await mutate<Promocode[] | undefined, void>(
|
items: displayedData.items.filter((item) => item.id !== id),
|
||||||
"promocodes",
|
};
|
||||||
promocodeApi.deletePromocode(id),
|
},
|
||||||
{
|
rollbackOnError: true,
|
||||||
optimisticData(currentData, displayedData) {
|
populateCache(result, currentData) {
|
||||||
if (!displayedData) return;
|
if (!currentData) return;
|
||||||
|
|
||||||
return displayedData.filter((item) => item.id !== id);
|
return {
|
||||||
},
|
count: currentData.count - 1,
|
||||||
rollbackOnError: true,
|
items: currentData.items.filter((item) => item.id !== id),
|
||||||
populateCache(result, currentData) {
|
};
|
||||||
if (!currentData) return;
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} 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);
|
return {
|
||||||
},
|
...swrResponse,
|
||||||
}
|
createPromocode,
|
||||||
);
|
deletePromocode,
|
||||||
} catch (error) {
|
promocodesCount: promocodesCountRef.current,
|
||||||
console.log("Error deleting promocode", error);
|
};
|
||||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -36,6 +36,6 @@ export type Promocode = CreatePromocodeBody & {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type PromocodeList = {
|
export type PromocodeList = {
|
||||||
count: 0;
|
count: number;
|
||||||
items: Promocode[];
|
items: Promocode[];
|
||||||
};
|
};
|
||||||
|
@ -20,7 +20,7 @@ import { SERVICE_LIST } from "@root/model/privilege";
|
|||||||
import theme from "@root/theme";
|
import theme from "@root/theme";
|
||||||
|
|
||||||
import type { TextFieldProps } from "@mui/material";
|
import type { TextFieldProps } from "@mui/material";
|
||||||
import { createPromocode } from "@root/api/promocode/swr";
|
import { CreatePromocodeBody } from "@root/model/promocodes";
|
||||||
import type { ChangeEvent } from "react";
|
import type { ChangeEvent } from "react";
|
||||||
|
|
||||||
type BonusType = "discount" | "privilege";
|
type BonusType = "discount" | "privilege";
|
||||||
@ -53,7 +53,11 @@ const initialValues: FormValues = {
|
|||||||
threshold: 0,
|
threshold: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CreatePromocodeForm = () => {
|
type Props = {
|
||||||
|
createPromocode: (body: CreatePromocodeBody) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const CreatePromocodeForm = ({ createPromocode }: Props) => {
|
||||||
const [bonusType, setBonusType] = useState<BonusType>("discount");
|
const [bonusType, setBonusType] = useState<BonusType>("discount");
|
||||||
const { privileges } = usePrivilegeStore();
|
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 { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||||
|
|
||||||
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
|
||||||
import { PromocodesList } from "./PromocodesList";
|
|
||||||
|
|
||||||
import { usePromocodes } from "@root/api/promocode/swr";
|
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 = () => {
|
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 (error) return <Typography>Ошибка загрузки промокодов</Typography>;
|
||||||
if (isLoading) return <CircularProgress />;
|
|
||||||
if (!data) return null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||||
@ -32,8 +35,44 @@ export const PromocodeManagement = () => {
|
|||||||
>
|
>
|
||||||
Создание промокода
|
Создание промокода
|
||||||
</Typography>
|
</Typography>
|
||||||
<CreatePromocodeForm />
|
<CreatePromocodeForm createPromocode={createPromocode} />
|
||||||
<PromocodesList promocodes={data} />
|
<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>
|
</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