Merge branch 'dev' into 'staging'
upgrade kitui See merge request frontend/admin!62
This commit is contained in:
commit
db4465c48d
@ -6,7 +6,7 @@
|
|||||||
"@date-io/dayjs": "^2.15.0",
|
"@date-io/dayjs": "^2.15.0",
|
||||||
"@emotion/react": "^11.10.4",
|
"@emotion/react": "^11.10.4",
|
||||||
"@emotion/styled": "^11.10.4",
|
"@emotion/styled": "^11.10.4",
|
||||||
"@frontend/kitui": "^1.0.59",
|
"@frontend/kitui": "^1.0.77",
|
||||||
"@material-ui/pickers": "^3.3.10",
|
"@material-ui/pickers": "^3.3.10",
|
||||||
"@mui/icons-material": "^5.10.3",
|
"@mui/icons-material": "^5.10.3",
|
||||||
"@mui/material": "^5.10.5",
|
"@mui/material": "^5.10.5",
|
||||||
@ -36,6 +36,7 @@
|
|||||||
"numeral": "^2.0.6",
|
"numeral": "^2.0.6",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
|
"react-error-boundary": "^4.0.13",
|
||||||
"react-numeral": "^1.1.1",
|
"react-numeral": "^1.1.1",
|
||||||
"react-router-dom": "^6.3.0",
|
"react-router-dom": "^6.3.0",
|
||||||
"react-scripts": "^5.0.1",
|
"react-scripts": "^5.0.1",
|
||||||
|
@ -8,6 +8,8 @@ import type {
|
|||||||
DiscountType,
|
DiscountType,
|
||||||
GetDiscountResponse,
|
GetDiscountResponse,
|
||||||
} from "@root/model/discount";
|
} from "@root/model/discount";
|
||||||
|
import useSWR from "swr";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
|
||||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
|
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
|
||||||
|
|
||||||
@ -213,3 +215,33 @@ export const requestDiscounts = async (): Promise<
|
|||||||
return [null, `Ошибка получения скидок. ${error}`];
|
return [null, `Ошибка получения скидок. ${error}`];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async function getDiscounts() {
|
||||||
|
try {
|
||||||
|
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
|
||||||
|
url: baseUrl + "/discounts",
|
||||||
|
method: "get",
|
||||||
|
useToken: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return discountsResponse.Discounts.filter((discount) => !discount.Deprecated);
|
||||||
|
} catch (nativeError) {
|
||||||
|
const [error] = parseAxiosError(nativeError);
|
||||||
|
|
||||||
|
throw new Error(`Ошибка получения списка скидок. ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDiscounts() {
|
||||||
|
const { data } = useSWR("discounts", getDiscounts, {
|
||||||
|
keepPreviousData: true,
|
||||||
|
suspense: true,
|
||||||
|
onError: (error) => {
|
||||||
|
if (!(error instanceof Error)) return;
|
||||||
|
|
||||||
|
enqueueSnackbar(error.message, { variant: "error" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import { makeRequest } from "@frontend/kitui";
|
import { CustomPrivilege, makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
import { parseAxiosError } from "@root/utils/parse-error";
|
import { parseAxiosError } from "@root/utils/parse-error";
|
||||||
|
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
import type { TMockData } from "./roles";
|
import type { TMockData } from "./roles";
|
||||||
|
|
||||||
type SeverPrivilegesResponse = {
|
type SeverPrivilegesResponse = {
|
||||||
templategen: PrivilegeWithAmount[];
|
templategen: CustomPrivilege[];
|
||||||
squiz: PrivilegeWithAmount[];
|
squiz: CustomPrivilege[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
|
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
|
||||||
@ -28,11 +28,11 @@ export const getRoles = async (): Promise<[TMockData | null, string?]> => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const putPrivilege = async (
|
export const putPrivilege = async (
|
||||||
body: Omit<PrivilegeWithAmount, "_id" | "updatedAt">
|
body: Omit<Privilege, "_id" | "updatedAt">
|
||||||
): Promise<[unknown, string?]> => {
|
): Promise<[unknown, string?]> => {
|
||||||
try {
|
try {
|
||||||
const putedPrivilege = await makeRequest<
|
const putedPrivilege = await makeRequest<
|
||||||
Omit<PrivilegeWithAmount, "_id" | "updatedAt">,
|
Omit<Privilege, "_id" | "updatedAt">,
|
||||||
unknown
|
unknown
|
||||||
>({
|
>({
|
||||||
url: baseUrl + "/privilege",
|
url: baseUrl + "/privilege",
|
||||||
@ -70,9 +70,9 @@ export const requestServicePrivileges = async (): Promise<
|
|||||||
|
|
||||||
export const requestPrivileges = async (
|
export const requestPrivileges = async (
|
||||||
signal: AbortSignal | undefined
|
signal: AbortSignal | undefined
|
||||||
): Promise<[PrivilegeWithAmount[], string?]> => {
|
): Promise<[CustomPrivilege[], string?]> => {
|
||||||
try {
|
try {
|
||||||
const privilegesResponse = await makeRequest<never, PrivilegeWithAmount[]>(
|
const privilegesResponse = await makeRequest<never, CustomPrivilege[]>(
|
||||||
{
|
{
|
||||||
url: baseUrl + "/privilege",
|
url: baseUrl + "/privilege",
|
||||||
method: "get",
|
method: "get",
|
||||||
|
@ -1,7 +1,15 @@
|
|||||||
import { makeRequest } from "@frontend/kitui";
|
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 { parseAxiosError } from "@root/utils/parse-error";
|
||||||
|
import { isAxiosError } from "axios";
|
||||||
|
|
||||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
|
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
|
||||||
|
|
||||||
@ -23,6 +31,45 @@ const getPromocodeList = async (body: GetPromocodeListBody) => {
|
|||||||
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const createFastlink = async (id: string) => {
|
||||||
|
try {
|
||||||
|
return await makeRequest<{ id: string }, { fastlink: string }>({
|
||||||
|
url: baseUrl + "/fastlink",
|
||||||
|
method: "POST",
|
||||||
|
body: { id },
|
||||||
|
});
|
||||||
|
} catch (nativeError) {
|
||||||
|
const [error] = parseAxiosError(nativeError);
|
||||||
|
throw new Error(`Ошибка при создании фастлинка. ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAllPromocodes = async () => {
|
||||||
|
try {
|
||||||
|
const promocodes: Promocode[] = [];
|
||||||
|
|
||||||
|
let page = 0;
|
||||||
|
while (true) {
|
||||||
|
const promocodeList = await getPromocodeList({
|
||||||
|
limit: 2,
|
||||||
|
filter: {
|
||||||
|
active: true,
|
||||||
|
},
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (promocodeList.items.length === 0) break;
|
||||||
|
|
||||||
|
promocodes.push(...promocodeList.items);
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return promocodes;
|
||||||
|
} catch (nativeError) {
|
||||||
|
const [error] = parseAxiosError(nativeError);
|
||||||
|
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const createPromocode = async (body: CreatePromocodeBody) => {
|
const createPromocode = async (body: CreatePromocodeBody) => {
|
||||||
try {
|
try {
|
||||||
@ -38,6 +85,13 @@ const createPromocode = async (body: CreatePromocodeBody) => {
|
|||||||
|
|
||||||
return createPromocodeResponse;
|
return createPromocodeResponse;
|
||||||
} catch (nativeError) {
|
} catch (nativeError) {
|
||||||
|
if (
|
||||||
|
isAxiosError(nativeError) &&
|
||||||
|
nativeError.response?.data.error === "Duplicate Codeword"
|
||||||
|
) {
|
||||||
|
throw new Error(`Промокод уже существует`);
|
||||||
|
}
|
||||||
|
|
||||||
const [error] = parseAxiosError(nativeError);
|
const [error] = parseAxiosError(nativeError);
|
||||||
throw new Error(`Ошибка создания промокода. ${error}`);
|
throw new Error(`Ошибка создания промокода. ${error}`);
|
||||||
}
|
}
|
||||||
@ -56,8 +110,34 @@ const deletePromocode = async (id: string): Promise<void> => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getPromocodeStatistics = async (id: string, from: number, to: number) => {
|
||||||
|
try {
|
||||||
|
const promocodeStatisticsResponse = await makeRequest<
|
||||||
|
unknown,
|
||||||
|
PromocodeStatistics
|
||||||
|
>({
|
||||||
|
url: baseUrl + `/stats`,
|
||||||
|
body: {
|
||||||
|
id: id,
|
||||||
|
from: from,
|
||||||
|
to: to,
|
||||||
|
},
|
||||||
|
method: "POST",
|
||||||
|
useToken: false,
|
||||||
|
});
|
||||||
|
console.log(promocodeStatisticsResponse);
|
||||||
|
return promocodeStatisticsResponse;
|
||||||
|
} catch (nativeError) {
|
||||||
|
const [error] = parseAxiosError(nativeError);
|
||||||
|
throw new Error(`Ошибка при получении статистики промокода. ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const promocodeApi = {
|
export const promocodeApi = {
|
||||||
getPromocodeList,
|
getPromocodeList,
|
||||||
createPromocode,
|
createPromocode,
|
||||||
deletePromocode,
|
deletePromocode,
|
||||||
|
getAllPromocodes,
|
||||||
|
getPromocodeStatistics,
|
||||||
|
createFastlink,
|
||||||
};
|
};
|
||||||
|
@ -1,11 +1,20 @@
|
|||||||
import { CreatePromocodeBody, PromocodeList } from "@root/model/promocodes";
|
|
||||||
import { enqueueSnackbar } from "notistack";
|
|
||||||
import { useCallback, useRef } from "react";
|
import { useCallback, useRef } from "react";
|
||||||
import useSwr, { mutate } from "swr";
|
import useSwr, { mutate } from "swr";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { promocodeApi } from "./requests";
|
import { promocodeApi } from "./requests";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
CreatePromocodeBody,
|
||||||
|
PromocodeList,
|
||||||
|
} from "@root/model/promocodes";
|
||||||
|
|
||||||
export function usePromocodes(page: number, pageSize: number) {
|
export function usePromocodes(
|
||||||
|
page: number,
|
||||||
|
pageSize: number,
|
||||||
|
promocodeId: string,
|
||||||
|
to: number,
|
||||||
|
from: number
|
||||||
|
) {
|
||||||
const promocodesCountRef = useRef<number>(0);
|
const promocodesCountRef = useRef<number>(0);
|
||||||
const swrResponse = useSwr(
|
const swrResponse = useSwr(
|
||||||
["promocodes", page, pageSize],
|
["promocodes", page, pageSize],
|
||||||
@ -31,17 +40,22 @@ export function usePromocodes(page: number, pageSize: number) {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const createPromocode = useCallback(async function (body: CreatePromocodeBody) {
|
const createPromocode = useCallback(
|
||||||
|
async function (body: CreatePromocodeBody) {
|
||||||
try {
|
try {
|
||||||
await promocodeApi.createPromocode(body);
|
await promocodeApi.createPromocode(body);
|
||||||
mutate(["promocodes", page, pageSize]);
|
mutate(["promocodes", page, pageSize]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error creating promocode", error);
|
console.log("Error creating promocode", error);
|
||||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
if (error instanceof Error)
|
||||||
|
enqueueSnackbar(error.message, { variant: "error" });
|
||||||
}
|
}
|
||||||
}, [page, pageSize]);
|
},
|
||||||
|
[page, pageSize]
|
||||||
|
);
|
||||||
|
|
||||||
const deletePromocode = useCallback(async function (id: string) {
|
const deletePromocode = useCallback(
|
||||||
|
async function (id: string) {
|
||||||
try {
|
try {
|
||||||
await mutate<PromocodeList | undefined, void>(
|
await mutate<PromocodeList | undefined, void>(
|
||||||
["promocodes", page, pageSize],
|
["promocodes", page, pageSize],
|
||||||
@ -68,14 +82,65 @@ export function usePromocodes(page: number, pageSize: number) {
|
|||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error deleting promocode", error);
|
console.log("Error deleting promocode", error);
|
||||||
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
|
if (error instanceof Error)
|
||||||
|
enqueueSnackbar(error.message, { variant: "error" });
|
||||||
}
|
}
|
||||||
}, [page, pageSize]);
|
},
|
||||||
|
[page, pageSize]
|
||||||
|
);
|
||||||
|
|
||||||
|
const promocodeStatistics = useSwr(
|
||||||
|
["promocodeStatistics", promocodeId, from, to],
|
||||||
|
async ([_, id, from, to]) => {
|
||||||
|
if (!id) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const promocodeStatisticsResponse =
|
||||||
|
await promocodeApi.getPromocodeStatistics(id, from, to);
|
||||||
|
|
||||||
|
return promocodeStatisticsResponse;
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onError(err) {
|
||||||
|
console.log("Error fetching promocode statistics", err);
|
||||||
|
enqueueSnackbar(err.message, { variant: "error" });
|
||||||
|
},
|
||||||
|
focusThrottleInterval: 60e3,
|
||||||
|
keepPreviousData: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const createFastLink = useCallback(async function (id: string) {
|
||||||
|
try {
|
||||||
|
await promocodeApi.createFastlink(id);
|
||||||
|
mutate(["promocodes", page, pageSize]);
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error creating fast link", error);
|
||||||
|
if (error instanceof Error)
|
||||||
|
enqueueSnackbar(error.message, { variant: "error" });
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...swrResponse,
|
...swrResponse,
|
||||||
createPromocode,
|
createPromocode,
|
||||||
deletePromocode,
|
deletePromocode,
|
||||||
|
createFastLink,
|
||||||
|
promocodeStatistics: promocodeStatistics.data,
|
||||||
promocodesCount: promocodesCountRef.current,
|
promocodesCount: promocodesCountRef.current,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useAllPromocodes() {
|
||||||
|
const swrResponse = useSwr("allPromocodes", promocodeApi.getAllPromocodes, {
|
||||||
|
keepPreviousData: true,
|
||||||
|
suspense: true,
|
||||||
|
onError(err) {
|
||||||
|
console.log("Error fetching all promocodes", err);
|
||||||
|
enqueueSnackbar(err.message, { variant: "error" });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return swrResponse.data;
|
||||||
|
}
|
||||||
|
28
src/api/quizStatistic.ts
Normal file
28
src/api/quizStatistic.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import { makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
|
export type QuizStatisticResponse = {
|
||||||
|
Registrations: number;
|
||||||
|
Quizes: number;
|
||||||
|
Results: number
|
||||||
|
};
|
||||||
|
|
||||||
|
type TRequest = {
|
||||||
|
to: number;
|
||||||
|
from: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getStatistic = async (
|
||||||
|
to: number,
|
||||||
|
from: number,
|
||||||
|
): Promise<QuizStatisticResponse> => {
|
||||||
|
try {
|
||||||
|
const generalResponse = await makeRequest<TRequest, QuizStatisticResponse>({
|
||||||
|
url: `${process.env.REACT_APP_DOMAIN}/squiz/statistic`,
|
||||||
|
body: { to, from }
|
||||||
|
})
|
||||||
|
return generalResponse;
|
||||||
|
} catch (nativeError) {
|
||||||
|
|
||||||
|
return { Registrations: 0, Quizes: 0, Results: 0 };
|
||||||
|
}
|
||||||
|
};
|
@ -2,7 +2,7 @@ import { makeRequest } from "@frontend/kitui";
|
|||||||
|
|
||||||
import { parseAxiosError } from "@root/utils/parse-error";
|
import { parseAxiosError } from "@root/utils/parse-error";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { Privilege } from "@frontend/kitui";
|
||||||
import type { Tariff } from "@frontend/kitui";
|
import type { Tariff } from "@frontend/kitui";
|
||||||
import type { EditTariffRequestBody } from "@root/model/tariff";
|
import type { EditTariffRequestBody } from "@root/model/tariff";
|
||||||
|
|
||||||
@ -12,7 +12,7 @@ type CreateTariffBackendRequest = {
|
|||||||
order: number;
|
order: number;
|
||||||
price: number;
|
price: number;
|
||||||
isCustom: boolean;
|
isCustom: boolean;
|
||||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||||
};
|
};
|
||||||
|
|
||||||
type GetTariffsResponse = {
|
type GetTariffsResponse = {
|
||||||
@ -52,7 +52,7 @@ export const putTariff = async (tariff: Tariff): Promise<[null, string?]> => {
|
|||||||
price: tariff.price ?? 0,
|
price: tariff.price ?? 0,
|
||||||
isCustom: false,
|
isCustom: false,
|
||||||
order: tariff.order || 1,
|
order: tariff.order || 1,
|
||||||
description: tariff.description,
|
description: tariff.description ?? "",
|
||||||
privileges: tariff.privileges,
|
privileges: tariff.privileges,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
@ -24,9 +24,11 @@ import { PromocodeManagement } from "@root/pages/dashboard/Content/PromocodeMana
|
|||||||
import { SettingRoles } from "@pages/Setting/SettingRoles";
|
import { SettingRoles } from "@pages/Setting/SettingRoles";
|
||||||
import Support from "@pages/dashboard/Content/Support/Support";
|
import Support from "@pages/dashboard/Content/Support/Support";
|
||||||
import ChatImageNewWindow from "@pages/dashboard/Content/Support/ChatImageNewWindow";
|
import ChatImageNewWindow from "@pages/dashboard/Content/Support/ChatImageNewWindow";
|
||||||
|
import QuizStatistic from "@pages/dashboard/Content/QuizStatistic";
|
||||||
|
|
||||||
import theme from "./theme";
|
import theme from "./theme";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
import { makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
const componentsArray = [
|
const componentsArray = [
|
||||||
["/users", <Users />],
|
["/users", <Users />],
|
||||||
@ -104,6 +106,14 @@ root.render(
|
|||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/quizStatistic"
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<QuizStatistic />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
{componentsArray.map((element) => (
|
{componentsArray.map((element) => (
|
||||||
<Route
|
<Route
|
||||||
key={element[0]}
|
key={element[0]}
|
||||||
|
@ -1,36 +1,38 @@
|
|||||||
|
import { calcCart } from "@frontend/kitui";
|
||||||
|
import Input from "@kitUI/input";
|
||||||
import {
|
import {
|
||||||
Button,
|
|
||||||
Paper,
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
TableHead,
|
|
||||||
TableRow,
|
|
||||||
TableCell,
|
|
||||||
TableBody,
|
|
||||||
Table,
|
|
||||||
Alert,
|
Alert,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
Checkbox,
|
Checkbox,
|
||||||
FormControlLabel,
|
FormControlLabel,
|
||||||
useTheme, useMediaQuery
|
Paper,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
Typography,
|
||||||
|
useMediaQuery,
|
||||||
|
useTheme
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Input from "@kitUI/input";
|
import { useDiscounts } from "@root/api/discounts";
|
||||||
import { useState } from "react";
|
import { useAllPromocodes } from "@root/api/promocode/swr";
|
||||||
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
|
import { requestPrivileges } from "@root/services/privilegies.service";
|
||||||
import { setCartData, useCartStore } from "@root/stores/cart";
|
import { setCartData, useCartStore } from "@root/stores/cart";
|
||||||
import { useTariffStore } from "@root/stores/tariffs";
|
import { useTariffStore } from "@root/stores/tariffs";
|
||||||
import { useDiscountStore } from "@root/stores/discounts";
|
import { createDiscountFromPromocode } from "@root/utils/createDiscountFromPromocode";
|
||||||
import { requestPrivileges } from "@root/services/privilegies.service";
|
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
|
||||||
import { DiscountTooltip } from "./DiscountTooltip";
|
|
||||||
import CartItemRow from "./CartItemRow";
|
|
||||||
import { calcCart, formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
|
||||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
|
import { useState } from "react";
|
||||||
|
import CartItemRow from "./CartItemRow";
|
||||||
|
|
||||||
|
|
||||||
export default function Cart() {
|
export default function Cart() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
||||||
let discounts = useDiscountStore(state => state.discounts);
|
const discounts = useDiscounts();
|
||||||
|
const promocodes = useAllPromocodes();
|
||||||
const cartData = useCartStore((store) => store.cartData);
|
const cartData = useCartStore((store) => store.cartData);
|
||||||
const tariffs = useTariffStore(state => state.tariffs);
|
const tariffs = useTariffStore(state => state.tariffs);
|
||||||
const [couponField, setCouponField] = useState<string>("");
|
const [couponField, setCouponField] = useState<string>("");
|
||||||
@ -39,10 +41,6 @@ export default function Cart() {
|
|||||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||||
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||||
|
|
||||||
const cartDiscounts = [cartData?.appliedCartPurchasesDiscount, cartData?.appliedLoyaltyDiscount].filter((d): d is Discount => !!d);
|
|
||||||
|
|
||||||
const cartDiscountsResultFactor = findDiscountFactor(cartData?.appliedCartPurchasesDiscount) * findDiscountFactor(cartData?.appliedLoyaltyDiscount);
|
|
||||||
|
|
||||||
async function handleCalcCartClick() {
|
async function handleCalcCartClick() {
|
||||||
await requestPrivileges();
|
await requestPrivileges();
|
||||||
await requestDiscounts();
|
await requestDiscounts();
|
||||||
@ -53,8 +51,21 @@ export default function Cart() {
|
|||||||
|
|
||||||
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
||||||
|
|
||||||
|
const promocode = promocodes.find(promocode => {
|
||||||
|
if (promocode.dueTo < (Date.now() / 1000)) return false;
|
||||||
|
|
||||||
|
return promocode.codeword === couponField.trim();
|
||||||
|
});
|
||||||
|
|
||||||
|
const userId = crypto.randomUUID();
|
||||||
|
|
||||||
|
const discountsWithPromocodeDiscount = promocode ? [
|
||||||
|
...discounts,
|
||||||
|
createDiscountFromPromocode(promocode, userId),
|
||||||
|
] : discounts;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const cartData = calcCart(cartTariffs, discounts, loyaltyValue, couponField);
|
const cartData = calcCart(cartTariffs, discountsWithPromocodeDiscount, loyaltyValue, userId);
|
||||||
|
|
||||||
setErrorMessage(null);
|
setErrorMessage(null);
|
||||||
setCartData(cartData);
|
setCartData(cartData);
|
||||||
@ -224,45 +235,22 @@ export default function Cart() {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{cartData.services.flatMap(service => service.tariffs.map(taroffCartData => (
|
{cartData.services.flatMap(service => service.tariffs.map(tariffCartData => {
|
||||||
|
const appliedDiscounts = tariffCartData.privileges.flatMap(
|
||||||
|
privilege => Array.from(privilege.appliedDiscounts)
|
||||||
|
).sort((a, b) => a.Layer - b.Layer);
|
||||||
|
|
||||||
|
return (
|
||||||
<CartItemRow
|
<CartItemRow
|
||||||
tariffCartData={taroffCartData}
|
key={tariffCartData.id}
|
||||||
appliedServiceDiscount={service.appliedServiceDiscount}
|
tariffCartData={tariffCartData}
|
||||||
|
appliedDiscounts={appliedDiscounts}
|
||||||
/>
|
/>
|
||||||
)))}
|
);
|
||||||
|
}))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
|
|
||||||
<Typography
|
|
||||||
id="transition-modal-title"
|
|
||||||
variant="h6"
|
|
||||||
sx={{
|
|
||||||
fontWeight: "normal",
|
|
||||||
textAlign: "center",
|
|
||||||
marginTop: "15px",
|
|
||||||
fontSize: "16px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Скидки корзины:
|
|
||||||
{cartDiscounts && (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "inline-flex",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{cartDiscounts?.map((discount, index, arr) => (
|
|
||||||
<span key={discount.ID}>
|
|
||||||
<DiscountTooltip discount={discount} />
|
|
||||||
{index < arr.length - 1 && <span>, </span>}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{cartDiscountsResultFactor && `= ${formatDiscountFactor(cartDiscountsResultFactor)}`}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography
|
<Typography
|
||||||
id="transition-modal-title"
|
id="transition-modal-title"
|
||||||
variant="h6"
|
variant="h6"
|
||||||
|
@ -7,14 +7,12 @@ import { useEffect } from "react";
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
tariffCartData: TariffCartData;
|
tariffCartData: TariffCartData;
|
||||||
appliedServiceDiscount: Discount | null;
|
appliedDiscounts: Discount[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CartItemRow({ tariffCartData, appliedServiceDiscount }: Props) {
|
export default function CartItemRow({ tariffCartData, appliedDiscounts }: Props) {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const envolvedDiscounts = [tariffCartData.privileges[0].appliedPrivilegeDiscount, appliedServiceDiscount].filter((d): d is Discount => !!d);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (tariffCartData.privileges.length > 1) {
|
if (tariffCartData.privileges.length > 1) {
|
||||||
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
|
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
|
||||||
@ -39,22 +37,17 @@ export default function CartItemRow({ tariffCartData, appliedServiceDiscount }:
|
|||||||
{tariffCartData.privileges[0].description}
|
{tariffCartData.privileges[0].description}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
{envolvedDiscounts.map((discount, index, arr) => (
|
{appliedDiscounts.map((discount, index, arr) => (
|
||||||
<span key={discount.ID}>
|
<span key={discount.ID}>
|
||||||
<DiscountTooltip discount={discount} />
|
<DiscountTooltip discount={discount} />
|
||||||
{index < arr.length - (appliedServiceDiscount ? 0 : 1) && (
|
{index < arr.length - 1 && (
|
||||||
<span>, </span>
|
<span>, </span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{appliedServiceDiscount && (
|
|
||||||
<span>
|
|
||||||
<DiscountTooltip discount={appliedServiceDiscount} />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
{currencyFormatter.format(tariffCartData.price)}
|
{currencyFormatter.format(tariffCartData.price / 100)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
);
|
);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { Tooltip, Typography } from "@mui/material";
|
import { Tooltip, Typography } from "@mui/material";
|
||||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
||||||
import { formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
|
||||||
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@ -14,8 +14,9 @@ export function DiscountTooltip({ discount }: Props) {
|
|||||||
<Tooltip
|
<Tooltip
|
||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
<Typography>Скидка: {discount?.Name}</Typography>
|
<Typography>Слой: {discount.Layer}</Typography>
|
||||||
<Typography>{discount?.Description}</Typography>
|
<Typography>Название: {discount.Name}</Typography>
|
||||||
|
<Typography>Описание: {discount.Description}</Typography>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
export interface Promocode {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
endless: boolean;
|
|
||||||
from: string;
|
|
||||||
dueTo: string;
|
|
||||||
privileges: string[];
|
|
||||||
}
|
|
@ -33,9 +33,16 @@ export type Promocode = CreatePromocodeBody & {
|
|||||||
offLimit: boolean;
|
offLimit: boolean;
|
||||||
delete: boolean;
|
delete: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
fastLinks: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PromocodeList = {
|
export type PromocodeList = {
|
||||||
count: number;
|
count: number;
|
||||||
items: Promocode[];
|
items: Promocode[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type PromocodeStatistics = {
|
||||||
|
id: string;
|
||||||
|
usageCount: number;
|
||||||
|
usageMap: Record<string, number>;
|
||||||
|
};
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
|
|
||||||
export const SERVICE_LIST = [
|
export const SERVICE_LIST = [
|
||||||
{
|
{
|
||||||
@ -25,5 +25,5 @@ export type EditTariffRequestBody = {
|
|||||||
order: number;
|
order: number;
|
||||||
price: number;
|
price: number;
|
||||||
isCustom: boolean;
|
isCustom: boolean;
|
||||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||||
};
|
};
|
||||||
|
@ -2,14 +2,14 @@ import { KeyboardEvent, useRef, useState } from "react";
|
|||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
|
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
|
||||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { CustomPrivilege } from "@frontend/kitui";
|
||||||
import { putPrivilege } from "@root/api/privilegies";
|
import { putPrivilege } from "@root/api/privilegies";
|
||||||
import SaveIcon from '@mui/icons-material/Save';
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
|
|
||||||
|
|
||||||
interface CardPrivilege {
|
interface CardPrivilege {
|
||||||
privilege: PrivilegeWithAmount;
|
privilege: CustomPrivilege;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||||
@ -27,7 +27,7 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
|||||||
|
|
||||||
const putPrivileges = async () => {
|
const putPrivileges = async () => {
|
||||||
|
|
||||||
const [_, putedPrivilegeError] = await putPrivilege({
|
const [, putedPrivilegeError] = await putPrivilege({
|
||||||
name: privilege.name,
|
name: privilege.name,
|
||||||
privilegeId: privilege.privilegeId,
|
privilegeId: privilege.privilegeId,
|
||||||
serviceKey: privilege.serviceKey,
|
serviceKey: privilege.serviceKey,
|
||||||
|
@ -6,6 +6,7 @@ import { changeDiscount } from "@root/api/discounts";
|
|||||||
import { findDiscountsById } from "@root/stores/discounts";
|
import { findDiscountsById } from "@root/stores/discounts";
|
||||||
|
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedRows: GridSelectionModel;
|
selectedRows: GridSelectionModel;
|
||||||
@ -24,7 +25,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
|||||||
return enqueueSnackbar("Скидка не найдена");
|
return enqueueSnackbar("Скидка не найдена");
|
||||||
}
|
}
|
||||||
|
|
||||||
const [_, changedDiscountError] = await changeDiscount(String(id), {
|
const [, changedDiscountError] = await changeDiscount(String(id), {
|
||||||
...discount,
|
...discount,
|
||||||
Deprecated: isActive,
|
Deprecated: isActive,
|
||||||
});
|
});
|
||||||
@ -34,6 +35,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
|||||||
} else {
|
} else {
|
||||||
fatal += 1;
|
fatal += 1;
|
||||||
}
|
}
|
||||||
|
mutate("discounts");
|
||||||
}
|
}
|
||||||
|
|
||||||
await requestDiscounts();
|
await requestDiscounts();
|
||||||
|
@ -23,6 +23,7 @@ import { DiscountType, discountTypes } from "@root/model/discount";
|
|||||||
import { createDiscount } from "@root/api/discounts";
|
import { createDiscount } from "@root/api/discounts";
|
||||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
interface Values {
|
interface Values {
|
||||||
discountNameField: string,
|
discountNameField: string,
|
||||||
@ -92,6 +93,7 @@ export default function CreateDiscount() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (createdDiscountResponse) {
|
if (createdDiscountResponse) {
|
||||||
|
mutate("discounts");
|
||||||
addDiscount(createdDiscountResponse);
|
addDiscount(createdDiscountResponse);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,8 @@ import { deleteDiscount } from "@root/api/discounts";
|
|||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
import { formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
// {
|
// {
|
||||||
@ -93,6 +94,7 @@ const columns: GridColDef[] = [
|
|||||||
disabled={row.deleted}
|
disabled={row.deleted}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
deleteDiscount(row.id).then(([discount]) => {
|
deleteDiscount(row.id).then(([discount]) => {
|
||||||
|
mutate("discounts");
|
||||||
if (discount) {
|
if (discount) {
|
||||||
updateDiscount(discount);
|
updateDiscount(discount);
|
||||||
}
|
}
|
||||||
|
@ -31,6 +31,7 @@ import { getDiscountTypeFromLayer } from "@root/utils/discount";
|
|||||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
export default function EditDiscountDialog() {
|
export default function EditDiscountDialog() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@ -59,17 +60,17 @@ export default function EditDiscountDialog() {
|
|||||||
function setDiscountFields() {
|
function setDiscountFields() {
|
||||||
if (!discount) return;
|
if (!discount) return;
|
||||||
|
|
||||||
setServiceType(discount.Condition.Group);
|
setServiceType(discount.Condition.Group ?? "");
|
||||||
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
||||||
setDiscountNameField(discount.Name);
|
setDiscountNameField(discount.Name);
|
||||||
setDiscountDescriptionField(discount.Description);
|
setDiscountDescriptionField(discount.Description);
|
||||||
setPrivilegeIdField(discount.Condition.Product);
|
setPrivilegeIdField(discount.Condition.Product ?? "");
|
||||||
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
|
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
|
||||||
setPurchasesAmountField(discount.Condition.PurchasesAmount.toString());
|
setPurchasesAmountField(discount.Condition.PurchasesAmount ?? "");
|
||||||
setCartPurchasesAmountField(
|
setCartPurchasesAmountField(
|
||||||
discount.Condition.CartPurchasesAmount.toString()
|
discount.Condition.CartPurchasesAmount ?? ""
|
||||||
);
|
);
|
||||||
setDiscountMinValueField(discount.Condition.PriceFrom.toString());
|
setDiscountMinValueField(discount.Condition.PriceFrom ?? "");
|
||||||
},
|
},
|
||||||
[discount]
|
[discount]
|
||||||
);
|
);
|
||||||
@ -137,6 +138,7 @@ export default function EditDiscountDialog() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (patchedDiscountResponse) {
|
if (patchedDiscountResponse) {
|
||||||
|
mutate("discounts");
|
||||||
updateDiscount(patchedDiscountResponse);
|
updateDiscount(patchedDiscountResponse);
|
||||||
closeEditDiscountDialog();
|
closeEditDiscountDialog();
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,6 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
|
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
|
||||||
import { Field, Form, Formik } from "formik";
|
import { Field, Form, Formik } from "formik";
|
||||||
import moment from "moment";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
import { requestPrivileges } from "@root/services/privilegies.service";
|
import { requestPrivileges } from "@root/services/privilegies.service";
|
||||||
@ -135,10 +134,8 @@ export const CreatePromocodeForm = ({ createPromocode }: Props) => {
|
|||||||
as={DesktopDatePicker}
|
as={DesktopDatePicker}
|
||||||
inputFormat="DD/MM/YYYY"
|
inputFormat="DD/MM/YYYY"
|
||||||
value={values.dueTo ? new Date(Number(values.dueTo) * 1000) : null}
|
value={values.dueTo ? new Date(Number(values.dueTo) * 1000) : null}
|
||||||
onChange={(date: Date | null) => {
|
onChange={(event: any) => {
|
||||||
if (date) {
|
setFieldValue("dueTo", event.$d.getTime() / 1000 || null);
|
||||||
setFieldValue("dueTo", moment(date).unix() || null);
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
renderInput={(params: TextFieldProps) => <TextField {...params} />}
|
renderInput={(params: TextFieldProps) => <TextField {...params} />}
|
||||||
InputProps={{
|
InputProps={{
|
||||||
|
@ -0,0 +1,59 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import Box from '@mui/material/Box';
|
||||||
|
import Modal from '@mui/material/Modal';
|
||||||
|
import Button from '@mui/material/Button';
|
||||||
|
import { Typography } from '@mui/material';
|
||||||
|
|
||||||
|
const style = {
|
||||||
|
position: 'absolute' as 'absolute',
|
||||||
|
top: '50%',
|
||||||
|
left: '50%',
|
||||||
|
transform: 'translate(-50%, -50%)',
|
||||||
|
width: 400,
|
||||||
|
bgcolor: '#c1c1c1',
|
||||||
|
border: '2px solid #000',
|
||||||
|
boxShadow: 24,
|
||||||
|
pt: 2,
|
||||||
|
px: 4,
|
||||||
|
pb: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
id: string;
|
||||||
|
setModal: (id: string) => void;
|
||||||
|
deletePromocode: (id: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ({
|
||||||
|
id,
|
||||||
|
setModal,
|
||||||
|
deletePromocode
|
||||||
|
}: Props) {
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={Boolean(id)}
|
||||||
|
onClose={() => setModal("")}
|
||||||
|
>
|
||||||
|
<Box sx={{ ...style, width: 400 }}>
|
||||||
|
<Typography
|
||||||
|
variant='h5'
|
||||||
|
textAlign="center"
|
||||||
|
>Точно удалить промокод?</Typography>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-evenly",
|
||||||
|
mt: "15px"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
onClick={() => { deletePromocode(id); setModal("") }}
|
||||||
|
>Да</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => setModal("")}
|
||||||
|
>Нет</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
@ -0,0 +1,285 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Typography,
|
||||||
|
Modal,
|
||||||
|
TextField,
|
||||||
|
useTheme,
|
||||||
|
useMediaQuery,
|
||||||
|
IconButton,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
|
||||||
|
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||||
|
|
||||||
|
import { fadeIn } from "@root/utils/style/keyframes";
|
||||||
|
|
||||||
|
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||||
|
|
||||||
|
import type { GridColDef } from "@mui/x-data-grid";
|
||||||
|
import type { Promocode, PromocodeStatistics } from "@root/model/promocodes";
|
||||||
|
|
||||||
|
type StatisticsModalProps = {
|
||||||
|
id: string;
|
||||||
|
to: number;
|
||||||
|
from: number;
|
||||||
|
setId: (id: string) => void;
|
||||||
|
setTo: (date: number) => void;
|
||||||
|
setFrom: (date: number) => void;
|
||||||
|
promocodes: Promocode[];
|
||||||
|
promocodeStatistics: PromocodeStatistics | null | undefined;
|
||||||
|
createFastLink: (id: string) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Row = {
|
||||||
|
id: number;
|
||||||
|
link: string;
|
||||||
|
useCount: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const COLUMNS: GridColDef<Row, string>[] = [
|
||||||
|
{
|
||||||
|
field: "copy",
|
||||||
|
headerName: "копировать",
|
||||||
|
width: 50,
|
||||||
|
sortable: false,
|
||||||
|
valueGetter: ({ row }) => String(row.useCount),
|
||||||
|
renderCell: (params) => {
|
||||||
|
return (
|
||||||
|
<IconButton
|
||||||
|
onClick={() => navigator.clipboard.writeText(params.row.link)}
|
||||||
|
>
|
||||||
|
<ContentCopyIcon />
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "link",
|
||||||
|
headerName: "Ссылка",
|
||||||
|
width: 320,
|
||||||
|
sortable: false,
|
||||||
|
valueGetter: ({ row }) => row.link,
|
||||||
|
renderCell: ({ value }) =>
|
||||||
|
value?.split("|").map((link) => <Typography>{link}</Typography>),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "useCount",
|
||||||
|
headerName: "Использований",
|
||||||
|
width: 120,
|
||||||
|
sortable: false,
|
||||||
|
valueGetter: ({ row }) => String(row.useCount),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "purchasesCount",
|
||||||
|
headerName: "Покупок",
|
||||||
|
width: 70,
|
||||||
|
sortable: false,
|
||||||
|
valueGetter: ({ row }) => String(0),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const StatisticsModal = ({
|
||||||
|
id,
|
||||||
|
setId,
|
||||||
|
setFrom,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
setTo,
|
||||||
|
promocodeStatistics,
|
||||||
|
promocodes,
|
||||||
|
createFastLink,
|
||||||
|
}: 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));
|
||||||
|
const [rows, setRows] = useState<Row[]>([]);
|
||||||
|
const createFastlink = async () => {
|
||||||
|
await createFastLink(id);
|
||||||
|
|
||||||
|
getParseData();
|
||||||
|
};
|
||||||
|
|
||||||
|
const getParseData = async () => {
|
||||||
|
const rows = promocodes
|
||||||
|
.find((promocode) => promocode.id === id)
|
||||||
|
?.fastLinks?.map((link, index) => ({
|
||||||
|
link,
|
||||||
|
id: index,
|
||||||
|
useCount: promocodeStatistics?.usageMap[link] ?? 0,
|
||||||
|
})) as Row[];
|
||||||
|
|
||||||
|
setRows(rows);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (id.length > 0) {
|
||||||
|
getParseData();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
setRows([]);
|
||||||
|
}
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
// const formatTo = to === null ? 0 : moment(to).unix()
|
||||||
|
// const formatFrom = from === null ? 0 : moment(from).unix()
|
||||||
|
// useEffect(() => {
|
||||||
|
// (async () => {
|
||||||
|
// const gottenGeneral = await promocodeStatistics(id, startDate, endDate)
|
||||||
|
// setGeneral(gottenGeneral[0])
|
||||||
|
// })()
|
||||||
|
// }, [to, from]);
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={Boolean(id)}
|
||||||
|
onClose={() => {
|
||||||
|
setId("");
|
||||||
|
setStartDate(new Date());
|
||||||
|
setEndDate(new Date());
|
||||||
|
}}
|
||||||
|
sx={{ "& > .MuiBox-root": { outline: "none" } }}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
top: "50%",
|
||||||
|
left: "50%",
|
||||||
|
transform: "translate(-50%, -50%)",
|
||||||
|
width: "95%",
|
||||||
|
maxWidth: "600px",
|
||||||
|
background: "#1F2126",
|
||||||
|
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={createFastlink}>
|
||||||
|
Создать короткую ссылку
|
||||||
|
</Button>
|
||||||
|
<Button sx={{ maxWidth: "100px" }} onClick={getParseData}>
|
||||||
|
Обновить статистику
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ minWidth: "200px" }}>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
|
||||||
|
<Typography sx={{ minWidth: "20px", color: "#FFFFFF" }}>
|
||||||
|
от
|
||||||
|
</Typography>
|
||||||
|
<DatePicker
|
||||||
|
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", color: "#FFFFFF" }}>
|
||||||
|
до
|
||||||
|
</Typography>
|
||||||
|
<DatePicker
|
||||||
|
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={rows}
|
||||||
|
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`,
|
||||||
|
},
|
||||||
|
"& .MuiDataGrid-virtualScrollerContent": { maxHeight: "200px" },
|
||||||
|
"& .MuiDataGrid-virtualScrollerRenderZone": {
|
||||||
|
maxHeight: "200px",
|
||||||
|
overflowY: "auto",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Toolbar: GridToolbar,
|
||||||
|
LoadingOverlay: GridLoadingOverlay,
|
||||||
|
}}
|
||||||
|
rowsPerPageOptions={[10, 25, 50, 100]}
|
||||||
|
autoHeight
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
@ -1,21 +1,42 @@
|
|||||||
|
import { useState } from "react";
|
||||||
import { Box, Typography, useTheme } from "@mui/material";
|
import { Box, Typography, useTheme } from "@mui/material";
|
||||||
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
|
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 { usePromocodes } from "@root/api/promocode/swr";
|
import { usePromocodes } from "@root/api/promocode/swr";
|
||||||
import { fadeIn } from "@root/utils/style/keyframes";
|
import { fadeIn } from "@root/utils/style/keyframes";
|
||||||
import { useState } from "react";
|
|
||||||
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
||||||
import { usePromocodeGridColDef } from "./usePromocodeGridColDef";
|
import { usePromocodeGridColDef } from "./usePromocodeGridColDef";
|
||||||
|
import { StatisticsModal } from "./StatisticsModal";
|
||||||
|
import DeleteModal from "./DeleteModal";
|
||||||
|
|
||||||
export const PromocodeManagement = () => {
|
export const PromocodeManagement = () => {
|
||||||
const theme = useTheme();
|
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 [deleteModal, setDeleteModal] = useState<string>("");
|
||||||
|
const deleteModalHC = (id: string) => setDeleteModal(id);
|
||||||
|
|
||||||
|
const [showStatisticsModalId, setShowStatisticsModalId] =
|
||||||
|
useState<string>("");
|
||||||
|
const [page, setPage] = useState<number>(0);
|
||||||
|
const [to, setTo] = useState(0);
|
||||||
|
const [from, setFrom] = useState(0);
|
||||||
|
const [pageSize, setPageSize] = useState<number>(10);
|
||||||
|
const {
|
||||||
|
data,
|
||||||
|
error,
|
||||||
|
isValidating,
|
||||||
|
promocodesCount,
|
||||||
|
promocodeStatistics,
|
||||||
|
deletePromocode,
|
||||||
|
createPromocode,
|
||||||
|
createFastLink,
|
||||||
|
} = usePromocodes(page, pageSize, showStatisticsModalId, to, from);
|
||||||
|
const columns = usePromocodeGridColDef(
|
||||||
|
setShowStatisticsModalId,
|
||||||
|
deleteModalHC
|
||||||
|
);
|
||||||
|
console.log(showStatisticsModalId);
|
||||||
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
|
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -73,6 +94,22 @@ export const PromocodeManagement = () => {
|
|||||||
autoHeight
|
autoHeight
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
<StatisticsModal
|
||||||
|
id={showStatisticsModalId}
|
||||||
|
setId={setShowStatisticsModalId}
|
||||||
|
promocodeStatistics={promocodeStatistics}
|
||||||
|
to={to}
|
||||||
|
setTo={setTo}
|
||||||
|
from={from}
|
||||||
|
setFrom={setFrom}
|
||||||
|
promocodes={data?.items ?? []}
|
||||||
|
createFastLink={createFastLink}
|
||||||
|
/>
|
||||||
|
<DeleteModal
|
||||||
|
id={deleteModal}
|
||||||
|
setModal={setDeleteModal}
|
||||||
|
deletePromocode={deletePromocode}
|
||||||
|
/>
|
||||||
</LocalizationProvider>
|
</LocalizationProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -1,11 +1,18 @@
|
|||||||
import DeleteIcon from '@mui/icons-material/Delete';
|
|
||||||
import { IconButton } from "@mui/material";
|
import { IconButton } from "@mui/material";
|
||||||
import { GridColDef } from "@mui/x-data-grid";
|
import { GridColDef } from "@mui/x-data-grid";
|
||||||
import { Promocode } from "@root/model/promocodes";
|
import { Promocode } from "@root/model/promocodes";
|
||||||
import { useMemo } from "react";
|
import { useMemo, useState } from "react";
|
||||||
|
|
||||||
export function usePromocodeGridColDef(deletePromocode: (id: string) => void) {
|
import { BarChart, Delete } from "@mui/icons-material";
|
||||||
return useMemo<GridColDef<Promocode, string | number, string>[]>(() => [
|
import {promocodeApi} from "@root/api/promocode/requests";
|
||||||
|
|
||||||
|
export function usePromocodeGridColDef(
|
||||||
|
setStatistics: (id: string) => void,
|
||||||
|
deletePromocode: (id: string) => void
|
||||||
|
) {
|
||||||
|
const validity = (value:string|number) => {if(value===0){return "неоганичен"}else {return new Date(value).toLocaleString()}}
|
||||||
|
return useMemo<GridColDef<Promocode, string | number, string >[]>(
|
||||||
|
() => [
|
||||||
{
|
{
|
||||||
field: "id",
|
field: "id",
|
||||||
headerName: "ID",
|
headerName: "ID",
|
||||||
@ -25,7 +32,8 @@ export function usePromocodeGridColDef(deletePromocode: (id: string) => void) {
|
|||||||
headerName: "Коэф. скидки",
|
headerName: "Коэф. скидки",
|
||||||
width: 120,
|
width: 120,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
valueGetter: ({ row }) => row.bonus.discount.factor,
|
valueGetter: ({ row }) =>
|
||||||
|
Math.round(row.bonus.discount.factor * 1000) / 1000,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "activationCount",
|
field: "activationCount",
|
||||||
@ -40,7 +48,23 @@ export function usePromocodeGridColDef(deletePromocode: (id: string) => void) {
|
|||||||
width: 160,
|
width: 160,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
valueGetter: ({ row }) => row.dueTo * 1000,
|
valueGetter: ({ row }) => row.dueTo * 1000,
|
||||||
valueFormatter: ({ value }) => new Date(value).toLocaleString(),
|
valueFormatter: ({ value }) => `${validity(value)}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "settings",
|
||||||
|
headerName: "",
|
||||||
|
width: 60,
|
||||||
|
sortable: false,
|
||||||
|
renderCell: (params) => {
|
||||||
|
return (
|
||||||
|
<IconButton onClick={() => {
|
||||||
|
setStatistics(params.row.id,)
|
||||||
|
promocodeApi.getPromocodeStatistics(params.row.id, 0, 0)
|
||||||
|
}}>
|
||||||
|
<BarChart />
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "delete",
|
field: "delete",
|
||||||
@ -50,10 +74,12 @@ export function usePromocodeGridColDef(deletePromocode: (id: string) => void) {
|
|||||||
renderCell: (params) => {
|
renderCell: (params) => {
|
||||||
return (
|
return (
|
||||||
<IconButton onClick={() => deletePromocode(params.row.id)}>
|
<IconButton onClick={() => deletePromocode(params.row.id)}>
|
||||||
<DeleteIcon />
|
<Delete />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
], [deletePromocode]);
|
],
|
||||||
|
[deletePromocode, setStatistics]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
169
src/pages/dashboard/Content/QuizStatistic/index.tsx
Normal file
169
src/pages/dashboard/Content/QuizStatistic/index.tsx
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
import { Table, TableBody, TableCell, TableHead, TableRow, useTheme, Typography, Box, TextField, Button } from '@mui/material';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import moment from "moment";
|
||||||
|
import type { Moment } from "moment";
|
||||||
|
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
|
||||||
|
import { useQuizStatistic } from '@root/utils/hooks/useQuizStatistic';
|
||||||
|
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment'
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
const theme = useTheme()
|
||||||
|
|
||||||
|
const [isOpen, setOpen] = useState<boolean>(false);
|
||||||
|
const [isOpenEnd, setOpenEnd] = useState<boolean>(false);
|
||||||
|
|
||||||
|
const [from, setFrom] = useState<Moment | null>(null);
|
||||||
|
const [to, setTo] = useState<Moment | null>(moment(Date.now()));
|
||||||
|
|
||||||
|
|
||||||
|
const { Registrations, Quizes, Results } = useQuizStatistic({
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
});
|
||||||
|
|
||||||
|
const resetTime = () => {
|
||||||
|
setFrom(moment(0));
|
||||||
|
setTo(moment(Date.now()));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpen = () => {
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onAdornmentClick = () => {
|
||||||
|
setOpen((old) => !old);
|
||||||
|
if (isOpenEnd) {
|
||||||
|
handleCloseEnd();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCloseEnd = () => {
|
||||||
|
setOpenEnd(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenEnd = () => {
|
||||||
|
setOpenEnd(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onAdornmentClickEnd = () => {
|
||||||
|
setOpenEnd((old) => !old);
|
||||||
|
if (isOpen) {
|
||||||
|
handleClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<LocalizationProvider dateAdapter={AdapterMoment}>
|
||||||
|
<Box>
|
||||||
|
<Typography
|
||||||
|
sx={{
|
||||||
|
fontSize: "16px",
|
||||||
|
marginBottom: "5px",
|
||||||
|
fontWeight: 500,
|
||||||
|
color: "4D4D4D",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Дата начала
|
||||||
|
</Typography>
|
||||||
|
<DatePicker
|
||||||
|
inputFormat="DD/MM/YYYY"
|
||||||
|
value={from}
|
||||||
|
onChange={(date) => date && setFrom(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>
|
||||||
|
<Typography
|
||||||
|
sx={{
|
||||||
|
fontSize: "16px",
|
||||||
|
marginBottom: "5px",
|
||||||
|
fontWeight: 500,
|
||||||
|
color: "4D4D4D",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Дата окончания
|
||||||
|
</Typography>
|
||||||
|
<DatePicker
|
||||||
|
inputFormat="DD/MM/YYYY"
|
||||||
|
value={to}
|
||||||
|
onChange={(date) => date && setTo(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>
|
||||||
|
<Button
|
||||||
|
sx={{
|
||||||
|
m: '10px 0'
|
||||||
|
}}
|
||||||
|
onClick={resetTime}
|
||||||
|
>
|
||||||
|
Сбросить даты
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
sx={{
|
||||||
|
width: "80%",
|
||||||
|
border: "2px solid",
|
||||||
|
borderColor: theme.palette.secondary.main,
|
||||||
|
bgcolor: theme.palette.content.main,
|
||||||
|
color: "white"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TableHead>
|
||||||
|
<TableRow
|
||||||
|
sx={{
|
||||||
|
borderBottom: "2px solid",
|
||||||
|
borderColor: theme.palette.grayLight.main,
|
||||||
|
height: "100px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">Регистраций</TableCell>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">Quiz</TableCell>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">Результаты</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">{Registrations}</TableCell>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">{Quizes}</TableCell>
|
||||||
|
<TableCell sx={{color: "inherit"}} align="center">{Results}</TableCell>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</LocalizationProvider>
|
||||||
|
</>
|
||||||
|
}
|
@ -24,6 +24,7 @@ export default function ChatDocument({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
gap: "9px",
|
gap: "9px",
|
||||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||||
|
justifyContent: isSelf ? "end" : "start",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography sx={{
|
<Typography sx={{
|
||||||
|
@ -32,6 +32,7 @@ export default function ChatImage({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
gap: "9px",
|
gap: "9px",
|
||||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||||
|
justifyContent: isSelf ? "end" : "start",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography sx={{
|
<Typography sx={{
|
||||||
|
@ -24,6 +24,7 @@ export default function ChatMessage({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
gap: "9px",
|
gap: "9px",
|
||||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||||
|
justifyContent: isSelf ? "end" : "start",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography sx={{
|
<Typography sx={{
|
||||||
|
@ -24,6 +24,7 @@ export default function ChatImage({
|
|||||||
display: "flex",
|
display: "flex",
|
||||||
gap: "9px",
|
gap: "9px",
|
||||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||||
|
justifyContent: isSelf ? "end" : "start",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography
|
<Typography
|
||||||
|
@ -18,7 +18,7 @@ export default function Message({ message, isSelf }: Props) {
|
|||||||
{new Date(message.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
{new Date(message.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||||
</Typography>
|
</Typography>
|
||||||
);
|
);
|
||||||
|
console.log(isSelf)
|
||||||
return (
|
return (
|
||||||
<Box sx={{
|
<Box sx={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
|
@ -17,7 +17,7 @@ import {
|
|||||||
findPrivilegeById,
|
findPrivilegeById,
|
||||||
usePrivilegeStore,
|
usePrivilegeStore,
|
||||||
} from "@root/stores/privilegesStore";
|
} from "@root/stores/privilegesStore";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ interface Values {
|
|||||||
customPriceField: string,
|
customPriceField: string,
|
||||||
privilegeIdField: string,
|
privilegeIdField: string,
|
||||||
orderField: number,
|
orderField: number,
|
||||||
privilege: PrivilegeWithAmount | null
|
privilege: Privilege | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CreateTariff() {
|
export default function CreateTariff() {
|
||||||
@ -68,7 +68,7 @@ export default function CreateTariff() {
|
|||||||
formikHelpers: FormikHelpers<Values>
|
formikHelpers: FormikHelpers<Values>
|
||||||
) => {
|
) => {
|
||||||
if (values.privilege !== null) {
|
if (values.privilege !== null) {
|
||||||
const [_, createdTariffError] = await createTariff({
|
const [, createdTariffError] = await createTariff({
|
||||||
name: values.nameField,
|
name: values.nameField,
|
||||||
price: Number(values.customPriceField) * 100,
|
price: Number(values.customPriceField) * 100,
|
||||||
order: values.orderField,
|
order: values.orderField,
|
||||||
@ -185,7 +185,7 @@ export default function CreateTariff() {
|
|||||||
{privileges.map((privilege) => (
|
{privileges.map((privilege) => (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
data-cy={`select-option-${privilege.description}`}
|
data-cy={`select-option-${privilege.description}`}
|
||||||
key={privilege.description}
|
key={privilege._id}
|
||||||
value={privilege._id}
|
value={privilege._id}
|
||||||
sx={{whiteSpace: "normal", wordBreak: "break-world"}}
|
sx={{whiteSpace: "normal", wordBreak: "break-world"}}
|
||||||
>
|
>
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
import { Typography } from "@mui/material";
|
import { CircularProgress, Typography } from "@mui/material";
|
||||||
import Cart from "@root/kitUI/Cart/Cart";
|
import Cart from "@root/kitUI/Cart/Cart";
|
||||||
import TariffsDG from "./tariffsDG";
|
import TariffsDG from "./tariffsDG";
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { ErrorBoundary } from "react-error-boundary";
|
||||||
|
|
||||||
|
|
||||||
export default function TariffsInfo() {
|
export default function TariffsInfo() {
|
||||||
@ -11,7 +13,11 @@ export default function TariffsInfo() {
|
|||||||
Список тарифов
|
Список тарифов
|
||||||
</Typography>
|
</Typography>
|
||||||
<TariffsDG />
|
<TariffsDG />
|
||||||
|
<ErrorBoundary fallback={<Typography>Что-то пошло не так</Typography>}>
|
||||||
|
<Suspense fallback={<CircularProgress />}>
|
||||||
<Cart />
|
<Cart />
|
||||||
|
</Suspense>
|
||||||
|
</ErrorBoundary>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,7 @@ const columns: GridColDef<Tariff, string | number>[] = [
|
|||||||
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privileges[0].type },
|
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privileges[0].type },
|
||||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => currencyFormatter.format(row.privileges[0].price / 100) },
|
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => currencyFormatter.format(row.privileges[0].price / 100) },
|
||||||
{ field: "isCustom", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
{ field: "isCustom", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
||||||
{ field: "total", headerName: "Сумма", width: 60, valueGetter: ({ row }) => currencyFormatter.format(getTariffPrice(row) / 100) },
|
{ field: "total", headerName: "Сумма", width: 100, valueGetter: ({ row }) => currencyFormatter.format(getTariffPrice(row) / 100) },
|
||||||
{
|
{
|
||||||
field: "delete",
|
field: "delete",
|
||||||
headerName: "Удаление",
|
headerName: "Удаление",
|
||||||
|
@ -131,7 +131,7 @@ const Users: React.FC = () => {
|
|||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
<Button
|
{/* <Button
|
||||||
variant="text"
|
variant="text"
|
||||||
onClick={() => navigate("/modalAdmin")}
|
onClick={() => navigate("/modalAdmin")}
|
||||||
sx={{
|
sx={{
|
||||||
@ -151,7 +151,7 @@ const Users: React.FC = () => {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
ИНФОРМАЦИЯ О ПРОЕКТЕ
|
ИНФОРМАЦИЯ О ПРОЕКТЕ
|
||||||
</Button>
|
</Button> */}
|
||||||
|
|
||||||
<Accordion
|
<Accordion
|
||||||
sx={{
|
sx={{
|
||||||
|
@ -100,6 +100,7 @@ const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== "open"
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const links: { path: string; element: JSX.Element; title: string; className: string }[] = [
|
const links: { path: string; element: JSX.Element; title: string; className: string }[] = [
|
||||||
|
{ path: "/quizStatistic", element: <>📝</>, title: "Статистика Quiz", className: "menu" },
|
||||||
{ path: "/users", element: <PersonOutlineOutlinedIcon />, title: "Информация о проекте", className: "menu" },
|
{ path: "/users", element: <PersonOutlineOutlinedIcon />, title: "Информация о проекте", className: "menu" },
|
||||||
{ path: "/entities", element: <SettingsOutlinedIcon />, title: "Юридические лица", className: "menu" },
|
{ path: "/entities", element: <SettingsOutlinedIcon />, title: "Юридические лица", className: "menu" },
|
||||||
{ path: "/tariffs", element: <BathtubOutlinedIcon />, title: "Тарифы", className: "menu" },
|
{ path: "/tariffs", element: <BathtubOutlinedIcon />, title: "Тарифы", className: "menu" },
|
||||||
|
48
src/pages/dashboard/ModalUser/QuizTab.tsx
Normal file
48
src/pages/dashboard/ModalUser/QuizTab.tsx
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
import {Box, Button, TextField, Typography} from "@mui/material";
|
||||||
|
import {ChangeEvent, useState} from "react";
|
||||||
|
import {makeRequest} from "@frontend/kitui";
|
||||||
|
|
||||||
|
type QuizTabProps = {
|
||||||
|
userId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function QuizTab({ userId }: QuizTabProps) {
|
||||||
|
const [quizId, setQuizId] = useState<string>("")
|
||||||
|
console.log(quizId)
|
||||||
|
return(
|
||||||
|
<Box sx={{ padding: "25px" }}>
|
||||||
|
<Typography
|
||||||
|
sx={{
|
||||||
|
marginBottom: "10px",
|
||||||
|
fontWeight: "bold",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Передача Квиза
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{display: "flex", gap: "15px"}}>
|
||||||
|
<TextField
|
||||||
|
placeholder={"Ссылка на квиз"}
|
||||||
|
onChange={(event: ChangeEvent<HTMLTextAreaElement>)=>{
|
||||||
|
setQuizId(event.target.value.split("link/")[1])
|
||||||
|
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="text"
|
||||||
|
sx={{ background: "#9A9AAF" }}
|
||||||
|
onClick={async() => {
|
||||||
|
await makeRequest({
|
||||||
|
method: "post",
|
||||||
|
//useToken: true,
|
||||||
|
url: process.env.REACT_APP_DOMAIN + "/squiz/quiz/move",
|
||||||
|
body: {Qid: quizId, AccountID: userId}
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Ок
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
@ -21,10 +21,11 @@ import { ReactComponent as PackageIcon } from "@root/assets/icons/package.svg";
|
|||||||
import { ReactComponent as TransactionsIcon } from "@root/assets/icons/transactions.svg";
|
import { ReactComponent as TransactionsIcon } from "@root/assets/icons/transactions.svg";
|
||||||
import { ReactComponent as CheckIcon } from "@root/assets/icons/check.svg";
|
import { ReactComponent as CheckIcon } from "@root/assets/icons/check.svg";
|
||||||
import { ReactComponent as CloseIcon } from "@root/assets/icons/close.svg";
|
import { ReactComponent as CloseIcon } from "@root/assets/icons/close.svg";
|
||||||
|
import QuizIcon from '@mui/icons-material/Quiz';
|
||||||
import forwardIcon from "@root/assets/icons/forward.svg";
|
import forwardIcon from "@root/assets/icons/forward.svg";
|
||||||
|
|
||||||
import type { SyntheticEvent } from "react";
|
import type { SyntheticEvent } from "react";
|
||||||
|
import QuizTab from "@pages/dashboard/ModalUser/QuizTab";
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
{ name: "Пользователь", icon: UserIcon, activeStyles: { fill: "#7E2AEA" } },
|
{ name: "Пользователь", icon: UserIcon, activeStyles: { fill: "#7E2AEA" } },
|
||||||
@ -39,6 +40,7 @@ const TABS = [
|
|||||||
activeStyles: { stroke: "#7E2AEA" },
|
activeStyles: { stroke: "#7E2AEA" },
|
||||||
},
|
},
|
||||||
{ name: "Верификация", icon: CheckIcon, activeStyles: { stroke: "#7E2AEA" } },
|
{ name: "Верификация", icon: CheckIcon, activeStyles: { stroke: "#7E2AEA" } },
|
||||||
|
{ name: "Квизы", icon: QuizIcon, activeStyles: { stroke: "#7E2AEA" } },
|
||||||
];
|
];
|
||||||
|
|
||||||
type ModalUserProps = {
|
type ModalUserProps = {
|
||||||
@ -194,6 +196,7 @@ const ModalUser = ({ open, onClose, userId }: ModalUserProps) => {
|
|||||||
{value === 1 && <PurchaseTab userId={userId} />}
|
{value === 1 && <PurchaseTab userId={userId} />}
|
||||||
{value === 2 && <TransactionsTab />}
|
{value === 2 && <TransactionsTab />}
|
||||||
{value === 3 && <VerificationTab userId={userId} />}
|
{value === 3 && <VerificationTab userId={userId} />}
|
||||||
|
{value === 4 && <QuizTab userId={userId} />}
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||||
import { requestServicePrivileges } from "@root/api/privilegies";
|
import { requestServicePrivileges } from "@root/api/privilegies";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
const mutatePrivileges = (privileges: PrivilegeWithAmount[]) => {
|
const mutatePrivileges = (privileges: CustomPrivilege[]) => {
|
||||||
let extracted: PrivilegeWithAmount[] = [];
|
let extracted: CustomPrivilege[] = [];
|
||||||
for (let serviceKey in privileges) {
|
for (let serviceKey in privileges) {
|
||||||
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||||
extracted = extracted.concat(privileges[serviceKey]);
|
extracted = extracted.concat(privileges[serviceKey]);
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
|
|
||||||
interface PrivilegeStore {
|
interface PrivilegeStore {
|
||||||
privileges: PrivilegeWithAmount[];
|
privileges: CustomPrivilege[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,82 +0,0 @@
|
|||||||
import { CartData, Discount, PrivilegeCartData, Tariff, TariffCartData, applyCartDiscount, applyLoyaltyDiscount, applyPrivilegeDiscounts, applyServiceDiscounts } from "@frontend/kitui";
|
|
||||||
|
|
||||||
|
|
||||||
export function calcCart(
|
|
||||||
tariffs: Tariff[],
|
|
||||||
discounts: Discount[],
|
|
||||||
purchasesAmount: number,
|
|
||||||
coupon?: string,
|
|
||||||
): CartData {
|
|
||||||
const cartData: CartData = {
|
|
||||||
services: [],
|
|
||||||
priceBeforeDiscounts: 0,
|
|
||||||
priceAfterDiscounts: 0,
|
|
||||||
itemCount: 0,
|
|
||||||
appliedCartPurchasesDiscount: null,
|
|
||||||
appliedLoyaltyDiscount: null,
|
|
||||||
allAppliedDiscounts: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
const serviceTariffType: Record<string, number> = {};
|
|
||||||
|
|
||||||
tariffs.forEach(tariff => {
|
|
||||||
let serviceData = cartData.services.find(service => service.serviceKey === tariff.privileges[0].serviceKey);
|
|
||||||
if (!serviceData) {
|
|
||||||
serviceData = {
|
|
||||||
serviceKey: tariff.privileges[0].serviceKey,
|
|
||||||
tariffs: [],
|
|
||||||
price: 0,
|
|
||||||
appliedServiceDiscount: null,
|
|
||||||
};
|
|
||||||
cartData.services.push(serviceData);
|
|
||||||
}
|
|
||||||
|
|
||||||
const tariffCartData: TariffCartData = {
|
|
||||||
price: tariff.price ?? 0,
|
|
||||||
isCustom: tariff.isCustom,
|
|
||||||
privileges: [],
|
|
||||||
id: tariff._id,
|
|
||||||
name: tariff.name,
|
|
||||||
};
|
|
||||||
serviceData.tariffs.push(tariffCartData);
|
|
||||||
|
|
||||||
tariff.privileges.forEach(privilege => {
|
|
||||||
serviceTariffType[privilege.serviceKey] ??= +tariff.isCustom;
|
|
||||||
const isIncompatibleTariffs = serviceTariffType[privilege.serviceKey] ^ +tariff.isCustom;
|
|
||||||
if (isIncompatibleTariffs) throw new Error("Если взят готовый тариф, то кастомный на этот сервис сделать уже нельзя");
|
|
||||||
|
|
||||||
const privilegePrice = privilege.amount * privilege.price;
|
|
||||||
|
|
||||||
if (!tariff.price) tariffCartData.price += privilegePrice;
|
|
||||||
|
|
||||||
const privilegeCartData: PrivilegeCartData = {
|
|
||||||
serviceKey: privilege.serviceKey,
|
|
||||||
amount: privilege.amount,
|
|
||||||
privilegeId: privilege.privilegeId,
|
|
||||||
description: privilege.description,
|
|
||||||
price: privilegePrice,
|
|
||||||
appliedPrivilegeDiscount: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
tariffCartData.privileges.push(privilegeCartData);
|
|
||||||
cartData.priceAfterDiscounts += privilegePrice;
|
|
||||||
cartData.itemCount++;
|
|
||||||
});
|
|
||||||
|
|
||||||
cartData.priceBeforeDiscounts += tariffCartData.price;
|
|
||||||
serviceData.price += tariffCartData.price;
|
|
||||||
});
|
|
||||||
|
|
||||||
applyPrivilegeDiscounts(cartData, discounts);
|
|
||||||
applyServiceDiscounts(cartData, discounts);
|
|
||||||
applyCartDiscount(cartData, discounts);
|
|
||||||
applyLoyaltyDiscount(cartData, discounts, purchasesAmount);
|
|
||||||
|
|
||||||
cartData.allAppliedDiscounts = Array.from(new Set(cartData.allAppliedDiscounts));
|
|
||||||
|
|
||||||
return cartData;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatDiscountFactor(factor: number): string {
|
|
||||||
return `${((1 - factor) * 100).toFixed(1)}%`;
|
|
||||||
}
|
|
42
src/utils/createDiscountFromPromocode.ts
Normal file
42
src/utils/createDiscountFromPromocode.ts
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import { Promocode } from "@root/model/promocodes";
|
||||||
|
|
||||||
|
|
||||||
|
export function createDiscountFromPromocode(promocode: Promocode, userId: string) {
|
||||||
|
return {
|
||||||
|
"ID": crypto.randomUUID(),
|
||||||
|
"Name": promocode.codeword,
|
||||||
|
"Layer": promocode.bonus.discount.layer,
|
||||||
|
"Description": "",
|
||||||
|
"Condition": {
|
||||||
|
"User": userId,
|
||||||
|
"UserType": "",
|
||||||
|
"Coupon": promocode.codeword,
|
||||||
|
"PurchasesAmount": "0",
|
||||||
|
"CartPurchasesAmount": "0",
|
||||||
|
"Product": promocode.bonus.discount.target,
|
||||||
|
"Term": "0",
|
||||||
|
"Usage": "0",
|
||||||
|
"PriceFrom": "0",
|
||||||
|
"Group": promocode.bonus.discount.target
|
||||||
|
},
|
||||||
|
"Target": {
|
||||||
|
"Products": promocode.bonus.discount.layer === 1 ? [
|
||||||
|
{
|
||||||
|
"ID": promocode.bonus.discount.target,
|
||||||
|
"Factor": promocode.bonus.discount.factor,
|
||||||
|
"Overhelm": false
|
||||||
|
}
|
||||||
|
] : [],
|
||||||
|
"Factor": promocode.bonus.discount.layer === 2 ? promocode.bonus.discount.factor : 0,
|
||||||
|
"TargetScope": "Sum",
|
||||||
|
"TargetGroup": promocode.bonus.discount.target,
|
||||||
|
"Overhelm": true
|
||||||
|
},
|
||||||
|
"Audit": {
|
||||||
|
"UpdatedAt": "",
|
||||||
|
"CreatedAt": "",
|
||||||
|
"Deleted": false
|
||||||
|
},
|
||||||
|
"Deprecated": false
|
||||||
|
};
|
||||||
|
}
|
3
src/utils/formatDiscountFactor.ts
Normal file
3
src/utils/formatDiscountFactor.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export function formatDiscountFactor(factor: number): string {
|
||||||
|
return `${((1 - factor) * 100).toFixed(1)}%`;
|
||||||
|
}
|
@ -2,13 +2,13 @@ import { useEffect } from "react";
|
|||||||
|
|
||||||
import { requestPrivileges } from "@root/api/privilegies";
|
import { requestPrivileges } from "@root/api/privilegies";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
export default function usePrivileges({
|
export default function usePrivileges({
|
||||||
onError,
|
onError,
|
||||||
onNewPrivileges,
|
onNewPrivileges,
|
||||||
}: {
|
}: {
|
||||||
onNewPrivileges: (response: PrivilegeWithAmount[]) => void;
|
onNewPrivileges: (response: CustomPrivilege[]) => void;
|
||||||
onError?: (error: any) => void;
|
onError?: (error: any) => void;
|
||||||
}) {
|
}) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -19,7 +19,6 @@ export default function usePrivileges({
|
|||||||
if (privilegesError) {
|
if (privilegesError) {
|
||||||
return onError?.(privilegesError);
|
return onError?.(privilegesError);
|
||||||
}
|
}
|
||||||
|
|
||||||
onNewPrivileges(privilegesResponse);
|
onNewPrivileges(privilegesResponse);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
34
src/utils/hooks/useQuizStatistic.ts
Normal file
34
src/utils/hooks/useQuizStatistic.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
QuizStatisticResponse,
|
||||||
|
getStatistic
|
||||||
|
} from "@root/api/quizStatistic";
|
||||||
|
|
||||||
|
import type { Moment } from "moment";
|
||||||
|
|
||||||
|
interface useQuizStatisticProps {
|
||||||
|
to: Moment | null;
|
||||||
|
from: Moment | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useQuizStatistic({ to, from }: useQuizStatisticProps) {
|
||||||
|
const formatTo = to?.unix();
|
||||||
|
const formatFrom = from?.unix();
|
||||||
|
|
||||||
|
const [data, setData] = useState<QuizStatisticResponse | null>({ Registrations: 0, Quizes: 0, Results: 0 });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
|
||||||
|
const requestStatistics = async () => {
|
||||||
|
console.log("работаю раз")
|
||||||
|
console.log("работаю два")
|
||||||
|
|
||||||
|
const gottenData = await getStatistic(Number(formatTo), Number(formatFrom));
|
||||||
|
setData(gottenData)
|
||||||
|
}
|
||||||
|
|
||||||
|
requestStatistics();
|
||||||
|
}, [to, from]);
|
||||||
|
|
||||||
|
return { ...data };
|
||||||
|
}
|
15
yarn.lock
15
yarn.lock
@ -1433,10 +1433,10 @@
|
|||||||
lodash.isundefined "^3.0.1"
|
lodash.isundefined "^3.0.1"
|
||||||
lodash.uniq "^4.5.0"
|
lodash.uniq "^4.5.0"
|
||||||
|
|
||||||
"@frontend/kitui@^1.0.59":
|
"@frontend/kitui@^1.0.77":
|
||||||
version "1.0.59"
|
version "1.0.77"
|
||||||
resolved "https://penahub.gitlab.yandexcloud.net/api/v4/projects/21/packages/npm/@frontend/kitui/-/@frontend/kitui-1.0.59.tgz#c4584506bb5cab4fc1df35f5b1d0d66ec379a9a1"
|
resolved "https://penahub.gitlab.yandexcloud.net/api/v4/projects/21/packages/npm/@frontend/kitui/-/@frontend/kitui-1.0.77.tgz#a749dee0e7622b4c4509e8354ace47299b0606f7"
|
||||||
integrity sha1-xFhFBrtcq0/B3zX1sdDWbsN5qaE=
|
integrity sha1-p0ne4OdiK0xFCeg1Ss5HKZsGBvc=
|
||||||
dependencies:
|
dependencies:
|
||||||
immer "^10.0.2"
|
immer "^10.0.2"
|
||||||
reconnecting-eventsource "^1.6.2"
|
reconnecting-eventsource "^1.6.2"
|
||||||
@ -10472,6 +10472,13 @@ react-dom@^18.2.0:
|
|||||||
loose-envify "^1.1.0"
|
loose-envify "^1.1.0"
|
||||||
scheduler "^0.23.0"
|
scheduler "^0.23.0"
|
||||||
|
|
||||||
|
react-error-boundary@^4.0.13:
|
||||||
|
version "4.0.13"
|
||||||
|
resolved "https://registry.yarnpkg.com/react-error-boundary/-/react-error-boundary-4.0.13.tgz#80386b7b27b1131c5fbb7368b8c0d983354c7947"
|
||||||
|
integrity sha512-b6PwbdSv8XeOSYvjt8LpgpKrZ0yGdtZokYwkwV2wlcZbxgopHX/hgPl5VgpnoVOWd868n1hktM8Qm4b+02MiLQ==
|
||||||
|
dependencies:
|
||||||
|
"@babel/runtime" "^7.12.5"
|
||||||
|
|
||||||
react-error-overlay@^6.0.11:
|
react-error-overlay@^6.0.11:
|
||||||
version "6.0.11"
|
version "6.0.11"
|
||||||
resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.11.tgz"
|
resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.11.tgz"
|
||||||
|
Loading…
Reference in New Issue
Block a user