fix: statistics modal link

This commit is contained in:
IlyaDoronin 2024-04-02 16:21:17 +03:00
parent 78c3e9683d
commit 5f593cf8dc
4 changed files with 78 additions and 65 deletions

@ -33,16 +33,11 @@ const getPromocodeList = async (body: GetPromocodeListBody) => {
}; };
const createFastlink = async (id: string) => { const createFastlink = async (id: string) => {
try { try {
return await makeRequest< return await makeRequest<{ id: string }, { fastlink: string }>({
{id:string},
PromocodeList
>({
url: baseUrl + "/fastlink", url: baseUrl + "/fastlink",
method: "POST", method: "POST",
body: {id}, body: { id },
}); });
} catch (nativeError) { } catch (nativeError) {
const [error] = parseAxiosError(nativeError); const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при создании фастлинка. ${error}`); throw new Error(`Ошибка при создании фастлинка. ${error}`);
@ -115,22 +110,22 @@ const deletePromocode = async (id: string): Promise<void> => {
} }
}; };
const getPromocodeStatistics = async (id: string, from: number, to: number,) => { const getPromocodeStatistics = async (id: string, from: number, to: number) => {
try { try {
const promocodeStatisticsResponse = await makeRequest< const promocodeStatisticsResponse = await makeRequest<
unknown, unknown,
PromocodeStatistics[] PromocodeStatistics
>({ >({
url: baseUrl + `/stats`, url: baseUrl + `/stats`,
body: { body: {
"id": id, id: id,
"from": from, from: from,
"to": to to: to,
}, },
method: "POST", method: "POST",
useToken: false, useToken: false,
}); });
console.log(promocodeStatisticsResponse) console.log(promocodeStatisticsResponse);
return promocodeStatisticsResponse; return promocodeStatisticsResponse;
} catch (nativeError) { } catch (nativeError) {
const [error] = parseAxiosError(nativeError); const [error] = parseAxiosError(nativeError);

@ -33,6 +33,7 @@ export type Promocode = CreatePromocodeBody & {
offLimit: boolean; offLimit: boolean;
delete: boolean; delete: boolean;
createdAt: string; createdAt: string;
fastLinks: string[];
}; };
export type PromocodeList = { export type PromocodeList = {
@ -42,7 +43,6 @@ export type PromocodeList = {
export type PromocodeStatistics = { export type PromocodeStatistics = {
id: string; id: string;
link: string; usageCount: number;
useCount: number; usageMap: Record<string, number>;
purchasesCount: number;
}; };

@ -14,11 +14,12 @@ import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { fadeIn } from "@root/utils/style/keyframes"; import { fadeIn } from "@root/utils/style/keyframes";
import type { GridColDef } from "@mui/x-data-grid";
import type { PromocodeStatistics } from "@root/model/promocodes";
import moment from "moment"; import moment from "moment";
import { promocodeApi } from "@root/api/promocode/requests"; import { promocodeApi } from "@root/api/promocode/requests";
import ContentCopyIcon from '@mui/icons-material/ContentCopy'; import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import type { GridColDef } from "@mui/x-data-grid";
import type { Promocode } from "@root/model/promocodes";
type StatisticsModalProps = { type StatisticsModalProps = {
id: string; id: string;
@ -27,20 +28,29 @@ type StatisticsModalProps = {
setId: (id: string) => void; setId: (id: string) => void;
setTo: (date: number) => void; setTo: (date: number) => void;
setFrom: (date: number) => void; setFrom: (date: number) => void;
promocodes: Promocode[];
// promocodeStatistics: PromocodeStatistics[] | null | undefined; // promocodeStatistics: PromocodeStatistics[] | null | undefined;
// promocodeStatistics: any; // promocodeStatistics: any;
}; };
const COLUMNS: GridColDef<PromocodeStatistics, string>[] = [ type Row = {
id: number;
link: string;
useCount: number;
};
const COLUMNS: GridColDef<Row, string>[] = [
{ {
field: "copy", field: "copy",
headerName: "копировать", headerName: "копировать",
width: 50, width: 50,
sortable: false, sortable: false,
valueGetter: ({ row }) => String(row.purchasesCount), valueGetter: ({ row }) => String(row.useCount),
renderCell: (params) => { renderCell: (params) => {
return ( return (
<IconButton onClick={() => navigator.clipboard.writeText(params.row.link)}> <IconButton
onClick={() => navigator.clipboard.writeText(params.row.link)}
>
<ContentCopyIcon /> <ContentCopyIcon />
</IconButton> </IconButton>
); );
@ -65,15 +75,10 @@ const COLUMNS: GridColDef<PromocodeStatistics, string>[] = [
headerName: "Покупок", headerName: "Покупок",
width: 70, width: 70,
sortable: false, sortable: false,
valueGetter: ({ row }) => String(row.purchasesCount), valueGetter: ({ row }) => String(1),
}, },
]; ];
type ROW = {
link: string,
useCount: number
}
export const StatisticsModal = ({ export const StatisticsModal = ({
id, id,
setId, setId,
@ -81,40 +86,54 @@ export const StatisticsModal = ({
from, from,
to, to,
setTo, setTo,
//promocodeStatistics, promocodes,
}: StatisticsModalProps) => { }: StatisticsModalProps) => {
const [startDate, setStartDate] = useState<Date>(new Date()); const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date()); const [endDate, setEndDate] = useState<Date>(new Date());
const theme = useTheme(); const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(550)); const isMobile = useMediaQuery(theme.breakpoints.down(550));
const [general, setGeneral] = useState({}); const [general, setGeneral] = useState({});
const [rows, setRows] = useState([]); const [rows, setRows] = useState<Row[]>([]);
const createFastlink = async () => { const createFastlink = async () => {
await promocodeApi.createFastlink(id) await promocodeApi.createFastlink(id);
getParseData() getParseData();
} };
const getParseData = async () => { const getParseData = async () => {
const promocodeStatistics = await promocodeApi.getPromocodeStatistics(id, moment(startDate).unix(), moment(endDate).unix()) const promocodeStatistics = await promocodeApi.getPromocodeStatistics(
const rows = [] as ROW[] id,
//@ts-ignore moment(startDate).unix(),
for (const [key, value] of Object.entries(promocodeStatistics.usageMap)) { moment(endDate).unix()
rows.push({ );
link: key,
//@ts-ignore const rows = Object.values(promocodeStatistics.usageMap).map(
(value, index) => ({
link:
promocodes.find((promocode) => promocode.id === id)?.fastLinks[0] ??
"",
useCount: value, useCount: value,
id:rows.length id: index,
}) })
} ) as Row[];
setGeneral(promocodeStatistics)
//@ts-ignore setGeneral(promocodeStatistics);
setRows(rows) setRows(rows);
} };
useEffect(() => { useEffect(() => {
if (id.length > 0) getParseData() if (id.length > 0) {
}, [id]) getParseData();
}
if (!id) {
setRows([]);
setGeneral({});
}
}, [id]);
// const formatTo = to === null ? 0 : moment(to).unix() // const formatTo = to === null ? 0 : moment(to).unix()
// const formatFrom = from === null ? 0 : moment(from).unix() // const formatFrom = from === null ? 0 : moment(from).unix()
console.log(general) console.log(general);
// useEffect(() => { // useEffect(() => {
// (async () => { // (async () => {
// const gottenGeneral = await promocodeStatistics(id, startDate, endDate) // const gottenGeneral = await promocodeStatistics(id, startDate, endDate)
@ -125,9 +144,9 @@ export const StatisticsModal = ({
<Modal <Modal
open={Boolean(id)} open={Boolean(id)}
onClose={() => { onClose={() => {
setId("") setId("");
setStartDate(new Date()) setStartDate(new Date());
setEndDate(new Date()) setEndDate(new Date());
}} }}
sx={{ "& > .MuiBox-root": { outline: "none" } }} sx={{ "& > .MuiBox-root": { outline: "none" } }}
> >
@ -163,16 +182,10 @@ export const StatisticsModal = ({
alignItems: "center", alignItems: "center",
}} }}
> >
<Button <Button sx={{ maxWidth: "100px" }} onClick={createFastlink}>
sx={{ maxWidth: "100px" }}
onClick={createFastlink}
>
Создать короткую ссылку Создать короткую ссылку
</Button> </Button>
<Button <Button sx={{ maxWidth: "100px" }} onClick={getParseData}>
sx={{ maxWidth: "100px" }}
onClick={getParseData}
>
Обновить статистику Обновить статистику
</Button> </Button>
</Box> </Box>

@ -12,9 +12,9 @@ import DeleteModal from "./DeleteModal";
export const PromocodeManagement = () => { export const PromocodeManagement = () => {
const theme = useTheme(); const theme = useTheme();
const [deleteModal, setDeleteModal] = useState<string>("") const [deleteModal, setDeleteModal] = useState<string>("");
const deleteModalHC = (id:string) => setDeleteModal(id) const deleteModalHC = (id: string) => setDeleteModal(id);
const [showStatisticsModalId, setShowStatisticsModalId] = const [showStatisticsModalId, setShowStatisticsModalId] =
useState<string>(""); useState<string>("");
@ -35,7 +35,7 @@ export const PromocodeManagement = () => {
setShowStatisticsModalId, setShowStatisticsModalId,
deleteModalHC deleteModalHC
); );
console.log(showStatisticsModalId) console.log(showStatisticsModalId);
if (error) return <Typography>Ошибка загрузки промокодов</Typography>; if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
return ( return (
@ -101,8 +101,13 @@ export const PromocodeManagement = () => {
setTo={setTo} setTo={setTo}
from={from} from={from}
setFrom={setFrom} setFrom={setFrom}
promocodes={data?.items ?? []}
/>
<DeleteModal
id={deleteModal}
setModal={setDeleteModal}
deletePromocode={deletePromocode}
/> />
<DeleteModal id={deleteModal} setModal={setDeleteModal} deletePromocode={deletePromocode}/>
</LocalizationProvider> </LocalizationProvider>
); );
}; };