commit
de1aa8c256
@ -26,6 +26,7 @@
|
|||||||
"craco": "^0.0.3",
|
"craco": "^0.0.3",
|
||||||
"dayjs": "^1.11.5",
|
"dayjs": "^1.11.5",
|
||||||
"formik": "^2.2.9",
|
"formik": "^2.2.9",
|
||||||
|
"immer": "^10.0.2",
|
||||||
"moment": "^2.29.4",
|
"moment": "^2.29.4",
|
||||||
"nanoid": "^4.0.1",
|
"nanoid": "^4.0.1",
|
||||||
"notistack": "^3.0.1",
|
"notistack": "^3.0.1",
|
||||||
|
@ -3,9 +3,44 @@ import { ServiceType } from "@root/model/tariff";
|
|||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
|
|
||||||
|
|
||||||
|
const baseUrl = process.env.NODE_ENV === "production" ? "/price" : "https://admin.pena.digital/price";
|
||||||
|
|
||||||
const makeRequest = authStore.getState().makeRequest;
|
const makeRequest = authStore.getState().makeRequest;
|
||||||
|
|
||||||
type CreateDiscount = (props: {
|
export function createDiscount(discountParams: CreateDiscountParams) {
|
||||||
|
const discount = createDiscountObject(discountParams);
|
||||||
|
|
||||||
|
return makeRequest<CreateDiscountBody, Discount>({
|
||||||
|
url: baseUrl + "/discount",
|
||||||
|
method: "post",
|
||||||
|
useToken: true,
|
||||||
|
bearer: true,
|
||||||
|
body: discount,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export function deleteDiscount(discountId: string) {
|
||||||
|
return makeRequest<never, Discount>({
|
||||||
|
url: baseUrl + "/discount/" + discountId,
|
||||||
|
method: "delete",
|
||||||
|
useToken: true,
|
||||||
|
bearer: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchDiscount(discountId: string, discountParams: CreateDiscountParams) {
|
||||||
|
const discount = createDiscountObject(discountParams);
|
||||||
|
|
||||||
|
return makeRequest<CreateDiscountBody, Discount>({
|
||||||
|
url: baseUrl + "/discount/" + discountId,
|
||||||
|
method: "patch",
|
||||||
|
useToken: true,
|
||||||
|
bearer: true,
|
||||||
|
body: discount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CreateDiscountParams {
|
||||||
purchasesAmount: number;
|
purchasesAmount: number;
|
||||||
cartPurchasesAmount: number;
|
cartPurchasesAmount: number;
|
||||||
discountMinValue: number;
|
discountMinValue: number;
|
||||||
@ -19,9 +54,9 @@ type CreateDiscount = (props: {
|
|||||||
serviceType: ServiceType;
|
serviceType: ServiceType;
|
||||||
discountType: DiscountType;
|
discountType: DiscountType;
|
||||||
privilegeId: string;
|
privilegeId: string;
|
||||||
}) => Promise<Discount>;
|
}
|
||||||
|
|
||||||
export const createDiscountJSON: CreateDiscount = ({
|
export function createDiscountObject({
|
||||||
endDate,
|
endDate,
|
||||||
startDate,
|
startDate,
|
||||||
discountName,
|
discountName,
|
||||||
@ -33,7 +68,7 @@ export const createDiscountJSON: CreateDiscount = ({
|
|||||||
serviceType,
|
serviceType,
|
||||||
discountType,
|
discountType,
|
||||||
privilegeId,
|
privilegeId,
|
||||||
}) => {
|
}: CreateDiscountParams) {
|
||||||
const discount: CreateDiscountBody = {
|
const discount: CreateDiscountBody = {
|
||||||
Name: discountName,
|
Name: discountName,
|
||||||
Layer: 1,
|
Layer: 1,
|
||||||
@ -96,11 +131,5 @@ export const createDiscountJSON: CreateDiscount = ({
|
|||||||
|
|
||||||
console.log("Constructed discount", discount);
|
console.log("Constructed discount", discount);
|
||||||
|
|
||||||
return makeRequest<CreateDiscountBody, Discount>({
|
return discount;
|
||||||
url: "https://admin.pena.digital/price/discount",
|
}
|
||||||
method: "post",
|
|
||||||
useToken: true,
|
|
||||||
bearer: true,
|
|
||||||
body: discount,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
@ -1,43 +1,33 @@
|
|||||||
import { usePrivilegeStore } from "@root/stores/privileges";
|
import { useEffect, useState } from "react";
|
||||||
import { usePrivilegies } from "./privilege.hook";
|
|
||||||
import { addMergedPrivileges } from "@root/stores/mergedPrivileges";
|
|
||||||
|
|
||||||
export type mergedPrivilege = {
|
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
createdAt?: string;
|
import { useRefreshPrivilegesStore } from "./useRefreshPrivilegesStore.hook";
|
||||||
description: string;
|
import { exampleCartValues } from "@stores/mocks/exampleCartValues"
|
||||||
isDeleted?: boolean;
|
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
||||||
name: string;
|
|
||||||
price: number;
|
|
||||||
privilegeId: string;
|
|
||||||
serviceKey: string;
|
|
||||||
type: "count" | "day" | "mb";
|
|
||||||
updatedAt?: string;
|
|
||||||
value?: string;
|
|
||||||
_id?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useCombinedPrivileges = () => {
|
interface UseCombinedPrivileges {
|
||||||
const { privilegies, isError, errorMessage } = usePrivilegies();
|
mergedPrivileges: mergedBackFrontPrivilege[]
|
||||||
const examplePrivileges = usePrivilegeStore((state) => state.privileges);
|
}
|
||||||
|
const translatorServiceKey = {
|
||||||
|
Шаблонизатор: "templategen"
|
||||||
|
}
|
||||||
|
export const useCombinedPrivileges = ():UseCombinedPrivileges => {
|
||||||
|
|
||||||
const mergedPrivileges: mergedPrivilege[] = [];
|
const [mergedPrivileges, setMergedPrivileges] = useState<mergedBackFrontPrivilege[]>([])
|
||||||
|
|
||||||
const getPrivilegeId = (privilegeId: string): string | undefined => {
|
const backendPrivileges = usePrivilegeStore((state) => state.privileges);
|
||||||
const privilege = mergedPrivileges.find((privilege) => privilege.privilegeId === privilegeId);
|
const frontendPrivileges = exampleCartValues.privileges;
|
||||||
|
|
||||||
return privilege?._id;
|
useEffect(() => {
|
||||||
};
|
setMergedPrivileges([...backendPrivileges.map((privilege) => ({
|
||||||
|
serviceKey: privilege.serviceKey,
|
||||||
const privilegesGridData = mergedPrivileges.map((privilege) => ({
|
privilegeId: privilege.privilegeId,
|
||||||
name: privilege.name,
|
name: privilege.name,
|
||||||
description: privilege.description,
|
description: privilege.description,
|
||||||
type: privilege.type,
|
type: privilege.type,
|
||||||
price: privilege.price,
|
price: privilege.price,
|
||||||
}));
|
})), ...frontendPrivileges])
|
||||||
|
}, [backendPrivileges])
|
||||||
|
|
||||||
if (privilegies) {
|
return { mergedPrivileges };
|
||||||
mergedPrivileges.push(...privilegies.Шаблонизатор, ...examplePrivileges);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { mergedPrivileges, isError, errorMessage, getPrivilegeId, privilegesGridData };
|
|
||||||
};
|
};
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { RealPrivilege } from "@root/model/privilege";
|
||||||
|
|
||||||
export type Privilege = {
|
export type Privilege = {
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
@ -16,21 +17,21 @@ export type Privilege = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
type UsePrivilegies = {
|
type UsePrivilegies = {
|
||||||
privilegies: Record<string, Privilege[]> | undefined;
|
privilegies: RealPrivilege[]
|
||||||
isError: boolean;
|
isError: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
errorMessage: string;
|
errorMessage: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const usePrivilegies = (): UsePrivilegies => {
|
export const useGetPrivilegies = (): UsePrivilegies => {
|
||||||
const [privilegies, setPrivilegies] = useState<Record<string, Privilege[]>>();
|
const [privilegies, setPrivilegies] = useState<RealPrivilege[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isError, setIsError] = useState(false);
|
const [isError, setIsError] = useState(false);
|
||||||
const [errorMessage, setErrorMessage] = useState("");
|
const [errorMessage, setErrorMessage] = useState("");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getPrivilegies = async () => {
|
const getPrivilegies = async () => {
|
||||||
const { data } = await axios<Record<string, Privilege[]>>({
|
const { data } = await axios<RealPrivilege[]>({
|
||||||
method: "get",
|
method: "get",
|
||||||
url: "https://admin.pena.digital/strator/privilege/service",
|
url: "https://admin.pena.digital/strator/privilege/service",
|
||||||
});
|
});
|
82
src/hooks/useGetTariffs.hook.ts
Normal file
82
src/hooks/useGetTariffs.hook.ts
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import axios from "axios";
|
||||||
|
import { authStore } from "@root/stores/auth";
|
||||||
|
import { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
||||||
|
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
||||||
|
|
||||||
|
|
||||||
|
type UseGetTariffs = {
|
||||||
|
requestTariffs: (page?: number, limit?: number) => Promise<void>;
|
||||||
|
isLoading: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type GetTariffsResponse = {
|
||||||
|
totalPages: number;
|
||||||
|
tariffs: Tariff_BACKEND[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useGetTariffs = (): UseGetTariffs => {
|
||||||
|
const token = authStore((state) => state.token);
|
||||||
|
const [allTariffs, setAllTariffs] = useState<Record<string, Tariff>>({});
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
let newSt:Record<string, Tariff>
|
||||||
|
|
||||||
|
|
||||||
|
const requestTariffs = async (page: number = 1): Promise<void> => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data } = await axios.get<GetTariffsResponse>(
|
||||||
|
"https://admin.pena.digital/strator/tariff/",
|
||||||
|
{
|
||||||
|
params: { page, limit: 100 },
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// data.tariffs.forEach(async (t:any) => {
|
||||||
|
// await axios({
|
||||||
|
// method: "delete",
|
||||||
|
// url: "https://admin.pena.digital/strator/tariff/delete",
|
||||||
|
// headers: {
|
||||||
|
// Authorization: `Bearer ${token}`,
|
||||||
|
// },
|
||||||
|
// data: { id: t._id },
|
||||||
|
// });
|
||||||
|
// })
|
||||||
|
|
||||||
|
|
||||||
|
const tariffsObj:Record<string, Tariff> = {}
|
||||||
|
data.tariffs.filter((tariff) => {return !tariff.isDeleted}).forEach((tariff) => {
|
||||||
|
tariffsObj[tariff._id] = {
|
||||||
|
id: tariff._id,
|
||||||
|
name: tariff.name,
|
||||||
|
isCustom: tariff.price ? true : false,
|
||||||
|
amount: tariff.privilegies[0].amount,
|
||||||
|
isFront: false,
|
||||||
|
privilegeId: tariff.privilegies[0].privilegeId,
|
||||||
|
price: tariff.privilegies[0].price,
|
||||||
|
isDeleted: tariff.isDeleted,
|
||||||
|
customPricePerUnit: tariff.price,
|
||||||
|
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
newSt = {...newSt, ...tariffsObj}
|
||||||
|
|
||||||
|
|
||||||
|
if (page < data.totalPages) {
|
||||||
|
return requestTariffs(page + 1);
|
||||||
|
}
|
||||||
|
resetTariffsStore(newSt)
|
||||||
|
setIsLoading(false);
|
||||||
|
} catch {
|
||||||
|
setIsLoading(false);
|
||||||
|
|
||||||
|
throw new Error("Ошибка при получении тарифов");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { requestTariffs, isLoading };
|
||||||
|
};
|
40
src/hooks/useRefreshPrivilegesStore.hook.ts
Normal file
40
src/hooks/useRefreshPrivilegesStore.hook.ts
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import axios from "axios";
|
||||||
|
import { RealPrivilege } from "@root/model/privilege";
|
||||||
|
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||||
|
import { useGetPrivilegies } from "./useGetPrivileges.hook";
|
||||||
|
|
||||||
|
type RefreshPrivilegesStore = {
|
||||||
|
isError: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
errorMessage: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useRefreshPrivilegesStore = (): RefreshPrivilegesStore => {
|
||||||
|
const gotten = useGetPrivilegies()
|
||||||
|
const [isLoading, setIsLoading] = useState(gotten.isLoading);
|
||||||
|
const [isError, setIsError] = useState(gotten.isError);
|
||||||
|
const [errorMessage, setErrorMessage] = useState(gotten.errorMessage);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let extracted:RealPrivilege[] = []
|
||||||
|
for (let serviceKey in gotten.privilegies) { //Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||||
|
extracted = extracted.concat(gotten.privilegies[serviceKey])
|
||||||
|
}
|
||||||
|
let readyArray = extracted.map((privilege) => ({
|
||||||
|
serviceKey: privilege.serviceKey,
|
||||||
|
privilegeId: privilege.privilegeId,
|
||||||
|
name: privilege.name,
|
||||||
|
description: privilege.description,
|
||||||
|
type: privilege.type,
|
||||||
|
price: privilege.price,
|
||||||
|
value: privilege.value,
|
||||||
|
id: privilege._id,
|
||||||
|
}))
|
||||||
|
resetPrivilegeArray(readyArray)
|
||||||
|
}, [gotten.privilegies]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
return {isError:gotten.isError, isLoading:gotten.isLoading, errorMessage:gotten.errorMessage};
|
||||||
|
};
|
@ -15,17 +15,20 @@ import {
|
|||||||
FormControlLabel,
|
FormControlLabel,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Input from "@kitUI/input";
|
import Input from "@kitUI/input";
|
||||||
import { useCartStore } from "@root/stores/cart";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
import { testUser } from "@root/stores/mocks/user";
|
|
||||||
import { useMockDiscountStore } from "@root/stores/discounts";
|
|
||||||
import { calcCartData, createCartItem, findDiscountFactor, formatDiscountFactor } from "./calc";
|
import { calcCartData, createCartItem, findDiscountFactor, formatDiscountFactor } from "./calc";
|
||||||
import { useTariffStore } from "@root/stores/tariffs";
|
|
||||||
import { AnyDiscount, CartItemTotal } from "@root/model/cart";
|
import { AnyDiscount, CartItemTotal } from "@root/model/cart";
|
||||||
import { findPrivilegeById } from "@root/stores/privileges";
|
|
||||||
import { Privilege } from "@root/model/tariff";
|
import { Privilege } from "@root/model/tariff";
|
||||||
|
|
||||||
|
import { useMockDiscountStore } from "@root/stores/discounts";
|
||||||
|
import { useCartStore } from "@root/stores/cart";
|
||||||
|
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||||
|
import { testUser } from "@root/stores/mocks/user";
|
||||||
|
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedTariffs: GridSelectionModel;
|
selectedTariffs: GridSelectionModel;
|
||||||
}
|
}
|
||||||
@ -47,6 +50,7 @@ interface MergedTariff {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Cart({ selectedTariffs }: Props) {
|
export default function Cart({ selectedTariffs }: Props) {
|
||||||
|
let cartTariffs = Object.values(useTariffStore().tariffs)
|
||||||
const discounts = useMockDiscountStore((store) => store.discounts);
|
const discounts = useMockDiscountStore((store) => store.discounts);
|
||||||
const cartTotal = useCartStore((state) => state.cartTotal);
|
const cartTotal = useCartStore((state) => state.cartTotal);
|
||||||
const setCartTotal = useCartStore((store) => store.setCartTotal);
|
const setCartTotal = useCartStore((store) => store.setCartTotal);
|
||||||
@ -55,13 +59,6 @@ export default function Cart({ selectedTariffs }: Props) {
|
|||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||||
|
|
||||||
const exampleTariffs = useTariffStore((state) => state.tariffs);
|
|
||||||
const [tariffs, setTariffs] = useState<any>();
|
|
||||||
const mergeTariffs: MergedTariff[] = [...exampleTariffs, ...(tariffs || [])];
|
|
||||||
|
|
||||||
console.log(cartTotal, "cartTotal");
|
|
||||||
|
|
||||||
|
|
||||||
const cartRows = cartTotal?.items.map((cartItemTotal) => {
|
const cartRows = cartTotal?.items.map((cartItemTotal) => {
|
||||||
const privilege = findPrivilegeById(cartItemTotal.tariff.privilegeId);
|
const privilege = findPrivilegeById(cartItemTotal.tariff.privilegeId);
|
||||||
|
|
||||||
@ -121,13 +118,8 @@ export default function Cart({ selectedTariffs }: Props) {
|
|||||||
|
|
||||||
function handleCalcCartClick() {
|
function handleCalcCartClick() {
|
||||||
//рассчитать
|
//рассчитать
|
||||||
const cartTariffs = mergeTariffs.filter((tariff) => selectedTariffs.includes(tariff._id ? tariff._id : tariff.id));
|
|
||||||
|
|
||||||
const cartItems = cartTariffs.map((tariff) => createCartItem(tariff));
|
const cartItems = cartTariffs.map((tariff) => createCartItem(tariff));
|
||||||
console.log(cartTariffs);
|
|
||||||
// console.log(cartItems);
|
|
||||||
// console.log("selectedTariffs");
|
|
||||||
// console.log(selectedTariffs);
|
|
||||||
|
|
||||||
let loyaltyValue = parseInt(loyaltyField);
|
let loyaltyValue = parseInt(loyaltyField);
|
||||||
|
|
||||||
@ -135,14 +127,6 @@ export default function Cart({ selectedTariffs }: Props) {
|
|||||||
|
|
||||||
const activeDiscounts = discounts.filter((discount) => !discount.disabled);
|
const activeDiscounts = discounts.filter((discount) => !discount.disabled);
|
||||||
|
|
||||||
console.log({
|
|
||||||
user: testUser,
|
|
||||||
purchasesAmount: loyaltyValue,
|
|
||||||
cartItems,
|
|
||||||
discounts: activeDiscounts,
|
|
||||||
isNonCommercial,
|
|
||||||
coupon: couponField,
|
|
||||||
});
|
|
||||||
const cartData = calcCartData({
|
const cartData = calcCartData({
|
||||||
user: testUser,
|
user: testUser,
|
||||||
purchasesAmount: loyaltyValue,
|
purchasesAmount: loyaltyValue,
|
||||||
|
@ -11,7 +11,7 @@ import {
|
|||||||
UserDiscount,
|
UserDiscount,
|
||||||
} from "@root/model/cart";
|
} from "@root/model/cart";
|
||||||
import { User } from "../../model/user";
|
import { User } from "../../model/user";
|
||||||
import { findPrivilegeById } from "@root/stores/privileges";
|
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||||
import { SERVICE_LIST, ServiceType, Tariff } from "@root/model/tariff";
|
import { SERVICE_LIST, ServiceType, Tariff } from "@root/model/tariff";
|
||||||
|
|
||||||
export function calcCartData({
|
export function calcCartData({
|
||||||
@ -38,11 +38,7 @@ export function calcCartData({
|
|||||||
};
|
};
|
||||||
|
|
||||||
cartItems.forEach((cartItem) => {
|
cartItems.forEach((cartItem) => {
|
||||||
|
|
||||||
console.log(cartItem)
|
|
||||||
console.log(cartItem.tariff.privilegeId)
|
|
||||||
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
|
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
|
||||||
console.log(privilege)
|
|
||||||
if (!privilege)
|
if (!privilege)
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Привилегия с id ${cartItem.tariff.privilegeId} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`
|
`Привилегия с id ${cartItem.tariff.privilegeId} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`
|
||||||
|
@ -90,9 +90,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps
|
|||||||
<path
|
<path
|
||||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||||
stroke="#7E2AEA"
|
stroke="#7E2AEA"
|
||||||
stroke-width="1.5"
|
strokeWidth="1.5"
|
||||||
stroke-linecap="round"
|
strokeLinecap="round"
|
||||||
stroke-linejoin="round"
|
strokeLinejoin="round"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
@ -113,9 +113,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps
|
|||||||
<path
|
<path
|
||||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||||
stroke="#fe9903"
|
stroke="#fe9903"
|
||||||
stroke-width="1.5"
|
strokeWidth="1.5"
|
||||||
stroke-linecap="round"
|
strokeLinecap="round"
|
||||||
stroke-linejoin="round"
|
strokeLinejoin="round"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)}
|
)}
|
||||||
|
@ -4,36 +4,63 @@ import Button from "@mui/material/Button";
|
|||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import Modal from "@mui/material/Modal";
|
import Modal from "@mui/material/Modal";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
|
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
import axios from "axios";
|
||||||
|
import { authStore } from "@root/stores/auth";
|
||||||
|
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||||
|
|
||||||
type DeleteModalProps = {
|
type DeleteModalProps = {
|
||||||
open: boolean;
|
open: boolean | string;
|
||||||
handleClose: () => void;
|
handleClose: () => void;
|
||||||
|
selectedTariffs: any;
|
||||||
tariffDelete: (tarifIid: GridSelectionModel) => Promise<void>;
|
|
||||||
errorDelete: boolean;
|
|
||||||
tariffId: GridSelectionModel;
|
|
||||||
tariffName: string[];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function DeleteModal({
|
export default function DeleteModal({
|
||||||
open,
|
open,
|
||||||
handleClose,
|
handleClose,
|
||||||
tariffDelete,
|
selectedTariffs
|
||||||
errorDelete,
|
|
||||||
tariffId,
|
|
||||||
tariffName,
|
|
||||||
}: DeleteModalProps) {
|
}: DeleteModalProps) {
|
||||||
const onClickTariffDelete = () => {
|
const { requestTariffs } = useGetTariffs()
|
||||||
if (errorDelete) {
|
const { token } = authStore();
|
||||||
return;
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
|
|
||||||
|
const deleteTariff = async (id: string): Promise<void> => {
|
||||||
|
const currentTariff = tariffs[id]
|
||||||
|
|
||||||
|
if (!currentTariff) {
|
||||||
|
enqueueSnackbar("Тариф не найден");
|
||||||
|
return
|
||||||
}
|
}
|
||||||
tariffDelete(tariffId);
|
|
||||||
|
try {
|
||||||
|
await axios.delete("https://admin.pena.digital/strator/tariff/", {
|
||||||
|
data: { id },
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
|
||||||
|
enqueueSnackbar("Ошибка при удалении тарифа на бэкэнде");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onClickTariffDelete = () => {
|
||||||
|
if (typeof open === 'string' ) {
|
||||||
|
deleteTariff(open)
|
||||||
|
requestTariffs()
|
||||||
handleClose();
|
handleClose();
|
||||||
|
return
|
||||||
|
}
|
||||||
|
selectedTariffs.forEach((id:string) => {
|
||||||
|
deleteTariff(id)
|
||||||
|
})
|
||||||
|
handleClose();
|
||||||
|
requestTariffs()
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={Boolean(open)}
|
||||||
onClose={handleClose}
|
onClose={handleClose}
|
||||||
aria-labelledby="modal-modal-title"
|
aria-labelledby="modal-modal-title"
|
||||||
aria-describedby="modal-modal-description"
|
aria-describedby="modal-modal-description"
|
||||||
@ -53,7 +80,7 @@ export default function DeleteModal({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography id="modal-modal-title" variant="h6" component="h2">
|
<Typography id="modal-modal-title" variant="h6" component="h2">
|
||||||
Вы уверены, что хотите удалить тариф
|
Вы уверены, что хотите удалить {typeof open === 'string' ? "тариф" : "тарифы"} ?
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box
|
<Box
|
||||||
sx={{ mt: "20px", display: "flex", width: "332px", justifyContent: "space-between", alignItems: "center" }}
|
sx={{ mt: "20px", display: "flex", width: "332px", justifyContent: "space-between", alignItems: "center" }}
|
||||||
@ -61,10 +88,10 @@ export default function DeleteModal({
|
|||||||
<Button onClick={() => onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}>
|
<Button onClick={() => onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}>
|
||||||
Да
|
Да
|
||||||
</Button>
|
</Button>
|
||||||
<Typography>Тариф:</Typography>
|
{/* <Typography>Тариф:</Typography>
|
||||||
{tariffName.map((name, index) => (
|
{tariffName.map((name, index) => (
|
||||||
<Typography key={index}>{name};</Typography>
|
<Typography key={index}>{name};</Typography>
|
||||||
))}
|
))} */}
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
@ -7,36 +7,36 @@ export type Discount = {
|
|||||||
Layer: number;
|
Layer: number;
|
||||||
Description: string;
|
Description: string;
|
||||||
Condition: {
|
Condition: {
|
||||||
Period?: {
|
Period: {
|
||||||
From: string;
|
From: string;
|
||||||
To: string;
|
To: string;
|
||||||
};
|
};
|
||||||
User?: string;
|
User: string;
|
||||||
UserType?: string;
|
UserType: string;
|
||||||
Coupon?: string;
|
Coupon: string;
|
||||||
PurchasesAmount?: number;
|
PurchasesAmount: number;
|
||||||
CartPurchasesAmount?: number;
|
CartPurchasesAmount: number;
|
||||||
Product?: string;
|
Product: string;
|
||||||
Term?: string;
|
Term: string;
|
||||||
Usage?: string;
|
Usage: string;
|
||||||
PriceFrom?: number;
|
PriceFrom: number;
|
||||||
Group?: string;
|
Group: ServiceType;
|
||||||
};
|
};
|
||||||
Target: {
|
Target: {
|
||||||
Products?: {
|
Products: [{
|
||||||
ID: string;
|
ID: string;
|
||||||
Factor: number;
|
Factor: number;
|
||||||
Overhelm: boolean;
|
Overhelm: boolean;
|
||||||
}[];
|
}];
|
||||||
Factor?: number;
|
Factor: number;
|
||||||
TargetScope?: string;
|
TargetScope: string;
|
||||||
TargetGroup?: string;
|
TargetGroup: ServiceType;
|
||||||
Overhelm?: boolean;
|
Overhelm: boolean;
|
||||||
};
|
};
|
||||||
Audit: {
|
Audit: {
|
||||||
UpdatedAt: string;
|
UpdatedAt: string;
|
||||||
CreatedAt: string;
|
CreatedAt: string;
|
||||||
DeletedAt: string;
|
DeletedAt?: string;
|
||||||
Deleted: boolean;
|
Deleted: boolean;
|
||||||
};
|
};
|
||||||
Deprecated: boolean;
|
Deprecated: boolean;
|
||||||
|
@ -1,21 +1,49 @@
|
|||||||
|
export const SERVICE_LIST = [
|
||||||
|
{
|
||||||
|
serviceKey: "templategen",
|
||||||
|
displayName: "Шаблонизатор документов",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
serviceKey: "squiz",
|
||||||
|
displayName: "Опросник",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
serviceKey: "dwarfener",
|
||||||
|
displayName: "Аналитика сокращателя",
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
export interface RealPrivilege {
|
export interface RealPrivilege {
|
||||||
_id: string;
|
createdAt: string;
|
||||||
name: string;
|
|
||||||
privilegeId: string;
|
|
||||||
serviceKey: string;
|
|
||||||
description: string;
|
description: string;
|
||||||
type: "day" | "count";
|
isDeleted: boolean;
|
||||||
value: PrivilegeValueType;
|
name: string;
|
||||||
price: number;
|
price: number;
|
||||||
updatedAt?: string;
|
privilegeId: string;
|
||||||
isDeleted?: boolean;
|
serviceKey: ServiceType;
|
||||||
createdAt?: string;
|
type: "count" | "day" | "mb";
|
||||||
|
updatedAt: string;
|
||||||
|
value: string;
|
||||||
|
_id: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PrivilegeMap = Record<string, RealPrivilege[]>;
|
export interface mergedBackFrontPrivilege {
|
||||||
|
serviceKey: ServiceType;
|
||||||
|
privilegeId: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
type: "count" | "day" | "mb";
|
||||||
|
amount?: number;
|
||||||
|
price: number;
|
||||||
|
isDeleted?: boolean;
|
||||||
|
value?: string
|
||||||
|
id?: string
|
||||||
|
}
|
||||||
|
export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
|
||||||
|
// export type PrivilegeMap = Record<string, RealPrivilege[]>;
|
||||||
|
|
||||||
export type PrivilegeValueType = "шаблон" | "день" | "МБ";
|
// export type PrivilegeValueType = "шаблон" | "день" | "МБ";
|
||||||
|
|
||||||
export type PrivilegeWithAmount = Omit<RealPrivilege, "_id"> & { amount: number; };
|
// export type PrivilegeWithAmount = Omit<RealPrivilege, "_id"> & { amount: number; };
|
||||||
|
|
||||||
export type PrivilegeWithoutPrice = Omit<PrivilegeWithAmount, "price">;
|
// export type PrivilegeWithoutPrice = Omit<PrivilegeWithAmount, "price">;
|
||||||
|
@ -29,17 +29,6 @@ export interface Privilege_BACKEND {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
_id: string;
|
_id: string;
|
||||||
}
|
}
|
||||||
export type Tariff_BACKEND = {
|
|
||||||
_id: string,
|
|
||||||
name: string,
|
|
||||||
price: number,
|
|
||||||
isCustom: boolean,
|
|
||||||
isFront: boolean,
|
|
||||||
privilegies: Privilege_BACKEND[],
|
|
||||||
isDeleted: boolean,
|
|
||||||
createdAt: string,
|
|
||||||
updatedAt: string;
|
|
||||||
};
|
|
||||||
export type Tariff_FRONTEND = {
|
export type Tariff_FRONTEND = {
|
||||||
id: string,
|
id: string,
|
||||||
name: string,
|
name: string,
|
||||||
@ -60,14 +49,25 @@ export interface Privilege {
|
|||||||
price: number;
|
price: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated */
|
export type Tariff_BACKEND = {
|
||||||
export interface Tariff {
|
_id: string,
|
||||||
|
name: string,
|
||||||
|
price: number,
|
||||||
|
isCustom: boolean,
|
||||||
|
isFront: false,
|
||||||
|
privilegies: Privilege_BACKEND[],
|
||||||
|
isDeleted: boolean,
|
||||||
|
createdAt: string,
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
export type Tariff = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
isCustom?: boolean;
|
||||||
|
price?: number;
|
||||||
privilegeId: string;
|
privilegeId: string;
|
||||||
/** Количество единиц привелегии */
|
amount: number; //Количество единиц привелегии
|
||||||
amount: number;
|
customPricePerUnit?: number; //Кастомная цена, если есть, то используется вместо privilege.price
|
||||||
/** Кастомная цена, если есть, то используется вместо privilege.price */
|
isDeleted?: boolean,
|
||||||
customPricePerUnit?: number;
|
|
||||||
isFront?: boolean;
|
isFront?: boolean;
|
||||||
}
|
}
|
||||||
|
@ -12,6 +12,7 @@ interface CardPrivilegie {
|
|||||||
value?: string;
|
value?: string;
|
||||||
privilegeId: string;
|
privilegeId: string;
|
||||||
serviceKey: string;
|
serviceKey: string;
|
||||||
|
amount: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const СardPrivilegie = ({ name, type, price, description, value, privilegeId, serviceKey }: CardPrivilegie) => {
|
export const СardPrivilegie = ({ name, type, price, description, value, privilegeId, serviceKey }: CardPrivilegie) => {
|
||||||
@ -34,9 +35,10 @@ export const СardPrivilegie = ({ name, type, price, description, value, privile
|
|||||||
privilegeId: privilegeId,
|
privilegeId: privilegeId,
|
||||||
serviceKey: serviceKey,
|
serviceKey: serviceKey,
|
||||||
description: description,
|
description: description,
|
||||||
|
amount:1,
|
||||||
type: type,
|
type: type,
|
||||||
value: value,
|
value: value,
|
||||||
price: inputValue,
|
price: Number(inputValue),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@ -99,9 +101,9 @@ export const СardPrivilegie = ({ name, type, price, description, value, privile
|
|||||||
<path
|
<path
|
||||||
d="M9.25 9.25H10V14.5H10.75"
|
d="M9.25 9.25H10V14.5H10.75"
|
||||||
stroke="#7E2AEA"
|
stroke="#7E2AEA"
|
||||||
stroke-width="1.5"
|
strokeWidth="1.5"
|
||||||
stroke-linecap="round"
|
strokeLinecap="round"
|
||||||
stroke-linejoin="round"
|
strokeLinejoin="round"
|
||||||
/>
|
/>
|
||||||
<path
|
<path
|
||||||
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
|
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
|
||||||
|
@ -1,22 +1,19 @@
|
|||||||
import { Typography } from "@mui/material";
|
import { Typography } from "@mui/material";
|
||||||
import { СardPrivilegie } from "./CardPrivilegie";
|
import { СardPrivilegie } from "./CardPrivilegie";
|
||||||
import { mergedPrivilegeStore } from "@root/stores/mergedPrivileges";
|
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
|
|
||||||
export default function ListPrivilegie() {
|
export default function ListPrivilegie() {
|
||||||
const { mergedPrivileges, isError, errorMessage } = mergedPrivilegeStore();
|
const privileges = usePrivilegeStore().privileges;
|
||||||
|
|
||||||
console.log(mergedPrivileges);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{isError ? (
|
{privileges.map(({ name, type, price, description, value, privilegeId, serviceKey, id, amount }) => (
|
||||||
<Typography>{errorMessage}</Typography>
|
|
||||||
) : (
|
|
||||||
mergedPrivileges.map(({ name, type, price, description, value, privilegeId, serviceKey, _id }) => (
|
|
||||||
<СardPrivilegie
|
<СardPrivilegie
|
||||||
key={_id}
|
key={id}
|
||||||
name={name}
|
name={name}
|
||||||
type={type}
|
type={type}
|
||||||
|
amount={1}
|
||||||
price={price}
|
price={price}
|
||||||
value={value}
|
value={value}
|
||||||
privilegeId={privilegeId}
|
privilegeId={privilegeId}
|
||||||
@ -24,7 +21,7 @@ export default function ListPrivilegie() {
|
|||||||
description={description}
|
description={description}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
)}
|
}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -90,9 +90,9 @@ export const PrivilegiesWrapper = ({ text, sx, result }: CustomWrapperProps) =>
|
|||||||
<path
|
<path
|
||||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||||
stroke="#7E2AEA"
|
stroke="#7E2AEA"
|
||||||
stroke-width="1.5"
|
strokeWidth="1.5"
|
||||||
stroke-linecap="round"
|
strokeLinecap="round"
|
||||||
stroke-linejoin="round"
|
strokeLinejoin="round"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
@ -113,9 +113,9 @@ export const PrivilegiesWrapper = ({ text, sx, result }: CustomWrapperProps) =>
|
|||||||
<path
|
<path
|
||||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||||
stroke="#fe9903"
|
stroke="#fe9903"
|
||||||
stroke-width="1.5"
|
strokeWidth="1.5"
|
||||||
stroke-linecap="round"
|
strokeLinecap="round"
|
||||||
stroke-linejoin="round"
|
strokeLinejoin="round"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)}
|
)}
|
||||||
|
@ -110,7 +110,7 @@ export const SettingRoles = (): JSX.Element => {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<PrivilegiesWrapper text="Привелегии" sx={{ mt: "50px" }} />
|
<PrivilegiesWrapper text="Привилегии" sx={{ mt: "50px" }} />
|
||||||
</AccordionDetails>
|
</AccordionDetails>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -4,17 +4,17 @@ import Select, { SelectChangeEvent } from "@mui/material/Select";
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { SERVICE_LIST, ServiceType } from "@root/model/tariff";
|
import { SERVICE_LIST, ServiceType } from "@root/model/tariff";
|
||||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
import { addRealPrivileges, useRealPrivilegeStore } from "@root/stores/privileges";
|
import { resetPrivilegeArray, usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
import { addDiscounts } from "@root/stores/discounts";
|
import { addDiscount } from "@root/stores/discounts";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { DiscountType, discountTypes } from "@root/model/discount";
|
import { DiscountType, discountTypes } from "@root/model/discount";
|
||||||
import { createDiscountJSON } from "@root/api/discounts";
|
import { createDiscount } from "@root/api/discounts";
|
||||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
|
|
||||||
|
|
||||||
export default function CreateDiscount() {
|
export default function CreateDiscount() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const privileges = useRealPrivilegeStore(state => state.privileges);
|
const privileges = usePrivilegeStore(state => state.privileges);
|
||||||
const [serviceType, setServiceType] = useState<ServiceType>("templategen");
|
const [serviceType, setServiceType] = useState<ServiceType>("templategen");
|
||||||
const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
|
const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
|
||||||
const [discountNameField, setDiscountNameField] = useState<string>("");
|
const [discountNameField, setDiscountNameField] = useState<string>("");
|
||||||
@ -25,7 +25,7 @@ export default function CreateDiscount() {
|
|||||||
const [cartPurchasesAmountField, setCartPurchasesAmountField] = useState<string>("0");
|
const [cartPurchasesAmountField, setCartPurchasesAmountField] = useState<string>("0");
|
||||||
const [discountMinValueField, setDiscountMinValueField] = useState<string>("0");
|
const [discountMinValueField, setDiscountMinValueField] = useState<string>("0");
|
||||||
|
|
||||||
usePrivileges({ onNewPrivileges: addRealPrivileges });
|
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
|
||||||
|
|
||||||
const handleDiscountTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
const handleDiscountTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
setDiscountType(event.target.value as DiscountType);
|
setDiscountType(event.target.value as DiscountType);
|
||||||
@ -46,9 +46,12 @@ export default function CreateDiscount() {
|
|||||||
if (!isFinite(cartPurchasesAmount)) return enqueueSnackbar("Поле cartPurchasesAmount не число");
|
if (!isFinite(cartPurchasesAmount)) return enqueueSnackbar("Поле cartPurchasesAmount не число");
|
||||||
if (!isFinite(discountMinValue)) return enqueueSnackbar("Поле discountMinValue не число");
|
if (!isFinite(discountMinValue)) return enqueueSnackbar("Поле discountMinValue не число");
|
||||||
if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана");
|
if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана");
|
||||||
|
if (!discountNameField) return enqueueSnackbar("Поле \"Имя\" пустое");
|
||||||
|
if (!discountDescriptionField) return enqueueSnackbar("Поле \"Описание\" пустое");
|
||||||
|
if (discountFactor < 0) return enqueueSnackbar("Процент скидки не может быть больше 100");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const createdDiscount = await createDiscountJSON({
|
const createdDiscount = await createDiscount({
|
||||||
cartPurchasesAmount,
|
cartPurchasesAmount,
|
||||||
discountFactor,
|
discountFactor,
|
||||||
discountMinValue,
|
discountMinValue,
|
||||||
@ -62,7 +65,7 @@ export default function CreateDiscount() {
|
|||||||
privilegeId: privilegeIdField,
|
privilegeId: privilegeIdField,
|
||||||
});
|
});
|
||||||
|
|
||||||
addDiscounts([createdDiscount]);
|
addDiscount(createdDiscount);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error creating discount", error);
|
console.log("Error creating discount", error);
|
||||||
enqueueSnackbar("Ошибка при создании скидки");
|
enqueueSnackbar("Ошибка при создании скидки");
|
||||||
@ -216,12 +219,12 @@ export default function CreateDiscount() {
|
|||||||
fontSize: "16px",
|
fontSize: "16px",
|
||||||
lineHeight: "19px",
|
lineHeight: "19px",
|
||||||
}}
|
}}
|
||||||
>Привелегия</InputLabel>
|
>Привилегия</InputLabel>
|
||||||
<Select
|
<Select
|
||||||
labelId="privilege-select-label"
|
labelId="privilege-select-label"
|
||||||
id="privilege-select"
|
id="privilege-select"
|
||||||
value={privilegeIdField}
|
value={privilegeIdField}
|
||||||
label="Привелегия"
|
label="Привилегия"
|
||||||
onChange={e => setPrivilegeIdField(e.target.value)}
|
onChange={e => setPrivilegeIdField(e.target.value)}
|
||||||
sx={{
|
sx={{
|
||||||
color: theme.palette.secondary.main,
|
color: theme.palette.secondary.main,
|
||||||
|
@ -1,16 +1,13 @@
|
|||||||
import { Box, Button, styled, useTheme } from "@mui/material";
|
import { Box, IconButton, useTheme } from "@mui/material";
|
||||||
import { DataGrid, GridColDef, GridRowsProp, GridToolbar } from "@mui/x-data-grid";
|
import { DataGrid, GridColDef, GridRowsProp, GridToolbar } from "@mui/x-data-grid";
|
||||||
import { findDiscountFactor, formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
import { formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
||||||
import { activateMockDiscounts, addDiscounts, deactivateMockDiscounts, setMockSelectedDiscountIds, useDiscountStore, useMockDiscountStore, } from "@root/stores/discounts";
|
import { openEditDiscountDialog, setDiscounts, setSelectedDiscountIds, updateDiscount, useDiscountStore } from "@root/stores/discounts";
|
||||||
import useDiscounts from "@root/utils/hooks/useDiscounts";
|
import useDiscounts from "@root/utils/hooks/useDiscounts";
|
||||||
|
import DeleteIcon from '@mui/icons-material/Delete';
|
||||||
|
import EditIcon from '@mui/icons-material/Edit';
|
||||||
|
import { deleteDiscount } from "@root/api/discounts";
|
||||||
|
|
||||||
|
|
||||||
const BoxButton = styled("div")(({ theme }) => ({
|
|
||||||
[theme.breakpoints.down(400)]: {
|
|
||||||
justifyContent: "center",
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
// {
|
// {
|
||||||
// field: "id",
|
// field: "id",
|
||||||
@ -23,6 +20,9 @@ const columns: GridColDef[] = [
|
|||||||
headerName: "Название скидки",
|
headerName: "Название скидки",
|
||||||
width: 150,
|
width: 150,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
|
renderCell: ({ row, value }) => (
|
||||||
|
<Box color={row.deleted && "#ff4545"}>{value}</Box>
|
||||||
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "description",
|
field: "description",
|
||||||
@ -51,9 +51,42 @@ const columns: GridColDef[] = [
|
|||||||
{
|
{
|
||||||
field: "active",
|
field: "active",
|
||||||
headerName: "Активна",
|
headerName: "Активна",
|
||||||
width: 120,
|
width: 80,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
field: "edit",
|
||||||
|
headerName: "Изменить",
|
||||||
|
width: 80,
|
||||||
|
sortable: false,
|
||||||
|
renderCell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<IconButton
|
||||||
|
onClick={() => {
|
||||||
|
openEditDiscountDialog(row.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<EditIcon />
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: "delete",
|
||||||
|
headerName: "Удалить",
|
||||||
|
width: 80,
|
||||||
|
sortable: false,
|
||||||
|
renderCell: ({ row }) => (
|
||||||
|
<IconButton
|
||||||
|
disabled={row.deleted}
|
||||||
|
onClick={() => {
|
||||||
|
deleteDiscount(row.id).then(updateDiscount);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const layerTranslate = [
|
const layerTranslate = [
|
||||||
@ -62,67 +95,44 @@ const layerTranslate = [
|
|||||||
"Сервис",
|
"Сервис",
|
||||||
"корзина",
|
"корзина",
|
||||||
"лояльность",
|
"лояльность",
|
||||||
]
|
];
|
||||||
const layerValue = [
|
const layerValue = [
|
||||||
"",
|
"",
|
||||||
"Term",
|
"Term",
|
||||||
"PriceFrom",
|
"PriceFrom",
|
||||||
"CartPurchasesAmount",
|
"CartPurchasesAmount",
|
||||||
"PurchasesAmount",
|
"PurchasesAmount",
|
||||||
]
|
];
|
||||||
|
|
||||||
export default function DiscountDataGrid() {
|
export default function DiscountDataGrid() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const exampleDiscounts = useMockDiscountStore((state) => state.discounts);
|
const selectedDiscountIds = useDiscountStore((state) => state.selectedDiscountIds);
|
||||||
const selectedDiscountIds = useMockDiscountStore((state) => state.selectedDiscountIds);
|
|
||||||
const realDiscounts = useDiscountStore(state => state.discounts);
|
const realDiscounts = useDiscountStore(state => state.discounts);
|
||||||
|
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
||||||
|
|
||||||
useDiscounts({ onNewDiscounts: addDiscounts });
|
useDiscounts({ onNewDiscounts: setDiscounts });
|
||||||
console.log(realDiscounts)
|
|
||||||
|
|
||||||
const rowBackDicounts: any = realDiscounts.filter(e => e.Layer > 0).map((discount:any) => {
|
const rowBackDicounts: GridRowsProp = realDiscounts.filter(e => e.Layer > 0).map(discount => ({
|
||||||
return {
|
|
||||||
id: discount.ID,
|
id: discount.ID,
|
||||||
name: discount.Name,
|
name: discount.Name,
|
||||||
description: discount.Description,
|
description: discount.Description,
|
||||||
conditionType: layerTranslate[discount.Layer],
|
conditionType: layerTranslate[discount.Layer],
|
||||||
factor: Math.floor(Number((1-discount.Target.Factor)*100)),
|
factor: formatDiscountFactor(discount.Target.Factor),
|
||||||
value: layerValue[discount.Layer],
|
value: layerValue[discount.Layer],
|
||||||
active: discount.Deprecated ? "🚫" : "✅"
|
active: discount.Deprecated ? "🚫" : "✅",
|
||||||
};
|
deleted: discount.Audit.Deleted,
|
||||||
|
}));
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
const discountsGridData: any = exampleDiscounts.map((discount) => {
|
|
||||||
const value =
|
|
||||||
(discount.condition as any).purchasesAmount ??
|
|
||||||
(discount.condition as any).cartPurchasesAmount ??
|
|
||||||
(discount.condition as any).service?.value ??
|
|
||||||
(discount.condition as any).privilege?.value ??
|
|
||||||
"-";
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: discount._id,
|
|
||||||
name: discount.name,
|
|
||||||
description: discount.description,
|
|
||||||
conditionType: discount.conditionType,
|
|
||||||
factor: formatDiscountFactor(findDiscountFactor(discount)),
|
|
||||||
active: discount.disabled ? "🚫" : "✅",
|
|
||||||
value,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const mix = [...rowBackDicounts, ...discountsGridData]
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
|
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
|
||||||
<Box sx={{ height: 600 }}>
|
<Box sx={{ height: 600 }}>
|
||||||
<DataGrid
|
<DataGrid
|
||||||
checkboxSelection={true}
|
checkboxSelection={true}
|
||||||
rows={mix}
|
rows={rowBackDicounts}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
selectionModel={selectedDiscountIds}
|
selectionModel={selectedDiscountIds}
|
||||||
onSelectionModelChange={setMockSelectedDiscountIds}
|
onSelectionModelChange={setSelectedDiscountIds}
|
||||||
|
disableSelectionOnClick
|
||||||
sx={{
|
sx={{
|
||||||
color: theme.palette.secondary.main,
|
color: theme.palette.secondary.main,
|
||||||
"& .MuiDataGrid-iconSeparator": {
|
"& .MuiDataGrid-iconSeparator": {
|
||||||
@ -147,60 +157,6 @@ export default function DiscountDataGrid() {
|
|||||||
components={{ Toolbar: GridToolbar }}
|
components={{ Toolbar: GridToolbar }}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
justifyContent: "center",
|
|
||||||
alignItems: "center",
|
|
||||||
width: "100%",
|
|
||||||
marginTop: "45px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<BoxButton
|
|
||||||
sx={{
|
|
||||||
maxWidth: "420px",
|
|
||||||
width: "100%",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
onClick={deactivateMockDiscounts}
|
|
||||||
sx={{
|
|
||||||
backgroundColor: theme.palette.menu.main,
|
|
||||||
width: "200px",
|
|
||||||
height: "48px",
|
|
||||||
fontWeight: "normal",
|
|
||||||
fontSize: "17px",
|
|
||||||
marginBottom: "10px",
|
|
||||||
"&:hover": {
|
|
||||||
backgroundColor: theme.palette.grayMedium.main,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Деактивировать
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
onClick={activateMockDiscounts}
|
|
||||||
sx={{
|
|
||||||
backgroundColor: theme.palette.menu.main,
|
|
||||||
width: "200px",
|
|
||||||
height: "48px",
|
|
||||||
fontWeight: "normal",
|
|
||||||
fontSize: "17px",
|
|
||||||
"&:hover": {
|
|
||||||
backgroundColor: theme.palette.grayMedium.main,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Активировать
|
|
||||||
</Button>
|
|
||||||
</BoxButton>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -3,13 +3,13 @@ import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
|||||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||||
import DiscountDataGrid from "./DiscountDataGrid";
|
import DiscountDataGrid from "./DiscountDataGrid";
|
||||||
import CreateDiscount from "./CreateDiscount";
|
import CreateDiscount from "./CreateDiscount";
|
||||||
|
import EditDiscountDialog from "./EditDiscountDialog";
|
||||||
|
|
||||||
|
|
||||||
const DiscountManagement: React.FC = () => {
|
const DiscountManagement: React.FC = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
<LocalizationProvider dateAdapter={AdapterDayjs}>
|
||||||
<Typography
|
<Typography
|
||||||
variant="subtitle1"
|
variant="subtitle1"
|
||||||
@ -26,8 +26,8 @@ const DiscountManagement: React.FC = () => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
<CreateDiscount />
|
<CreateDiscount />
|
||||||
<DiscountDataGrid />
|
<DiscountDataGrid />
|
||||||
|
<EditDiscountDialog />
|
||||||
</LocalizationProvider>
|
</LocalizationProvider>
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -0,0 +1,325 @@
|
|||||||
|
import { Box, Button, Dialog, FormControl, FormControlLabel, FormLabel, InputLabel, MenuItem, Radio, RadioGroup, Select, SelectChangeEvent, Typography, useTheme } from "@mui/material";
|
||||||
|
import { patchDiscount } from "@root/api/discounts";
|
||||||
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
|
import { DiscountType, discountTypes } from "@root/model/discount";
|
||||||
|
import { ServiceType, SERVICE_LIST } from "@root/model/tariff";
|
||||||
|
import { closeEditDiscountDialog, updateDiscount, useDiscountStore } from "@root/stores/discounts";
|
||||||
|
import { resetPrivilegeArray, usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
|
import { getDiscountTypeFromLayer } from "@root/utils/discount";
|
||||||
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
|
||||||
|
export default function EditDiscountDialog() {
|
||||||
|
const theme = useTheme();
|
||||||
|
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
||||||
|
const discounts = useDiscountStore(state => state.discounts);
|
||||||
|
const privileges = usePrivilegeStore(state => state.privileges);
|
||||||
|
const [serviceType, setServiceType] = useState<ServiceType>("templategen");
|
||||||
|
const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
|
||||||
|
const [discountNameField, setDiscountNameField] = useState<string>("");
|
||||||
|
const [discountDescriptionField, setDiscountDescriptionField] = useState<string>("");
|
||||||
|
const [privilegeIdField, setPrivilegeIdField] = useState<string | "">("");
|
||||||
|
const [discountFactorField, setDiscountFactorField] = useState<string>("0");
|
||||||
|
const [purchasesAmountField, setPurchasesAmountField] = useState<string>("0");
|
||||||
|
const [cartPurchasesAmountField, setCartPurchasesAmountField] = useState<string>("0");
|
||||||
|
const [discountMinValueField, setDiscountMinValueField] = useState<string>("0");
|
||||||
|
|
||||||
|
const discount = discounts.find(discount => discount.ID === editDiscountId);
|
||||||
|
|
||||||
|
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
|
||||||
|
|
||||||
|
useEffect(function setDiscountFields() {
|
||||||
|
if (!discount) return;
|
||||||
|
|
||||||
|
setServiceType(discount.Condition.Group);
|
||||||
|
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
||||||
|
setDiscountNameField(discount.Name);
|
||||||
|
setDiscountDescriptionField(discount.Description);
|
||||||
|
setPrivilegeIdField(discount.Condition.Product);
|
||||||
|
setDiscountFactorField(discount.Target.Factor.toString());
|
||||||
|
setPurchasesAmountField(discount.Condition.PurchasesAmount.toString());
|
||||||
|
setCartPurchasesAmountField(discount.Condition.CartPurchasesAmount.toString());
|
||||||
|
setDiscountMinValueField(discount.Condition.PriceFrom.toString());
|
||||||
|
}, [discount]);
|
||||||
|
|
||||||
|
const handleDiscountTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
setDiscountType(event.target.value as DiscountType);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleServiceTypeChange = (event: SelectChangeEvent) => {
|
||||||
|
setServiceType(event.target.value as ServiceType);
|
||||||
|
};
|
||||||
|
|
||||||
|
async function handleSaveDiscount() {
|
||||||
|
if (!discount) return;
|
||||||
|
|
||||||
|
const purchasesAmount = parseFloat(purchasesAmountField.replace(",", "."));
|
||||||
|
const discountFactor = (100 - parseFloat(discountFactorField.replace(",", "."))) / 100;
|
||||||
|
const cartPurchasesAmount = parseFloat(cartPurchasesAmountField.replace(",", "."));
|
||||||
|
const discountMinValue = parseFloat(discountMinValueField.replace(",", "."));
|
||||||
|
|
||||||
|
if (!isFinite(purchasesAmount)) return enqueueSnackbar("Поле purchasesAmount не число");
|
||||||
|
if (!isFinite(discountFactor)) return enqueueSnackbar("Поле discountFactor не число");
|
||||||
|
if (!isFinite(cartPurchasesAmount)) return enqueueSnackbar("Поле cartPurchasesAmount не число");
|
||||||
|
if (!isFinite(discountMinValue)) return enqueueSnackbar("Поле discountMinValue не число");
|
||||||
|
if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана");
|
||||||
|
if (!discountNameField) return enqueueSnackbar("Поле \"Имя\" пустое");
|
||||||
|
if (!discountDescriptionField) return enqueueSnackbar("Поле \"Описание\" пустое");
|
||||||
|
if (discountFactor < 0) return enqueueSnackbar("Процент скидки не может быть больше 100");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const createdDiscount = await patchDiscount(discount.ID, {
|
||||||
|
cartPurchasesAmount,
|
||||||
|
discountFactor,
|
||||||
|
discountMinValue,
|
||||||
|
purchasesAmount,
|
||||||
|
discountDescription: discountDescriptionField,
|
||||||
|
discountName: discountNameField,
|
||||||
|
startDate: new Date().toISOString(),
|
||||||
|
endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
|
||||||
|
serviceType,
|
||||||
|
discountType,
|
||||||
|
privilegeId: privilegeIdField,
|
||||||
|
});
|
||||||
|
|
||||||
|
updateDiscount(createdDiscount);
|
||||||
|
closeEditDiscountDialog();
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error patching discount", error);
|
||||||
|
enqueueSnackbar("Ошибка при обновлении скидки");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={editDiscountId !== null}
|
||||||
|
onClose={closeEditDiscountDialog}
|
||||||
|
PaperProps={{
|
||||||
|
sx: {
|
||||||
|
width: "600px",
|
||||||
|
maxWidth: "600px",
|
||||||
|
backgroundColor: theme.palette.grayMedium.main,
|
||||||
|
position: "relative",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
p: "20px",
|
||||||
|
gap: "20px",
|
||||||
|
borderRadius: "12px",
|
||||||
|
boxShadow: "none",
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
slotProps={{ backdrop: { style: { backgroundColor: "rgb(0 0 0 / 0.7)" } } }}
|
||||||
|
>
|
||||||
|
<Box sx={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
justifyContent: "left",
|
||||||
|
alignItems: "left",
|
||||||
|
marginTop: "15px",
|
||||||
|
width: "100%",
|
||||||
|
padding: "16px",
|
||||||
|
maxWidth: "600px",
|
||||||
|
gap: "1em",
|
||||||
|
}}>
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-name"
|
||||||
|
label="Название"
|
||||||
|
value={discountNameField}
|
||||||
|
onChange={e => setDiscountNameField(e.target.value)}
|
||||||
|
/>
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-desc"
|
||||||
|
label="Описание"
|
||||||
|
value={discountDescriptionField}
|
||||||
|
onChange={e => setDiscountDescriptionField(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Typography
|
||||||
|
variant="h4"
|
||||||
|
sx={{
|
||||||
|
width: "90%",
|
||||||
|
fontWeight: "normal",
|
||||||
|
color: theme.palette.grayDisabled.main,
|
||||||
|
paddingLeft: "10px",
|
||||||
|
}}>
|
||||||
|
Условия:
|
||||||
|
</Typography>
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-factor"
|
||||||
|
label="Процент скидки"
|
||||||
|
value={discountFactorField}
|
||||||
|
type="number"
|
||||||
|
onChange={e => setDiscountFactorField(e.target.value)}
|
||||||
|
/>
|
||||||
|
<FormControl>
|
||||||
|
<FormLabel
|
||||||
|
id="discount-type"
|
||||||
|
sx={{
|
||||||
|
color: "white",
|
||||||
|
"&.Mui-focused": {
|
||||||
|
color: "white",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>Тип скидки</FormLabel>
|
||||||
|
<RadioGroup
|
||||||
|
row
|
||||||
|
aria-labelledby="discount-type"
|
||||||
|
name="discount-type"
|
||||||
|
value={discountType}
|
||||||
|
onChange={handleDiscountTypeChange}
|
||||||
|
>
|
||||||
|
{Object.keys(discountTypes).map(type =>
|
||||||
|
<FormControlLabel
|
||||||
|
key={type}
|
||||||
|
value={type}
|
||||||
|
control={<Radio color="secondary" />}
|
||||||
|
label={discountTypes[type as DiscountType]}
|
||||||
|
sx={{ color: "white" }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</RadioGroup>
|
||||||
|
</FormControl>
|
||||||
|
{discountType === "purchasesAmount" &&
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-purchases"
|
||||||
|
label="Внесено больше"
|
||||||
|
type="number"
|
||||||
|
sx={{
|
||||||
|
marginTop: "15px"
|
||||||
|
}}
|
||||||
|
value={purchasesAmountField}
|
||||||
|
onChange={e => setPurchasesAmountField(e.target.value)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
{discountType === "cartPurchasesAmount" &&
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-cart-purchases"
|
||||||
|
label="Объем в корзине"
|
||||||
|
type="number"
|
||||||
|
sx={{
|
||||||
|
marginTop: "15px"
|
||||||
|
}}
|
||||||
|
value={cartPurchasesAmountField}
|
||||||
|
onChange={e => setCartPurchasesAmountField(e.target.value)}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
{discountType === "service" &&
|
||||||
|
<>
|
||||||
|
<Select
|
||||||
|
labelId="discount-service-label"
|
||||||
|
id="discount-service"
|
||||||
|
value={serviceType}
|
||||||
|
onChange={handleServiceTypeChange}
|
||||||
|
sx={{
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
borderColor: theme.palette.secondary.main,
|
||||||
|
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||||
|
borderColor: theme.palette.secondary.main
|
||||||
|
},
|
||||||
|
".MuiSvgIcon-root ": {
|
||||||
|
fill: theme.palette.secondary.main,
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{SERVICE_LIST.map(service =>
|
||||||
|
<MenuItem key={service.serviceKey} value={service.serviceKey}>{service.displayName}</MenuItem>
|
||||||
|
)}
|
||||||
|
</Select>
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-min-value"
|
||||||
|
label="Минимальное значение"
|
||||||
|
type="number"
|
||||||
|
sx={{
|
||||||
|
marginTop: "15px"
|
||||||
|
}}
|
||||||
|
value={discountMinValueField}
|
||||||
|
onChange={e => setDiscountMinValueField(e.target.value)}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
{discountType === "privilege" &&
|
||||||
|
<>
|
||||||
|
<FormControl
|
||||||
|
fullWidth
|
||||||
|
sx={{
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
"& .MuiInputLabel-outlined": {
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
},
|
||||||
|
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<InputLabel
|
||||||
|
id="privilege-select-label"
|
||||||
|
sx={{
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
fontSize: "16px",
|
||||||
|
lineHeight: "19px",
|
||||||
|
}}
|
||||||
|
>Привилегия</InputLabel>
|
||||||
|
<Select
|
||||||
|
labelId="privilege-select-label"
|
||||||
|
id="privilege-select"
|
||||||
|
value={privilegeIdField}
|
||||||
|
label="Привилегия"
|
||||||
|
onChange={e => setPrivilegeIdField(e.target.value)}
|
||||||
|
sx={{
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
borderColor: theme.palette.secondary.main,
|
||||||
|
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||||
|
borderColor: theme.palette.secondary.main,
|
||||||
|
},
|
||||||
|
".MuiSvgIcon-root ": {
|
||||||
|
fill: theme.palette.secondary.main,
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
inputProps={{ sx: { pt: "12px" } }}
|
||||||
|
>
|
||||||
|
{privileges.map((privilege, index) => (
|
||||||
|
<MenuItem key={index} value={privilege.privilegeId}>
|
||||||
|
{privilege.description}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
<CustomTextField
|
||||||
|
id="discount-min-value"
|
||||||
|
label="Минимальное значение"
|
||||||
|
type="number"
|
||||||
|
sx={{
|
||||||
|
marginTop: "15px"
|
||||||
|
}}
|
||||||
|
value={discountMinValueField}
|
||||||
|
onChange={e => setDiscountMinValueField(e.target.value)}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
<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={handleSaveDiscount}
|
||||||
|
>Сохранить</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
@ -22,7 +22,6 @@ export default function ServiceUsersDG({ handleSelectionChange, users }: Props)
|
|||||||
if (!users) {
|
if (!users) {
|
||||||
return <Skeleton>Loading...</Skeleton>;
|
return <Skeleton>Loading...</Skeleton>;
|
||||||
}
|
}
|
||||||
console.log(users)
|
|
||||||
const gridData = users.users.map((user:any) => ({
|
const gridData = users.users.map((user:any) => ({
|
||||||
login: user.login,
|
login: user.login,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
|
@ -45,7 +45,6 @@ export default function Chat() {
|
|||||||
body: getTicketsBody,
|
body: getTicketsBody,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
}).then(result => {
|
}).then(result => {
|
||||||
console.log("GetMessagesResponse", result);
|
|
||||||
if (result?.length > 0) {
|
if (result?.length > 0) {
|
||||||
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
|
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
|
||||||
addOrUpdateMessages(result);
|
addOrUpdateMessages(result);
|
||||||
|
@ -6,99 +6,99 @@ import axios from "axios";
|
|||||||
|
|
||||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
|
|
||||||
import { addTariffs } from "@root/stores/tariffs";
|
import { Tariff } from "@root/model/tariff";
|
||||||
|
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import { mergedPrivilegeStore } from "@root/stores/mergedPrivileges";
|
import { findPrivilegeById, usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
import { Tariff_BACKEND } from "@root/model/tariff";
|
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
getTariffs: () => void
|
||||||
|
}
|
||||||
|
|
||||||
export default function CreateTariff() {
|
export default function CreateTariff() {
|
||||||
|
|
||||||
|
const { token } = authStore();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
|
const privileges = usePrivilegeStore( store => store.privileges);
|
||||||
|
|
||||||
const [nameField, setNameField] = useState<string>("");
|
const [nameField, setNameField] = useState<string>("");
|
||||||
const [amountField, setAmountField] = useState<string>("");
|
const [amountField, setAmountField] = useState<string>("");
|
||||||
const [customPriceField, setCustomPriceField] = useState<string>("");
|
const [customPriceField, setCustomPriceField] = useState<string>("");
|
||||||
const [privilegeIdField, setPrivilegeIdField] = useState<string>("");
|
const [privilegeIdField, setPrivilegeIdField] = useState<string>("");
|
||||||
const { mergedPrivileges, isError, errorMessage } = mergedPrivilegeStore();
|
|
||||||
const { token } = authStore();
|
|
||||||
|
|
||||||
const findPrivilegeById = (privilegeId: string) => {
|
const privilege = findPrivilegeById(privilegeIdField)
|
||||||
return mergedPrivileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const privilege = findPrivilegeById(privilegeIdField);
|
const { requestTariffs } = useGetTariffs()
|
||||||
|
|
||||||
console.log(mergedPrivileges);
|
const checkFulledFields = () => {
|
||||||
|
if (nameField.length === 0) {
|
||||||
|
enqueueSnackbar("Пустое название тарифа");
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (amountField.length === 0) {
|
||||||
|
enqueueSnackbar("Пустое кол-во едениц привилегии");
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (privilegeIdField.length === 0) {
|
||||||
|
enqueueSnackbar("Не выбрана привилегия");
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (!privilege) {
|
||||||
|
enqueueSnackbar("Привилегия с таким id не найдена");
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// function handleCreateTariffClick() {
|
const createTariffBackend = () => {
|
||||||
// if (nameField === "") {
|
if (checkFulledFields() && privilege !== null) {
|
||||||
// enqueueSnackbar("Пустое название тарифа");
|
axios({
|
||||||
// }
|
url: "https://admin.pena.digital/strator/tariff/",
|
||||||
// if (amountField === "") {
|
method: "post",
|
||||||
// enqueueSnackbar("Пустое кол-во едениц привилегия");
|
headers: {
|
||||||
// }
|
Authorization: `Bearer ${token}`,
|
||||||
// if (privilegeIdField === "") {
|
},
|
||||||
// enqueueSnackbar("Не выбрана привилегия");
|
data: {
|
||||||
// }
|
name: nameField,
|
||||||
|
price: Number(customPriceField) * 100,
|
||||||
// const amount = Number(amountField);
|
isCustom: false,
|
||||||
// const customPrice = Number(customPriceField);
|
privilegies: [
|
||||||
|
{
|
||||||
// if (isNaN(amount) || !privilege) return;
|
name: privilege.name,
|
||||||
|
privilegeId: privilege.id ?? "",
|
||||||
// const newTariff: Tariff = {
|
serviceKey: privilege.serviceKey,
|
||||||
|
description: privilege.description,
|
||||||
|
type: privilege.type,
|
||||||
|
value: privilege.value ?? "",
|
||||||
|
price: privilege.price,
|
||||||
|
amount: Number(amountField),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
requestTariffs()
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
enqueueSnackbar("что-то пошло не так")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// const createTariffFrontend = () => {
|
||||||
|
// if (checkFulledFields() && privilege !== null) {
|
||||||
|
// updateTariffStore({
|
||||||
// id: nanoid(5),
|
// id: nanoid(5),
|
||||||
// name: nameField,
|
// name: nameField,
|
||||||
// amount:amount,
|
// amount: Number(amountField),
|
||||||
// isFront: true,
|
// isFront: true,
|
||||||
// privilegeId: privilege.privilegeId,
|
// privilegeId: privilege.privilegeId,
|
||||||
// customPricePerUnit: customPrice ? customPrice / amount : undefined,
|
// customPricePerUnit: customPriceField.length !== 0 ? Number(customPriceField)*100: undefined,
|
||||||
// };
|
// })
|
||||||
// addTariffs([newTariff]);
|
|
||||||
|
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// const createTariff = async () => {
|
|
||||||
// if (nameField === "" || amountField === "" || privilegeIdField === "") {
|
|
||||||
// return;
|
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// try {
|
|
||||||
// if (!privilege) {
|
|
||||||
// throw new Error("Привилегия не выбрана");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if (!privilege._id) {
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const { data } = await axios({
|
|
||||||
// url: "https://admin.pena.digital/strator/tariff/",
|
|
||||||
// method: "post",
|
|
||||||
// headers: {
|
|
||||||
// Authorization: `Bearer ${token}`,
|
|
||||||
// },
|
|
||||||
// data: {
|
|
||||||
// name: nameField,
|
|
||||||
// price: Number(customPriceField) * 100,
|
|
||||||
// isCustom: false,
|
|
||||||
// privilegies: [
|
|
||||||
// {
|
|
||||||
// name: privilege.name,
|
|
||||||
// privilegeId: privilege._id,
|
|
||||||
// serviceKey: privilege.serviceKey,
|
|
||||||
// description: privilege.description,
|
|
||||||
// type: privilege.type,
|
|
||||||
// value: privilege.value,
|
|
||||||
// price: privilege.price,
|
|
||||||
// amount: Number(amountField),
|
|
||||||
// },
|
|
||||||
// ],
|
|
||||||
// },
|
|
||||||
// });
|
|
||||||
// } catch (error) {
|
|
||||||
// enqueueSnackbar((error as Error).message);
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container
|
<Container
|
||||||
sx={{
|
sx={{
|
||||||
@ -136,14 +136,11 @@ export default function CreateTariff() {
|
|||||||
>
|
>
|
||||||
Привилегия
|
Привилегия
|
||||||
</InputLabel>
|
</InputLabel>
|
||||||
{isError ? (
|
|
||||||
<Typography>{errorMessage}</Typography>
|
|
||||||
) : (
|
|
||||||
<Select
|
<Select
|
||||||
labelId="privilege-select-label"
|
labelId="privilege-select-label"
|
||||||
id="privilege-select"
|
id="privilege-select"
|
||||||
value={privilegeIdField}
|
value={privilegeIdField}
|
||||||
label="Привелегия"
|
label="Привилегия"
|
||||||
onChange={(e) => setPrivilegeIdField(e.target.value)}
|
onChange={(e) => setPrivilegeIdField(e.target.value)}
|
||||||
sx={{
|
sx={{
|
||||||
color: theme.palette.secondary.main,
|
color: theme.palette.secondary.main,
|
||||||
@ -158,13 +155,12 @@ export default function CreateTariff() {
|
|||||||
}}
|
}}
|
||||||
inputProps={{ sx: { pt: "12px" } }}
|
inputProps={{ sx: { pt: "12px" } }}
|
||||||
>
|
>
|
||||||
{mergedPrivileges.map((privilege) => (
|
{privileges.map((privilege) => (
|
||||||
<MenuItem key={privilege.description} value={privilege.privilegeId}>
|
<MenuItem key={privilege.description} value={privilege.id}>
|
||||||
{privilege.description}
|
{privilege.description}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
)}
|
|
||||||
</FormControl>
|
</FormControl>
|
||||||
{privilege && (
|
{privilege && (
|
||||||
<Box
|
<Box
|
||||||
@ -208,16 +204,9 @@ export default function CreateTariff() {
|
|||||||
type="number"
|
type="number"
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
// onClick={() => {
|
onClick={() => {
|
||||||
// const privilege = findPrivilegeById(privilegeIdField);
|
createTariffBackend()
|
||||||
// if (true) {
|
}}
|
||||||
// //тариф создан на основе привилегии из БЕКЕНДА
|
|
||||||
// createTariff();
|
|
||||||
// } else {
|
|
||||||
// //тариф создан на основе привилегии из ФРОНТА
|
|
||||||
// handleCreateTariffClick();
|
|
||||||
// }
|
|
||||||
// }}
|
|
||||||
>
|
>
|
||||||
Создать
|
Создать
|
||||||
</Button>
|
</Button>
|
||||||
|
@ -7,11 +7,12 @@ import Modal from "@mui/material/Modal";
|
|||||||
import TextField from "@mui/material/TextField";
|
import TextField from "@mui/material/TextField";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import { Privilege, Tariff_FRONTEND } from "@root/model/tariff";
|
import { Privilege, Tariff } from "@root/model/tariff";
|
||||||
import { findPrivilegeById } from "@root/stores/privileges";
|
import { useTariffStore, updateTariff } from "@root/stores/tariffsStore";
|
||||||
import { mergedPrivilegeStore } from "@root/stores/mergedPrivileges";
|
|
||||||
import { useTariffStore, updateTariff } from "@root/stores/tariffs";
|
|
||||||
import { arrayBuffer } from "stream/consumers";
|
import { arrayBuffer } from "stream/consumers";
|
||||||
|
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||||
|
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
|
||||||
|
|
||||||
interface EditProps {
|
interface EditProps {
|
||||||
@ -39,31 +40,27 @@ const editTariff = ({
|
|||||||
data: {
|
data: {
|
||||||
name: tariffName,
|
name: tariffName,
|
||||||
price: tariffPrice,
|
price: tariffPrice,
|
||||||
isCustom: true,
|
isCustom: false,
|
||||||
privilegies: [privilege]
|
privilegies: [privilege]
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
interface Props {
|
interface Props {
|
||||||
tariff: Tariff_FRONTEND,
|
tariff: Tariff
|
||||||
getTariffs: () => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated */
|
export default function EditModal({tariff = undefined}:Props) {
|
||||||
export default function EditModal({tariff, getTariffs}:Props) {
|
|
||||||
|
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [price, setPrice] = useState("");
|
const [price, setPrice] = useState("");
|
||||||
const { token } = authStore();
|
const { token } = authStore();
|
||||||
const mergedPrivileges = mergedPrivilegeStore((state:any) => state.mergedPrivileges);
|
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
|
const currentTariff = tariff ? tariffs[tariff.id] : undefined
|
||||||
|
const { requestTariffs } = useGetTariffs()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setOpen(tariff !== undefined)
|
setOpen(tariff !== undefined)
|
||||||
}, [tariff])
|
}, [tariff])
|
||||||
console.log(tariff)
|
|
||||||
if (tariff?.privilege[0].privilegeId !== undefined) console.log(findPrivilegeById(tariff?.privilege[0].privilegeId))
|
|
||||||
|
|
||||||
return <Modal
|
return <Modal
|
||||||
open={open}
|
open={open}
|
||||||
@ -89,9 +86,9 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
|||||||
Редактирование тариффа
|
Редактирование тариффа
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
{tariff !== undefined && (
|
{currentTariff !== undefined && (
|
||||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
||||||
<Typography>Название Тарифа: {tariff.name}</Typography>
|
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
||||||
<TextField
|
<TextField
|
||||||
onChange={(event) => setName(event.target.value)}
|
onChange={(event) => setName(event.target.value)}
|
||||||
label="Имя"
|
label="Имя"
|
||||||
@ -99,7 +96,7 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
|||||||
value={name}
|
value={name}
|
||||||
sx={{ marginBottom: "10px" }}
|
sx={{ marginBottom: "10px" }}
|
||||||
/>
|
/>
|
||||||
<Typography>Цена за единицу: {tariff.pricePerUnit}</Typography>
|
<Typography>Цена за единицу: {currentTariff.pricePerUnit}</Typography>
|
||||||
<TextField
|
<TextField
|
||||||
onChange={(event) => setPrice(event.target.value)}
|
onChange={(event) => setPrice(event.target.value)}
|
||||||
label="Цена за единицу"
|
label="Цена за единицу"
|
||||||
@ -108,31 +105,41 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
|||||||
sx={{ marginBottom: "10px" }}
|
sx={{ marginBottom: "10px" }}
|
||||||
/>
|
/>
|
||||||
<Button onClick={() => {
|
<Button onClick={() => {
|
||||||
if (tariff.privilege.length) {
|
if (!currentTariff.isFront) {
|
||||||
let privelege = tariff.privilege[0]
|
const privilege = findPrivilegeById(currentTariff.privilegeId);
|
||||||
|
privilege.privilegeId = privilege.id
|
||||||
mergedPrivileges.forEach((p:any) => {
|
console.log(privilege)
|
||||||
if (privelege.privilegeId == p.privilegeId) tariff.privilege[0].privilegeId = p._id
|
|
||||||
})
|
|
||||||
|
|
||||||
//back
|
//back
|
||||||
|
if (privilege !== null) {
|
||||||
|
|
||||||
|
privilege.amount = tariff.amount
|
||||||
|
privilege.privilegeName = privilege.name
|
||||||
|
privilege.privilegeId = privilege.id
|
||||||
|
privilege.serviceName = privilege.serviceKey
|
||||||
|
console.log(privilege)
|
||||||
|
|
||||||
editTariff({
|
editTariff({
|
||||||
tarifIid: tariff.id,
|
tarifIid: currentTariff.id,
|
||||||
tariffName: name ? name : tariff.name,
|
tariffName: name ? name : currentTariff.name,
|
||||||
tariffPrice: price ? Number(price) : tariff.privilege[0].price,
|
tariffPrice: price ? Number(price) : currentTariff.price ? currentTariff.price : privilege.price,
|
||||||
privilege: privelege,
|
isDeleted: currentTariff.isDeleted,
|
||||||
|
customPricePerUnit: currentTariff.price,
|
||||||
|
privilege: privilege,
|
||||||
token: token
|
token: token
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
getTariffs()
|
requestTariffs()
|
||||||
})
|
})} else {
|
||||||
|
enqueueSnackbar(`Привилегия с id ${currentTariff.privilegeId} не найдена в тарифе ${currentTariff.name} с id ${currentTariff.id}`)
|
||||||
|
}
|
||||||
} else {//front/store
|
} else {//front/store
|
||||||
|
|
||||||
let array = tariffs
|
let array = tariffs
|
||||||
let index
|
let index
|
||||||
tariffs.forEach((p:any, i:number) => {
|
tariffs.forEach((p:any, i:number) => {
|
||||||
if (tariff.id == p.id) index = i
|
if (currentTariff.id == p.id) index = i
|
||||||
})
|
})
|
||||||
if (index !== undefined) {
|
if (index !== undefined) {
|
||||||
array[index].name = name
|
array[index].name = name
|
||||||
|
@ -1,43 +1,44 @@
|
|||||||
import { Box, Button, Dialog, useTheme } from "@mui/material";
|
import { Box, Button, Dialog, useTheme } from "@mui/material";
|
||||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
import {
|
// import {
|
||||||
changeModalPriceField,
|
// changeModalPriceField,
|
||||||
changePrivilegePrice,
|
// changePrivilegePrice,
|
||||||
closePrivilegePriceModal,
|
// closePrivilegePriceModal,
|
||||||
usePrivilegeStore,
|
// usePrivilegeStore,
|
||||||
} from "@root/stores/privileges";
|
// } from "@root/stores/privileges";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
|
||||||
export default function ChangePriceModal() {
|
export default function ChangePriceModal() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const isModalOpen = usePrivilegeStore((state) => state.isModalOpen);
|
// const isModalOpen = usePrivilegeStore((state) => state.isModalOpen);
|
||||||
const modalPriceField = usePrivilegeStore((state) => state.modalPriceField);
|
// const modalPriceField = usePrivilegeStore((state) => state.modalPriceField);
|
||||||
|
|
||||||
function handleSaveChange() {
|
function handleSaveChange() {
|
||||||
const errorMessage = changePrivilegePrice();
|
// const errorMessage = changePrivilegePrice();
|
||||||
if (errorMessage) enqueueSnackbar(errorMessage);
|
// if (errorMessage) enqueueSnackbar(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isModalOpen} onClose={closePrivilegePriceModal}>
|
<></>
|
||||||
<Box
|
// <Dialog open={isModalOpen} onClose={closePrivilegePriceModal}>
|
||||||
sx={{
|
// <Box
|
||||||
p: "20px",
|
// sx={{
|
||||||
backgroundColor: theme.palette.grayLight.main,
|
// p: "20px",
|
||||||
display: "flex",
|
// backgroundColor: theme.palette.grayLight.main,
|
||||||
flexDirection: "column",
|
// display: "flex",
|
||||||
gap: "8px",
|
// flexDirection: "column",
|
||||||
}}
|
// gap: "8px",
|
||||||
>
|
// }}
|
||||||
<CustomTextField
|
// >
|
||||||
id="privilege-custom-price"
|
// <CustomTextField
|
||||||
label="Цена"
|
// id="privilege-custom-price"
|
||||||
value={modalPriceField}
|
// label="Цена"
|
||||||
onChange={(e) => changeModalPriceField(e.target.value)}
|
// value={modalPriceField}
|
||||||
type="number"
|
// onChange={(e) => changeModalPriceField(e.target.value)}
|
||||||
/>
|
// type="number"
|
||||||
<Button onClick={handleSaveChange}>Сохранить</Button>
|
// />
|
||||||
</Box>
|
// <Button onClick={handleSaveChange}>Сохранить</Button>
|
||||||
</Dialog>
|
// </Box>
|
||||||
|
// </Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -2,10 +2,10 @@ import { GridColDef } from "@mui/x-data-grid";
|
|||||||
import DataGrid from "@kitUI/datagrid";
|
import DataGrid from "@kitUI/datagrid";
|
||||||
import { Typography } from "@mui/material";
|
import { Typography } from "@mui/material";
|
||||||
import { useCombinedPrivileges } from "@root/hooks/useCombinedPrivileges.hook";
|
import { useCombinedPrivileges } from "@root/hooks/useCombinedPrivileges.hook";
|
||||||
import { addMergedPrivileges } from "@root/stores/mergedPrivileges";
|
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
{ field: "id", headerName: "id", width: 40 },
|
{ field: "id", headerName: "id", width: 150 },
|
||||||
{ field: "name", headerName: "Привелегия", width: 150 },
|
{ field: "name", headerName: "Привелегия", width: 150 },
|
||||||
{ field: "description", headerName: "Описание", width: 550 }, //инфо из гитлаба.
|
{ field: "description", headerName: "Описание", width: 550 }, //инфо из гитлаба.
|
||||||
{ field: "type", headerName: "Тип", width: 150 },
|
{ field: "type", headerName: "Тип", width: 150 },
|
||||||
@ -13,8 +13,13 @@ const columns: GridColDef[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export default function Privileges() {
|
export default function Privileges() {
|
||||||
const { mergedPrivileges, isError, errorMessage } = useCombinedPrivileges();
|
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||||
const privilegesGridData = mergedPrivileges.map((privilege) => ({
|
// const { mergedPrivileges } = useCombinedPrivileges();
|
||||||
|
const privilegesGridData = privileges
|
||||||
|
.filter(privilege => (
|
||||||
|
!privilege.isDeleted
|
||||||
|
))
|
||||||
|
.map((privilege) => ({
|
||||||
id: privilege.privilegeId,
|
id: privilege.privilegeId,
|
||||||
name: privilege.name,
|
name: privilege.name,
|
||||||
description: privilege.description,
|
description: privilege.description,
|
||||||
@ -22,19 +27,10 @@ export default function Privileges() {
|
|||||||
price: privilege.price,
|
price: privilege.price,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
addMergedPrivileges(mergedPrivileges, isError, errorMessage);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
{isError ? (
|
|
||||||
<Typography>{errorMessage}</Typography>
|
|
||||||
) : (
|
|
||||||
<DataGrid
|
<DataGrid
|
||||||
// checkboxSelection={true}
|
|
||||||
rows={privilegesGridData}
|
rows={privilegesGridData}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -4,62 +4,27 @@ import { GridSelectionModel } from "@mui/x-data-grid";
|
|||||||
|
|
||||||
import Cart from "@root/kitUI/Cart/Cart";
|
import Cart from "@root/kitUI/Cart/Cart";
|
||||||
|
|
||||||
import Privileges from "./Privileges/Privileges";
|
import axios from "axios";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
import { authStore } from "@root/stores/auth";
|
||||||
|
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||||
|
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
|
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||||
|
|
||||||
import TariffsDG from "./tariffsDG";
|
import TariffsDG from "./tariffsDG";
|
||||||
import CreateTariff from "./CreateTariff";
|
import CreateTariff from "./CreateTariff";
|
||||||
|
import Privileges from "./Privileges/Privileges";
|
||||||
import ChangePriceModal from "./Privileges/ChangePriceModal";
|
import ChangePriceModal from "./Privileges/ChangePriceModal";
|
||||||
import { Tariff_BACKEND } from "@root/model/tariff";
|
import {useRefreshPrivilegesStore} from "@root/hooks/useRefreshPrivilegesStore.hook"
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { Tariff } from "@root/model/tariff";
|
||||||
import axios from "axios";
|
|
||||||
import { updateTariff } from "@root/stores/tariffs";
|
|
||||||
|
|
||||||
export default function Tariffs() {
|
export default function Tariffs() {
|
||||||
|
const token = authStore((state) => state.token);
|
||||||
|
// const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
|
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||||
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>([]);
|
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>([]);
|
||||||
|
|
||||||
const getTariffs = () => {
|
|
||||||
axios({
|
|
||||||
method: "get",
|
|
||||||
url: "https://admin.pena.digital/strator/tariff",
|
|
||||||
})
|
|
||||||
.then((data: any) => {
|
|
||||||
//Получили список тарифов. Сразу убираем удалённые и записываем остальное в стор
|
|
||||||
data.data.tariffs.forEach((tariff: Tariff_BACKEND) => {
|
|
||||||
if (!tariff.isDeleted) {
|
|
||||||
let toFrontTariff = {
|
|
||||||
id: tariff._id,
|
|
||||||
name: tariff.name,
|
|
||||||
amount: tariff.privilegies[0].amount,
|
|
||||||
isFront: false,
|
|
||||||
privilegeId: tariff.privilegies[0].privilegeId,
|
|
||||||
customPricePerUnit: tariff.price,
|
|
||||||
};
|
|
||||||
|
|
||||||
updateTariff(toFrontTariff);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// data.data.tariffs.forEach(async (t:any) => {
|
|
||||||
// if (t._id) {
|
|
||||||
// console.log(t._id)
|
|
||||||
// await axios({
|
|
||||||
// method: "delete",
|
|
||||||
// url: "https://admin.pena.digital/strator/tariff/delete",
|
|
||||||
// headers: {
|
|
||||||
// Authorization: `Bearer ${token}`,
|
|
||||||
// },
|
|
||||||
// data: { id: t._id },
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// })
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
enqueueSnackbar("Ошибка получения тарифов");
|
|
||||||
});
|
|
||||||
};
|
|
||||||
useEffect(() => {
|
|
||||||
getTariffs();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container
|
<Container
|
||||||
@ -71,7 +36,12 @@ export default function Tariffs() {
|
|||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography variant="h6">Список привелегий</Typography>
|
|
||||||
|
|
||||||
|
<button onClick={() => console.log(privileges)}>provileges</button>
|
||||||
|
<button onClick={() => console.log(tariffs)}>tariffs</button>
|
||||||
|
|
||||||
|
<Typography variant="h6">Список привилегий</Typography>
|
||||||
|
|
||||||
<Privileges />
|
<Privileges />
|
||||||
|
|
||||||
@ -85,7 +55,6 @@ export default function Tariffs() {
|
|||||||
<TariffsDG
|
<TariffsDG
|
||||||
selectedTariffs={selectedTariffs}
|
selectedTariffs={selectedTariffs}
|
||||||
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
|
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
|
||||||
getTariffs={getTariffs}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Cart selectedTariffs={selectedTariffs} />
|
<Cart selectedTariffs={selectedTariffs} />
|
||||||
|
@ -9,100 +9,50 @@ import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutl
|
|||||||
|
|
||||||
import DataGrid from "@kitUI/datagrid";
|
import DataGrid from "@kitUI/datagrid";
|
||||||
|
|
||||||
import { deleteTariffs, useTariffStore } from "@root/stores/tariffs";
|
import { deleteTariffs, useTariffStore } from "@root/stores/tariffsStore";
|
||||||
import { SERVICE_LIST } from "@root/model/tariff";
|
import { SERVICE_LIST } from "@root/model/tariff";
|
||||||
import { findPrivilegeById } from "@root/stores/privileges";
|
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||||
|
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import DeleteModal from "@root/kitUI/DeleteModal";
|
import DeleteModal from "@root/kitUI/DeleteModal";
|
||||||
import EditModal from "./EditModal";
|
import EditModal from "./EditModal";
|
||||||
import { Tariff_FRONTEND } from "@root/model/tariff";
|
import { Tariff } from "@root/model/tariff";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedTariffs: GridSelectionModel;
|
selectedTariffs: GridSelectionModel;
|
||||||
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
||||||
getTariffs: () => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated */
|
export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) {
|
||||||
export default function TariffsDG({ selectedTariffs, handleSelectionChange, getTariffs }: Props) {
|
const tariffs = Object.values(useTariffStore().tariffs)
|
||||||
const { token } = authStore();
|
|
||||||
|
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
|
||||||
|
|
||||||
const [deletedRows, setDeletedRows] = useState<string[]>([]);
|
const [deletedRows, setDeletedRows] = useState<string[]>([]);
|
||||||
const [openDeleteModal, setOpenDeleteModal] = useState(false);
|
const [openDeleteModal, setOpenDeleteModal] = useState(false);
|
||||||
const [changingTariff, setChangingTariff] = useState<Tariff_FRONTEND | undefined>();
|
const [changingTariff, setChangingTariff] = useState<Tariff | undefined>();
|
||||||
const [errorDelete, setErrorDelete] = useState(false);
|
const [tariffDelete, setTariffDelete] = useState(false);
|
||||||
|
|
||||||
const tariffDeleteDataGrid = async (tarifIid: string) => {
|
const closeDeleteModal = () => {
|
||||||
if (exampleTariffs.find((tariff) => tariff.id === tarifIid)) {
|
setOpenDeleteModal(false)
|
||||||
deleteTariffs(tarifIid);
|
|
||||||
enqueueSnackbar("Тариф удалён");
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
await axios({
|
|
||||||
method: "delete",
|
|
||||||
url: "https://admin.pena.digital/strator/tariff",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
data: { id: tarifIid },
|
|
||||||
});
|
|
||||||
setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]);
|
|
||||||
enqueueSnackbar("Тариф удалён");
|
|
||||||
getTariffs();
|
|
||||||
} catch (error: any) {
|
|
||||||
setErrorDelete(true);
|
|
||||||
enqueueSnackbar("Ошибка удаления :", error.message);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const tariffDelete = async (tarifIid: GridSelectionModel) => {
|
|
||||||
const deleted = [];
|
|
||||||
const notDeleted = [];
|
|
||||||
|
|
||||||
for (let index = 0; index < tarifIid.length; index++) {
|
|
||||||
if (exampleTariffs.find((tariff) => tariff.id === (tarifIid[index] as string))) {
|
|
||||||
deleted.push(tarifIid[index]);
|
|
||||||
deleteTariffs(tarifIid[index] as string);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await axios({
|
|
||||||
method: "delete",
|
|
||||||
url: "https://admin.pena.digital/strator/tariff",
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
},
|
|
||||||
data: { id: tarifIid[index] },
|
|
||||||
});
|
|
||||||
setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid[index] as string]);
|
|
||||||
|
|
||||||
deleted.push(tarifIid[index]);
|
|
||||||
} catch (error: any) {
|
|
||||||
notDeleted.push(tarifIid[index]);
|
|
||||||
|
|
||||||
setErrorDelete(true);
|
|
||||||
enqueueSnackbar(error.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
getTariffs();
|
|
||||||
|
|
||||||
enqueueSnackbar(`Deleted: ${deleted.join(", ")}`);
|
|
||||||
enqueueSnackbar(`Not deleted: ${notDeleted.join(", ")}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
{ field: "id", headerName: "ID", width: 100 },
|
{ field: "id", headerName: "ID", width: 100 },
|
||||||
|
{
|
||||||
|
field: "edit",
|
||||||
|
headerName: "Изменение",
|
||||||
|
width: 60,
|
||||||
|
renderCell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<IconButton onClick={() => setChangingTariff(row)}>
|
||||||
|
<ModeEditOutlineOutlinedIcon />
|
||||||
|
</IconButton>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
{ field: "name", headerName: "Название тарифа", width: 150 },
|
{ field: "name", headerName: "Название тарифа", width: 150 },
|
||||||
{ field: "amount", headerName: "Количество", width: 110 },
|
{ field: "amount", headerName: "Количество", width: 110 },
|
||||||
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
|
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
|
||||||
{ field: "privilegeName", headerName: "Привелегия", width: 150 },
|
{ field: "privilegeName", headerName: "Привилегия", width: 150 },
|
||||||
{ field: "type", headerName: "Единица", width: 100 },
|
{ field: "type", headerName: "Единица", width: 100 },
|
||||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
|
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
|
||||||
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130 },
|
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130 },
|
||||||
@ -115,7 +65,7 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
|||||||
return (
|
return (
|
||||||
<IconButton
|
<IconButton
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
tariffDeleteDataGrid(row.id);
|
setOpenDeleteModal(row.id);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<BackspaceIcon />
|
<BackspaceIcon />
|
||||||
@ -123,42 +73,47 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
field: "edit",
|
|
||||||
headerName: "Изменение",
|
|
||||||
width: 60,
|
|
||||||
renderCell: ({ row }) => {
|
|
||||||
// console.log(row)
|
|
||||||
return (
|
|
||||||
<IconButton onClick={() => setChangingTariff(row)}>
|
|
||||||
<ModeEditOutlineOutlinedIcon />
|
|
||||||
</IconButton>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]);
|
|
||||||
// const selectedTariffPrivilege = selectedTariff ? selectedTariff.privilege : [];
|
|
||||||
|
|
||||||
const allName = () => {
|
const gridData = tariffs
|
||||||
const selectedNames = [];
|
?.map((tariff) => {
|
||||||
|
const privilege = findPrivilegeById(tariff.privilegeId);
|
||||||
for (let index = 0; index < selectedTariffs.length; index++) {
|
console.log(tariff.privilegeId)
|
||||||
const tariff = gridData.find((tariff) => tariff.id === selectedTariffs[index]);
|
console.log(privilege)
|
||||||
const name = tariff ? tariff.name : "";
|
return {
|
||||||
selectedNames.push(name);
|
id: tariff.id,
|
||||||
}
|
name: tariff.name,
|
||||||
|
serviceName: privilege?.serviceKey == "templategen" ? "Шаблонизатор" : privilege?.serviceKey,
|
||||||
return selectedNames;
|
privilegeName: privilege?.name,
|
||||||
|
amount: tariff.amount,
|
||||||
|
pricePerUnit: tariff.isCustom
|
||||||
|
? (tariff.customPricePerUnit || 0) / 100
|
||||||
|
: (tariff?.price || 0) / 100,
|
||||||
|
type:
|
||||||
|
findPrivilegeById(tariff.privilegeId)?.type === "count"
|
||||||
|
? "день"
|
||||||
|
: "шт.",
|
||||||
|
customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
|
||||||
|
total: tariff.amount
|
||||||
|
? (tariff.amount *
|
||||||
|
(tariff.isCustom
|
||||||
|
? tariff.customPricePerUnit || 0 * tariff.amount
|
||||||
|
: findPrivilegeById(tariff.privilegeId)?.price || 0)) /
|
||||||
|
100
|
||||||
|
: 0,
|
||||||
};
|
};
|
||||||
|
})
|
||||||
|
.sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));
|
||||||
|
|
||||||
|
console.log(gridData)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DataGrid
|
<DataGrid
|
||||||
disableSelectionOnClick={true}
|
disableSelectionOnClick={true}
|
||||||
checkboxSelection={true}
|
checkboxSelection={true}
|
||||||
rows={tariffs}
|
rows={gridData}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
getRowId={(row) => row.id}
|
getRowId={(row) => row.id}
|
||||||
components={{ Toolbar: GridToolbar }}
|
components={{ Toolbar: GridToolbar }}
|
||||||
@ -173,18 +128,14 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
|||||||
) : (
|
) : (
|
||||||
<React.Fragment />
|
<React.Fragment />
|
||||||
)}
|
)}
|
||||||
{/* <DeleteModal
|
<DeleteModal
|
||||||
tariffDelete={tariffDelete}
|
|
||||||
errorDelete={errorDelete}
|
|
||||||
tariffId={selectedTariffs}
|
|
||||||
tariffName={allName()}
|
|
||||||
open={openDeleteModal}
|
open={openDeleteModal}
|
||||||
handleClose={() => {
|
handleClose={() => {
|
||||||
setOpenDeleteModal(false);
|
closeDeleteModal();
|
||||||
}}
|
}}
|
||||||
/> */}
|
selectedTariffs={selectedTariffs}
|
||||||
{console.log(changingTariff)}
|
/>
|
||||||
<EditModal tariff={changingTariff} getTariffs={getTariffs} />
|
<EditModal tariff={changingTariff}/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -10,8 +10,15 @@ import ModalAdmin from "./ModalAdmin";
|
|||||||
import ModalUser from "./ModalUser";
|
import ModalUser from "./ModalUser";
|
||||||
import ModalEntities from "./ModalEntities";
|
import ModalEntities from "./ModalEntities";
|
||||||
import {useMatch} from "react-router-dom";
|
import {useMatch} from "react-router-dom";
|
||||||
|
import {useRefreshPrivilegesStore} from "@root/hooks/useRefreshPrivilegesStore.hook"
|
||||||
|
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
|
useRefreshPrivilegesStore()
|
||||||
|
const {requestTariffs} = useGetTariffs()
|
||||||
|
React.useEffect(() => {
|
||||||
|
requestTariffs()
|
||||||
|
},[])
|
||||||
const theme = useTheme()
|
const theme = useTheme()
|
||||||
return (
|
return (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
|
@ -4,11 +4,13 @@ import { create } from "zustand";
|
|||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { exampleCartValues } from "./mocks/exampleCartValues";
|
import { exampleCartValues } from "./mocks/exampleCartValues";
|
||||||
import { Discount } from "@root/model/discount";
|
import { Discount } from "@root/model/discount";
|
||||||
|
import { produce } from "immer";
|
||||||
|
|
||||||
|
|
||||||
interface DiscountStore {
|
interface DiscountStore {
|
||||||
discounts: Discount[];
|
discounts: Discount[];
|
||||||
selectedDiscountIds: GridSelectionModel,
|
selectedDiscountIds: GridSelectionModel,
|
||||||
|
editDiscountId: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useDiscountStore = create<DiscountStore>()(
|
export const useDiscountStore = create<DiscountStore>()(
|
||||||
@ -16,6 +18,7 @@ export const useDiscountStore = create<DiscountStore>()(
|
|||||||
(set, get) => ({
|
(set, get) => ({
|
||||||
discounts: [],
|
discounts: [],
|
||||||
selectedDiscountIds: [],
|
selectedDiscountIds: [],
|
||||||
|
editDiscountId: null,
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
name: "Real discount store",
|
name: "Real discount store",
|
||||||
@ -24,15 +27,26 @@ export const useDiscountStore = create<DiscountStore>()(
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
export const addDiscounts = (newDiscounts: DiscountStore["discounts"]) => {
|
export const setDiscounts = (discounts: DiscountStore["discounts"]) => useDiscountStore.setState({ discounts });
|
||||||
console.log(useDiscountStore.getState())
|
|
||||||
console.log(newDiscounts)
|
export const addDiscount = (discount: DiscountStore["discounts"][number]) => useDiscountStore.setState(
|
||||||
useDiscountStore.setState(state => ({ discounts: [...state.discounts, ...newDiscounts] }));
|
state => ({ discounts: [...state.discounts, discount] })
|
||||||
console.log(useDiscountStore.getState())
|
);
|
||||||
}
|
|
||||||
|
export const updateDiscount = (updatedDiscount: DiscountStore["discounts"][number]) => useDiscountStore.setState(
|
||||||
|
produce<DiscountStore>(state => {
|
||||||
|
const discountIndex = state.discounts.findIndex(discount => discount.ID === updatedDiscount.ID);
|
||||||
|
if (discountIndex === -1) throw new Error(`Discount not found when updating: ${updatedDiscount.ID}`);
|
||||||
|
|
||||||
|
state.discounts.splice(discountIndex, 1, updatedDiscount);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
export const setSelectedDiscountIds = (selectedDiscountIds: DiscountStore["selectedDiscountIds"]) => useDiscountStore.setState({ selectedDiscountIds });
|
export const setSelectedDiscountIds = (selectedDiscountIds: DiscountStore["selectedDiscountIds"]) => useDiscountStore.setState({ selectedDiscountIds });
|
||||||
|
|
||||||
|
export const openEditDiscountDialog = (editDiscountId: DiscountStore["editDiscountId"]) => useDiscountStore.setState({ editDiscountId });
|
||||||
|
|
||||||
|
export const closeEditDiscountDialog = () => useDiscountStore.setState({ editDiscountId: null });
|
||||||
|
|
||||||
/** @deprecated */
|
/** @deprecated */
|
||||||
interface MockDiscountStore {
|
interface MockDiscountStore {
|
||||||
|
@ -1,43 +0,0 @@
|
|||||||
import { create } from "zustand";
|
|
||||||
import { persist } from "zustand/middleware";
|
|
||||||
|
|
||||||
type mergedPrivilege = {
|
|
||||||
createdAt?: string;
|
|
||||||
description: string;
|
|
||||||
isDeleted?: boolean;
|
|
||||||
name: string;
|
|
||||||
price: number;
|
|
||||||
privilegeId: string;
|
|
||||||
serviceKey: string;
|
|
||||||
type: "count" | "day" | "mb";
|
|
||||||
updatedAt?: string;
|
|
||||||
value?: string;
|
|
||||||
_id?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type MergedPrivilegeType = {
|
|
||||||
mergedPrivileges: mergedPrivilege[];
|
|
||||||
isError: boolean;
|
|
||||||
errorMessage: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const mergedPrivilegeStore = create<MergedPrivilegeType>()(
|
|
||||||
persist(
|
|
||||||
(set, get) => ({
|
|
||||||
mergedPrivileges: [],
|
|
||||||
isError: false,
|
|
||||||
errorMessage: "",
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
name: "MergedPrivileg store",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
export const addMergedPrivileges = (newPrivileges: mergedPrivilege[], isError: boolean, errorMessage: string) => {
|
|
||||||
mergedPrivilegeStore.setState((state) => ({
|
|
||||||
mergedPrivileges: [...newPrivileges],
|
|
||||||
isError: isError,
|
|
||||||
errorMessage: errorMessage,
|
|
||||||
}));
|
|
||||||
};
|
|
@ -1,91 +0,0 @@
|
|||||||
import { Privilege } from "@root/model/tariff";
|
|
||||||
import { create } from "zustand";
|
|
||||||
import { devtools } from "zustand/middleware";
|
|
||||||
import { exampleCartValues } from "./mocks/exampleCartValues";
|
|
||||||
import { RealPrivilege } from "@root/model/privilege";
|
|
||||||
|
|
||||||
interface RealPrivilegeStore {
|
|
||||||
privileges: RealPrivilege[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export const useRealPrivilegeStore = create<RealPrivilegeStore>()(
|
|
||||||
devtools(
|
|
||||||
(set, get) => ({
|
|
||||||
privileges: [],
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
name: "Privilege store",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
export const addRealPrivileges = (privileges: RealPrivilegeStore["privileges"]) => useRealPrivilegeStore.setState({ privileges });
|
|
||||||
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
interface PrivilegeStore {
|
|
||||||
privileges: Privilege[];
|
|
||||||
isModalOpen: boolean;
|
|
||||||
modalPrivilegeId: string | null;
|
|
||||||
modalPriceField: string;
|
|
||||||
addPrivileges: (newPrivileges: Privilege[]) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
|
||||||
devtools(
|
|
||||||
(set, get) => ({
|
|
||||||
privileges: exampleCartValues.privileges,
|
|
||||||
isModalOpen: false,
|
|
||||||
modalPrivilegeId: null,
|
|
||||||
modalPriceField: "",
|
|
||||||
addPrivileges: (newPrivileges) => set((state) => ({ privileges: [...state.privileges, ...newPrivileges] })),
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
name: "Mock Privilege store",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const closePrivilegePriceModal = () => usePrivilegeStore.setState({ isModalOpen: false });
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const openPrivilegePriceModal = (modalPrivilegeId: string | null, defaultPrice: number) =>
|
|
||||||
usePrivilegeStore.setState({
|
|
||||||
isModalOpen: true,
|
|
||||||
modalPriceField: defaultPrice.toString(),
|
|
||||||
modalPrivilegeId,
|
|
||||||
});
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const changeModalPriceField = (modalPriceField: string) => usePrivilegeStore.setState({ modalPriceField });
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const changePrivilegePrice = () => {
|
|
||||||
const { privileges, modalPrivilegeId, modalPriceField } = usePrivilegeStore.getState();
|
|
||||||
|
|
||||||
const privilegeIndex = privileges.findIndex((privilege) => privilege.privilegeId === modalPrivilegeId);
|
|
||||||
if (privilegeIndex === -1) throw new Error("Privilege not found by id");
|
|
||||||
|
|
||||||
const price = parseFloat(modalPriceField.replace(",", "."));
|
|
||||||
if (!isFinite(price)) return "Error parsing price";
|
|
||||||
|
|
||||||
const newPrivilege: Privilege = {
|
|
||||||
...privileges[privilegeIndex],
|
|
||||||
price: price,
|
|
||||||
};
|
|
||||||
|
|
||||||
const newPrivileges = [...privileges];
|
|
||||||
newPrivileges.splice(privilegeIndex, 1, newPrivilege);
|
|
||||||
|
|
||||||
usePrivilegeStore.setState({
|
|
||||||
privileges: newPrivileges,
|
|
||||||
isModalOpen: false,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @deprecated */
|
|
||||||
export const findPrivilegeById = (privilegeId: string) => {
|
|
||||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null;
|
|
||||||
};
|
|
27
src/stores/privilegesStore.ts
Normal file
27
src/stores/privilegesStore.ts
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import { Privilege } from "@root/model/tariff";
|
||||||
|
import { create } from "zustand";
|
||||||
|
import { devtools } from "zustand/middleware";
|
||||||
|
import { exampleCartValues } from "./mocks/exampleCartValues";
|
||||||
|
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
||||||
|
|
||||||
|
interface PrivilegeStore {
|
||||||
|
privileges: mergedBackFrontPrivilege[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||||
|
devtools(
|
||||||
|
(set, get) => ({
|
||||||
|
privileges: [],
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: "Privilege store",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
@ -36,6 +36,7 @@ export const updateTariff = (tariff: Tariff_FRONTEND) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const addTariffs = (newTariffs: Tariff_FRONTEND[]) => {
|
export const addTariffs = (newTariffs: Tariff_FRONTEND[]) => {
|
||||||
let stateTariffs = useTariffStore.getState().tariffs
|
let stateTariffs = useTariffStore.getState().tariffs
|
||||||
let newArrayTariffs = [...stateTariffs, ...newTariffs]
|
let newArrayTariffs = [...stateTariffs, ...newTariffs]
|
||||||
|
39
src/stores/tariffsStore.ts
Normal file
39
src/stores/tariffsStore.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import { persist } from "zustand/middleware";
|
||||||
|
import { Tariff } from "@root/model/tariff";
|
||||||
|
|
||||||
|
|
||||||
|
interface TariffStore {
|
||||||
|
tariffs: Record<string, Tariff>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useTariffStore = create<TariffStore>()(
|
||||||
|
persist(
|
||||||
|
(set, get) => ({
|
||||||
|
tariffs: {},
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
name: "Tariff store",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const updateTariffs = (newTariffs: Record<string, Tariff>) => {
|
||||||
|
useTariffStore.setState((state) => ({
|
||||||
|
tariffs: {...state.tariffs, ...newTariffs},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteTariffs = (tariffId: string) => {
|
||||||
|
let tariffs = useTariffStore.getState().tariffs
|
||||||
|
delete tariffs[tariffId]
|
||||||
|
useTariffStore.setState(() => ({tariffs: tariffs}));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const resetTariffsStore = (newTariffs: Record<string, Tariff>) => {
|
||||||
|
useTariffStore.setState(() => ({tariffs: {}}));
|
||||||
|
console.log(newTariffs)
|
||||||
|
useTariffStore.setState(() => ({tariffs: newTariffs}));
|
||||||
|
};
|
11
src/utils/discount.ts
Normal file
11
src/utils/discount.ts
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { Discount, DiscountType } from "@root/model/discount";
|
||||||
|
|
||||||
|
export function getDiscountTypeFromLayer(layer: Discount["Layer"]): DiscountType {
|
||||||
|
switch (layer) {
|
||||||
|
case 1: return "privilege";
|
||||||
|
case 2: return "service";
|
||||||
|
case 3: return "cartPurchasesAmount";
|
||||||
|
case 4: return "purchasesAmount";
|
||||||
|
default: throw new Error("Wrong discount layer");
|
||||||
|
}
|
||||||
|
}
|
@ -19,10 +19,8 @@ export default function usePrivileges({ onError, onNewPrivileges }: {
|
|||||||
bearer: true,
|
bearer: true,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
}).then(result => {
|
}).then(result => {
|
||||||
console.log("New privileges", result);
|
|
||||||
onNewPrivileges(result);
|
onNewPrivileges(result);
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
console.log("Error fetching privileges", error);
|
|
||||||
onError?.(error);
|
onError?.(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -6671,6 +6671,11 @@ immediate@~3.0.5:
|
|||||||
resolved "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz"
|
resolved "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz"
|
||||||
integrity sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==
|
integrity sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==
|
||||||
|
|
||||||
|
immer@^10.0.2:
|
||||||
|
version "10.0.2"
|
||||||
|
resolved "https://registry.yarnpkg.com/immer/-/immer-10.0.2.tgz#11636c5b77acf529e059582d76faf338beb56141"
|
||||||
|
integrity sha512-Rx3CqeqQ19sxUtYV9CU911Vhy8/721wRFnJv3REVGWUmoAcIwzifTsdmJte/MV+0/XpM35LZdQMBGkRIoLPwQA==
|
||||||
|
|
||||||
immer@^9.0.7:
|
immer@^9.0.7:
|
||||||
version "9.0.19"
|
version "9.0.19"
|
||||||
resolved "https://registry.npmjs.org/immer/-/immer-9.0.19.tgz"
|
resolved "https://registry.npmjs.org/immer/-/immer-9.0.19.tgz"
|
||||||
|
Loading…
Reference in New Issue
Block a user