feat: Promocode statistics modal

This commit is contained in:
IlyaDoronin 2024-03-26 18:41:22 +03:00
parent e4ecd541ff
commit fd80f38b4f
6 changed files with 577 additions and 261 deletions

@ -1,5 +1,12 @@
import { makeRequest } from "@frontend/kitui";
import { CreatePromocodeBody, GetPromocodeListBody, Promocode, PromocodeList } from "@root/model/promocodes";
import type {
CreatePromocodeBody,
GetPromocodeListBody,
Promocode,
PromocodeList,
PromocodeStatistics,
} from "@root/model/promocodes";
import { parseAxiosError } from "@root/utils/parse-error";
import { isAxiosError } from "axios";
@ -7,62 +14,84 @@ import { isAxiosError } from "axios";
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
const getPromocodeList = async (body: GetPromocodeListBody) => {
try {
const promocodeListResponse = await makeRequest<
GetPromocodeListBody,
PromocodeList
>({
url: baseUrl + "/getList",
method: "POST",
body,
useToken: false,
});
try {
const promocodeListResponse = await makeRequest<
GetPromocodeListBody,
PromocodeList
>({
url: baseUrl + "/getList",
method: "POST",
body,
useToken: false,
});
return promocodeListResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
return promocodeListResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
};
const createPromocode = async (body: CreatePromocodeBody) => {
try {
const createPromocodeResponse = await makeRequest<
CreatePromocodeBody,
Promocode
>({
url: baseUrl + "/create",
method: "POST",
body,
useToken: false,
});
try {
const createPromocodeResponse = await makeRequest<
CreatePromocodeBody,
Promocode
>({
url: baseUrl + "/create",
method: "POST",
body,
useToken: false,
});
return createPromocodeResponse;
} catch (nativeError) {
if (isAxiosError(nativeError) && nativeError.response?.data.error === "Duplicate Codeword") {
throw new Error(`Промокод уже существует`);
}
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка создания промокода. ${error}`);
return createPromocodeResponse;
} catch (nativeError) {
if (
isAxiosError(nativeError) &&
nativeError.response?.data.error === "Duplicate Codeword"
) {
throw new Error(`Промокод уже существует`);
}
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка создания промокода. ${error}`);
}
};
const deletePromocode = async (id: string): Promise<void> => {
try {
await makeRequest<never, never>({
url: `${baseUrl}/${id}`,
method: "DELETE",
useToken: false,
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка удаления промокода. ${error}`);
}
try {
await makeRequest<never, never>({
url: `${baseUrl}/${id}`,
method: "DELETE",
useToken: false,
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка удаления промокода. ${error}`);
}
};
const getPromocodeStatistics = async (id: string) => {
try {
const promocodeStatisticsResponse = await makeRequest<
unknown,
PromocodeStatistics[]
>({
url: baseUrl + `/getStatistics/${id}`,
method: "GET",
useToken: false,
});
return promocodeStatisticsResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении статистики промокода. ${error}`);
}
};
export const promocodeApi = {
getPromocodeList,
createPromocode,
deletePromocode,
getPromocodeList,
createPromocode,
deletePromocode,
getPromocodeStatistics,
};

@ -1,81 +1,119 @@
import { CreatePromocodeBody, PromocodeList } from "@root/model/promocodes";
import { enqueueSnackbar } from "notistack";
import { useCallback, useRef } from "react";
import useSwr, { mutate } from "swr";
import { enqueueSnackbar } from "notistack";
import { promocodeApi } from "./requests";
import type {
CreatePromocodeBody,
PromocodeList,
} from "@root/model/promocodes";
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;
export function usePromocodes(
page: number,
pageSize: number,
promocodeId: string
) {
const promocodesCountRef = useRef<number>(0);
const swrResponse = useSwr(
["promocodes", page, pageSize],
async (key) => {
const result = await promocodeApi.getPromocodeList({
limit: key[2],
filter: {
active: true,
},
{
onError(err) {
console.log("Error fetching promocodes", err);
enqueueSnackbar(err.message, { variant: "error" });
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,
}
);
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]
);
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;
return {
count: displayedData.count - 1,
items: displayedData.items.filter((item) => item.id !== id),
};
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
rollbackOnError: true,
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 {
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]
);
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;
const promocodeStatistics = useSwr(
["promocodeStatistics", promocodeId],
async ([_, id]) => {
if (!id) {
return null;
}
return {
count: displayedData.count - 1,
items: displayedData.items.filter((item) => item.id !== id),
};
},
rollbackOnError: true,
populateCache(result, currentData) {
if (!currentData) return;
const promocodeStatisticsResponse =
await promocodeApi.getPromocodeStatistics(id);
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 promocodeStatisticsResponse;
},
{
onError(err) {
console.log("Error fetching promocode statistics", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return {
...swrResponse,
createPromocode,
deletePromocode,
promocodesCount: promocodesCountRef.current,
};
}
return {
...swrResponse,
createPromocode,
deletePromocode,
promocodeStatistics: promocodeStatistics.data,
promocodesCount: promocodesCountRef.current,
};
}

@ -1,41 +1,48 @@
export type CreatePromocodeBody = {
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
bonus: {
privilege: {
privilegeID: string;
amount: number;
};
discount: {
layer: number;
factor: number;
target: string;
threshold: number;
};
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
bonus: {
privilege: {
privilegeID: string;
amount: number;
};
discount: {
layer: number;
factor: number;
target: string;
threshold: number;
};
};
};
export type GetPromocodeListBody = {
page: number;
limit: number;
filter: {
active: boolean;
text?: string;
};
page: number;
limit: number;
filter: {
active: boolean;
text?: string;
};
};
export type Promocode = CreatePromocodeBody & {
id: string;
outdated: boolean;
offLimit: boolean;
delete: boolean;
createdAt: string;
id: string;
outdated: boolean;
offLimit: boolean;
delete: boolean;
createdAt: string;
};
export type PromocodeList = {
count: number;
items: Promocode[];
count: number;
items: Promocode[];
};
export type PromocodeStatistics = {
id: string;
link: string;
useCount: number;
purchasesCount: number;
};

@ -0,0 +1,203 @@
import { useState } from "react";
import {
Box,
Button,
Typography,
Modal,
TextField,
useTheme,
useMediaQuery,
} from "@mui/material";
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import { fadeIn } from "@root/utils/style/keyframes";
import type { GridColDef } from "@mui/x-data-grid";
import type { PromocodeStatistics } from "@root/model/promocodes";
type StatisticsModalProps = {
id: string;
setId: (id: string) => void;
promocodeStatistics: PromocodeStatistics[] | null | undefined;
};
const COLUMNS: GridColDef<PromocodeStatistics, string>[] = [
{
field: "link",
headerName: "Ссылка",
width: 320,
sortable: false,
valueGetter: ({ row }) => row.link,
},
{
field: "useCount",
headerName: "Использований",
width: 120,
sortable: false,
valueGetter: ({ row }) => String(row.useCount),
},
{
field: "purchasesCount",
headerName: "Покупок",
width: 70,
sortable: false,
valueGetter: ({ row }) => String(row.purchasesCount),
},
];
export const StatisticsModal = ({
id,
setId,
promocodeStatistics,
}: StatisticsModalProps) => {
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(550));
return (
<Modal
open={Boolean(id)}
onClose={() => setId("")}
sx={{ "& > .MuiBox-root": { outline: "none" } }}
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: "95%",
maxWidth: "600px",
bgcolor: "background.paper",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
flexDirection: isMobile ? "column" : "row",
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
sx={{ maxWidth: "100px" }}
// onClick={() => }
>
Создать короткую ссылку
</Button>
<Button
sx={{ maxWidth: "100px" }}
// onClick={() => }
>
Обновить статистику
</Button>
</Box>
<Box sx={{ minWidth: "200px" }}>
<Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
<Typography sx={{ minWidth: "20px" }}>от</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={startDate}
onChange={(date) => date && setStartDate(date)}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
marginTop: "10px",
}}
>
<Typography sx={{ minWidth: "20px" }}>до</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={endDate}
onChange={(date) => date && setEndDate(date)}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
</Box>
</Box>
<DataGrid
disableSelectionOnClick={true}
rows={promocodeStatistics ?? []}
columns={COLUMNS}
sx={{
marginTop: "30px",
background: "#1F2126",
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,
}}
rowsPerPageOptions={[10, 25, 50, 100]}
autoHeight
/>
</Box>
</Modal>
);
};

@ -1,78 +1,96 @@
import { useState } from "react";
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 { usePromocodes } from "@root/api/promocode/swr";
import { fadeIn } from "@root/utils/style/keyframes";
import { useState } from "react";
import { CreatePromocodeForm } from "./CreatePromocodeForm";
import { usePromocodeGridColDef } from "./usePromocodeGridColDef";
import { StatisticsModal } from "./StatisticsModal";
export const PromocodeManagement = () => {
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);
const theme = useTheme();
const [showStatisticsModalId, setShowStatisticsModalId] =
useState<string>("");
const [page, setPage] = useState<number>(0);
const [pageSize, setPageSize] = useState<number>(10);
const {
data,
error,
isValidating,
promocodesCount,
promocodeStatistics,
deletePromocode,
createPromocode,
} = usePromocodes(page, pageSize, showStatisticsModalId);
const columns = usePromocodeGridColDef(
setShowStatisticsModalId,
deletePromocode
);
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
textTransform: "uppercase",
color: theme.palette.secondary.main,
}}
>
Создание промокода
</Typography>
<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>
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
textTransform: "uppercase",
color: theme.palette.secondary.main,
}}
>
Создание промокода
</Typography>
<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>
<StatisticsModal
id={showStatisticsModalId}
setId={setShowStatisticsModalId}
promocodeStatistics={promocodeStatistics}
/>
</LocalizationProvider>
);
};

@ -1,59 +1,80 @@
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,
import { BarChart, Delete } from "@mui/icons-material";
export function usePromocodeGridColDef(
setStatistics: (id: string) => void,
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 }) =>
Math.round(row.bonus.discount.factor * 1000) / 1000,
},
{
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: "settings",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton onClick={() => setStatistics(params.row.id)}>
<BarChart />
</IconButton>
);
},
{
field: "codeword",
headerName: "Кодовое слово",
width: 160,
sortable: false,
valueGetter: ({ row }) => row.codeword,
},
{
field: "delete",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton onClick={() => deletePromocode(params.row.id)}>
<Delete />
</IconButton>
);
},
{
field: "factor",
headerName: "Коэф. скидки",
width: 120,
sortable: false,
valueGetter: ({ row }) => Math.round(row.bonus.discount.factor * 1000) / 1000,
},
{
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]);
},
],
[deletePromocode, setStatistics]
);
}