Merge branch 'staging' into 'main'
add promocode datafetching See merge request frontend/admin!73
This commit is contained in:
commit
b0ff7f0b39
14
admin.conf
14
admin.conf
@ -44,6 +44,20 @@ server {
|
||||
add_header Access-Control-Allow-Methods OPTIONS,GET,POST,PATCH,PUT,DELETE;
|
||||
proxy_pass http://10.8.0.8:59300;
|
||||
}
|
||||
location /manager/ {
|
||||
if ($request_method = OPTIONS) {
|
||||
add_header Access-Control-Allow-Origin $http_origin always;
|
||||
add_header Access-Control-Allow-Credentials true always;
|
||||
add_header Access-Control-Allow-Headers content-type,authorization always;
|
||||
add_header Access-Control-Allow-Methods OPTIONS,GET,POST,PATCH,PUT,DELETE;
|
||||
return 200;
|
||||
}
|
||||
add_header Access-Control-Allow-Origin $http_origin always;
|
||||
add_header Access-Control-Allow-Credentials true always;
|
||||
add_header Access-Control-Allow-Headers content-type,authorization always;
|
||||
add_header Access-Control-Allow-Methods OPTIONS,GET,POST,PATCH,PUT,DELETE;
|
||||
proxy_pass http://10.6.0.11:59301/;
|
||||
}
|
||||
|
||||
location /swagger/ {
|
||||
proxy_pass http://10.8.0.8:59300/;
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
"@date-io/dayjs": "^2.15.0",
|
||||
"@emotion/react": "^11.10.4",
|
||||
"@emotion/styled": "^11.10.4",
|
||||
"@frontend/kitui": "^1.0.59",
|
||||
"@frontend/kitui": "^1.0.82",
|
||||
"@material-ui/pickers": "^3.3.10",
|
||||
"@mui/icons-material": "^5.10.3",
|
||||
"@mui/material": "^5.10.5",
|
||||
@ -26,6 +26,7 @@
|
||||
"axios": "^1.4.0",
|
||||
"craco": "^0.0.3",
|
||||
"cypress": "^12.17.2",
|
||||
"date-fns": "^3.3.1",
|
||||
"dayjs": "^1.11.5",
|
||||
"formik": "^2.2.9",
|
||||
"immer": "^10.0.2",
|
||||
@ -35,12 +36,14 @@
|
||||
"numeral": "^2.0.6",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-error-boundary": "^4.0.13",
|
||||
"react-numeral": "^1.1.1",
|
||||
"react-router-dom": "^6.3.0",
|
||||
"react-scripts": "^5.0.1",
|
||||
"reconnecting-eventsource": "^1.6.2",
|
||||
"start-server-and-test": "^2.0.0",
|
||||
"styled-components": "^5.3.5",
|
||||
"swr": "^2.2.5",
|
||||
"typescript": "^4.8.2",
|
||||
"use-debounce": "^9.0.4",
|
||||
"web-vitals": "^2.1.4",
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
@ -23,9 +23,8 @@ export const signin = async (
|
||||
|
||||
return [signinResponse];
|
||||
} catch (nativeError) {
|
||||
console.log(nativeError)
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
console.log(error)
|
||||
console.error(error)
|
||||
return [null, `Ошибка авторизации. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
@ -8,6 +8,8 @@ import type {
|
||||
DiscountType,
|
||||
GetDiscountResponse,
|
||||
} from "@root/model/discount";
|
||||
import useSWR from "swr";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
|
||||
|
||||
@ -104,8 +106,6 @@ export function createDiscountObject({
|
||||
break;
|
||||
}
|
||||
|
||||
console.log("Constructed discount", discount);
|
||||
|
||||
return discount;
|
||||
}
|
||||
|
||||
@ -213,3 +213,33 @@ export const requestDiscounts = async (): Promise<
|
||||
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;
|
||||
}
|
||||
|
||||
50
src/api/history/requests.ts
Normal file
50
src/api/history/requests.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
type RawDetail = {
|
||||
Key: string;
|
||||
Value: number | string | RawDetail[];
|
||||
};
|
||||
|
||||
type History = {
|
||||
id: string;
|
||||
userId: string;
|
||||
comment: string;
|
||||
key: string;
|
||||
rawDetails: RawDetail[];
|
||||
isDeleted: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
type HistoryResponse = {
|
||||
records: History[];
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/customer";
|
||||
|
||||
const getUserHistory = async (
|
||||
accountId: string,
|
||||
page: number
|
||||
): Promise<[HistoryResponse | null, string?]> => {
|
||||
try {
|
||||
const historyResponse = await makeRequest<never, HistoryResponse>({
|
||||
method: "GET",
|
||||
url:
|
||||
baseUrl +
|
||||
`/history?page=${page}&limit=${100}&accountID=${accountId}&type=payCart`,
|
||||
});
|
||||
|
||||
return [historyResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении пользователей. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
export const historyApi = {
|
||||
getUserHistory,
|
||||
};
|
||||
43
src/api/history/swr.ts
Normal file
43
src/api/history/swr.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { useState } from "react";
|
||||
import useSWRInfinite from "swr/infinite";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
|
||||
import { historyApi } from "./requests";
|
||||
|
||||
export function useHistory(accountId: string) {
|
||||
const [currentPage, setCurrentPage] = useState<number>(1);
|
||||
|
||||
const swrResponse = useSWRInfinite(
|
||||
() => `history-${currentPage}`,
|
||||
async () => {
|
||||
const [historyResponse, error] = await historyApi.getUserHistory(
|
||||
accountId,
|
||||
currentPage
|
||||
);
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
if (!historyResponse) {
|
||||
throw new Error("Empty history data");
|
||||
}
|
||||
|
||||
if (currentPage < historyResponse.totalPages) {
|
||||
setCurrentPage((page) => page + 1);
|
||||
}
|
||||
|
||||
return historyResponse;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.error("Error fetching users", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
return swrResponse;
|
||||
}
|
||||
23
src/api/makeRequest.ts
Normal file
23
src/api/makeRequest.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import * as KIT from "@frontend/kitui";
|
||||
import { Method, ResponseType, AxiosError } from "axios";
|
||||
import { clearAuthToken } from "@frontend/kitui";
|
||||
import { redirect } from "react-router-dom";
|
||||
|
||||
interface MakeRequest { method?: Method | undefined; url: string; body?: unknown; useToken?: boolean | undefined; contentType?: boolean | undefined; responseType?: ResponseType | undefined; signal?: AbortSignal | undefined; withCredentials?: boolean | undefined; }
|
||||
|
||||
async function makeRequest<TRequest = unknown, TResponse = unknown> (data:MakeRequest): Promise<TResponse> {
|
||||
try {
|
||||
const response = await KIT.makeRequest<unknown>(data)
|
||||
|
||||
return response as TResponse
|
||||
} catch (e) {
|
||||
const error = e as AxiosError;
|
||||
//@ts-ignore
|
||||
if (error.response?.status === 400 && error.response?.data?.message === "refreshToken is empty") {
|
||||
clearAuthToken()
|
||||
redirect("/");
|
||||
}
|
||||
throw e
|
||||
};
|
||||
};
|
||||
export default makeRequest;
|
||||
@ -1,13 +1,14 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import { CustomPrivilege } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
import { Privilege } from "@frontend/kitui";
|
||||
import type { TMockData } from "./roles";
|
||||
|
||||
type SeverPrivilegesResponse = {
|
||||
templategen: PrivilegeWithAmount[];
|
||||
squiz: PrivilegeWithAmount[];
|
||||
templategen: CustomPrivilege[];
|
||||
squiz: CustomPrivilege[];
|
||||
};
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
|
||||
@ -28,11 +29,11 @@ export const getRoles = async (): Promise<[TMockData | null, string?]> => {
|
||||
};
|
||||
|
||||
export const putPrivilege = async (
|
||||
body: Omit<PrivilegeWithAmount, "_id" | "updatedAt">
|
||||
body: Omit<Privilege, "_id" | "updatedAt">
|
||||
): Promise<[unknown, string?]> => {
|
||||
try {
|
||||
const putedPrivilege = await makeRequest<
|
||||
Omit<PrivilegeWithAmount, "_id" | "updatedAt">,
|
||||
Omit<Privilege, "_id" | "updatedAt">,
|
||||
unknown
|
||||
>({
|
||||
url: baseUrl + "/privilege",
|
||||
@ -70,9 +71,9 @@ export const requestServicePrivileges = async (): Promise<
|
||||
|
||||
export const requestPrivileges = async (
|
||||
signal: AbortSignal | undefined
|
||||
): Promise<[PrivilegeWithAmount[], string?]> => {
|
||||
): Promise<[CustomPrivilege[], string?]> => {
|
||||
try {
|
||||
const privilegesResponse = await makeRequest<never, PrivilegeWithAmount[]>(
|
||||
const privilegesResponse = await makeRequest<never, CustomPrivilege[]>(
|
||||
{
|
||||
url: baseUrl + "/privilege",
|
||||
method: "get",
|
||||
|
||||
142
src/api/promocode/requests.ts
Normal file
142
src/api/promocode/requests.ts
Normal file
@ -0,0 +1,142 @@
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import type {
|
||||
CreatePromocodeBody,
|
||||
GetPromocodeListBody,
|
||||
Promocode,
|
||||
PromocodeList,
|
||||
PromocodeStatistics,
|
||||
} from "@root/model/promocodes";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
import { isAxiosError } from "axios";
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
|
||||
|
||||
const getPromocodeList = async (body: GetPromocodeListBody) => {
|
||||
try {
|
||||
const promocodeListResponse = await makeRequest<
|
||||
GetPromocodeListBody,
|
||||
PromocodeList
|
||||
>({
|
||||
url: baseUrl + "/getList",
|
||||
method: "POST",
|
||||
body,
|
||||
useToken: false,
|
||||
});
|
||||
|
||||
return promocodeListResponse;
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
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: 100,
|
||||
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) => {
|
||||
try {
|
||||
const createPromocodeResponse = await makeRequest<
|
||||
CreatePromocodeBody,
|
||||
Promocode
|
||||
>({
|
||||
url: baseUrl + "/create",
|
||||
method: "POST",
|
||||
body,
|
||||
useToken: false,
|
||||
});
|
||||
|
||||
return createPromocodeResponse;
|
||||
} catch (nativeError) {
|
||||
if (
|
||||
isAxiosError(nativeError) &&
|
||||
nativeError.response?.data.error === "Duplicate Codeword"
|
||||
) {
|
||||
throw new Error(`Промокод уже существует`);
|
||||
}
|
||||
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
throw new Error(`Ошибка создания промокода. ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
const deletePromocode = async (id: string): Promise<void> => {
|
||||
try {
|
||||
await makeRequest<never, never>({
|
||||
url: `${baseUrl}/${id}`,
|
||||
method: "DELETE",
|
||||
useToken: false,
|
||||
});
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
throw new Error(`Ошибка удаления промокода. ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
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,
|
||||
});
|
||||
return promocodeStatisticsResponse;
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
throw new Error(`Ошибка при получении статистики промокода. ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const promocodeApi = {
|
||||
getPromocodeList,
|
||||
createPromocode,
|
||||
deletePromocode,
|
||||
getAllPromocodes,
|
||||
getPromocodeStatistics,
|
||||
createFastlink,
|
||||
};
|
||||
149
src/api/promocode/swr.ts
Normal file
149
src/api/promocode/swr.ts
Normal file
@ -0,0 +1,149 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import useSwr, { mutate } from "swr";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { promocodeApi } from "./requests";
|
||||
|
||||
import type {
|
||||
CreatePromocodeBody,
|
||||
PromocodeList,
|
||||
} from "@root/model/promocodes";
|
||||
|
||||
export function usePromocodes(
|
||||
page: number,
|
||||
pageSize: number,
|
||||
promocodeId: string,
|
||||
to: number,
|
||||
from: number
|
||||
) {
|
||||
const promocodesCountRef = useRef<number>(0);
|
||||
const swrResponse = useSwr(
|
||||
["promocodes", page, pageSize],
|
||||
async (key) => {
|
||||
const result = await promocodeApi.getPromocodeList({
|
||||
limit: key[2],
|
||||
filter: {
|
||||
active: true,
|
||||
},
|
||||
page: key[1],
|
||||
});
|
||||
|
||||
promocodesCountRef.current = result.count;
|
||||
return result;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.error("Error fetching promocodes", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
const createPromocode = useCallback(
|
||||
async function (body: CreatePromocodeBody) {
|
||||
try {
|
||||
await promocodeApi.createPromocode(body);
|
||||
mutate(["promocodes", page, pageSize]);
|
||||
} catch (error) {
|
||||
console.error("Error creating promocode", error);
|
||||
if (error instanceof Error)
|
||||
enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
},
|
||||
[page, pageSize]
|
||||
);
|
||||
|
||||
const deletePromocode = useCallback(
|
||||
async function (id: string) {
|
||||
try {
|
||||
await mutate<PromocodeList | undefined, void>(
|
||||
["promocodes", page, pageSize],
|
||||
promocodeApi.deletePromocode(id),
|
||||
{
|
||||
optimisticData(currentData, displayedData) {
|
||||
if (!displayedData) return;
|
||||
|
||||
return {
|
||||
count: displayedData.count - 1,
|
||||
items: displayedData.items.filter((item) => item.id !== id),
|
||||
};
|
||||
},
|
||||
rollbackOnError: true,
|
||||
populateCache(result, currentData) {
|
||||
if (!currentData) return;
|
||||
|
||||
return {
|
||||
count: currentData.count - 1,
|
||||
items: currentData.items.filter((item) => item.id !== id),
|
||||
};
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error deleting promocode", error);
|
||||
if (error instanceof Error)
|
||||
enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
},
|
||||
[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.error("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.error("Error creating fast link", error);
|
||||
if (error instanceof Error)
|
||||
enqueueSnackbar(error.message, { variant: "error" });
|
||||
}
|
||||
},
|
||||
[page, pageSize]
|
||||
);
|
||||
|
||||
return {
|
||||
...swrResponse,
|
||||
createPromocode,
|
||||
deletePromocode,
|
||||
createFastLink,
|
||||
promocodeStatistics: promocodeStatistics.data,
|
||||
promocodesCount: promocodesCountRef.current,
|
||||
};
|
||||
}
|
||||
|
||||
export function useAllPromocodes() {
|
||||
const swrResponse = useSwr("allPromocodes", promocodeApi.getAllPromocodes, {
|
||||
keepPreviousData: true,
|
||||
suspense: true,
|
||||
onError(err) {
|
||||
console.error("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 "@root/api/makeRequest";
|
||||
|
||||
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 };
|
||||
}
|
||||
};
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
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 { EditTariffRequestBody } from "@root/model/tariff";
|
||||
|
||||
@ -12,7 +12,7 @@ type CreateTariffBackendRequest = {
|
||||
order: number;
|
||||
price: number;
|
||||
isCustom: boolean;
|
||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||
};
|
||||
|
||||
type GetTariffsResponse = {
|
||||
@ -52,7 +52,7 @@ export const putTariff = async (tariff: Tariff): Promise<[null, string?]> => {
|
||||
price: tariff.price ?? 0,
|
||||
isCustom: false,
|
||||
order: tariff.order || 1,
|
||||
description: tariff.description,
|
||||
description: tariff.description ?? "",
|
||||
privileges: tariff.privileges,
|
||||
},
|
||||
});
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
|
||||
@ -1,70 +0,0 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
import type { UserType } from "@root/api/roles";
|
||||
|
||||
type RegisteredUsersResponse = {
|
||||
tatalPages: number;
|
||||
users: UserType[];
|
||||
};
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/user";
|
||||
|
||||
export const getUserInfo = async (
|
||||
id: string
|
||||
): Promise<[UserType | null, string?]> => {
|
||||
try {
|
||||
const userInfoResponse = await makeRequest<never, UserType>({
|
||||
url: `${baseUrl}/${id}`,
|
||||
method: "GET",
|
||||
useToken: true,
|
||||
});
|
||||
|
||||
return [userInfoResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка получения информации о пользователе. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
export const getRegisteredUsers = async (): Promise<
|
||||
[RegisteredUsersResponse | null, string?]
|
||||
> => {
|
||||
try {
|
||||
const registeredUsersResponse = await makeRequest<
|
||||
never,
|
||||
RegisteredUsersResponse
|
||||
>({
|
||||
method: "get",
|
||||
url: baseUrl + "/",
|
||||
});
|
||||
|
||||
return [registeredUsersResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении пользователей. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
export const getManagersList = async (): Promise<
|
||||
[RegisteredUsersResponse | null, string?]
|
||||
> => {
|
||||
try {
|
||||
const managersListResponse = await makeRequest<
|
||||
never,
|
||||
RegisteredUsersResponse
|
||||
>({
|
||||
method: "get",
|
||||
url: baseUrl + "/",
|
||||
});
|
||||
|
||||
return [managersListResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении менеджеров. ${error}`];
|
||||
}
|
||||
};
|
||||
89
src/api/user/requests.ts
Normal file
89
src/api/user/requests.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
import type { UserType } from "@root/api/roles";
|
||||
|
||||
export type UsersListResponse = {
|
||||
totalPages: number;
|
||||
users: UserType[];
|
||||
};
|
||||
|
||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/user";
|
||||
|
||||
const getUserInfo = async (id: string): Promise<[UserType | null, string?]> => {
|
||||
try {
|
||||
const userInfoResponse = await makeRequest<never, UserType>({
|
||||
url: `${baseUrl}/${id}`,
|
||||
method: "GET",
|
||||
useToken: true,
|
||||
});
|
||||
|
||||
return [userInfoResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка получения информации о пользователе. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
const getUserList = async (
|
||||
page = 1,
|
||||
limit = 10
|
||||
): Promise<[UsersListResponse | null, string?]> => {
|
||||
try {
|
||||
const userResponse = await makeRequest<never, UsersListResponse>({
|
||||
method: "get",
|
||||
url: baseUrl + `/?page=${page}&limit=${limit}`,
|
||||
});
|
||||
|
||||
return [userResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении пользователей. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
const getManagerList = async (
|
||||
page = 1,
|
||||
limit = 10
|
||||
): Promise<[UsersListResponse | null, string?]> => {
|
||||
try {
|
||||
const managerResponse = await makeRequest<never, UsersListResponse>({
|
||||
method: "get",
|
||||
url: baseUrl + `/?page=${page}&limit=${limit}`,
|
||||
});
|
||||
|
||||
return [managerResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении менеджеров. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
const getAdminList = async (
|
||||
page = 1,
|
||||
limit = 10
|
||||
): Promise<[UsersListResponse | null, string?]> => {
|
||||
try {
|
||||
const adminResponse = await makeRequest<never, UsersListResponse>({
|
||||
method: "get",
|
||||
url: baseUrl + `/?page=${page}&limit=${limit}`,
|
||||
});
|
||||
|
||||
return [adminResponse];
|
||||
} catch (nativeError) {
|
||||
const [error] = parseAxiosError(nativeError);
|
||||
|
||||
return [null, `Ошибка при получении админов. ${error}`];
|
||||
}
|
||||
};
|
||||
|
||||
export const userApi = {
|
||||
getUserInfo,
|
||||
getUserList,
|
||||
getManagerList,
|
||||
getAdminList,
|
||||
};
|
||||
104
src/api/user/swr.ts
Normal file
104
src/api/user/swr.ts
Normal file
@ -0,0 +1,104 @@
|
||||
import { useRef } from "react";
|
||||
import useSwr from "swr";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
|
||||
import { userApi } from "./requests";
|
||||
|
||||
export function useAdmins(page: number, pageSize: number) {
|
||||
const adminPagesRef = useRef<number>(0);
|
||||
|
||||
const swrResponse = useSwr(
|
||||
["admin", page, pageSize],
|
||||
async ([_, page, pageSize]) => {
|
||||
const [adminResponse, error] = await userApi.getManagerList(
|
||||
page,
|
||||
pageSize
|
||||
);
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
adminPagesRef.current = adminResponse?.totalPages || 1;
|
||||
return adminResponse;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.error("Error fetching users", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
...swrResponse,
|
||||
adminPages: adminPagesRef.current,
|
||||
};
|
||||
}
|
||||
|
||||
export function useManagers(page: number, pageSize: number) {
|
||||
const managerPagesRef = useRef<number>(0);
|
||||
|
||||
const swrResponse = useSwr(
|
||||
["manager", page, pageSize],
|
||||
async ([_, page, pageSize]) => {
|
||||
const [managerResponse, error] = await userApi.getManagerList(
|
||||
page,
|
||||
pageSize
|
||||
);
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
managerPagesRef.current = managerResponse?.totalPages || 1;
|
||||
return managerResponse;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.error("Error fetching users", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
...swrResponse,
|
||||
managerPages: managerPagesRef.current,
|
||||
};
|
||||
}
|
||||
|
||||
export function useUsers(page: number, pageSize: number) {
|
||||
const userPagesRef = useRef<number>(0);
|
||||
|
||||
const swrResponse = useSwr(
|
||||
["users", page, pageSize],
|
||||
async ([_, page, pageSize]) => {
|
||||
const [userResponse, error] = await userApi.getUserList(page, pageSize);
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
userPagesRef.current = userResponse?.totalPages || 1;
|
||||
return userResponse;
|
||||
},
|
||||
{
|
||||
onError(err) {
|
||||
console.error("Error fetching users", err);
|
||||
enqueueSnackbar(err.message, { variant: "error" });
|
||||
},
|
||||
focusThrottleInterval: 60e3,
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
...swrResponse,
|
||||
userPagesCount: userPagesRef.current,
|
||||
};
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
import { parseAxiosError } from "@root/utils/parse-error";
|
||||
|
||||
|
||||
74
src/assets/icons/close.svg
Normal file
74
src/assets/icons/close.svg
Normal file
@ -0,0 +1,74 @@
|
||||
<svg
|
||||
width="35"
|
||||
height="33"
|
||||
viewBox="0 0 35 33"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g id="Close">
|
||||
<g id="Rectangle 57" opacity="0.3" filter="url(#filter0_d_4080_12482)">
|
||||
<rect x="6" y="4" width="24" height="24" rx="12" fill="#9A9AAF"></rect>
|
||||
</g>
|
||||
<g id="Group 331">
|
||||
<path
|
||||
id="Vector 586"
|
||||
d="M22.8516 10.9517L12.9521 20.8512"
|
||||
stroke="#FDFDFF"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
></path>
|
||||
<path
|
||||
id="Vector 587"
|
||||
d="M22.8516 20.8462L12.9521 10.9467"
|
||||
stroke="#FDFDFF"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
></path>
|
||||
</g>
|
||||
</g>
|
||||
<defs>
|
||||
<filter
|
||||
id="filter0_d_4080_12482"
|
||||
x="0"
|
||||
y="0"
|
||||
width="36"
|
||||
height="36"
|
||||
filterUnits="userSpaceOnUse"
|
||||
color-interpolation-filters="sRGB"
|
||||
>
|
||||
<feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood>
|
||||
<feColorMatrix
|
||||
in="SourceAlpha"
|
||||
type="matrix"
|
||||
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||
result="hardAlpha"
|
||||
></feColorMatrix>
|
||||
<feMorphology
|
||||
radius="1"
|
||||
operator="dilate"
|
||||
in="SourceAlpha"
|
||||
result="effect1_dropShadow_4080_12482"
|
||||
></feMorphology>
|
||||
<feOffset dy="2"></feOffset>
|
||||
<feGaussianBlur stdDeviation="2.5"></feGaussianBlur>
|
||||
<feComposite in2="hardAlpha" operator="out"></feComposite>
|
||||
<feColorMatrix
|
||||
type="matrix"
|
||||
values="0 0 0 0 0.416562 0 0 0 0 0.452406 0 0 0 0 0.775 0 0 0 0.18 0"
|
||||
></feColorMatrix>
|
||||
<feBlend
|
||||
mode="normal"
|
||||
in2="BackgroundImageFix"
|
||||
result="effect1_dropShadow_4080_12482"
|
||||
></feBlend>
|
||||
<feBlend
|
||||
mode="normal"
|
||||
in="SourceGraphic"
|
||||
in2="effect1_dropShadow_4080_12482"
|
||||
result="shape"
|
||||
></feBlend>
|
||||
</filter>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@ -20,9 +20,11 @@ import Users from "@pages/dashboard/Content/Users";
|
||||
import Entities from "@pages/dashboard/Content/Entities";
|
||||
import Tariffs from "@pages/dashboard/Content/Tariffs";
|
||||
import DiscountManagement from "@root/pages/dashboard/Content/DiscountManagement/DiscountManagement";
|
||||
import PromocodeManagement from "@pages/dashboard/Content/PromocodeManagement";
|
||||
import { PromocodeManagement } from "@root/pages/dashboard/Content/PromocodeManagement";
|
||||
import { SettingRoles } from "@pages/Setting/SettingRoles";
|
||||
import Support from "@pages/dashboard/Content/Support/Support";
|
||||
import ChatImageNewWindow from "@pages/dashboard/Content/Support/ChatImageNewWindow";
|
||||
import QuizStatistic from "@pages/dashboard/Content/QuizStatistic";
|
||||
|
||||
import theme from "./theme";
|
||||
import "./index.css";
|
||||
@ -103,10 +105,23 @@ root.render(
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/quizStatistic"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<QuizStatistic />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{componentsArray.map((element) => (
|
||||
<Route key={element[0]} path={element[0]} element={element[1]} />
|
||||
<Route
|
||||
key={element[0]}
|
||||
path={element[0]}
|
||||
element={element[1]}
|
||||
/>
|
||||
))}
|
||||
</Route>
|
||||
<Route path={"/image/:srcImage"} element={<ChatImageNewWindow />} />
|
||||
|
||||
<Route path="*" element={<Error404 />} />
|
||||
</Routes>
|
||||
|
||||
@ -1,35 +1,38 @@
|
||||
import { calcCart } from "@frontend/kitui";
|
||||
import Input from "@kitUI/input";
|
||||
import {
|
||||
Button,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableBody,
|
||||
Table,
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
Paper,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
useMediaQuery,
|
||||
useTheme
|
||||
} from "@mui/material";
|
||||
import Input from "@kitUI/input";
|
||||
import { useState } from "react";
|
||||
import { useDiscounts } from "@root/api/discounts";
|
||||
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 { useTariffStore } from "@root/stores/tariffs";
|
||||
import { useDiscountStore } from "@root/stores/discounts";
|
||||
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 { createDiscountFromPromocode } from "@root/utils/createDiscountFromPromocode";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { useState } from "react";
|
||||
import CartItemRow from "./CartItemRow";
|
||||
|
||||
|
||||
export default function Cart() {
|
||||
const theme = useTheme();
|
||||
let discounts = useDiscountStore(state => state.discounts);
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
||||
const discounts = useDiscounts();
|
||||
const promocodes = useAllPromocodes();
|
||||
const cartData = useCartStore((store) => store.cartData);
|
||||
const tariffs = useTariffStore(state => state.tariffs);
|
||||
const [couponField, setCouponField] = useState<string>("");
|
||||
@ -38,10 +41,6 @@ export default function Cart() {
|
||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||
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() {
|
||||
await requestPrivileges();
|
||||
await requestDiscounts();
|
||||
@ -52,8 +51,21 @@ export default function Cart() {
|
||||
|
||||
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 {
|
||||
const cartData = calcCart(cartTariffs, discounts, loyaltyValue, couponField);
|
||||
const cartData = calcCart(cartTariffs, discountsWithPromocodeDiscount, loyaltyValue, userId);
|
||||
|
||||
setErrorMessage(null);
|
||||
setCartData(cartData);
|
||||
@ -84,6 +96,7 @@ export default function Cart() {
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "20px",
|
||||
flexDirection: mobile ? "column" : undefined
|
||||
}}
|
||||
>
|
||||
<FormControlLabel
|
||||
@ -143,7 +156,7 @@ export default function Cart() {
|
||||
padding: "3px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
ml: "auto",
|
||||
ml: mobile ? 0 : "auto",
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
@ -222,45 +235,22 @@ export default function Cart() {
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{cartData.services.flatMap(service => service.tariffs.map(taroffCartData => (
|
||||
<CartItemRow
|
||||
tariffCartData={taroffCartData}
|
||||
appliedServiceDiscount={service.appliedServiceDiscount}
|
||||
/>
|
||||
)))}
|
||||
{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
|
||||
key={tariffCartData.id}
|
||||
tariffCartData={tariffCartData}
|
||||
appliedDiscounts={appliedDiscounts}
|
||||
/>
|
||||
);
|
||||
}))}
|
||||
</TableBody>
|
||||
</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
|
||||
id="transition-modal-title"
|
||||
variant="h6"
|
||||
|
||||
@ -7,14 +7,12 @@ import { useEffect } from "react";
|
||||
|
||||
interface Props {
|
||||
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 envolvedDiscounts = [tariffCartData.privileges[0].appliedPrivilegeDiscount, appliedServiceDiscount].filter((d): d is Discount => !!d);
|
||||
|
||||
useEffect(() => {
|
||||
if (tariffCartData.privileges.length > 1) {
|
||||
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
|
||||
@ -39,22 +37,17 @@ export default function CartItemRow({ tariffCartData, appliedServiceDiscount }:
|
||||
{tariffCartData.privileges[0].description}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{envolvedDiscounts.map((discount, index, arr) => (
|
||||
{appliedDiscounts.map((discount, index, arr) => (
|
||||
<span key={discount.ID}>
|
||||
<DiscountTooltip discount={discount} />
|
||||
{index < arr.length - (appliedServiceDiscount ? 0 : 1) && (
|
||||
{index < arr.length - 1 && (
|
||||
<span>, </span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
{appliedServiceDiscount && (
|
||||
<span>
|
||||
<DiscountTooltip discount={appliedServiceDiscount} />
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{currencyFormatter.format(tariffCartData.price)}
|
||||
{currencyFormatter.format(tariffCartData.price / 100)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@ -1,27 +1,28 @@
|
||||
import { Tooltip, Typography } from "@mui/material";
|
||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
||||
import { formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
||||
|
||||
|
||||
interface Props {
|
||||
discount: Discount;
|
||||
}
|
||||
|
||||
export function DiscountTooltip({ discount }: Props) {
|
||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
||||
|
||||
return discountText ? (
|
||||
<Tooltip
|
||||
title={
|
||||
<>
|
||||
<Typography>Скидка: {discount?.Name}</Typography>
|
||||
<Typography>{discount?.Description}</Typography>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<span>{discountText}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span>Ошибка поиска значения скидки</span>
|
||||
);
|
||||
}
|
||||
import { Tooltip, Typography } from "@mui/material";
|
||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
||||
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
|
||||
|
||||
|
||||
interface Props {
|
||||
discount: Discount;
|
||||
}
|
||||
|
||||
export function DiscountTooltip({ discount }: Props) {
|
||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
||||
|
||||
return discountText ? (
|
||||
<Tooltip
|
||||
title={
|
||||
<>
|
||||
<Typography>Слой: {discount.Layer}</Typography>
|
||||
<Typography>Название: {discount.Name}</Typography>
|
||||
<Typography>Описание: {discount.Description}</Typography>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<span>{discountText}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span>Ошибка поиска значения скидки</span>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
export interface Promocode {
|
||||
id: string;
|
||||
name: string;
|
||||
endless: boolean;
|
||||
from: string;
|
||||
dueTo: string;
|
||||
privileges: string[];
|
||||
}
|
||||
51
src/model/promocodes.ts
Normal file
51
src/model/promocodes.ts
Normal file
@ -0,0 +1,51 @@
|
||||
export type CreatePromocodeBody = {
|
||||
codeword: string;
|
||||
description: string;
|
||||
greetings: string;
|
||||
dueTo: number;
|
||||
activationCount: number;
|
||||
bonus: {
|
||||
privilege: {
|
||||
privilegeID: string;
|
||||
amount: number;
|
||||
serviceKey: string;
|
||||
};
|
||||
discount: {
|
||||
layer: number;
|
||||
factor: number;
|
||||
target: string;
|
||||
threshold: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
export type GetPromocodeListBody = {
|
||||
page: number;
|
||||
limit: number;
|
||||
filter: {
|
||||
active: boolean;
|
||||
text?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type Promocode = CreatePromocodeBody & {
|
||||
id: string;
|
||||
dueTo: number;
|
||||
activationLimit: number;
|
||||
outdated: boolean;
|
||||
offLimit: boolean;
|
||||
delete: boolean;
|
||||
createdAt: string;
|
||||
fastLinks: string[];
|
||||
};
|
||||
|
||||
export type PromocodeList = {
|
||||
count: number;
|
||||
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 = [
|
||||
{
|
||||
@ -25,5 +25,5 @@ export type EditTariffRequestBody = {
|
||||
order: number;
|
||||
price: number;
|
||||
isCustom: boolean;
|
||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||
};
|
||||
|
||||
@ -8,7 +8,7 @@ import {
|
||||
Checkbox,
|
||||
Typography,
|
||||
FormControlLabel,
|
||||
Button,
|
||||
Button, useMediaQuery,
|
||||
} from "@mui/material";
|
||||
import Logo from "@pages/Logo";
|
||||
import OutlinedInput from "@kitUI/outlinedInput";
|
||||
@ -44,7 +44,7 @@ function validate(values: Values) {
|
||||
const SigninForm = () => {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down(600));
|
||||
const initialValues: Values = {
|
||||
email: "",
|
||||
password: "",
|
||||
@ -99,6 +99,7 @@ const SigninForm = () => {
|
||||
"> *": {
|
||||
marginTop: "15px",
|
||||
},
|
||||
padding: isMobile ? "0 16px" : undefined
|
||||
}}
|
||||
>
|
||||
<Logo />
|
||||
|
||||
@ -1,21 +1,23 @@
|
||||
import { KeyboardEvent, useRef, useState } from "react";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { Box, IconButton, TextField, Tooltip, Typography } from "@mui/material";
|
||||
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
|
||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
import { CustomPrivilege } from "@frontend/kitui";
|
||||
import { putPrivilege } from "@root/api/privilegies";
|
||||
import SaveIcon from '@mui/icons-material/Save';
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
|
||||
|
||||
interface CardPrivilege {
|
||||
privilege: PrivilegeWithAmount;
|
||||
privilege: CustomPrivilege;
|
||||
}
|
||||
|
||||
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||
const [inputOpen, setInputOpen] = useState<boolean>(false);
|
||||
const [inputValue, setInputValue] = useState<string>("");
|
||||
const priceRef = useRef<HTMLDivElement>(null);
|
||||
const theme = useTheme();
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(600));
|
||||
|
||||
const translationType = {
|
||||
count: "за единицу",
|
||||
@ -24,7 +26,8 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||
};
|
||||
|
||||
const putPrivileges = async () => {
|
||||
const [_, putedPrivilegeError] = await putPrivilege({
|
||||
|
||||
const [, putedPrivilegeError] = await putPrivilege({
|
||||
name: privilege.name,
|
||||
privilegeId: privilege.privilegeId,
|
||||
serviceKey: privilege.serviceKey,
|
||||
@ -79,7 +82,7 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
|
||||
<Box sx={{ width: "200px", py: "25px" }}>
|
||||
<Box sx={{ width: mobile ? "120px" : "200px", py: "25px" }}>
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{
|
||||
@ -120,7 +123,7 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ width: "600px", display: "flex", justifyContent: "space-around" }}>
|
||||
<Box sx={{ maxWidth: "600px", width: "100%", display: "flex", alignItems: mobile ? "center" : undefined, justifyContent: "space-around", flexDirection: mobile ? "column" : "row", gap: "5px" }}>
|
||||
{inputOpen ? (
|
||||
<TextField
|
||||
type="number"
|
||||
@ -130,7 +133,9 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||
onChange={(event) => setInputValue(event.target.value)}
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
width: "400px",
|
||||
maxWidth: "400px",
|
||||
width: "100%",
|
||||
marginLeft: "5px",
|
||||
"& .MuiInputBase-root": {
|
||||
backgroundColor: "#F2F3F7",
|
||||
height: "48px",
|
||||
|
||||
@ -1,14 +1,14 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
FormControl,
|
||||
ListItemText,
|
||||
MenuItem,
|
||||
Select,
|
||||
SelectChangeEvent,
|
||||
TextField,
|
||||
Button,
|
||||
Checkbox,
|
||||
FormControl,
|
||||
ListItemText,
|
||||
MenuItem,
|
||||
Select,
|
||||
SelectChangeEvent,
|
||||
TextField, useMediaQuery, useTheme,
|
||||
} from "@mui/material";
|
||||
import { MOCK_DATA_USERS } from "@root/api/roles";
|
||||
|
||||
@ -24,7 +24,8 @@ const MenuProps = {
|
||||
|
||||
export default function CreateForm() {
|
||||
const [personName, setPersonName] = useState<string[]>([]);
|
||||
|
||||
const theme = useTheme();
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(600));
|
||||
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
|
||||
const {
|
||||
target: { value },
|
||||
@ -39,7 +40,8 @@ export default function CreateForm() {
|
||||
fullWidth
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
width: "400px",
|
||||
maxWidth: "400px",
|
||||
width: "100%",
|
||||
"& .MuiInputBase-root": {
|
||||
backgroundColor: "#F2F3F7",
|
||||
height: "48px",
|
||||
@ -54,8 +56,8 @@ export default function CreateForm() {
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Button sx={{ ml: "5px", bgcolor: "#fe9903", color: "white" }}>Отправить</Button>
|
||||
<FormControl sx={{ ml: "25px", width: "80%" }}>
|
||||
<Button sx={{ ml: "5px", bgcolor: "#fe9903", color: "white", minWidth: "85px" }}>Отправить</Button>
|
||||
<FormControl sx={{ ml: mobile ? "10px" : "25px", width: "80%" }}>
|
||||
<Select
|
||||
sx={{ bgcolor: "white", height: "48px" }}
|
||||
labelId="demo-multiple-checkbox-label"
|
||||
|
||||
@ -55,7 +55,8 @@ export default function DeleteForm() {
|
||||
fullWidth
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
width: "400px",
|
||||
maxWidth: "400px",
|
||||
width: "100%",
|
||||
"& .MuiInputBase-root": {
|
||||
backgroundColor: "#F2F3F7",
|
||||
height: "48px",
|
||||
|
||||
@ -1,4 +1,14 @@
|
||||
import { AccordionDetails, Table, TableBody, TableCell, TableHead, TableRow, Typography } from "@mui/material";
|
||||
import {
|
||||
AccordionDetails,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Typography,
|
||||
useMediaQuery,
|
||||
useTheme
|
||||
} from "@mui/material";
|
||||
|
||||
import { CustomWrapper } from "@root/kitUI/CustomWrapper";
|
||||
|
||||
@ -9,15 +19,19 @@ import { PrivilegesWrapper } from "./PrivilegiesWrapper";
|
||||
import theme from "../../theme";
|
||||
|
||||
export const SettingRoles = (): JSX.Element => {
|
||||
const theme = useTheme();
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(600));
|
||||
return (
|
||||
<AccordionDetails sx={{ width: "890px" }}>
|
||||
<AccordionDetails sx={{ maxWidth: "890px",
|
||||
width: "100%", }}>
|
||||
<CustomWrapper
|
||||
text="Роли"
|
||||
children={
|
||||
<>
|
||||
<Table
|
||||
sx={{
|
||||
width: "890px",
|
||||
maxWidth: "890px",
|
||||
width: "100%",
|
||||
border: "2px solid",
|
||||
borderColor: "gray",
|
||||
}}
|
||||
@ -52,8 +66,10 @@ export const SettingRoles = (): JSX.Element => {
|
||||
alignItems: "center",
|
||||
borderTop: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
height: "100px",
|
||||
height: mobile ? undefined : "100px",
|
||||
cursor: "pointer",
|
||||
flexDirection: mobile ? "column" : "row",
|
||||
gap: "5px"
|
||||
}}
|
||||
>
|
||||
<FormCreateRoles />
|
||||
@ -63,7 +79,8 @@ export const SettingRoles = (): JSX.Element => {
|
||||
<Table
|
||||
sx={{
|
||||
mt: "30px",
|
||||
width: "890px",
|
||||
maxWidth: "890px",
|
||||
width: "100%",
|
||||
border: "2px solid",
|
||||
borderColor: "gray",
|
||||
}}
|
||||
@ -98,8 +115,10 @@ export const SettingRoles = (): JSX.Element => {
|
||||
alignItems: "center",
|
||||
borderTop: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
height: "100px",
|
||||
cursor: "pointer",
|
||||
height: mobile ? undefined : "100px",
|
||||
cursor: "pointer",
|
||||
flexDirection: mobile ? "column" : "row",
|
||||
gap: "5px"
|
||||
}}
|
||||
>
|
||||
<FormDeleteRoles />
|
||||
@ -110,7 +129,8 @@ export const SettingRoles = (): JSX.Element => {
|
||||
}
|
||||
/>
|
||||
|
||||
<PrivilegesWrapper text="Привилегии" sx={{ mt: "50px" }} />
|
||||
<PrivilegesWrapper text="Привилегии" sx={{ mt: "50px", maxWidth: "890px",
|
||||
width: "100%", }} />
|
||||
</AccordionDetails>
|
||||
);
|
||||
};
|
||||
|
||||
@ -1,16 +1,19 @@
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
import { Box, Button } from "@mui/material";
|
||||
import {Box, Button, useMediaQuery, useTheme} from "@mui/material";
|
||||
|
||||
import { changeDiscount } from "@root/api/discounts";
|
||||
import { findDiscountsById } from "@root/stores/discounts";
|
||||
|
||||
import { requestDiscounts } from "@root/services/discounts.service";
|
||||
import { mutate } from "swr";
|
||||
|
||||
interface Props {
|
||||
selectedRows: GridSelectionModel;
|
||||
}
|
||||
export default function DiscountDataGrid({ selectedRows }: Props) {
|
||||
const theme = useTheme();
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
||||
const changeData = async (isActive: boolean) => {
|
||||
let done = 0;
|
||||
let fatal = 0;
|
||||
@ -22,7 +25,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
||||
return enqueueSnackbar("Скидка не найдена");
|
||||
}
|
||||
|
||||
const [_, changedDiscountError] = await changeDiscount(String(id), {
|
||||
const [, changedDiscountError] = await changeDiscount(String(id), {
|
||||
...discount,
|
||||
Deprecated: isActive,
|
||||
});
|
||||
@ -32,6 +35,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
||||
} else {
|
||||
fatal += 1;
|
||||
}
|
||||
mutate("discounts");
|
||||
}
|
||||
|
||||
await requestDiscounts();
|
||||
@ -46,7 +50,13 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box width="400px" display="flex" justifyContent="space-between">
|
||||
<Box
|
||||
sx={{
|
||||
width: mobile ? "250px" : "400px",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
flexDirection: mobile ? "column" : undefined,
|
||||
gap: "10px"}}>
|
||||
<Button onClick={() => changeData(false)}>Активировать</Button>
|
||||
<Button onClick={() => changeData(true)}>Деактивировать</Button>
|
||||
</Box>
|
||||
|
||||
@ -23,6 +23,7 @@ import { DiscountType, discountTypes } from "@root/model/discount";
|
||||
import { createDiscount } from "@root/api/discounts";
|
||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||
import { mutate } from "swr";
|
||||
|
||||
interface Values {
|
||||
discountNameField: string,
|
||||
@ -58,7 +59,6 @@ export default function CreateDiscount() {
|
||||
values: Values,
|
||||
formikHelpers: FormikHelpers<Values>
|
||||
) => {
|
||||
console.log("работаю")
|
||||
const purchasesAmount = Number(parseFloat(values.purchasesAmountField.replace(",", "."))) * 100;
|
||||
|
||||
const discountFactor =
|
||||
@ -86,12 +86,13 @@ export default function CreateDiscount() {
|
||||
});
|
||||
|
||||
if (createdDiscountError) {
|
||||
console.log("Error creating discount", createdDiscountError);
|
||||
console.error("Error creating discount", createdDiscountError);
|
||||
|
||||
return enqueueSnackbar(createdDiscountError);
|
||||
}
|
||||
|
||||
if (createdDiscountResponse) {
|
||||
mutate("discounts");
|
||||
addDiscount(createdDiscountResponse);
|
||||
}
|
||||
}
|
||||
@ -125,7 +126,7 @@ export default function CreateDiscount() {
|
||||
if (values.discountType === ("service" || "privilege") && !isFinite(parseFloat(values.discountMinValueField.replace(",", ".")))) {
|
||||
errors.discountMinValueField = 'Поле "Минимальное значение" не число'
|
||||
}
|
||||
console.log(errors)
|
||||
console.error(errors)
|
||||
return errors;
|
||||
}
|
||||
|
||||
|
||||
@ -18,7 +18,8 @@ import { deleteDiscount } from "@root/api/discounts";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
import { requestDiscounts } from "@root/services/discounts.service";
|
||||
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[] = [
|
||||
// {
|
||||
@ -93,6 +94,7 @@ const columns: GridColDef[] = [
|
||||
disabled={row.deleted}
|
||||
onClick={() => {
|
||||
deleteDiscount(row.id).then(([discount]) => {
|
||||
mutate("discounts");
|
||||
if (discount) {
|
||||
updateDiscount(discount);
|
||||
}
|
||||
@ -130,11 +132,6 @@ export default function DiscountDataGrid({ selectedRowsHC }: Props) {
|
||||
const rowBackDicounts: GridRowsProp = realDiscounts
|
||||
.filter(({ Layer }) => Layer > 0)
|
||||
.map((discount) => {
|
||||
console.log(
|
||||
discount.Condition[
|
||||
layerValue[discount.Layer] as keyof typeof discount.Condition
|
||||
]
|
||||
);
|
||||
return {
|
||||
id: discount.ID,
|
||||
name: discount.Name,
|
||||
|
||||
@ -31,6 +31,7 @@ import { getDiscountTypeFromLayer } from "@root/utils/discount";
|
||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { useEffect, useState } from "react";
|
||||
import { mutate } from "swr";
|
||||
|
||||
export default function EditDiscountDialog() {
|
||||
const theme = useTheme();
|
||||
@ -59,17 +60,17 @@ export default function EditDiscountDialog() {
|
||||
function setDiscountFields() {
|
||||
if (!discount) return;
|
||||
|
||||
setServiceType(discount.Condition.Group);
|
||||
setServiceType(discount.Condition.Group ?? "");
|
||||
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
||||
setDiscountNameField(discount.Name);
|
||||
setDiscountDescriptionField(discount.Description);
|
||||
setPrivilegeIdField(discount.Condition.Product);
|
||||
setPrivilegeIdField(discount.Condition.Product ?? "");
|
||||
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
|
||||
setPurchasesAmountField(discount.Condition.PurchasesAmount.toString());
|
||||
setPurchasesAmountField(discount.Condition.PurchasesAmount ?? "");
|
||||
setCartPurchasesAmountField(
|
||||
discount.Condition.CartPurchasesAmount.toString()
|
||||
discount.Condition.CartPurchasesAmount ?? ""
|
||||
);
|
||||
setDiscountMinValueField(discount.Condition.PriceFrom.toString());
|
||||
setDiscountMinValueField(discount.Condition.PriceFrom ?? "");
|
||||
},
|
||||
[discount]
|
||||
);
|
||||
@ -131,12 +132,13 @@ export default function EditDiscountDialog() {
|
||||
);
|
||||
|
||||
if (patchedDiscountError) {
|
||||
console.log("Error patching discount", patchedDiscountError);
|
||||
console.error("Error patching discount", patchedDiscountError);
|
||||
|
||||
return enqueueSnackbar(patchedDiscountError);
|
||||
}
|
||||
|
||||
if (patchedDiscountResponse) {
|
||||
mutate("discounts");
|
||||
updateDiscount(patchedDiscountResponse);
|
||||
closeEditDiscountDialog();
|
||||
}
|
||||
|
||||
@ -1,436 +0,0 @@
|
||||
import { Box, Typography, TextField, Checkbox, Button } from "@mui/material";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
|
||||
import Table from "@mui/material/Table";
|
||||
import TableBody from "@mui/material/TableBody";
|
||||
import TableCell from "@mui/material/TableCell";
|
||||
import TableRow from "@mui/material/TableRow";
|
||||
import TableContainer from "@mui/material/TableContainer";
|
||||
import Paper from "@mui/material/Paper";
|
||||
import { DataGrid, GridColDef, GridToolbar } from "@mui/x-data-grid";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import Select, { SelectChangeEvent } from "@mui/material/Select";
|
||||
import theme from "../../../theme";
|
||||
import { usePromocodeStore } from "../../../stores/promocodes";
|
||||
import { useRef, useState } from "react";
|
||||
import { ServiceType } from "@root/model/tariff";
|
||||
|
||||
|
||||
const columns: GridColDef[] = [
|
||||
{
|
||||
field: "id",
|
||||
headerName: "ID",
|
||||
width: 30,
|
||||
sortable: false,
|
||||
},
|
||||
{
|
||||
field: "name",
|
||||
headerName: "Название промокода",
|
||||
width: 200,
|
||||
sortable: false,
|
||||
},
|
||||
{
|
||||
field: "endless",
|
||||
headerName: "Бесконечный",
|
||||
width: 120,
|
||||
sortable: false,
|
||||
},
|
||||
{
|
||||
field: "from",
|
||||
headerName: "От",
|
||||
width: 120,
|
||||
sortable: false,
|
||||
},
|
||||
{
|
||||
field: "dueTo",
|
||||
headerName: "До",
|
||||
width: 120,
|
||||
sortable: false,
|
||||
},
|
||||
{
|
||||
field: "privileges",
|
||||
headerName: "Привилегии",
|
||||
width: 210,
|
||||
sortable: false,
|
||||
}
|
||||
];
|
||||
|
||||
const PromocodeManagement: React.FC = () => {
|
||||
const [checkboxState, setCheckboxState] = useState<boolean>(false);
|
||||
const toggleCheckbox = () => { setCheckboxState(!checkboxState); };
|
||||
|
||||
const [value1, setValue1] = useState<Date>(new Date());
|
||||
const [value2, setValue2] = useState<Date>(new Date());
|
||||
|
||||
const [service, setService] = useState<ServiceType>("templategen");
|
||||
const handleChange = (event: SelectChangeEvent) => {
|
||||
setService(event.target.value as ServiceType);
|
||||
};
|
||||
|
||||
const promocodes = usePromocodeStore(state => state.promocodes);
|
||||
const addPromocodes = usePromocodeStore(state => state.addPromocodes);
|
||||
|
||||
function createPromocode() {
|
||||
// TODO
|
||||
}
|
||||
|
||||
// const promocodeArrayConverted = promocodes.map((item) => {
|
||||
// const dateFrom = item.from ? new Date(Number(item.from)) : "";
|
||||
// const dateDueTo = item.from ? new Date(Number(item.dueTo)) : "";
|
||||
|
||||
// const strFrom = dateFrom
|
||||
// ? `${dateFrom.getDate()}.${dateFrom.getMonth()}.${dateFrom.getFullYear()}`
|
||||
// : "-";
|
||||
|
||||
// const strDueTo = dateDueTo
|
||||
// ? `${dateDueTo.getDate()}.${dateDueTo.getMonth()}.${dateDueTo.getFullYear()}`
|
||||
// : "-";
|
||||
|
||||
// if (item.privileges.length) {
|
||||
// const result = item.privileges.reduce((acc, privilege) => {
|
||||
// acc = acc
|
||||
// ? `${acc}, ${privilege.serviceKey} - ${privilege.discount}%`
|
||||
// : `${privilege.serviceKey} - ${privilege.discount * 100}%`;
|
||||
|
||||
// return acc;
|
||||
// }, "");
|
||||
|
||||
// return { ...item, privileges: result, from: strFrom, dueTo: strDueTo };
|
||||
// } else {
|
||||
// return { ...item, from: strFrom, dueTo: strDueTo };
|
||||
// }
|
||||
// });
|
||||
|
||||
// const createPromocode = (name: string, discount: number) => {
|
||||
// const newPromocode = {
|
||||
// id: new Date().getTime(),
|
||||
// name,
|
||||
// endless: checkboxState,
|
||||
// from: checkboxState ? "" : new Date(value1).getTime() + "",
|
||||
// dueTo: checkboxState ? "" : new Date(value2).getTime() + "",
|
||||
// privileges: [{
|
||||
// good: service,
|
||||
// discount: discount / 100
|
||||
// }]
|
||||
// };
|
||||
|
||||
// const promocodeArrayUpdated = [...promocodes, newPromocode];
|
||||
// addPromocodes(promocodeArrayUpdated);
|
||||
// };
|
||||
|
||||
const promocodeGridData = promocodes.map(procomode => {
|
||||
// TODO
|
||||
})
|
||||
|
||||
const fieldName = useRef<HTMLInputElement | null>(null);
|
||||
const fieldDiscount = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
// const checkFields = () => {
|
||||
// if (fieldName.current != null && fieldDiscount.current != null) {
|
||||
// createPromocode(fieldName.current.value, Number(fieldDiscount.current.value));
|
||||
// }
|
||||
// };
|
||||
|
||||
return (
|
||||
<>
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
width: "90%",
|
||||
height: "60px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
color: theme.palette.secondary.main
|
||||
}}>
|
||||
ПРОМОКОД
|
||||
</Typography>
|
||||
|
||||
<Box sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "left",
|
||||
alignItems: "left",
|
||||
marginTop: "15px",
|
||||
}}>
|
||||
{/*<Typography */}
|
||||
{/* variant="h4" */}
|
||||
{/* sx={{*/}
|
||||
{/* width: "90%",*/}
|
||||
{/* height: "40px",*/}
|
||||
{/* fontWeight: "normal",*/}
|
||||
{/* color: theme.palette.grayDisabled.main,*/}
|
||||
{/* marginTop: "35px"*/}
|
||||
{/*}}>*/}
|
||||
{/* Название:*/}
|
||||
{/*</Typography>*/}
|
||||
<TextField
|
||||
id="standard-basic"
|
||||
label={"Название"}
|
||||
variant="filled"
|
||||
color="secondary"
|
||||
sx={{
|
||||
height: "30px",
|
||||
}}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
}
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main
|
||||
}
|
||||
}}
|
||||
inputRef={fieldName}
|
||||
/>
|
||||
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{
|
||||
width: "90%",
|
||||
height: "40px",
|
||||
fontWeight: "normal",
|
||||
color: theme.palette.grayDisabled.main,
|
||||
marginTop: "75px"
|
||||
}}>
|
||||
Условия:
|
||||
</Typography>
|
||||
|
||||
<Select
|
||||
labelId="demo-simple-select-label"
|
||||
id="demo-simple-select"
|
||||
value={service}
|
||||
label="Age"
|
||||
onChange={handleChange}
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||
borderColor: theme.palette.secondary.main
|
||||
},
|
||||
".MuiSvgIcon-root ": {
|
||||
fill: theme.palette.secondary.main,
|
||||
}
|
||||
}}
|
||||
>
|
||||
<MenuItem value={"Шаблонизатор документов"}>Шаблонизатор</MenuItem>
|
||||
<MenuItem value={"Опросник"}>Опросник</MenuItem>
|
||||
<MenuItem value={"Аналитика сокращателя"}>Аналитика сокращателя</MenuItem>
|
||||
<MenuItem value={"АБ тесты"}>АБ тесты</MenuItem>
|
||||
</Select>
|
||||
|
||||
<TextField
|
||||
id="standard-basic"
|
||||
label={"Процент скидки"}
|
||||
variant="filled"
|
||||
color="secondary"
|
||||
sx={{
|
||||
marginTop: "15px"
|
||||
}}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
}
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main
|
||||
}
|
||||
}}
|
||||
inputRef={fieldDiscount}
|
||||
/>
|
||||
|
||||
<TableContainer component={Paper} sx={{
|
||||
width: "100%",
|
||||
marginTop: "35px",
|
||||
backgroundColor: theme.palette.content.main
|
||||
}}>
|
||||
<Table aria-label="simple table">
|
||||
<TableBody>
|
||||
<TableRow sx={{ border: "1px solid white" }} >
|
||||
<TableCell component="th" scope="row" sx={{ color: theme.palette.secondary.main }}>
|
||||
Работает, если заплатите 100500 денег
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow sx={{ border: "1px solid white" }} >
|
||||
<TableCell component="th" scope="row" sx={{ color: theme.palette.secondary.main }}>
|
||||
Вы должны будете продать душу дьяволу
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{
|
||||
width: "90%",
|
||||
height: "40px",
|
||||
fontWeight: "normal",
|
||||
color: theme.palette.grayDisabled.main,
|
||||
marginTop: "55px"
|
||||
}}>
|
||||
Дата действия:
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
flexWrap: 'wrap'
|
||||
}}
|
||||
>
|
||||
<Typography sx={{
|
||||
width: "35px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "left",
|
||||
}}>С</Typography>
|
||||
|
||||
<DesktopDatePicker
|
||||
inputFormat="DD/MM/YYYY"
|
||||
value={value1}
|
||||
onChange={(e) => { if (e) { setValue1(e); } }}
|
||||
renderInput={(params) => <TextField {...params} />}
|
||||
InputProps={{
|
||||
sx: {
|
||||
height: "40px",
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<Typography sx={{
|
||||
width: "65px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}>по</Typography>
|
||||
|
||||
<DesktopDatePicker
|
||||
inputFormat="DD/MM/YYYY"
|
||||
value={value2}
|
||||
onChange={(e) => { if (e) { setValue2(e); } }}
|
||||
renderInput={(params) => <TextField {...params} />}
|
||||
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",
|
||||
width: "90%",
|
||||
marginTop: theme.spacing(2),
|
||||
}}>
|
||||
<Box sx={{
|
||||
width: "20px",
|
||||
height: "42px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "left",
|
||||
alignItems: "left",
|
||||
marginRight: theme.spacing(1)
|
||||
}}>
|
||||
<Checkbox sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"&.Mui-checked": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}} onClick={() => toggleCheckbox()} />
|
||||
</Box>
|
||||
<Box sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "center"
|
||||
}}>
|
||||
Бессрочно
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{
|
||||
width: "90%",
|
||||
marginTop: "55px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "center"
|
||||
}}>
|
||||
<Button
|
||||
variant="contained"
|
||||
sx={{
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
height: "52px",
|
||||
fontWeight: "normal",
|
||||
fontSize: "17px",
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.grayMedium.main
|
||||
}
|
||||
}}
|
||||
onClick={createPromocode} >
|
||||
Cоздать
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
</Box>
|
||||
|
||||
<Box style={{ width: "80%", marginTop: "55px" }}>
|
||||
<Box style={{ height: 400 }}>
|
||||
<DataGrid
|
||||
checkboxSelection={true}
|
||||
rows={promocodeGridData}
|
||||
columns={columns}
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"& .MuiDataGrid-iconSeparator": {
|
||||
display: "none"
|
||||
},
|
||||
"& .css-levciy-MuiTablePagination-displayedRows": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
"& .MuiSvgIcon-root": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
"& .MuiTablePagination-selectLabel": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
"& .MuiInputBase-root": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
"& .MuiButton-text": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
}}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
onSelectionModelChange={(ids) => console.log("datagrid select")}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
</LocalizationProvider>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export default PromocodeManagement;
|
||||
@ -0,0 +1,426 @@
|
||||
import {
|
||||
Button,
|
||||
FormControlLabel,
|
||||
MenuItem,
|
||||
Radio,
|
||||
RadioGroup,
|
||||
Select,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
|
||||
import { Field, Form, Formik } from "formik";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { requestPrivileges } from "@root/services/privilegies.service";
|
||||
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||
|
||||
import { SERVICE_LIST } from "@root/model/privilege";
|
||||
import theme from "@root/theme";
|
||||
|
||||
import type { TextFieldProps } from "@mui/material";
|
||||
import { CreatePromocodeBody } from "@root/model/promocodes";
|
||||
import type { ChangeEvent } from "react";
|
||||
|
||||
type BonusType = "discount" | "privilege";
|
||||
|
||||
type FormValues = {
|
||||
codeword: string;
|
||||
description: string;
|
||||
greetings: string;
|
||||
dueTo: number;
|
||||
activationCount: number;
|
||||
privilegeId: string;
|
||||
amount: number;
|
||||
layer: 1 | 2;
|
||||
factor: number;
|
||||
target: string;
|
||||
threshold: number;
|
||||
serviceKey: string;
|
||||
};
|
||||
|
||||
type SelectChangeProps = {
|
||||
target: {
|
||||
name: string;
|
||||
value: string;
|
||||
};
|
||||
};
|
||||
|
||||
const initialValues: FormValues = {
|
||||
codeword: "",
|
||||
description: "",
|
||||
greetings: "",
|
||||
dueTo: 0,
|
||||
activationCount: 0,
|
||||
privilegeId: "",
|
||||
amount: 0,
|
||||
layer: 1,
|
||||
factor: 0,
|
||||
target: "",
|
||||
threshold: 0,
|
||||
serviceKey: "",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
createPromocode: (body: CreatePromocodeBody) => Promise<void>;
|
||||
};
|
||||
|
||||
export const CreatePromocodeForm = ({ createPromocode }: Props) => {
|
||||
const [bonusType, setBonusType] = useState<BonusType>("discount");
|
||||
const { privileges } = usePrivilegeStore();
|
||||
|
||||
useEffect(() => {
|
||||
requestPrivileges();
|
||||
}, []);
|
||||
|
||||
const submitForm = (values: FormValues) => {
|
||||
|
||||
const currentPrivilege = privileges.find(
|
||||
(item) => item.privilegeId === values.privilegeId
|
||||
);
|
||||
|
||||
const body = {
|
||||
...values,
|
||||
};
|
||||
|
||||
if ((body.layer === 1 && bonusType === "discount") || bonusType === "privilege") {
|
||||
if (currentPrivilege === undefined) return;
|
||||
body.serviceKey = currentPrivilege?.serviceKey
|
||||
body.target = body.privilegeId
|
||||
}
|
||||
if ((body.layer === 2 && bonusType === "discount")) {
|
||||
if (body.serviceKey === undefined) return;
|
||||
body.target = body.serviceKey
|
||||
}
|
||||
|
||||
const factorFromDiscountValue = 1 - body.factor / 100;
|
||||
|
||||
return createPromocode({
|
||||
codeword: body.codeword,
|
||||
description: body.description,
|
||||
greetings: body.greetings,
|
||||
dueTo: body.dueTo,
|
||||
activationCount: body.activationCount,
|
||||
bonus: {
|
||||
privilege: {
|
||||
privilegeID: body.privilegeId,
|
||||
amount: body.amount,
|
||||
serviceKey: body.serviceKey,
|
||||
},
|
||||
discount: {
|
||||
layer: body.layer,
|
||||
factor: factorFromDiscountValue,
|
||||
target: body.target,
|
||||
threshold: body.threshold,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Formik initialValues={initialValues} onSubmit={submitForm}>
|
||||
{({ values, handleChange, handleBlur, setFieldValue }) => (
|
||||
<Form
|
||||
style={{
|
||||
width: "100%",
|
||||
maxWidth: "600px",
|
||||
padding: "0 10px",
|
||||
}}
|
||||
>
|
||||
<CustomTextField
|
||||
name="codeword"
|
||||
label="Кодовое слово"
|
||||
required
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<CustomTextField
|
||||
name="description"
|
||||
label="Описание"
|
||||
required
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<CustomTextField
|
||||
name="greetings"
|
||||
label="Приветственное сообщение"
|
||||
required
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{
|
||||
height: "40px",
|
||||
fontWeight: "normal",
|
||||
marginTop: "15px",
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
Время существования промокода
|
||||
</Typography>
|
||||
<Field
|
||||
name="dueTo"
|
||||
as={DesktopDatePicker}
|
||||
inputFormat="DD/MM/YYYY"
|
||||
value={values.dueTo ? new Date(Number(values.dueTo) * 1000) : null}
|
||||
onChange={(event: any) => {
|
||||
setFieldValue("dueTo", event.$d.getTime() / 1000 || null);
|
||||
}}
|
||||
renderInput={(params: TextFieldProps) => <TextField {...params} />}
|
||||
InputProps={{
|
||||
sx: {
|
||||
height: "40px",
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<CustomTextField
|
||||
name="activationCount"
|
||||
label="Количество активаций промокода"
|
||||
onChange={({ target }) =>
|
||||
setFieldValue(
|
||||
"activationCount",
|
||||
Number(target.value.replace(/\D/g, ""))
|
||||
)
|
||||
}
|
||||
/>
|
||||
<RadioGroup
|
||||
row
|
||||
name="bonusType"
|
||||
value={bonusType}
|
||||
sx={{ marginTop: "15px" }}
|
||||
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setBonusType(target.value as BonusType);
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
>
|
||||
<FormControlLabel
|
||||
value="discount"
|
||||
control={<Radio color="secondary" />}
|
||||
label="Скидка"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="privilege"
|
||||
control={<Radio color="secondary" />}
|
||||
label="Привилегия"
|
||||
/>
|
||||
</RadioGroup>
|
||||
{bonusType === "discount" && (
|
||||
<>
|
||||
<RadioGroup
|
||||
row
|
||||
name="layer"
|
||||
value={values.layer}
|
||||
sx={{ marginTop: "15px" }}
|
||||
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFieldValue("target", "");
|
||||
setFieldValue("layer", Number(target.value));
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
>
|
||||
<FormControlLabel
|
||||
value="1"
|
||||
control={<Radio color="secondary" />}
|
||||
label="Привилегия"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="2"
|
||||
control={<Radio color="secondary" />}
|
||||
label="Сервис"
|
||||
/>
|
||||
</RadioGroup>
|
||||
<CustomTextField
|
||||
name="factor"
|
||||
label="Процент скидки"
|
||||
required
|
||||
onChange={({ target }) => {
|
||||
setFieldValue(
|
||||
"factor",
|
||||
Number(target.value.replace(/\D/g, ""))
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{
|
||||
height: "40px",
|
||||
fontWeight: "normal",
|
||||
marginTop: "15px",
|
||||
padding: "0 12px",
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
{values.layer === 1 ? "Выбор привилегии" : "Выбор сервиса"}
|
||||
</Typography>
|
||||
{
|
||||
values.layer === 1 ?
|
||||
|
||||
<Field
|
||||
name="privilegeId"
|
||||
as={Select}
|
||||
label={"Привилегия"}
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "2px solid",
|
||||
color: theme.palette.secondary.main,
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||
border: "none",
|
||||
},
|
||||
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
|
||||
}}
|
||||
onChange={({ target }: SelectChangeProps) => {
|
||||
setFieldValue("target", target.value)
|
||||
setFieldValue("privilegeId", target.value)
|
||||
}}
|
||||
children={
|
||||
privileges.map(({ name, privilegeId }) => (
|
||||
<MenuItem key={privilegeId} value={privilegeId}>
|
||||
{name}
|
||||
</MenuItem>
|
||||
))
|
||||
}
|
||||
/>
|
||||
:
|
||||
<Field
|
||||
name="serviceKey"
|
||||
as={Select}
|
||||
label={"Сервис"}
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "2px solid",
|
||||
color: theme.palette.secondary.main,
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||
border: "none",
|
||||
},
|
||||
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
|
||||
}}
|
||||
onChange={({ target }: SelectChangeProps) => {
|
||||
setFieldValue("target", target.value)
|
||||
setFieldValue("serviceKey", target.value)
|
||||
}}
|
||||
children={
|
||||
SERVICE_LIST.map(({ displayName, serviceKey }) => (
|
||||
<MenuItem key={serviceKey} value={serviceKey}>
|
||||
{displayName}
|
||||
</MenuItem>
|
||||
))
|
||||
}
|
||||
/>
|
||||
|
||||
}
|
||||
<CustomTextField
|
||||
name="threshold"
|
||||
label="При каком значении применяется скидка"
|
||||
onChange={({ target }) =>
|
||||
setFieldValue(
|
||||
"threshold",
|
||||
Number(target.value.replace(/\D/g, ""))
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{bonusType === "privilege" && (
|
||||
<>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{
|
||||
height: "40px",
|
||||
fontWeight: "normal",
|
||||
marginTop: "15px",
|
||||
padding: "0 12px",
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
Выбор привилегии
|
||||
</Typography>
|
||||
<Field
|
||||
name="privilegeId"
|
||||
as={Select}
|
||||
label="Привилегия"
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "2px solid",
|
||||
color: theme.palette.secondary.main,
|
||||
borderColor: theme.palette.secondary.main,
|
||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||
border: "none",
|
||||
},
|
||||
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
|
||||
}}
|
||||
children={privileges.map(({ name, privilegeId }) => (
|
||||
<MenuItem key={privilegeId} value={privilegeId}>
|
||||
{name}
|
||||
</MenuItem>
|
||||
))}
|
||||
/>
|
||||
<CustomTextField
|
||||
name="amount"
|
||||
label="Количество"
|
||||
required
|
||||
onChange={({ target }) =>
|
||||
setFieldValue(
|
||||
"amount",
|
||||
Number(target.value.replace(/\D/g, ""))
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="contained"
|
||||
sx={{
|
||||
display: "block",
|
||||
padding: "10px",
|
||||
margin: "15px auto 0",
|
||||
fontWeight: "normal",
|
||||
fontSize: "18px",
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
"&:hover": { backgroundColor: theme.palette.grayMedium.main },
|
||||
}}
|
||||
type="submit"
|
||||
>
|
||||
Cоздать
|
||||
</Button>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
type CustomTextFieldProps = {
|
||||
name: string;
|
||||
label: string;
|
||||
required?: boolean;
|
||||
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
|
||||
};
|
||||
|
||||
const CustomTextField = ({
|
||||
name,
|
||||
label,
|
||||
required = false,
|
||||
onChange,
|
||||
}: CustomTextFieldProps) => (
|
||||
<Field
|
||||
name={name}
|
||||
label={label}
|
||||
required={required}
|
||||
variant="filled"
|
||||
color="secondary"
|
||||
as={TextField}
|
||||
onChange={onChange}
|
||||
sx={{ width: "100%", marginTop: "15px" }}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: { color: theme.palette.secondary.main },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
@ -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,338 @@
|
||||
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 { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||
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";
|
||||
|
||||
const host = window.location.hostname;
|
||||
let isTest = host.includes("s");
|
||||
|
||||
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(`https://${isTest ? "s" : ""}quiz.pena.digital/?fl=${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 { privileges } = usePrivilegeStore();
|
||||
const currentPrivilegeId = promocodes.find((promocode) => promocode.id === id)
|
||||
?.bonus.privilege.privilegeID;
|
||||
const privilege = privileges.find(
|
||||
(item) => item.privilegeId === currentPrivilegeId
|
||||
);
|
||||
const promocode = promocodes.find((item) => item.id === id);
|
||||
const createFastlink = async () => {
|
||||
await createFastLink(id);
|
||||
};
|
||||
|
||||
const getParseData = () => {
|
||||
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, promocodes]);
|
||||
|
||||
// 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", padding: "32px 32px 16px" },
|
||||
}}
|
||||
>
|
||||
<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
|
||||
/>
|
||||
{privilege === undefined ? (
|
||||
<Typography
|
||||
sx={{
|
||||
margin: "10px 0 0",
|
||||
textAlign: "center",
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
Нет привилегии
|
||||
</Typography>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
color: "#e6e8ec",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
margin: "20px 0",
|
||||
}}
|
||||
>
|
||||
<Typography>название привилегии: {privilege.name}</Typography>
|
||||
<Typography>
|
||||
{promocode?.activationCount} активаций из{" "}
|
||||
{promocode?.activationLimit}
|
||||
</Typography>
|
||||
<Typography>приветствие: "{promocode?.greetings}"</Typography>
|
||||
{promocode?.bonus?.discount?.factor !== undefined && (
|
||||
<Typography>
|
||||
скидка: {100 - promocode?.bonus?.discount?.factor * 100}%
|
||||
</Typography>
|
||||
)}
|
||||
{
|
||||
<Typography>
|
||||
количество привилегии: {promocode?.bonus?.privilege?.amount}
|
||||
</Typography>
|
||||
}
|
||||
{promocode?.dueTo !== undefined && promocode.dueTo > 0 && (
|
||||
<Typography>
|
||||
действует до: {new Date(promocode.dueTo).toLocaleString()}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
114
src/pages/dashboard/Content/PromocodeManagement/index.tsx
Normal file
114
src/pages/dashboard/Content/PromocodeManagement/index.tsx
Normal file
@ -0,0 +1,114 @@
|
||||
import { useState } from "react";
|
||||
import { Box, Typography, useTheme } from "@mui/material";
|
||||
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { usePromocodes } from "@root/api/promocode/swr";
|
||||
import { fadeIn } from "@root/utils/style/keyframes";
|
||||
import { CreatePromocodeForm } from "./CreatePromocodeForm";
|
||||
import { usePromocodeGridColDef } from "./usePromocodeGridColDef";
|
||||
import { StatisticsModal } from "./StatisticsModal";
|
||||
import DeleteModal from "./DeleteModal";
|
||||
|
||||
export const PromocodeManagement = () => {
|
||||
const theme = useTheme();
|
||||
|
||||
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
|
||||
);
|
||||
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
|
||||
|
||||
return (
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
width: "90%",
|
||||
height: "60px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
textTransform: "uppercase",
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
Создание промокода
|
||||
</Typography>
|
||||
<CreatePromocodeForm createPromocode={createPromocode} />
|
||||
<Box style={{ width: "80%", marginTop: "55px" }}>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
rows={data?.items ?? []}
|
||||
columns={columns}
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"& .MuiDataGrid-iconSeparator": { display: "none" },
|
||||
"& .css-levciy-MuiTablePagination-displayedRows": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiTablePagination-selectLabel": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
|
||||
"& .MuiButton-text": { color: theme.palette.secondary.main },
|
||||
"& .MuiDataGrid-overlay": {
|
||||
backgroundColor: "rgba(255, 255, 255, 0.1)",
|
||||
animation: `${fadeIn} 0.5s ease-out`,
|
||||
},
|
||||
}}
|
||||
components={{
|
||||
Toolbar: GridToolbar,
|
||||
LoadingOverlay: GridLoadingOverlay,
|
||||
}}
|
||||
loading={isValidating}
|
||||
paginationMode="server"
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
rowCount={promocodesCount}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
rowsPerPageOptions={[10, 25, 50, 100]}
|
||||
autoHeight
|
||||
/>
|
||||
</Box>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
@ -0,0 +1,85 @@
|
||||
import { IconButton } from "@mui/material";
|
||||
import { GridColDef } from "@mui/x-data-grid";
|
||||
import { Promocode } from "@root/model/promocodes";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import { BarChart, Delete } from "@mui/icons-material";
|
||||
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",
|
||||
headerName: "ID",
|
||||
width: 30,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.id,
|
||||
},
|
||||
{
|
||||
field: "codeword",
|
||||
headerName: "Кодовое слово",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.codeword,
|
||||
},
|
||||
{
|
||||
field: "factor",
|
||||
headerName: "Коэф. скидки",
|
||||
width: 120,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) =>
|
||||
Math.round(row.bonus.discount.factor * 1000) / 1000,
|
||||
},
|
||||
{
|
||||
field: "activationCount",
|
||||
headerName: "Кол-во активаций",
|
||||
width: 140,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.activationCount,
|
||||
},
|
||||
{
|
||||
field: "dueTo",
|
||||
headerName: "Истекает",
|
||||
width: 160,
|
||||
sortable: false,
|
||||
valueGetter: ({ row }) => row.dueTo * 1000,
|
||||
valueFormatter: ({ value }) => `${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",
|
||||
headerName: "",
|
||||
width: 60,
|
||||
sortable: false,
|
||||
renderCell: (params) => {
|
||||
return (
|
||||
<IconButton onClick={() => deletePromocode(params.row.id)}>
|
||||
<Delete />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[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>
|
||||
</>
|
||||
}
|
||||
@ -42,11 +42,21 @@ const columns: GridColDef<UserType, string>[] = [
|
||||
interface Props {
|
||||
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
||||
users: UserType[];
|
||||
page: number;
|
||||
setPage: (page: number) => void;
|
||||
pageSize: number;
|
||||
pagesCount: number;
|
||||
onPageSizeChange?: (count: number) => void;
|
||||
}
|
||||
|
||||
export default function ServiceUsersDG({
|
||||
handleSelectionChange,
|
||||
users = [],
|
||||
page,
|
||||
setPage,
|
||||
pageSize = 10,
|
||||
pagesCount = 1,
|
||||
onPageSizeChange,
|
||||
}: Props) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
@ -60,6 +70,13 @@ export default function ServiceUsersDG({
|
||||
rows={users}
|
||||
columns={columns}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
rowCount={pageSize * pagesCount}
|
||||
rowsPerPageOptions={[10, 25, 50, 100]}
|
||||
paginationMode="server"
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={onPageSizeChange}
|
||||
onSelectionModelChange={handleSelectionChange}
|
||||
onCellClick={({ row }, event) => {
|
||||
event.stopPropagation();
|
||||
|
||||
@ -10,7 +10,38 @@ import { sendTicketMessage } from "@root/api/tickets";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { useTicketStore } from "@root/stores/tickets";
|
||||
import { getMessageFromFetchError, throttle, useEventListener, useSSESubscription, useTicketMessages, useToken } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
import ChatImage from "./ChatImage";
|
||||
import ChatDocument from "./ChatDocument";
|
||||
import ChatVideo from "./ChatVideo";
|
||||
import ChatMessage from "./ChatMessage";
|
||||
import { ACCEPT_SEND_MEDIA_TYPES_MAP, MAX_FILE_SIZE, MAX_PHOTO_SIZE, MAX_VIDEO_SIZE } from "./fileUpload";
|
||||
|
||||
const tooLarge = "Файл слишком большой"
|
||||
const checkAcceptableMediaType = (file: File) => {
|
||||
if (file === null) return ""
|
||||
|
||||
const segments = file?.name.split('.');
|
||||
const extension = segments[segments.length - 1];
|
||||
const type = extension.toLowerCase();
|
||||
|
||||
switch (type) {
|
||||
case ACCEPT_SEND_MEDIA_TYPES_MAP.document.find(name => name === type):
|
||||
if (file.size > MAX_FILE_SIZE) return tooLarge
|
||||
return ""
|
||||
|
||||
case ACCEPT_SEND_MEDIA_TYPES_MAP.picture.find(name => name === type):
|
||||
if (file.size > MAX_PHOTO_SIZE) return tooLarge
|
||||
return ""
|
||||
|
||||
case ACCEPT_SEND_MEDIA_TYPES_MAP.video.find(name => name === type):
|
||||
if (file.size > MAX_VIDEO_SIZE) return tooLarge
|
||||
return ""
|
||||
|
||||
default:
|
||||
return "Не удалось отправить файл. Недопустимый тип"
|
||||
}
|
||||
}
|
||||
|
||||
export default function Chat() {
|
||||
const token = useToken();
|
||||
@ -26,6 +57,8 @@ export default function Chat() {
|
||||
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
|
||||
const fetchState = useMessageStore(state => state.ticketMessagesFetchState);
|
||||
const lastMessageId = useMessageStore(state => state.lastMessageId);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [disableFileButton, setDisableFileButton] = useState(false);
|
||||
|
||||
const ticket = tickets.find(ticket => ticket.id === ticketId);
|
||||
|
||||
@ -107,7 +140,40 @@ export default function Chat() {
|
||||
setMessageField("");
|
||||
}
|
||||
|
||||
function handleAddAttachment() { }
|
||||
const sendFile = async (file: File) => {
|
||||
if (file === undefined) return true;
|
||||
|
||||
let data;
|
||||
|
||||
const ticketId = ticket?.id
|
||||
if (ticketId !== undefined) {
|
||||
try {
|
||||
const body = new FormData();
|
||||
|
||||
body.append(file.name, file);
|
||||
body.append("ticket", ticketId);
|
||||
await makeRequest({
|
||||
url: process.env.REACT_APP_DOMAIN + "/heruvym/sendFiles",
|
||||
body: body,
|
||||
method: "POST",
|
||||
});
|
||||
} catch (error: any) {
|
||||
const errorMessage = getMessageFromFetchError(error);
|
||||
if (errorMessage) enqueueSnackbar(errorMessage);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
const sendFileHC = async (file: File) => {
|
||||
const check = checkAcceptableMediaType(file)
|
||||
if (check.length > 0) {
|
||||
enqueueSnackbar(check)
|
||||
return
|
||||
}
|
||||
setDisableFileButton(true)
|
||||
await sendFile(file)
|
||||
setDisableFileButton(false)
|
||||
};
|
||||
|
||||
function handleTextfieldKeyPress(e: KeyboardEvent) {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
@ -145,9 +211,66 @@ export default function Chat() {
|
||||
colorScheme: "dark",
|
||||
}}
|
||||
>
|
||||
{ticket && messages.map(message =>
|
||||
<Message key={message.id} message={message} isSelf={ticket.user !== message.user_id} />
|
||||
)}
|
||||
{ticket &&
|
||||
messages.map((message) => {
|
||||
const isFileVideo = () => {
|
||||
if (message.files) {
|
||||
return (ACCEPT_SEND_MEDIA_TYPES_MAP.video.some((fileType) =>
|
||||
message.files[0].toLowerCase().endsWith(fileType),
|
||||
))
|
||||
}
|
||||
};
|
||||
const isFileImage = () => {
|
||||
if (message.files) {
|
||||
return (ACCEPT_SEND_MEDIA_TYPES_MAP.picture.some((fileType) =>
|
||||
message.files[0].toLowerCase().endsWith(fileType),
|
||||
))
|
||||
}
|
||||
};
|
||||
const isFileDocument = () => {
|
||||
if (message.files) {
|
||||
return (ACCEPT_SEND_MEDIA_TYPES_MAP.document.some((fileType) =>
|
||||
message.files[0].toLowerCase().endsWith(fileType),
|
||||
))
|
||||
}
|
||||
};
|
||||
if (message.files !== null && message.files.length > 0 && isFileImage()) {
|
||||
return <ChatImage
|
||||
unAuthenticated
|
||||
key={message.id}
|
||||
file={message.files[0]}
|
||||
createdAt={message.created_at}
|
||||
isSelf={ticket.user !== message.user_id}
|
||||
/>
|
||||
}
|
||||
if (message.files !== null && message.files.length > 0 && isFileVideo()) {
|
||||
return <ChatVideo
|
||||
unAuthenticated
|
||||
key={message.id}
|
||||
file={message.files[0]}
|
||||
createdAt={message.created_at}
|
||||
isSelf={ticket.user !== message.user_id}
|
||||
/>
|
||||
}
|
||||
if (message.files !== null && message.files.length > 0 && isFileDocument()) {
|
||||
return <ChatDocument
|
||||
unAuthenticated
|
||||
key={message.id}
|
||||
file={message.files[0]}
|
||||
createdAt={message.created_at}
|
||||
isSelf={ticket.user !== message.user_id}
|
||||
/>
|
||||
}
|
||||
return <ChatMessage
|
||||
unAuthenticated
|
||||
key={message.id}
|
||||
text={message.message}
|
||||
createdAt={message.created_at}
|
||||
isSelf={ticket.user !== message.user_id}
|
||||
/>
|
||||
|
||||
})
|
||||
}
|
||||
</Box>
|
||||
{ticket &&
|
||||
<TextField
|
||||
@ -177,13 +300,24 @@ export default function Chat() {
|
||||
<SendIcon sx={{ color: theme.palette.golden.main }} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
onClick={handleAddAttachment}
|
||||
onClick={() => {
|
||||
if (!disableFileButton) fileInputRef.current?.click()
|
||||
}}
|
||||
sx={{
|
||||
height: "45px",
|
||||
width: "45px",
|
||||
p: 0,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
id="fileinput"
|
||||
onChange={(e) => {
|
||||
if (e.target.files?.[0]) sendFileHC(e.target.files?.[0]);
|
||||
}}
|
||||
style={{ display: "none" }}
|
||||
type="file"
|
||||
/>
|
||||
<AttachFileIcon sx={{ color: theme.palette.golden.main }} />
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
|
||||
62
src/pages/dashboard/Content/Support/Chat/ChatDocument.tsx
Normal file
62
src/pages/dashboard/Content/Support/Chat/ChatDocument.tsx
Normal file
@ -0,0 +1,62 @@
|
||||
import { Box, Link, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import DownloadIcon from '@mui/icons-material/Download';
|
||||
|
||||
interface Props {
|
||||
unAuthenticated?: boolean;
|
||||
isSelf: boolean;
|
||||
file: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ChatDocument({
|
||||
unAuthenticated = false,
|
||||
isSelf,
|
||||
file,
|
||||
createdAt,
|
||||
}: Props) {
|
||||
const theme = useTheme();
|
||||
|
||||
const date = new Date(createdAt);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
gap: "9px",
|
||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||
justifyContent: isSelf ? "end" : "start",
|
||||
}}
|
||||
>
|
||||
<Typography sx={{
|
||||
fontSize: "12px",
|
||||
alignSelf: "end",
|
||||
}}>
|
||||
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "#2a2b2c",
|
||||
p: "12px",
|
||||
border: `1px solid ${theme.palette.golden.main}`,
|
||||
borderRadius: "20px",
|
||||
borderTopLeftRadius: isSelf ? "20px" : 0,
|
||||
borderTopRightRadius: isSelf ? 0 : "20px",
|
||||
maxWidth: "90%",
|
||||
}}
|
||||
>
|
||||
<Link
|
||||
|
||||
download
|
||||
href={`https://storage.yandexcloud.net/pair/${file}`}
|
||||
style={{
|
||||
color: "#7E2AEA",
|
||||
display: "flex",
|
||||
gap: "10px",
|
||||
}}
|
||||
>
|
||||
<DownloadIcon/>
|
||||
</Link>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
68
src/pages/dashboard/Content/Support/Chat/ChatImage.tsx
Normal file
68
src/pages/dashboard/Content/Support/Chat/ChatImage.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
import {
|
||||
Box,
|
||||
ButtonBase,
|
||||
Link,
|
||||
Typography,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
interface Props {
|
||||
unAuthenticated?: boolean;
|
||||
isSelf: boolean;
|
||||
file: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ChatImage({
|
||||
unAuthenticated = false,
|
||||
isSelf,
|
||||
file,
|
||||
createdAt,
|
||||
}: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const navigate = useNavigate();
|
||||
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
gap: "9px",
|
||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||
justifyContent: isSelf ? "end" : "start",
|
||||
}}
|
||||
>
|
||||
<Typography sx={{
|
||||
fontSize: "12px",
|
||||
alignSelf: "end",
|
||||
}}>
|
||||
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "#2a2b2c",
|
||||
p: "12px",
|
||||
border: `1px solid ${theme.palette.golden.main}`,
|
||||
borderRadius: "20px",
|
||||
borderTopLeftRadius: isSelf ? "20px" : 0,
|
||||
borderTopRightRadius: isSelf ? 0 : "20px",
|
||||
maxWidth: "90%",
|
||||
}}
|
||||
>
|
||||
<ButtonBase target="_blank" href={`/image/${file}`}>
|
||||
<Box
|
||||
component="img"
|
||||
sx={{
|
||||
height: "217px",
|
||||
width: "217px",
|
||||
}}
|
||||
src={`https://storage.yandexcloud.net/pair/${file}`}
|
||||
/>
|
||||
</ButtonBase>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
53
src/pages/dashboard/Content/Support/Chat/ChatMessage.tsx
Normal file
53
src/pages/dashboard/Content/Support/Chat/ChatMessage.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
|
||||
interface Props {
|
||||
unAuthenticated?: boolean;
|
||||
isSelf: boolean;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ChatMessage({
|
||||
unAuthenticated = false,
|
||||
isSelf,
|
||||
text,
|
||||
createdAt,
|
||||
}: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
gap: "9px",
|
||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||
justifyContent: isSelf ? "end" : "start",
|
||||
}}
|
||||
>
|
||||
<Typography sx={{
|
||||
fontSize: "12px",
|
||||
alignSelf: "end",
|
||||
}}>
|
||||
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "#2a2b2c",
|
||||
p: "12px",
|
||||
border: `1px solid ${theme.palette.golden.main}`,
|
||||
borderRadius: "20px",
|
||||
borderTopLeftRadius: isSelf ? "20px" : 0,
|
||||
borderTopRightRadius: isSelf ? 0 : "20px",
|
||||
maxWidth: "90%",
|
||||
}}
|
||||
>
|
||||
<Typography fontSize="14px" sx={{ wordBreak: "break-word" }}>
|
||||
{text}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
67
src/pages/dashboard/Content/Support/Chat/ChatVideo.tsx
Normal file
67
src/pages/dashboard/Content/Support/Chat/ChatVideo.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
interface Props {
|
||||
unAuthenticated?: boolean;
|
||||
isSelf: boolean;
|
||||
file: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function ChatImage({
|
||||
unAuthenticated = false,
|
||||
isSelf,
|
||||
file,
|
||||
createdAt,
|
||||
}: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
gap: "9px",
|
||||
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
|
||||
justifyContent: isSelf ? "end" : "start",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: "12px",
|
||||
alignSelf: "end",
|
||||
}}
|
||||
>
|
||||
{new Date(createdAt).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "#2a2b2c",
|
||||
p: "12px",
|
||||
border: `1px solid ${theme.palette.golden.main}`,
|
||||
borderRadius: "20px",
|
||||
borderTopLeftRadius: isSelf ? "20px" : 0,
|
||||
borderTopRightRadius: isSelf ? 0 : "20px",
|
||||
maxWidth: "90%",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="video"
|
||||
sx={{
|
||||
pointerEvents: "auto",
|
||||
height: "217px",
|
||||
width: "auto",
|
||||
minWidth: "217px",
|
||||
}}
|
||||
controls
|
||||
>
|
||||
<source src={`https://storage.yandexcloud.net/pair/${file}`} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -18,7 +18,6 @@ export default function Message({ message, isSelf }: Props) {
|
||||
{new Date(message.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</Typography>
|
||||
);
|
||||
|
||||
return (
|
||||
<Box sx={{
|
||||
display: "flex",
|
||||
|
||||
9
src/pages/dashboard/Content/Support/Chat/fileUpload.ts
Normal file
9
src/pages/dashboard/Content/Support/Chat/fileUpload.ts
Normal file
@ -0,0 +1,9 @@
|
||||
export const MAX_FILE_SIZE = 10485760;
|
||||
export const MAX_PHOTO_SIZE = 5242880;
|
||||
export const MAX_VIDEO_SIZE = 52428800;
|
||||
|
||||
export const ACCEPT_SEND_MEDIA_TYPES_MAP = {
|
||||
picture: ["jpg", "png"],
|
||||
video: ["mp4"],
|
||||
document: ["doc", "docx", "pdf", "txt", "xlsx", "csv"],
|
||||
} as const;
|
||||
19
src/pages/dashboard/Content/Support/ChatImageNewWindow.tsx
Normal file
19
src/pages/dashboard/Content/Support/ChatImageNewWindow.tsx
Normal file
@ -0,0 +1,19 @@
|
||||
import { Box } from "@mui/material";
|
||||
import { useLocation } from "react-router-dom";
|
||||
|
||||
export default function ChatImageNewWindow() {
|
||||
const location = useLocation();
|
||||
const srcImage = location.pathname.split("image/")[1];
|
||||
return (
|
||||
<>
|
||||
<Box
|
||||
component="img"
|
||||
sx={{
|
||||
maxHeight: "100vh",
|
||||
maxWidth: "100vw",
|
||||
}}
|
||||
src={`https://storage.yandexcloud.net/pair/${srcImage}`}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -2,52 +2,52 @@ import { ReactNode, useState } from "react";
|
||||
import { Box, Typography, useTheme } from "@mui/material";
|
||||
import ExpandIcon from "./ExpandIcon";
|
||||
|
||||
|
||||
interface Props {
|
||||
headerText: string;
|
||||
children: ReactNode;
|
||||
headerText: string;
|
||||
children: (callback: () => void) => ReactNode;
|
||||
}
|
||||
|
||||
export default function Collapse({ headerText, children }: Props) {
|
||||
const theme = useTheme();
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
const theme = useTheme();
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
|
||||
return (
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: "relative",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
onClick={() => setIsExpanded((prev) => !prev)}
|
||||
sx={{
|
||||
height: "72px",
|
||||
p: "16px",
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
borderRadius: "12px",
|
||||
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4">{headerText}</Typography>
|
||||
<ExpandIcon isExpanded={isExpanded} />
|
||||
</Box>
|
||||
{isExpanded && (
|
||||
<Box
|
||||
sx={{
|
||||
position: "relative",
|
||||
}}
|
||||
sx={{
|
||||
mt: "8px",
|
||||
position: "absolute",
|
||||
zIndex: 100,
|
||||
backgroundColor: theme.palette.content.main,
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
onClick={() => setIsExpanded(prev => !prev)}
|
||||
sx={{
|
||||
height: "72px",
|
||||
p: "16px",
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
borderRadius: "12px",
|
||||
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4">{headerText}</Typography>
|
||||
<ExpandIcon isExpanded={isExpanded} />
|
||||
</Box>
|
||||
{isExpanded &&
|
||||
<Box sx={{
|
||||
mt: "8px",
|
||||
position: "absolute",
|
||||
zIndex: 100,
|
||||
backgroundColor: theme.palette.content.main,
|
||||
width: "100%",
|
||||
}}>
|
||||
{children}
|
||||
</Box>
|
||||
}
|
||||
</Box >
|
||||
|
||||
);
|
||||
}
|
||||
{children(() => setIsExpanded(false))}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,61 +1,103 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Box, useMediaQuery, useTheme } from "@mui/material";
|
||||
import Chat from "./Chat/Chat";
|
||||
import Collapse from "./Collapse";
|
||||
import TicketList from "./TicketList/TicketList";
|
||||
import { Ticket } from "@root/model/ticket";
|
||||
import { clearTickets, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
|
||||
import {
|
||||
clearTickets,
|
||||
setTicketsFetchState,
|
||||
updateTickets,
|
||||
useTicketStore,
|
||||
} from "@root/stores/tickets";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { clearMessageState } from "@root/stores/messages";
|
||||
import { getMessageFromFetchError, useSSESubscription, useTicketsFetcher, useToken } from "@frontend/kitui";
|
||||
import {
|
||||
getMessageFromFetchError,
|
||||
useSSESubscription,
|
||||
useTicketsFetcher,
|
||||
useToken,
|
||||
} from "@frontend/kitui";
|
||||
import ModalUser from "@root/pages/dashboard/ModalUser";
|
||||
|
||||
export default function Support() {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
||||
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
||||
const token = useToken();
|
||||
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
|
||||
const [activeUserId, setActiveUserId] = useState<string>("");
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
||||
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
||||
const token = useToken();
|
||||
|
||||
useTicketsFetcher({
|
||||
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
|
||||
ticketsPerPage,
|
||||
ticketApiPage,
|
||||
onSuccess: result => {
|
||||
if (result.data) updateTickets(result.data);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
},
|
||||
onFetchStateChange: setTicketsFetchState,
|
||||
});
|
||||
useTicketsFetcher({
|
||||
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
|
||||
ticketsPerPage,
|
||||
ticketApiPage,
|
||||
onSuccess: (result) => {
|
||||
if (result.data) updateTickets(result.data);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
},
|
||||
onFetchStateChange: setTicketsFetchState,
|
||||
});
|
||||
|
||||
useSSESubscription<Ticket>({
|
||||
enabled: Boolean(token),
|
||||
url: process.env.REACT_APP_DOMAIN + `/heruvym/subscribe?Authorization=${token}`,
|
||||
onNewData: updateTickets,
|
||||
onDisconnect: () => {
|
||||
clearMessageState();
|
||||
clearTickets();
|
||||
},
|
||||
marker: "ticket"
|
||||
});
|
||||
useSSESubscription<Ticket>({
|
||||
enabled: Boolean(token),
|
||||
url:
|
||||
process.env.REACT_APP_DOMAIN +
|
||||
`/heruvym/subscribe?Authorization=${token}`,
|
||||
onNewData: updateTickets,
|
||||
onDisconnect: () => {
|
||||
clearMessageState();
|
||||
clearTickets();
|
||||
},
|
||||
marker: "ticket",
|
||||
});
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
flexDirection: upMd ? "row" : "column",
|
||||
gap: "12px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<Collapse headerText="Тикеты">
|
||||
<TicketList />
|
||||
</Collapse>
|
||||
)}
|
||||
<Chat />
|
||||
{upMd && <TicketList />}
|
||||
</Box>
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!openUserModal) {
|
||||
setActiveUserId("");
|
||||
}
|
||||
}, [openUserModal]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeUserId) {
|
||||
setOpenUserModal(true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setOpenUserModal(false);
|
||||
}, [activeUserId]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
flexDirection: upMd ? "row" : "column",
|
||||
gap: "12px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<Collapse headerText="Тикеты">
|
||||
{(closeCollapse) => (
|
||||
<TicketList
|
||||
closeCollapse={closeCollapse}
|
||||
setActiveUserId={setActiveUserId}
|
||||
/>
|
||||
)}
|
||||
</Collapse>
|
||||
)}
|
||||
<Chat />
|
||||
{upMd && <TicketList setActiveUserId={setActiveUserId} />}
|
||||
<ModalUser
|
||||
open={openUserModal}
|
||||
onClose={() => setOpenUserModal(false)}
|
||||
userId={activeUserId}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,91 +1,108 @@
|
||||
import CircleIcon from "@mui/icons-material/Circle";
|
||||
import { Box, Card, CardActionArea, CardContent, CardHeader, Divider, Typography, useTheme } from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardActionArea,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
Divider,
|
||||
Typography,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { green } from "@mui/material/colors";
|
||||
import { Ticket } from "@root/model/ticket";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
|
||||
const flexCenterSx = {
|
||||
textAlign: "center",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
padding: "10px",
|
||||
textAlign: "center",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
padding: "10px",
|
||||
};
|
||||
|
||||
interface Props {
|
||||
ticket: Ticket;
|
||||
ticket: Ticket;
|
||||
setActiveUserId: (userId: string) => void;
|
||||
}
|
||||
|
||||
export default function TicketItem({ ticket }: Props) {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const ticketId = useParams().ticketId;
|
||||
export default function TicketItem({ ticket, setActiveUserId }: Props) {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const ticketId = useParams().ticketId;
|
||||
|
||||
const isUnread = ticket.user === ticket.top_message.user_id;
|
||||
const isSelected = ticket.id === ticketId;
|
||||
const isUnread = ticket.user === ticket.top_message.user_id;
|
||||
const isSelected = ticket.id === ticketId;
|
||||
|
||||
const unreadSx = {
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.golden.main,
|
||||
backgroundColor: theme.palette.goldenMedium.main
|
||||
};
|
||||
const unreadSx = {
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.golden.main,
|
||||
backgroundColor: theme.palette.goldenMedium.main,
|
||||
};
|
||||
|
||||
const selectedSx = {
|
||||
border: `2px solid ${theme.palette.secondary.main}`,
|
||||
};
|
||||
const selectedSx = {
|
||||
border: `2px solid ${theme.palette.secondary.main}`,
|
||||
};
|
||||
|
||||
function handleCardClick() {
|
||||
navigate(`/support/${ticket.id}`);
|
||||
}
|
||||
function handleCardClick() {
|
||||
navigate(`/support/${ticket.id}`);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card sx={{
|
||||
minHeight: "70px",
|
||||
return (
|
||||
<Card
|
||||
sx={{
|
||||
minHeight: "70px",
|
||||
backgroundColor: "transparent",
|
||||
color: "white",
|
||||
...(isUnread && unreadSx),
|
||||
...(isSelected && selectedSx),
|
||||
}}
|
||||
>
|
||||
<CardActionArea onClick={handleCardClick}>
|
||||
<CardHeader
|
||||
title={<Typography>{ticket.title}</Typography>}
|
||||
disableTypography
|
||||
sx={{
|
||||
textAlign: "center",
|
||||
p: "4px",
|
||||
}}
|
||||
/>
|
||||
<Divider />
|
||||
<CardContent
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
backgroundColor: "transparent",
|
||||
color: "white",
|
||||
...(isUnread && unreadSx),
|
||||
...(isSelected && selectedSx),
|
||||
}}>
|
||||
<CardActionArea onClick={handleCardClick}>
|
||||
<CardHeader
|
||||
title={<Typography>{ticket.title}</Typography>}
|
||||
disableTypography
|
||||
sx={{
|
||||
textAlign: "center",
|
||||
p: "4px",
|
||||
}}
|
||||
/>
|
||||
<Divider />
|
||||
<CardContent sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
backgroundColor: "transparent",
|
||||
p: 0,
|
||||
}}>
|
||||
<Box sx={flexCenterSx}>
|
||||
{new Date(ticket.top_message.created_at).toLocaleDateString()}
|
||||
</Box>
|
||||
<Box sx={{
|
||||
...flexCenterSx,
|
||||
overflow: "hidden",
|
||||
whiteSpace: "nowrap",
|
||||
display: "block",
|
||||
flexGrow: 1,
|
||||
}}>
|
||||
{ticket.top_message.message}
|
||||
</Box>
|
||||
<Box sx={flexCenterSx}>
|
||||
<CircleIcon sx={{
|
||||
color: green[700],
|
||||
transform: "scale(0.8)"
|
||||
}} />
|
||||
</Box>
|
||||
<Box sx={flexCenterSx}>
|
||||
ИНФО
|
||||
</Box>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
p: 0,
|
||||
}}
|
||||
>
|
||||
<Box sx={flexCenterSx}>
|
||||
{new Date(ticket.top_message.created_at).toLocaleDateString()}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
...flexCenterSx,
|
||||
overflow: "hidden",
|
||||
whiteSpace: "nowrap",
|
||||
display: "block",
|
||||
flexGrow: 1,
|
||||
}}
|
||||
>
|
||||
{ticket.top_message.message}
|
||||
</Box>
|
||||
<Box sx={flexCenterSx}>
|
||||
<CircleIcon
|
||||
sx={{
|
||||
color: green[700],
|
||||
transform: "scale(0.8)",
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={flexCenterSx} onClick={() => setActiveUserId(ticket.user)}>
|
||||
ИНФО
|
||||
</Box>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,122 +1,146 @@
|
||||
import HighlightOffOutlinedIcon from '@mui/icons-material/HighlightOffOutlined';
|
||||
import SearchOutlinedIcon from '@mui/icons-material/SearchOutlined';
|
||||
import HighlightOffOutlinedIcon from "@mui/icons-material/HighlightOffOutlined";
|
||||
import SearchOutlinedIcon from "@mui/icons-material/SearchOutlined";
|
||||
import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
|
||||
import { Ticket } from "@root/model/ticket";
|
||||
import { incrementTicketsApiPage, useTicketStore } from "@root/stores/tickets";
|
||||
import { useEffect, useRef } from "react";
|
||||
import TicketItem from "./TicketItem";
|
||||
import { throttle } from '@frontend/kitui';
|
||||
import { throttle } from "@frontend/kitui";
|
||||
|
||||
type TicketListProps = {
|
||||
closeCollapse?: () => void;
|
||||
setActiveUserId: (id: string) => void;
|
||||
};
|
||||
|
||||
export default function TicketList() {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const tickets = useTicketStore(state => state.tickets);
|
||||
const ticketsFetchState = useTicketStore(state => state.ticketsFetchState);
|
||||
const ticketsBoxRef = useRef<HTMLDivElement>(null);
|
||||
export default function TicketList({
|
||||
closeCollapse,
|
||||
setActiveUserId,
|
||||
}: TicketListProps) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const tickets = useTicketStore((state) => state.tickets);
|
||||
const ticketsFetchState = useTicketStore((state) => state.ticketsFetchState);
|
||||
const ticketsBoxRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(function updateCurrentPageOnScroll() {
|
||||
if (!ticketsBoxRef.current) return;
|
||||
useEffect(
|
||||
function updateCurrentPageOnScroll() {
|
||||
if (!ticketsBoxRef.current) return;
|
||||
|
||||
const ticketsBox = ticketsBoxRef.current;
|
||||
const scrollHandler = () => {
|
||||
const scrollBottom = ticketsBox.scrollHeight - ticketsBox.scrollTop - ticketsBox.clientHeight;
|
||||
if (
|
||||
scrollBottom < ticketsBox.clientHeight &&
|
||||
ticketsFetchState === "idle"
|
||||
) incrementTicketsApiPage();
|
||||
};
|
||||
const ticketsBox = ticketsBoxRef.current;
|
||||
const scrollHandler = () => {
|
||||
const scrollBottom =
|
||||
ticketsBox.scrollHeight -
|
||||
ticketsBox.scrollTop -
|
||||
ticketsBox.clientHeight;
|
||||
if (
|
||||
scrollBottom < ticketsBox.clientHeight &&
|
||||
ticketsFetchState === "idle"
|
||||
)
|
||||
incrementTicketsApiPage();
|
||||
};
|
||||
|
||||
const throttledScrollHandler = throttle(scrollHandler, 200);
|
||||
ticketsBox.addEventListener("scroll", throttledScrollHandler);
|
||||
const throttledScrollHandler = throttle(scrollHandler, 200);
|
||||
ticketsBox.addEventListener("scroll", throttledScrollHandler);
|
||||
|
||||
return () => {
|
||||
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
|
||||
};
|
||||
}, [ticketsFetchState]);
|
||||
return () => {
|
||||
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
|
||||
};
|
||||
},
|
||||
[ticketsFetchState]
|
||||
);
|
||||
|
||||
const sortedTickets = tickets.sort(sortTicketsByUpdateTime).sort(sortTicketsByUnread);
|
||||
const sortedTickets = tickets
|
||||
.sort(sortTicketsByUpdateTime)
|
||||
.sort(sortTicketsByUnread);
|
||||
|
||||
return (
|
||||
<Box sx={{
|
||||
display: "flex",
|
||||
flex: upMd ? "3 0 0" : undefined,
|
||||
maxWidth: upMd ? "400px" : undefined,
|
||||
maxHeight: "600px",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
}}>
|
||||
<Box sx={{
|
||||
width: "100%",
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.grayDark.main,
|
||||
borderRadius: "3px",
|
||||
padding: "10px"
|
||||
}}>
|
||||
<Button
|
||||
variant="contained"
|
||||
sx={{
|
||||
backgroundColor: theme.palette.grayDark.main,
|
||||
width: "100%",
|
||||
height: "45px",
|
||||
fontSize: "15px",
|
||||
fontWeight: "normal",
|
||||
textTransform: "capitalize",
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.menu.main
|
||||
}
|
||||
}}>
|
||||
Поиск
|
||||
<SearchOutlinedIcon />
|
||||
</Button>
|
||||
<Button
|
||||
variant="text"
|
||||
sx={{
|
||||
width: "100%",
|
||||
height: "35px",
|
||||
fontSize: "14px",
|
||||
fontWeight: "normal",
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.golden.main,
|
||||
borderRadius: 0,
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.menu.main
|
||||
}
|
||||
}}>
|
||||
ЗАКРЫТЬ ТИКЕТ
|
||||
<HighlightOffOutlinedIcon />
|
||||
</Button>
|
||||
</Box>
|
||||
<Box
|
||||
ref={ticketsBoxRef}
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.grayDark.main,
|
||||
borderRadius: "3px",
|
||||
overflow: "auto",
|
||||
overflowY: "auto",
|
||||
padding: "10px",
|
||||
colorScheme: "dark",
|
||||
}}
|
||||
>
|
||||
{sortedTickets.map(ticket =>
|
||||
<TicketItem ticket={ticket} key={ticket.id} />
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flex: upMd ? "3 0 0" : undefined,
|
||||
maxWidth: upMd ? "400px" : undefined,
|
||||
maxHeight: "600px",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.grayDark.main,
|
||||
borderRadius: "3px",
|
||||
padding: "10px",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
sx={{
|
||||
backgroundColor: theme.palette.grayDark.main,
|
||||
width: "100%",
|
||||
height: "45px",
|
||||
fontSize: "15px",
|
||||
fontWeight: "normal",
|
||||
textTransform: "capitalize",
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
},
|
||||
}}
|
||||
>
|
||||
Поиск
|
||||
<SearchOutlinedIcon />
|
||||
</Button>
|
||||
<Button
|
||||
variant="text"
|
||||
sx={{
|
||||
width: "100%",
|
||||
height: "35px",
|
||||
fontSize: "14px",
|
||||
fontWeight: "normal",
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.golden.main,
|
||||
borderRadius: 0,
|
||||
"&:hover": {
|
||||
backgroundColor: theme.palette.menu.main,
|
||||
},
|
||||
}}
|
||||
>
|
||||
ЗАКРЫТЬ ТИКЕТ
|
||||
<HighlightOffOutlinedIcon />
|
||||
</Button>
|
||||
</Box>
|
||||
<Box
|
||||
ref={ticketsBoxRef}
|
||||
sx={{
|
||||
width: "100%",
|
||||
border: "1px solid",
|
||||
borderColor: theme.palette.grayDark.main,
|
||||
borderRadius: "3px",
|
||||
overflow: "auto",
|
||||
overflowY: "auto",
|
||||
padding: "10px",
|
||||
colorScheme: "dark",
|
||||
}}
|
||||
>
|
||||
{sortedTickets.map((ticket) => (
|
||||
<Box key={ticket.id} onClick={closeCollapse}>
|
||||
<TicketItem ticket={ticket} setActiveUserId={setActiveUserId} />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function sortTicketsByUpdateTime(ticket1: Ticket, ticket2: Ticket) {
|
||||
const date1 = new Date(ticket1.updated_at).getTime();
|
||||
const date2 = new Date(ticket2.updated_at).getTime();
|
||||
return date2 - date1;
|
||||
const date1 = new Date(ticket1.updated_at).getTime();
|
||||
const date2 = new Date(ticket2.updated_at).getTime();
|
||||
return date2 - date1;
|
||||
}
|
||||
|
||||
function sortTicketsByUnread(ticket1: Ticket, ticket2: Ticket) {
|
||||
const isUnread1 = ticket1.user === ticket1.top_message.user_id;
|
||||
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
|
||||
return Number(isUnread2) - Number(isUnread1);
|
||||
const isUnread1 = ticket1.user === ticket1.top_message.user_id;
|
||||
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
|
||||
return Number(isUnread2) - Number(isUnread1);
|
||||
}
|
||||
|
||||
@ -17,7 +17,7 @@ import {
|
||||
findPrivilegeById,
|
||||
usePrivilegeStore,
|
||||
} from "@root/stores/privilegesStore";
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
import { Privilege } from "@frontend/kitui";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||
|
||||
@ -28,7 +28,7 @@ interface Values {
|
||||
customPriceField: string,
|
||||
privilegeIdField: string,
|
||||
orderField: number,
|
||||
privilege: PrivilegeWithAmount | null
|
||||
privilege: Privilege | null
|
||||
}
|
||||
|
||||
export default function CreateTariff() {
|
||||
@ -48,7 +48,6 @@ export default function CreateTariff() {
|
||||
if (values.privilegeIdField.length === 0) {
|
||||
errors.privilegeIdField = "Не выбрана привилегия"
|
||||
}
|
||||
console.log(errors)
|
||||
return errors;
|
||||
|
||||
};
|
||||
@ -68,7 +67,7 @@ export default function CreateTariff() {
|
||||
formikHelpers: FormikHelpers<Values>
|
||||
) => {
|
||||
if (values.privilege !== null) {
|
||||
const [_, createdTariffError] = await createTariff({
|
||||
const [, createdTariffError] = await createTariff({
|
||||
name: values.nameField,
|
||||
price: Number(values.customPriceField) * 100,
|
||||
order: values.orderField,
|
||||
@ -185,8 +184,9 @@ export default function CreateTariff() {
|
||||
{privileges.map((privilege) => (
|
||||
<MenuItem
|
||||
data-cy={`select-option-${privilege.description}`}
|
||||
key={privilege.description}
|
||||
key={privilege._id}
|
||||
value={privilege._id}
|
||||
sx={{whiteSpace: "normal", wordBreak: "break-world"}}
|
||||
>
|
||||
{privilege.serviceKey}:{privilege.description}
|
||||
</MenuItem>
|
||||
|
||||
@ -44,7 +44,7 @@ export default function EditModal() {
|
||||
updatedTariff.name = nameField;
|
||||
updatedTariff.price = price;
|
||||
updatedTariff.description = descriptionField;
|
||||
updatedTariff.order = orderField;
|
||||
updatedTariff.order = parseInt(orderField);
|
||||
|
||||
|
||||
const [_, putedTariffError] = await putTariff(updatedTariff);
|
||||
|
||||
@ -1,17 +1,23 @@
|
||||
import { Typography } from "@mui/material";
|
||||
import Cart from "@root/kitUI/Cart/Cart";
|
||||
import TariffsDG from "./tariffsDG";
|
||||
|
||||
|
||||
export default function TariffsInfo() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant="h6" mt="20px">
|
||||
Список тарифов
|
||||
</Typography>
|
||||
<TariffsDG />
|
||||
<Cart />
|
||||
</>
|
||||
);
|
||||
}
|
||||
import { CircularProgress, Typography } from "@mui/material";
|
||||
import Cart from "@root/kitUI/Cart/Cart";
|
||||
import TariffsDG from "./tariffsDG";
|
||||
import { Suspense } from "react";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
|
||||
|
||||
export default function TariffsInfo() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant="h6" mt="20px">
|
||||
Список тарифов
|
||||
</Typography>
|
||||
<TariffsDG />
|
||||
<ErrorBoundary fallback={<Typography>Что-то пошло не так</Typography>}>
|
||||
<Suspense fallback={<CircularProgress />}>
|
||||
<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: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => currencyFormatter.format(row.privileges[0].price / 100) },
|
||||
{ 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",
|
||||
headerName: "Удаление",
|
||||
|
||||
@ -23,14 +23,24 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import ConditionalRender from "@root/pages/Setting/ConditionalRender";
|
||||
import ModalUser from "@root/pages/dashboard/ModalUser";
|
||||
import ServiceUsersDG from "./ServiceUsersDG";
|
||||
import { getRegisteredUsers, getManagersList } from "@root/api/user";
|
||||
import { useUsers, useManagers, useAdmins } from "@root/api/user/swr";
|
||||
import { getRoles } from "@root/api/privilegies";
|
||||
|
||||
import { getRoles_mock, TMockData } from "../../../api/roles";
|
||||
|
||||
import theme from "../../../theme";
|
||||
|
||||
import type { UserType } from "../../../api/roles";
|
||||
type Pages = {
|
||||
adminPage: number;
|
||||
managerPage: number;
|
||||
userPage: number;
|
||||
};
|
||||
|
||||
type PagesSize = {
|
||||
adminPageSize: number;
|
||||
managerPageSize: number;
|
||||
userPageSize: number;
|
||||
};
|
||||
|
||||
const Users: React.FC = () => {
|
||||
const radioboxes = ["admin", "manager", "user"];
|
||||
@ -39,11 +49,11 @@ const Users: React.FC = () => {
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [data, setData] = React.useState<TMockData>([]);
|
||||
const [mockData, setMockData] = React.useState<TMockData>([]);
|
||||
|
||||
const handleChangeData = () => {
|
||||
getRoles_mock().then((mockdata) => {
|
||||
setData(mockdata);
|
||||
setMockData(mockdata);
|
||||
setAccordionText(mockdata[0].desc || "");
|
||||
});
|
||||
};
|
||||
@ -53,7 +63,7 @@ const Users: React.FC = () => {
|
||||
|
||||
const handleChange = (value: string) => {
|
||||
setSelectedValue(value);
|
||||
setAccordionText(data.find(({ name }) => name === value)?.desc || "");
|
||||
setAccordionText(mockData.find(({ name }) => name === value)?.desc || "");
|
||||
|
||||
if (selectedValue === "manager") {
|
||||
}
|
||||
@ -64,12 +74,33 @@ const Users: React.FC = () => {
|
||||
};
|
||||
|
||||
const [roles, setRoles] = React.useState<TMockData>([]);
|
||||
const [users, setUsers] = React.useState<UserType[]>([]);
|
||||
const [manager, setManager] = React.useState<UserType[]>([]);
|
||||
|
||||
const [page, setPage] = useState<Pages>({
|
||||
adminPage: 0,
|
||||
managerPage: 0,
|
||||
userPage: 0,
|
||||
});
|
||||
const [pageSize, setPageSize] = useState<PagesSize>({
|
||||
adminPageSize: 10,
|
||||
managerPageSize: 10,
|
||||
userPageSize: 10,
|
||||
});
|
||||
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
|
||||
const [activeUserId, setActiveUserId] = useState<string>("");
|
||||
|
||||
const { userId } = useParams();
|
||||
const { data: adminData, adminPages } = useAdmins(
|
||||
page.adminPage + 1,
|
||||
pageSize.adminPageSize
|
||||
);
|
||||
const { data: managerData, managerPages } = useManagers(
|
||||
page.managerPage + 1,
|
||||
pageSize.managerPageSize
|
||||
);
|
||||
const { data: userData, userPagesCount } = useUsers(
|
||||
page.userPage + 1,
|
||||
pageSize.userPageSize
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
handleChangeData();
|
||||
@ -88,18 +119,6 @@ const Users: React.FC = () => {
|
||||
}, [userId]);
|
||||
|
||||
useEffect(() => {
|
||||
getManagersList().then(([managersListResponse]) => {
|
||||
if (managersListResponse) {
|
||||
setManager(managersListResponse.users);
|
||||
}
|
||||
});
|
||||
|
||||
getRegisteredUsers().then(([registeredUsersResponse]) => {
|
||||
if (registeredUsersResponse) {
|
||||
setUsers(registeredUsersResponse.users);
|
||||
}
|
||||
});
|
||||
|
||||
getRoles().then(([rolesResponse]) => {
|
||||
if (rolesResponse) {
|
||||
setRoles(rolesResponse);
|
||||
@ -107,10 +126,12 @@ const Users: React.FC = () => {
|
||||
});
|
||||
}, [selectedValue]);
|
||||
|
||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>([]);
|
||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>(
|
||||
[]
|
||||
);
|
||||
return (
|
||||
<React.Fragment>
|
||||
<Button
|
||||
{/* <Button
|
||||
variant="text"
|
||||
onClick={() => navigate("/modalAdmin")}
|
||||
sx={{
|
||||
@ -130,7 +151,7 @@ const Users: React.FC = () => {
|
||||
}}
|
||||
>
|
||||
ИНФОРМАЦИЯ О ПРОЕКТЕ
|
||||
</Button>
|
||||
</Button> */}
|
||||
|
||||
<Accordion
|
||||
sx={{
|
||||
@ -142,7 +163,9 @@ const Users: React.FC = () => {
|
||||
<AccordionSummary
|
||||
sx={{ display: "flex" }}
|
||||
onClick={handleToggleAccordion}
|
||||
expandIcon={<ExpandMoreIcon sx={{ color: theme.palette.secondary.main }} />}
|
||||
expandIcon={
|
||||
<ExpandMoreIcon sx={{ color: theme.palette.secondary.main }} />
|
||||
}
|
||||
aria-controls="panel1a-content"
|
||||
id="panel1a-header"
|
||||
>
|
||||
@ -155,7 +178,7 @@ const Users: React.FC = () => {
|
||||
{accordionText}
|
||||
</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
<AccordionDetails sx={{overflowX: "auto"}}>
|
||||
<Table
|
||||
sx={{
|
||||
width: "100%",
|
||||
@ -206,8 +229,8 @@ const Users: React.FC = () => {
|
||||
</TableHead>
|
||||
|
||||
<TableBody>
|
||||
{data.length ? (
|
||||
data.map(function (item, index) {
|
||||
{mockData.length ? (
|
||||
mockData.map(function (item, index) {
|
||||
return (
|
||||
<TableRow
|
||||
sx={{
|
||||
@ -390,11 +413,61 @@ const Users: React.FC = () => {
|
||||
<ConditionalRender
|
||||
isLoading={false}
|
||||
role={selectedValue}
|
||||
childrenManager={<ServiceUsersDG users={manager} handleSelectionChange={setSelectedTariffs} />}
|
||||
childrenUser={<ServiceUsersDG users={users} handleSelectionChange={setSelectedTariffs} />}
|
||||
childrenAdmin={
|
||||
<ServiceUsersDG
|
||||
users={adminData?.users.length ? adminData.users : []}
|
||||
page={page.adminPage}
|
||||
setPage={(adminPage) =>
|
||||
setPage((pages) => ({ ...pages, adminPage }))
|
||||
}
|
||||
pagesCount={adminPages}
|
||||
pageSize={pageSize.adminPageSize}
|
||||
handleSelectionChange={setSelectedTariffs}
|
||||
onPageSizeChange={(adminPageSize) =>
|
||||
setPageSize((pageSize) => ({ ...pageSize, adminPageSize }))
|
||||
}
|
||||
/>
|
||||
}
|
||||
childrenManager={
|
||||
<ServiceUsersDG
|
||||
users={managerData?.users.length ? managerData.users : []}
|
||||
page={page.managerPage}
|
||||
setPage={(managerPage) =>
|
||||
setPage((pages) => ({ ...pages, managerPage }))
|
||||
}
|
||||
pagesCount={managerPages}
|
||||
pageSize={pageSize.managerPageSize}
|
||||
handleSelectionChange={setSelectedTariffs}
|
||||
onPageSizeChange={(managerPageSize) =>
|
||||
setPageSize((pageSize) => ({ ...pageSize, managerPageSize }))
|
||||
}
|
||||
/>
|
||||
}
|
||||
childrenUser={
|
||||
<ServiceUsersDG
|
||||
users={userData?.users.length ? userData.users : []}
|
||||
page={page.userPage}
|
||||
setPage={(userPage) =>
|
||||
setPage((pages) => ({ ...pages, userPage }))
|
||||
}
|
||||
pagesCount={userPagesCount}
|
||||
pageSize={pageSize.userPageSize}
|
||||
handleSelectionChange={setSelectedTariffs}
|
||||
onPageSizeChange={(userPageSize) =>
|
||||
setPageSize((pageSize) => ({ ...pageSize, userPageSize }))
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
<ModalUser open={openUserModal} setOpen={setOpenUserModal} userId={activeUserId} />
|
||||
<ModalUser
|
||||
open={openUserModal}
|
||||
userId={activeUserId}
|
||||
onClose={() => {
|
||||
setOpenUserModal(false);
|
||||
navigate(-1);
|
||||
}}
|
||||
/>
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
@ -100,6 +100,7 @@ const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== "open"
|
||||
}));
|
||||
|
||||
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: "/entities", element: <SettingsOutlinedIcon />, title: "Юридические лица", className: "menu" },
|
||||
{ path: "/tariffs", element: <BathtubOutlinedIcon />, title: "Тарифы", className: "menu" },
|
||||
@ -172,9 +173,9 @@ const Navigation = (props: Props) => {
|
||||
};
|
||||
|
||||
const Menu: React.FC = () => {
|
||||
const tablet = useMediaQuery("(max-width:600px)");
|
||||
const tablet = useMediaQuery("(max-width:900px)");
|
||||
|
||||
const mobile = useMediaQuery("(max-width:340px)");
|
||||
const mobile = useMediaQuery("(max-width:600px)");
|
||||
|
||||
const theme = useTheme();
|
||||
const [open, setOpen] = React.useState(tablet ? false : true);
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Box, useTheme, useMediaQuery } from "@mui/material";
|
||||
import { DataGrid } from "@mui/x-data-grid";
|
||||
import { format } from "date-fns";
|
||||
|
||||
import { useHistory } from "@root/api/history/swr";
|
||||
import { scrollBlock } from "@root/utils/scrollBlock";
|
||||
|
||||
import forwardIcon from "@root/assets/icons/forward.svg";
|
||||
@ -9,6 +11,10 @@ import forwardIcon from "@root/assets/icons/forward.svg";
|
||||
import type { ChangeEvent } from "react";
|
||||
import type { GridColDef } from "@mui/x-data-grid";
|
||||
|
||||
type PurchaseTabProps = {
|
||||
userId: string;
|
||||
};
|
||||
|
||||
const COLUMNS: GridColDef[] = [
|
||||
{
|
||||
field: "date",
|
||||
@ -68,12 +74,22 @@ const ROWS = [
|
||||
},
|
||||
];
|
||||
|
||||
export const PurchaseTab = () => {
|
||||
export const PurchaseTab = ({ userId }: PurchaseTabProps) => {
|
||||
const [canScrollToRight, setCanScrollToRight] = useState<boolean>(true);
|
||||
const [canScrollToLeft, setCanScrollToLeft] = useState<boolean>(false);
|
||||
const theme = useTheme();
|
||||
const smallScreen = useMediaQuery(theme.breakpoints.down(830));
|
||||
const gridContainer = useRef<HTMLDivElement>(null);
|
||||
const { data: historyData } = useHistory(userId);
|
||||
|
||||
const rows =
|
||||
historyData?.[0].records.map((history) => ({
|
||||
id: history.id,
|
||||
date: format(history.updatedAt, "dd.MM.yyyy"),
|
||||
time: format(history.updatedAt, "HH:mm"),
|
||||
product: "",
|
||||
amount: "",
|
||||
})) ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = (nativeEvent: unknown) => {
|
||||
@ -145,10 +161,8 @@ export const PurchaseTab = () => {
|
||||
}}
|
||||
>
|
||||
<DataGrid
|
||||
rows={ROWS}
|
||||
rows={rows}
|
||||
columns={COLUMNS}
|
||||
pageSize={5}
|
||||
rowsPerPageOptions={[5]}
|
||||
hideFooter
|
||||
disableColumnMenu
|
||||
disableSelectionOnClick
|
||||
@ -239,3 +253,62 @@ export const PurchaseTab = () => {
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const a = {
|
||||
id: "65e4f1b157004756bc5bb15c",
|
||||
userId: "64eb6ce57047f28fdabf69ec",
|
||||
comment: "Успешная оплата корзины",
|
||||
key: "payCart",
|
||||
rawDetails: [
|
||||
[
|
||||
{ Key: "id", Value: "65e4f1881747c1eea8007d3b" },
|
||||
{
|
||||
Key: "name",
|
||||
Value:
|
||||
"Количество Заявок, Скрытие шильдика в опроснике, 2024-03-03T21:54:16.434Z",
|
||||
},
|
||||
{ Key: "price", Value: 0 },
|
||||
{ Key: "iscustom", Value: true },
|
||||
{
|
||||
Key: "privileges",
|
||||
Value: [
|
||||
[
|
||||
{ Key: "id", Value: "" },
|
||||
{ Key: "name", Value: "Количество Заявок" },
|
||||
{ Key: "privilegeid", Value: "quizCnt" },
|
||||
{ Key: "servicekey", Value: "squiz" },
|
||||
{
|
||||
Key: "description",
|
||||
Value: "Количество полных прохождений опросов",
|
||||
},
|
||||
{ Key: "amount", Value: 100 },
|
||||
{ Key: "type", Value: "count" },
|
||||
{ Key: "value", Value: "заявка" },
|
||||
{ Key: "price", Value: 2000 },
|
||||
],
|
||||
[
|
||||
{ Key: "id", Value: "" },
|
||||
{ Key: "name", Value: "Скрытие шильдика в опроснике" },
|
||||
{ Key: "privilegeid", Value: "squizHideBadge" },
|
||||
{ Key: "servicekey", Value: "squiz" },
|
||||
{
|
||||
Key: "description",
|
||||
Value: "Количество дней скрытия шильдика в опроснике",
|
||||
},
|
||||
{ Key: "amount", Value: 30 },
|
||||
{ Key: "type", Value: "day" },
|
||||
{ Key: "value", Value: "день" },
|
||||
{ Key: "price", Value: 0 },
|
||||
],
|
||||
],
|
||||
},
|
||||
{ Key: "deleted", Value: false },
|
||||
{ Key: "createdat", Value: "2024-03-03T21:54:16.825Z" },
|
||||
{ Key: "updatedat", Value: "2024-03-03T21:54:16.825Z" },
|
||||
{ Key: "deletedat", Value: null },
|
||||
],
|
||||
],
|
||||
isDeleted: false,
|
||||
createdAt: "2024-03-03T21:54:57.433Z",
|
||||
updatedAt: "2024-03-03T21:54:57.433Z",
|
||||
};
|
||||
|
||||
47
src/pages/dashboard/ModalUser/QuizTab.tsx
Normal file
47
src/pages/dashboard/ModalUser/QuizTab.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
import {Box, Button, TextField, Typography} from "@mui/material";
|
||||
import {ChangeEvent, useState} from "react";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
type QuizTabProps = {
|
||||
userId: string;
|
||||
};
|
||||
|
||||
export default function QuizTab({ userId }: QuizTabProps) {
|
||||
const [quizId, setQuizId] = useState<string>("")
|
||||
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>
|
||||
)
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Box, Typography, useTheme, useMediaQuery } from "@mui/material";
|
||||
|
||||
import { getUserInfo } from "@root/api/user";
|
||||
import { userApi } from "@root/api/user/requests";
|
||||
import { getAccountInfo } from "@root/api/account";
|
||||
|
||||
import type { UserType } from "@root/api/roles";
|
||||
@ -19,7 +19,7 @@ export const UserTab = ({ userId }: UserTabProps) => {
|
||||
|
||||
useEffect(() => {
|
||||
if (userId) {
|
||||
getUserInfo(userId).then(([userInfo]) => setUser(userInfo));
|
||||
userApi.getUserInfo(userId).then(([userInfo]) => setUser(userInfo));
|
||||
getAccountInfo(userId).then(([accountsInfo]) => setAccount(accountsInfo));
|
||||
}
|
||||
}, []);
|
||||
|
||||
@ -6,7 +6,7 @@ import { useDebouncedCallback } from "use-debounce";
|
||||
|
||||
import type { ChangeEvent } from "react";
|
||||
import type { Verification } from "@root/api/verification";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import makeRequest from "@root/api/makeRequest";
|
||||
|
||||
type VerificationTabProps = {
|
||||
userId: string;
|
||||
@ -24,7 +24,6 @@ export const VerificationTab = ({ userId }: VerificationTabProps) => {
|
||||
const [verificationResponse, verificationError] = await verification(
|
||||
userId
|
||||
);
|
||||
console.log(verificationResponse)
|
||||
|
||||
setIsLoading(false);
|
||||
|
||||
@ -84,7 +83,6 @@ export const VerificationTab = ({ userId }: VerificationTabProps) => {
|
||||
await requestVefification();
|
||||
};
|
||||
|
||||
console.log("verificationInfo", verificationInfo)
|
||||
return (
|
||||
<Box sx={{ padding: "25px" }}>
|
||||
<Typography
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { Link, useLinkClickHandler } from "react-router-dom";
|
||||
import {
|
||||
Box,
|
||||
Modal,
|
||||
@ -11,7 +10,6 @@ import {
|
||||
useTheme,
|
||||
useMediaQuery,
|
||||
} from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { UserTab } from "./UserTab";
|
||||
import { PurchaseTab } from "./PurchaseTab";
|
||||
@ -22,10 +20,12 @@ import { ReactComponent as UserIcon } from "@root/assets/icons/user.svg";
|
||||
import { ReactComponent as PackageIcon } from "@root/assets/icons/package.svg";
|
||||
import { ReactComponent as TransactionsIcon } from "@root/assets/icons/transactions.svg";
|
||||
import { ReactComponent as CheckIcon } from "@root/assets/icons/check.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 type { SyntheticEvent } from "react";
|
||||
import QuizTab from "@pages/dashboard/ModalUser/QuizTab";
|
||||
|
||||
const TABS = [
|
||||
{ name: "Пользователь", icon: UserIcon, activeStyles: { fill: "#7E2AEA" } },
|
||||
@ -40,21 +40,21 @@ const TABS = [
|
||||
activeStyles: { stroke: "#7E2AEA" },
|
||||
},
|
||||
{ name: "Верификация", icon: CheckIcon, activeStyles: { stroke: "#7E2AEA" } },
|
||||
{ name: "Квизы", icon: QuizIcon, activeStyles: { stroke: "#7E2AEA" } },
|
||||
];
|
||||
|
||||
type ModalUserProps = {
|
||||
open: boolean;
|
||||
setOpen: (isOpened: boolean) => void;
|
||||
onClose: () => void;
|
||||
userId: string;
|
||||
};
|
||||
|
||||
const ModalUser = ({ open, setOpen, userId }: ModalUserProps) => {
|
||||
const ModalUser = ({ open, onClose, userId }: ModalUserProps) => {
|
||||
const [value, setValue] = useState<number>(0);
|
||||
const [openNavigation, setOpenNavigation] = useState<boolean>(false);
|
||||
const theme = useTheme();
|
||||
const tablet = useMediaQuery(theme.breakpoints.down(1070));
|
||||
const mobile = useMediaQuery(theme.breakpoints.down(700));
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<>
|
||||
@ -63,10 +63,7 @@ const ModalUser = ({ open, setOpen, userId }: ModalUserProps) => {
|
||||
aria-labelledby="transition-modal-title"
|
||||
aria-describedby="transition-modal-description"
|
||||
open
|
||||
onClose={() => {
|
||||
setOpen(false);
|
||||
navigate(-1);
|
||||
}}
|
||||
onClose={onClose}
|
||||
closeAfterTransition
|
||||
BackdropComponent={Backdrop}
|
||||
BackdropProps={{
|
||||
@ -93,6 +90,14 @@ const ModalUser = ({ open, setOpen, userId }: ModalUserProps) => {
|
||||
overflowX: "hidden",
|
||||
}}
|
||||
>
|
||||
{mobile && (
|
||||
<Box
|
||||
onClick={onClose}
|
||||
sx={{ position: "absolute", top: "10px", right: "5px" }}
|
||||
>
|
||||
<CloseIcon />
|
||||
</Box>
|
||||
)}
|
||||
<Typography
|
||||
id="transition-modal-title"
|
||||
variant="caption"
|
||||
@ -188,9 +193,10 @@ const ModalUser = ({ open, setOpen, userId }: ModalUserProps) => {
|
||||
}}
|
||||
>
|
||||
{value === 0 && <UserTab userId={userId} />}
|
||||
{value === 1 && <PurchaseTab />}
|
||||
{value === 1 && <PurchaseTab userId={userId} />}
|
||||
{value === 2 && <TransactionsTab />}
|
||||
{value === 3 && <VerificationTab userId={userId} />}
|
||||
{value === 4 && <QuizTab userId={userId} />}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||
import { requestServicePrivileges } from "@root/api/privilegies";
|
||||
|
||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
import type { CustomPrivilege } from "@frontend/kitui";
|
||||
|
||||
const mutatePrivileges = (privileges: PrivilegeWithAmount[]) => {
|
||||
let extracted: PrivilegeWithAmount[] = [];
|
||||
const mutatePrivileges = (privileges: CustomPrivilege[]) => {
|
||||
let extracted: CustomPrivilege[] = [];
|
||||
for (let serviceKey in privileges) {
|
||||
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||
extracted = extracted.concat(privileges[serviceKey]);
|
||||
|
||||
@ -1,26 +1,26 @@
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
|
||||
|
||||
interface PrivilegeStore {
|
||||
privileges: PrivilegeWithAmount[];
|
||||
}
|
||||
|
||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
privileges: [],
|
||||
}),
|
||||
{
|
||||
name: "Privileges",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||
|
||||
export const findPrivilegeById = (privilegeId: string) => {
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege._id === privilegeId || privilege.privilegeId === privilegeId) ?? null;
|
||||
};
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { CustomPrivilege } from "@frontend/kitui";
|
||||
|
||||
|
||||
interface PrivilegeStore {
|
||||
privileges: CustomPrivilege[];
|
||||
}
|
||||
|
||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
privileges: [],
|
||||
}),
|
||||
{
|
||||
name: "Privileges",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||
|
||||
export const findPrivilegeById = (privilegeId: string) => {
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege._id === privilegeId || privilege.privilegeId === privilegeId) ?? null;
|
||||
};
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
import { Promocode } from "@root/model/cart";
|
||||
import { create } from "zustand";
|
||||
import { devtools, persist } from "zustand/middleware";
|
||||
|
||||
|
||||
interface PromocodeStore {
|
||||
promocodes: Promocode[];
|
||||
addPromocodes: (newPromocodes: Promocode[]) => void;
|
||||
deletePromocodes: (promocodeIdsToDelete: string[]) => void;
|
||||
}
|
||||
|
||||
export const usePromocodeStore = create<PromocodeStore>()(
|
||||
devtools(
|
||||
// persist(
|
||||
(set, get) => ({
|
||||
promocodes: [],
|
||||
addPromocodes: newPromocodes => set(state => (
|
||||
{ promocodes: [...state.promocodes, ...newPromocodes] }
|
||||
)),
|
||||
deletePromocodes: promocodeIdsToDelete => set(state => (
|
||||
{ promocodes: state.promocodes.filter(promocode => !promocodeIdsToDelete.includes(promocode.id)) }
|
||||
)),
|
||||
}),
|
||||
// {
|
||||
// name: "promocodes",
|
||||
// getStorage: () => localStorage,
|
||||
// }
|
||||
// ),
|
||||
{
|
||||
name: "Promocode store"
|
||||
}
|
||||
)
|
||||
);
|
||||
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)}%`;
|
||||
}
|
||||
@ -1,29 +1,28 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { requestPrivileges } from "@root/api/privilegies";
|
||||
|
||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
|
||||
export default function usePrivileges({
|
||||
onError,
|
||||
onNewPrivileges,
|
||||
}: {
|
||||
onNewPrivileges: (response: PrivilegeWithAmount[]) => void;
|
||||
onError?: (error: any) => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
requestPrivileges(controller.signal).then(
|
||||
([privilegesResponse, privilegesError]) => {
|
||||
if (privilegesError) {
|
||||
return onError?.(privilegesError);
|
||||
}
|
||||
|
||||
onNewPrivileges(privilegesResponse);
|
||||
}
|
||||
);
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onError, onNewPrivileges]);
|
||||
}
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { requestPrivileges } from "@root/api/privilegies";
|
||||
|
||||
import type { CustomPrivilege } from "@frontend/kitui";
|
||||
|
||||
export default function usePrivileges({
|
||||
onError,
|
||||
onNewPrivileges,
|
||||
}: {
|
||||
onNewPrivileges: (response: CustomPrivilege[]) => void;
|
||||
onError?: (error: any) => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
requestPrivileges(controller.signal).then(
|
||||
([privilegesResponse, privilegesError]) => {
|
||||
if (privilegesError) {
|
||||
return onError?.(privilegesError);
|
||||
}
|
||||
onNewPrivileges(privilegesResponse);
|
||||
}
|
||||
);
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onError, onNewPrivileges]);
|
||||
}
|
||||
|
||||
32
src/utils/hooks/useQuizStatistic.ts
Normal file
32
src/utils/hooks/useQuizStatistic.ts
Normal file
@ -0,0 +1,32 @@
|
||||
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 () => {
|
||||
|
||||
const gottenData = await getStatistic(Number(formatTo), Number(formatFrom));
|
||||
setData(gottenData)
|
||||
}
|
||||
|
||||
requestStatistics();
|
||||
}, [to, from]);
|
||||
|
||||
return { ...data };
|
||||
}
|
||||
@ -19,7 +19,6 @@ const translateMessage: Record<string, string> = {
|
||||
|
||||
export const parseAxiosError = (nativeError: unknown): [string, number?] => {
|
||||
const error = nativeError as AxiosError;
|
||||
console.log(error)
|
||||
|
||||
if (
|
||||
error.response?.data && error.response?.data !== "Not Found" &&
|
||||
|
||||
11
src/utils/style/keyframes.ts
Normal file
11
src/utils/style/keyframes.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { keyframes } from "@emotion/react";
|
||||
|
||||
|
||||
export const fadeIn = keyframes`
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
||||
Loading…
Reference in New Issue
Block a user