Merge branch 'request-hooks' into 'dev'
feat: request hooks See merge request frontend/admin!27
This commit is contained in:
commit
9d39153e7f
@ -1,52 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import axios from "axios";
|
|
||||||
|
|
||||||
export type Privilege = {
|
|
||||||
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 UseTariffs = {
|
|
||||||
tariffs: Record<string, Privilege[]> | undefined;
|
|
||||||
isError: boolean;
|
|
||||||
isLoading: boolean;
|
|
||||||
errorMessage: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useTariffs = (): UseTariffs => {
|
|
||||||
const [tariffs, setTariffs] = useState<Record<string, Privilege[]>>();
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [isError, setIsError] = useState(false);
|
|
||||||
const [errorMessage, setErrorMessage] = useState("");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const getPrivilegies = async () => {
|
|
||||||
const { data } = await axios<Record<string, Privilege[]>>({
|
|
||||||
method: "get",
|
|
||||||
url: "https://admin.pena.digital/strator/tariff/",
|
|
||||||
});
|
|
||||||
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
getPrivilegies()
|
|
||||||
.then(setTariffs)
|
|
||||||
.catch(() => {
|
|
||||||
setIsError(true);
|
|
||||||
setErrorMessage("Ошибка при получении тарифов");
|
|
||||||
})
|
|
||||||
.finally(() => setIsLoading(false));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return { tariffs, isError, isLoading, errorMessage };
|
|
||||||
};
|
|
@ -1,33 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
|
||||||
import { useRefreshPrivilegesStore } from "./useRefreshPrivilegesStore.hook";
|
|
||||||
import { exampleCartValues } from "@stores/mocks/exampleCartValues"
|
|
||||||
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
|
||||||
|
|
||||||
interface UseCombinedPrivileges {
|
|
||||||
mergedPrivileges: mergedBackFrontPrivilege[]
|
|
||||||
}
|
|
||||||
const translatorServiceKey = {
|
|
||||||
Шаблонизатор: "templategen"
|
|
||||||
}
|
|
||||||
export const useCombinedPrivileges = ():UseCombinedPrivileges => {
|
|
||||||
|
|
||||||
const [mergedPrivileges, setMergedPrivileges] = useState<mergedBackFrontPrivilege[]>([])
|
|
||||||
|
|
||||||
const backendPrivileges = usePrivilegeStore((state) => state.privileges);
|
|
||||||
const frontendPrivileges = exampleCartValues.privileges;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setMergedPrivileges([...backendPrivileges.map((privilege) => ({
|
|
||||||
serviceKey: privilege.serviceKey,
|
|
||||||
privilegeId: privilege.privilegeId,
|
|
||||||
name: privilege.name,
|
|
||||||
description: privilege.description,
|
|
||||||
type: privilege.type,
|
|
||||||
price: privilege.price,
|
|
||||||
})), ...frontendPrivileges])
|
|
||||||
}, [backendPrivileges])
|
|
||||||
|
|
||||||
return { mergedPrivileges };
|
|
||||||
};
|
|
30
src/hooks/useDiscounts.hook.ts
Normal file
30
src/hooks/useDiscounts.hook.ts
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import { authStore } from "@root/stores/auth";
|
||||||
|
import { setDiscounts } from "@root/stores/discounts";
|
||||||
|
|
||||||
|
import type { GetDiscountResponse } from "@root/model/discount";
|
||||||
|
|
||||||
|
const makeRequest = authStore.getState().makeRequest;
|
||||||
|
|
||||||
|
export const useDiscounts = () => {
|
||||||
|
const requestDiscounts = async () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
makeRequest<never, GetDiscountResponse>({
|
||||||
|
url: "https://admin.pena.digital/price/discounts",
|
||||||
|
method: "get",
|
||||||
|
useToken: true,
|
||||||
|
bearer: true,
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
.then((result) => {
|
||||||
|
setDiscounts(result.Discounts);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.log("Error fetching discounts", error);
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => controller.abort();
|
||||||
|
};
|
||||||
|
|
||||||
|
return { requestDiscounts };
|
||||||
|
};
|
@ -1,53 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import axios from "axios";
|
|
||||||
import { RealPrivilege } from "@root/model/privilege";
|
|
||||||
|
|
||||||
export type Privilege = {
|
|
||||||
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 UsePrivilegies = {
|
|
||||||
privilegies: RealPrivilege[]
|
|
||||||
isError: boolean;
|
|
||||||
isLoading: boolean;
|
|
||||||
errorMessage: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useGetPrivilegies = (): UsePrivilegies => {
|
|
||||||
const [privilegies, setPrivilegies] = useState<RealPrivilege[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [isError, setIsError] = useState(false);
|
|
||||||
const [errorMessage, setErrorMessage] = useState("");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const getPrivilegies = async () => {
|
|
||||||
const { data } = await axios<RealPrivilege[]>({
|
|
||||||
method: "get",
|
|
||||||
url: "https://admin.pena.digital/strator/privilege/service",
|
|
||||||
});
|
|
||||||
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
getPrivilegies()
|
|
||||||
.then(setPrivilegies)
|
|
||||||
.catch(() => {
|
|
||||||
setIsError(true);
|
|
||||||
setErrorMessage("Ошибка при получении привилегий");
|
|
||||||
})
|
|
||||||
.finally(() => setIsLoading(false));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return { privilegies, isError, isLoading, errorMessage };
|
|
||||||
};
|
|
82
src/hooks/usePrivilegies.hook.ts
Normal file
82
src/hooks/usePrivilegies.hook.ts
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import axios from "axios";
|
||||||
|
|
||||||
|
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||||
|
import { exampleCartValues } from "@stores/mocks/exampleCartValues";
|
||||||
|
|
||||||
|
import type { RealPrivilege } from "@root/model/privilege";
|
||||||
|
|
||||||
|
export type Privilege = {
|
||||||
|
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 SeverPrivilegiesResponse = {
|
||||||
|
templategen: RealPrivilege[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type UsePrivilegies = {
|
||||||
|
requestPrivilegies: () => Promise<void>;
|
||||||
|
isError: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
errorMessage: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const usePrivilegies = (): UsePrivilegies => {
|
||||||
|
const [privilegies, setPrivilegies] = useState<RealPrivilege[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isError, setIsError] = useState(false);
|
||||||
|
const [errorMessage, setErrorMessage] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let extracted: RealPrivilege[] = [];
|
||||||
|
for (let serviceKey in privilegies) {
|
||||||
|
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||||
|
extracted = extracted.concat(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, ...exampleCartValues.privileges]);
|
||||||
|
}, [privilegies]);
|
||||||
|
|
||||||
|
const requestPrivilegies = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
await axios
|
||||||
|
.get<SeverPrivilegiesResponse>(
|
||||||
|
"https://admin.pena.digital/strator/privilege/service"
|
||||||
|
)
|
||||||
|
.then(({ data }) => setPrivilegies(data.templategen))
|
||||||
|
.catch(() => {
|
||||||
|
setIsError(true);
|
||||||
|
setErrorMessage("Ошибка при получении привилегий");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
requestPrivilegies,
|
||||||
|
isError,
|
||||||
|
isLoading,
|
||||||
|
errorMessage,
|
||||||
|
};
|
||||||
|
};
|
@ -1,40 +0,0 @@
|
|||||||
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};
|
|
||||||
};
|
|
@ -4,9 +4,8 @@ import { authStore } from "@root/stores/auth";
|
|||||||
import { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
import { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
||||||
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
||||||
|
|
||||||
|
|
||||||
type UseGetTariffs = {
|
type UseGetTariffs = {
|
||||||
requestTariffs: (page?: number, limit?: number) => Promise<void>;
|
requestTariffs: (page?: number, tariffs?: Tariff_BACKEND[]) => Promise<void>;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -15,15 +14,37 @@ type GetTariffsResponse = {
|
|||||||
tariffs: Tariff_BACKEND[];
|
tariffs: Tariff_BACKEND[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetTariffs = (): UseGetTariffs => {
|
export const useTariffs = (): UseGetTariffs => {
|
||||||
const token = authStore((state) => state.token);
|
const token = authStore((state) => state.token);
|
||||||
const [allTariffs, setAllTariffs] = useState<Record<string, Tariff>>({});
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [tariffs, setTariffs] = useState<Tariff_BACKEND[]>([]);
|
||||||
|
|
||||||
let newSt:Record<string, Tariff>
|
useEffect(() => {
|
||||||
|
const convertedTariffs: Record<string, Tariff> = {};
|
||||||
|
|
||||||
|
tariffs
|
||||||
|
.filter(({ isDeleted }) => !isDeleted)
|
||||||
|
.forEach((tariff) => {
|
||||||
|
convertedTariffs[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,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
const requestTariffs = async (page: number = 1): Promise<void> => {
|
resetTariffsStore(convertedTariffs);
|
||||||
|
}, [tariffs]);
|
||||||
|
|
||||||
|
const requestTariffs = async (
|
||||||
|
page: number = 1,
|
||||||
|
existingTariffs: Tariff_BACKEND[] = []
|
||||||
|
): Promise<void> => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -35,48 +56,17 @@ export const useGetTariffs = (): UseGetTariffs => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// 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) {
|
if (page < data.totalPages) {
|
||||||
return requestTariffs(page + 1);
|
return requestTariffs(page + 1, [...existingTariffs, ...data.tariffs]);
|
||||||
}
|
}
|
||||||
resetTariffsStore(newSt)
|
|
||||||
setIsLoading(false);
|
|
||||||
} catch {
|
|
||||||
setIsLoading(false);
|
|
||||||
|
|
||||||
|
setTariffs([...existingTariffs, ...data.tariffs]);
|
||||||
|
} catch {
|
||||||
throw new Error("Ошибка при получении тарифов");
|
throw new Error("Ошибка при получении тарифов");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
return { requestTariffs, isLoading };
|
return { requestTariffs, isLoading };
|
||||||
};
|
};
|
@ -15,10 +15,15 @@ import {
|
|||||||
FormControlLabel,
|
FormControlLabel,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Input from "@kitUI/input";
|
import Input from "@kitUI/input";
|
||||||
import { useEffect, useState } from "react";
|
import { useState } from "react";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
|
|
||||||
import { calcCartData, createCartItem, findDiscountFactor, formatDiscountFactor } from "./calc";
|
import {
|
||||||
|
calcCartData,
|
||||||
|
createCartItem,
|
||||||
|
findDiscountFactor,
|
||||||
|
formatDiscountFactor,
|
||||||
|
} from "./calc";
|
||||||
|
|
||||||
import { AnyDiscount, CartItemTotal } from "@root/model/cart";
|
import { AnyDiscount, CartItemTotal } from "@root/model/cart";
|
||||||
import { Privilege } from "@root/model/tariff";
|
import { Privilege } from "@root/model/tariff";
|
||||||
@ -29,10 +34,11 @@ import { findPrivilegeById } from "@root/stores/privilegesStore";
|
|||||||
import { testUser } from "@root/stores/mocks/user";
|
import { testUser } from "@root/stores/mocks/user";
|
||||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||||
import { Discount } from "@root/model/discount";
|
import { Discount } from "@root/model/discount";
|
||||||
import useDiscounts from "@root/utils/hooks/useDiscounts";
|
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
requestPrivilegies: () => Promise<void>;
|
||||||
|
requestDiscounts: () => Promise<() => void>;
|
||||||
selectedTariffs: GridSelectionModel;
|
selectedTariffs: GridSelectionModel;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,49 +58,63 @@ interface MergedTariff {
|
|||||||
isFront: boolean;
|
isFront: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Cart({ selectedTariffs }: Props) {
|
export default function Cart({
|
||||||
let cartTariffs = Object.values(useTariffStore().tariffs)
|
requestPrivilegies,
|
||||||
// useDiscounts({ onNewDiscounts: setDiscounts });
|
requestDiscounts,
|
||||||
|
selectedTariffs,
|
||||||
|
}: Props) {
|
||||||
|
let cartTariffs = Object.values(useTariffStore().tariffs);
|
||||||
// const discounts = useDiscountStore((store) => store.discounts);
|
// const discounts = useDiscountStore((store) => store.discounts);
|
||||||
const [discounts, setDiscounts] = useState<Discount[]>([]);
|
const [discounts, setDiscounts] = useState<Discount[]>([]);
|
||||||
const cartTotal = useCartStore((state) => state.cartTotal);
|
const cartTotal = useCartStore((state) => state.cartTotal);
|
||||||
const setCartTotal = useCartStore((store) => store.setCartTotal);
|
const setCartTotal = useCartStore((store) => store.setCartTotal);
|
||||||
const [couponField, setCouponField] = useState<string>("");
|
const [couponField, setCouponField] = useState<string>("");
|
||||||
const [loyaltyField, setLoyaltyField] = useState<string>("");
|
const [loyaltyField, setLoyaltyField] = useState<string>("");
|
||||||
const makeRequest = authStore.getState().makeRequest;
|
const makeRequest = authStore.getState().makeRequest;
|
||||||
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);
|
||||||
console.log(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);
|
||||||
|
|
||||||
const service = privilege?.serviceKey;
|
const service = privilege?.serviceKey;
|
||||||
const serviceDiscount = service ? cartTotal.discountsByService[privilege?.serviceKey] : null;
|
const serviceDiscount = service
|
||||||
|
? cartTotal.discountsByService[privilege?.serviceKey]
|
||||||
|
: null;
|
||||||
|
|
||||||
console.log(cartTotal.discountsByService)
|
console.log(cartTotal.discountsByService);
|
||||||
console.log(serviceDiscount)
|
console.log(serviceDiscount);
|
||||||
console.log(cartItemTotal)
|
console.log(cartItemTotal);
|
||||||
|
|
||||||
const envolvedDiscountsElement = (
|
const envolvedDiscountsElement = (
|
||||||
<Box>
|
<Box>
|
||||||
{cartItemTotal.envolvedDiscounts.map((discount, index, arr) => (
|
{cartItemTotal.envolvedDiscounts.map((discount, index, arr) => (
|
||||||
<span key={discount.ID}>
|
<span key={discount.ID}>
|
||||||
<DiscountTooltip discount={discount} cartItemTotal={cartItemTotal} />
|
<DiscountTooltip
|
||||||
{index < arr.length - (serviceDiscount ? 0 : 1) && <span>, </span>}
|
discount={discount}
|
||||||
|
cartItemTotal={cartItemTotal}
|
||||||
|
/>
|
||||||
|
{index < arr.length - (serviceDiscount ? 0 : 1) && (
|
||||||
|
<span>, </span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{serviceDiscount && (
|
{serviceDiscount && (
|
||||||
<span>
|
<span>
|
||||||
<DiscountTooltip discount={serviceDiscount} cartItemTotal={cartItemTotal} />
|
<DiscountTooltip
|
||||||
|
discount={serviceDiscount}
|
||||||
|
cartItemTotal={cartItemTotal}
|
||||||
|
/>
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalIncludingServiceDiscount = cartItemTotal.totalPrice * (serviceDiscount?.Target.Factor || 1);
|
const totalIncludingServiceDiscount =
|
||||||
console.log(cartItemTotal.totalPrice)
|
cartItemTotal.totalPrice * (serviceDiscount?.Target.Factor || 1);
|
||||||
console.log(serviceDiscount?.Target.Factor)
|
console.log(cartItemTotal.totalPrice);
|
||||||
console.log(serviceDiscount)
|
console.log(serviceDiscount?.Target.Factor);
|
||||||
|
console.log(serviceDiscount);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: cartItemTotal.tariff.id,
|
id: cartItemTotal.tariff.id,
|
||||||
@ -109,7 +129,10 @@ console.log(cartTotal)
|
|||||||
const cartDiscountsResultFactor =
|
const cartDiscountsResultFactor =
|
||||||
cartDiscounts &&
|
cartDiscounts &&
|
||||||
cartDiscounts?.length > 1 &&
|
cartDiscounts?.length > 1 &&
|
||||||
cartDiscounts.reduce((acc, discount) => acc * findDiscountFactor(discount), 1);
|
cartDiscounts.reduce(
|
||||||
|
(acc, discount) => acc * findDiscountFactor(discount),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
|
||||||
const envolvedCartDiscountsElement = cartDiscounts && (
|
const envolvedCartDiscountsElement = cartDiscounts && (
|
||||||
<Box
|
<Box
|
||||||
@ -125,31 +148,39 @@ console.log(cartTotal)
|
|||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{cartDiscountsResultFactor && `= ${formatDiscountFactor(cartDiscountsResultFactor)}`}
|
{cartDiscountsResultFactor &&
|
||||||
|
`= ${formatDiscountFactor(cartDiscountsResultFactor)}`}
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|
||||||
async function handleCalcCartClick() {
|
async function handleCalcCartClick() {
|
||||||
|
await requestPrivilegies();
|
||||||
|
await requestDiscounts();
|
||||||
|
|
||||||
//рассчитать
|
//рассчитать
|
||||||
const dis = await makeRequest<unknown>({
|
const dis = await makeRequest<unknown>({
|
||||||
url: "https://admin.pena.digital/price/discounts",
|
url: "https://admin.pena.digital/price/discounts",
|
||||||
method: "get",
|
method: "get",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
bearer: true,
|
||||||
})
|
});
|
||||||
console.log(dis)
|
console.log(dis);
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
setDiscounts(dis.Discounts)
|
setDiscounts(dis.Discounts);
|
||||||
|
|
||||||
const cartItems = cartTariffs.filter((tariff) => selectedTariffs.includes(tariff.id)).map((tariff) => createCartItem(tariff));
|
const cartItems = cartTariffs
|
||||||
|
.filter((tariff) => selectedTariffs.includes(tariff.id))
|
||||||
|
.map((tariff) => createCartItem(tariff));
|
||||||
|
|
||||||
console.log(cartItems)
|
console.log(cartItems);
|
||||||
|
|
||||||
let loyaltyValue = parseInt(loyaltyField);
|
let loyaltyValue = parseInt(loyaltyField);
|
||||||
|
|
||||||
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
||||||
|
|
||||||
const activeDiscounts = discounts.filter((discount) => !discount.Deprecated);
|
const activeDiscounts = discounts.filter(
|
||||||
|
(discount) => !discount.Deprecated
|
||||||
|
);
|
||||||
|
|
||||||
const cartData = calcCartData({
|
const cartData = calcCartData({
|
||||||
user: testUser,
|
user: testUser,
|
||||||
@ -293,22 +324,34 @@ console.log(cartTotal)
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
|
<Typography
|
||||||
|
variant="h4"
|
||||||
|
sx={{ color: theme.palette.secondary.main }}
|
||||||
|
>
|
||||||
Имя
|
Имя
|
||||||
</Typography>
|
</Typography>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
|
<Typography
|
||||||
|
variant="h4"
|
||||||
|
sx={{ color: theme.palette.secondary.main }}
|
||||||
|
>
|
||||||
Описание
|
Описание
|
||||||
</Typography>
|
</Typography>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
|
<Typography
|
||||||
|
variant="h4"
|
||||||
|
sx={{ color: theme.palette.secondary.main }}
|
||||||
|
>
|
||||||
Скидки
|
Скидки
|
||||||
</Typography>
|
</Typography>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
|
<Typography
|
||||||
|
variant="h4"
|
||||||
|
sx={{ color: theme.palette.secondary.main }}
|
||||||
|
>
|
||||||
стоимость
|
стоимость
|
||||||
</Typography>
|
</Typography>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
@ -349,7 +392,7 @@ console.log(cartTotal)
|
|||||||
color: theme.palette.secondary.main,
|
color: theme.palette.secondary.main,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{(row.price/100).toFixed(2)} ₽
|
{(row.price / 100).toFixed(2)} ₽
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
@ -378,7 +421,7 @@ console.log(cartTotal)
|
|||||||
marginTop: "10px",
|
marginTop: "10px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
ИТОГО: <span>{(cartTotal?.totalPrice/100).toFixed(2)} ₽</span>
|
ИТОГО: <span>{(cartTotal?.totalPrice / 100).toFixed(2)} ₽</span>
|
||||||
</Typography>
|
</Typography>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@ -392,10 +435,16 @@ console.log(cartTotal)
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DiscountTooltip({ discount, cartItemTotal }: { discount: Discount; cartItemTotal?: CartItemTotal }) {
|
function DiscountTooltip({
|
||||||
|
discount,
|
||||||
|
cartItemTotal,
|
||||||
|
}: {
|
||||||
|
discount: Discount;
|
||||||
|
cartItemTotal?: CartItemTotal;
|
||||||
|
}) {
|
||||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
||||||
|
|
||||||
return discountText ?
|
return discountText ? (
|
||||||
<Tooltip
|
<Tooltip
|
||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
@ -406,6 +455,7 @@ function DiscountTooltip({ discount, cartItemTotal }: { discount: Discount; cart
|
|||||||
>
|
>
|
||||||
<span>{discountText}</span>
|
<span>{discountText}</span>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
:
|
) : (
|
||||||
<span>Ошибка поиска значения скидки</span>
|
<span>Ошибка поиска значения скидки</span>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,169 +1,200 @@
|
|||||||
import { Box, IconButton, useTheme } from "@mui/material";
|
import { useEffect } from "react";
|
||||||
import { DataGrid, GridColDef, GridRowsProp, GridToolbar } from "@mui/x-data-grid";
|
import { Box, IconButton, useTheme, Tooltip } from "@mui/material";
|
||||||
|
import {
|
||||||
|
DataGrid,
|
||||||
|
GridColDef,
|
||||||
|
GridRowsProp,
|
||||||
|
GridToolbar,
|
||||||
|
} from "@mui/x-data-grid";
|
||||||
import { formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
import { formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
||||||
import { openEditDiscountDialog, setDiscounts, setSelectedDiscountIds, updateDiscount, useDiscountStore } from "@root/stores/discounts";
|
import {
|
||||||
import useDiscounts from "@root/utils/hooks/useDiscounts";
|
openEditDiscountDialog,
|
||||||
import DeleteIcon from '@mui/icons-material/Delete';
|
setSelectedDiscountIds,
|
||||||
import EditIcon from '@mui/icons-material/Edit';
|
updateDiscount,
|
||||||
|
useDiscountStore,
|
||||||
|
} from "@root/stores/discounts";
|
||||||
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
|
import EditIcon from "@mui/icons-material/Edit";
|
||||||
import { deleteDiscount } from "@root/api/discounts";
|
import { deleteDiscount } from "@root/api/discounts";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
|
import { useDiscounts } from "@root/hooks/useDiscounts.hook";
|
||||||
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
// {
|
// {
|
||||||
// field: "id",
|
// field: "id",
|
||||||
// headerName: "ID",
|
// headerName: "ID",
|
||||||
// width: 70,
|
// width: 70,
|
||||||
// sortable: false,
|
// sortable: false,
|
||||||
// },
|
// },
|
||||||
{
|
{
|
||||||
field: "name",
|
field: "name",
|
||||||
headerName: "Название скидки",
|
headerName: "Название скидки",
|
||||||
width: 150,
|
width: 150,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
renderCell: ({ row, value }) => (
|
renderCell: ({ row, value }) => (
|
||||||
<Box color={row.deleted && "#ff4545"}>{value}</Box>
|
<Box color={row.deleted && "#ff4545"}>{value}</Box>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "description",
|
field: "description",
|
||||||
headerName: "Описание",
|
headerName: "Описание",
|
||||||
width: 120,
|
width: 120,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "conditionType",
|
field: "conditionType",
|
||||||
headerName: "Тип условия",
|
headerName: "Тип условия",
|
||||||
width: 120,
|
width: 120,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "factor",
|
field: "factor",
|
||||||
headerName: "Процент скидки",
|
headerName: "Процент скидки",
|
||||||
width: 120,
|
width: 120,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "value",
|
field: "value",
|
||||||
headerName: "Значение",
|
headerName: "Значение",
|
||||||
width: 120,
|
width: 120,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "active",
|
field: "active",
|
||||||
headerName: "Активна",
|
headerName: "Активна",
|
||||||
width: 80,
|
width: 80,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
field: "edit",
|
field: "edit",
|
||||||
headerName: "Изменить",
|
headerName: "Изменить",
|
||||||
width: 80,
|
width: 80,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
renderCell: ({ row }) => {
|
renderCell: ({ row }) => {
|
||||||
return (
|
return (
|
||||||
<IconButton
|
<IconButton
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
openEditDiscountDialog(row.id);
|
openEditDiscountDialog(row.id);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<EditIcon />
|
<EditIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
);
|
);
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
field: "delete",
|
|
||||||
headerName: "Удалить",
|
|
||||||
width: 80,
|
|
||||||
sortable: false,
|
|
||||||
renderCell: ({ row }) => (
|
|
||||||
<IconButton
|
|
||||||
disabled={row.deleted}
|
|
||||||
onClick={() => {
|
|
||||||
deleteDiscount(row.id).then(updateDiscount);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DeleteIcon />
|
|
||||||
</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 = ["", "Товар", "Сервис", "корзина", "лояльность"];
|
||||||
"",
|
|
||||||
"Товар",
|
|
||||||
"Сервис",
|
|
||||||
"корзина",
|
|
||||||
"лояльность",
|
|
||||||
];
|
|
||||||
const layerValue = [
|
const layerValue = [
|
||||||
"",
|
"",
|
||||||
"Term",
|
"Term",
|
||||||
"PriceFrom",
|
"PriceFrom",
|
||||||
"CartPurchasesAmount",
|
"CartPurchasesAmount",
|
||||||
"PurchasesAmount",
|
"PurchasesAmount",
|
||||||
];
|
];
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedRowsHC: (array:GridSelectionModel) => void
|
selectedRowsHC: (array: GridSelectionModel) => void;
|
||||||
}
|
}
|
||||||
export default function DiscountDataGrid({selectedRowsHC}:Props) {
|
export default function DiscountDataGrid({ selectedRowsHC }: Props) {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const selectedDiscountIds = useDiscountStore((state) => state.selectedDiscountIds);
|
const selectedDiscountIds = useDiscountStore(
|
||||||
const realDiscounts = useDiscountStore(state => state.discounts);
|
(state) => state.selectedDiscountIds
|
||||||
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
);
|
||||||
|
const realDiscounts = useDiscountStore((state) => state.discounts);
|
||||||
|
const editDiscountId = useDiscountStore((state) => state.editDiscountId);
|
||||||
|
const { requestDiscounts } = useDiscounts();
|
||||||
|
|
||||||
useDiscounts({ onNewDiscounts: setDiscounts });
|
useEffect(() => {
|
||||||
|
requestDiscounts();
|
||||||
|
}, []);
|
||||||
|
|
||||||
const rowBackDicounts: GridRowsProp = realDiscounts.filter(e => e.Layer > 0).map(discount => {
|
const rowBackDicounts: GridRowsProp = realDiscounts
|
||||||
console.log(discount.Condition[layerValue[discount.Layer] as keyof typeof discount.Condition])
|
.filter((e) => e.Layer > 0)
|
||||||
return({
|
.map((discount) => {
|
||||||
|
console.log(
|
||||||
|
discount.Condition[
|
||||||
|
layerValue[discount.Layer] as keyof typeof discount.Condition
|
||||||
|
]
|
||||||
|
);
|
||||||
|
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: formatDiscountFactor(discount.Target.Factor),
|
factor: formatDiscountFactor(discount.Target.Factor),
|
||||||
value: discount.Condition[layerValue[discount.Layer] as keyof typeof discount.Condition],
|
value:
|
||||||
|
discount.Condition[
|
||||||
|
layerValue[discount.Layer] as keyof typeof discount.Condition
|
||||||
|
],
|
||||||
active: discount.Deprecated ? "🚫" : "✅",
|
active: discount.Deprecated ? "🚫" : "✅",
|
||||||
deleted: discount.Audit.Deleted,
|
deleted: discount.Audit.Deleted,
|
||||||
})});
|
};
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
|
<Box
|
||||||
<Box sx={{ height: 600 }}>
|
sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}
|
||||||
<DataGrid
|
>
|
||||||
checkboxSelection={true}
|
<Tooltip title="обновить список привилегий">
|
||||||
rows={rowBackDicounts}
|
<IconButton
|
||||||
columns={columns}
|
onClick={requestDiscounts}
|
||||||
selectionModel={selectedDiscountIds}
|
style={{ display: "block", margin: "0 auto" }}
|
||||||
onSelectionModelChange={(array:GridSelectionModel) => {
|
>
|
||||||
selectedRowsHC(array)
|
<AutorenewIcon sx={{ color: "white" }} />
|
||||||
setSelectedDiscountIds(array)
|
</IconButton>
|
||||||
}}
|
</Tooltip>
|
||||||
disableSelectionOnClick
|
<Box sx={{ height: 600 }}>
|
||||||
sx={{
|
<DataGrid
|
||||||
color: theme.palette.secondary.main,
|
checkboxSelection={true}
|
||||||
"& .MuiDataGrid-iconSeparator": {
|
rows={rowBackDicounts}
|
||||||
display: "none",
|
columns={columns}
|
||||||
},
|
selectionModel={selectedDiscountIds}
|
||||||
"& .css-levciy-MuiTablePagination-displayedRows": {
|
onSelectionModelChange={(array: GridSelectionModel) => {
|
||||||
color: theme.palette.secondary.main,
|
selectedRowsHC(array);
|
||||||
},
|
setSelectedDiscountIds(array);
|
||||||
"& .MuiSvgIcon-root": {
|
}}
|
||||||
color: theme.palette.secondary.main,
|
disableSelectionOnClick
|
||||||
},
|
sx={{
|
||||||
"& .MuiTablePagination-selectLabel": {
|
color: theme.palette.secondary.main,
|
||||||
color: theme.palette.secondary.main,
|
"& .MuiDataGrid-iconSeparator": {
|
||||||
},
|
display: "none",
|
||||||
"& .MuiInputBase-root": {
|
},
|
||||||
color: theme.palette.secondary.main,
|
"& .css-levciy-MuiTablePagination-displayedRows": {
|
||||||
},
|
color: theme.palette.secondary.main,
|
||||||
"& .MuiButton-text": {
|
},
|
||||||
color: theme.palette.secondary.main,
|
"& .MuiSvgIcon-root": {
|
||||||
},
|
color: theme.palette.secondary.main,
|
||||||
}}
|
},
|
||||||
components={{ Toolbar: GridToolbar }}
|
"& .MuiTablePagination-selectLabel": {
|
||||||
/>
|
color: theme.palette.secondary.main,
|
||||||
</Box>
|
},
|
||||||
</Box>
|
"& .MuiInputBase-root": {
|
||||||
);
|
color: theme.palette.secondary.main,
|
||||||
|
},
|
||||||
|
"& .MuiButton-text": {
|
||||||
|
color: theme.palette.secondary.main,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
components={{ Toolbar: GridToolbar }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,56 +1,63 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Typography, Container, Button, Select, MenuItem, FormControl, InputLabel, useTheme, Box } from "@mui/material";
|
import {
|
||||||
|
Typography,
|
||||||
|
Container,
|
||||||
|
Button,
|
||||||
|
Select,
|
||||||
|
MenuItem,
|
||||||
|
FormControl,
|
||||||
|
InputLabel,
|
||||||
|
useTheme,
|
||||||
|
Box,
|
||||||
|
} from "@mui/material";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
|
||||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
|
|
||||||
import { Tariff } from "@root/model/tariff";
|
|
||||||
|
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import { findPrivilegeById, usePrivilegeStore } from "@root/stores/privilegesStore";
|
import {
|
||||||
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
findPrivilegeById,
|
||||||
|
usePrivilegeStore,
|
||||||
|
} from "@root/stores/privilegesStore";
|
||||||
|
|
||||||
interface Props {
|
type CreateTariffProps = {
|
||||||
getTariffs: () => void
|
requestTariffs: () => Promise<void>;
|
||||||
}
|
};
|
||||||
|
|
||||||
export default function CreateTariff() {
|
|
||||||
|
|
||||||
|
export default function CreateTariff({ requestTariffs }: CreateTariffProps) {
|
||||||
const { token } = authStore();
|
const { token } = authStore();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const privileges = usePrivilegeStore( store => store.privileges);
|
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 privilege = findPrivilegeById(privilegeIdField)
|
const privilege = findPrivilegeById(privilegeIdField);
|
||||||
|
|
||||||
const { requestTariffs } = useGetTariffs()
|
|
||||||
|
|
||||||
const checkFulledFields = () => {
|
const checkFulledFields = () => {
|
||||||
if (nameField.length === 0) {
|
if (nameField.length === 0) {
|
||||||
enqueueSnackbar("Пустое название тарифа");
|
enqueueSnackbar("Пустое название тарифа");
|
||||||
return false
|
return false;
|
||||||
}
|
}
|
||||||
if (amountField.length === 0) {
|
if (amountField.length === 0) {
|
||||||
enqueueSnackbar("Пустое кол-во едениц привилегии");
|
enqueueSnackbar("Пустое кол-во едениц привилегии");
|
||||||
return false
|
return false;
|
||||||
}
|
}
|
||||||
if (privilegeIdField.length === 0) {
|
if (privilegeIdField.length === 0) {
|
||||||
enqueueSnackbar("Не выбрана привилегия");
|
enqueueSnackbar("Не выбрана привилегия");
|
||||||
return false
|
return false;
|
||||||
}
|
}
|
||||||
if (!privilege) {
|
if (!privilege) {
|
||||||
enqueueSnackbar("Привилегия с таким id не найдена");
|
enqueueSnackbar("Привилегия с таким id не найдена");
|
||||||
return false
|
return false;
|
||||||
}
|
}
|
||||||
return true
|
return true;
|
||||||
}
|
};
|
||||||
|
|
||||||
const createTariffBackend = () => {
|
const createTariffBackend = () => {
|
||||||
if (checkFulledFields() && privilege !== null) {
|
if (checkFulledFields() && privilege !== null) {
|
||||||
@ -78,14 +85,14 @@ export default function CreateTariff() {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
requestTariffs()
|
requestTariffs();
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
enqueueSnackbar("что-то пошло не так")
|
enqueueSnackbar("что-то пошло не так");
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
// const createTariffFrontend = () => {
|
// const createTariffFrontend = () => {
|
||||||
// if (checkFulledFields() && privilege !== null) {
|
// if (checkFulledFields() && privilege !== null) {
|
||||||
// updateTariffStore({
|
// updateTariffStore({
|
||||||
@ -137,30 +144,30 @@ export default function CreateTariff() {
|
|||||||
Привилегия
|
Привилегия
|
||||||
</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,
|
||||||
|
borderColor: theme.palette.secondary.main,
|
||||||
|
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
||||||
borderColor: theme.palette.secondary.main,
|
borderColor: theme.palette.secondary.main,
|
||||||
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
|
border: "1px solid",
|
||||||
borderColor: theme.palette.secondary.main,
|
},
|
||||||
border: "1px solid",
|
".MuiSvgIcon-root ": {
|
||||||
},
|
fill: theme.palette.secondary.main,
|
||||||
".MuiSvgIcon-root ": {
|
},
|
||||||
fill: theme.palette.secondary.main,
|
}}
|
||||||
},
|
inputProps={{ sx: { pt: "12px" } }}
|
||||||
}}
|
>
|
||||||
inputProps={{ sx: { pt: "12px" } }}
|
{privileges.map((privilege) => (
|
||||||
>
|
<MenuItem key={privilege.description} value={privilege.id}>
|
||||||
{privileges.map((privilege) => (
|
{privilege.description}
|
||||||
<MenuItem key={privilege.description} value={privilege.id}>
|
</MenuItem>
|
||||||
{privilege.description}
|
))}
|
||||||
</MenuItem>
|
</Select>
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
</FormControl>
|
||||||
{privilege && (
|
{privilege && (
|
||||||
<Box
|
<Box
|
||||||
@ -205,7 +212,7 @@ export default function CreateTariff() {
|
|||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
createTariffBackend()
|
createTariffBackend();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Создать
|
Создать
|
||||||
|
@ -8,54 +8,53 @@ import { useTariffStore } from "@root/stores/tariffsStore";
|
|||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
|
||||||
|
|
||||||
type DeleteModalProps = {
|
type DeleteModalProps = {
|
||||||
open: boolean | string;
|
open: boolean | string;
|
||||||
handleClose: () => void;
|
handleClose: () => void;
|
||||||
selectedTariffs: any;
|
selectedTariffs: any;
|
||||||
|
requestTariffs: () => Promise<void>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function DeleteModal({
|
export default function DeleteModal({
|
||||||
open,
|
open,
|
||||||
handleClose,
|
handleClose,
|
||||||
selectedTariffs
|
selectedTariffs,
|
||||||
|
requestTariffs,
|
||||||
}: DeleteModalProps) {
|
}: DeleteModalProps) {
|
||||||
const { requestTariffs } = useGetTariffs()
|
|
||||||
const { token } = authStore();
|
const { token } = authStore();
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
|
|
||||||
const deleteTariff = async (id: string): Promise<void> => {
|
const deleteTariff = async (id: string): Promise<void> => {
|
||||||
const currentTariff = tariffs[id]
|
const currentTariff = tariffs[id];
|
||||||
|
|
||||||
if (!currentTariff) {
|
if (!currentTariff) {
|
||||||
enqueueSnackbar("Тариф не найден");
|
enqueueSnackbar("Тариф не найден");
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await axios.delete("https://admin.pena.digital/strator/tariff/", {
|
await axios.delete("https://admin.pena.digital/strator/tariff/", {
|
||||||
data: { id },
|
data: { id },
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
|
enqueueSnackbar("Ошибка при удалении тарифа на бэкэнде");
|
||||||
enqueueSnackbar("Ошибка при удалении тарифа на бэкэнде");
|
}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const onClickTariffDelete = () => {
|
const onClickTariffDelete = () => {
|
||||||
if (typeof open === 'string' ) {
|
if (typeof open === "string") {
|
||||||
deleteTariff(open)
|
deleteTariff(open);
|
||||||
requestTariffs()
|
requestTariffs();
|
||||||
handleClose();
|
handleClose();
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
selectedTariffs.forEach((id:string) => {
|
selectedTariffs.forEach((id: string) => {
|
||||||
deleteTariff(id)
|
deleteTariff(id);
|
||||||
})
|
});
|
||||||
handleClose();
|
handleClose();
|
||||||
requestTariffs()
|
requestTariffs();
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@ -80,12 +79,22 @@ 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' ? "тариф" : "тарифы"} ?
|
Вы уверены, что хотите удалить{" "}
|
||||||
|
{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",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Button onClick={() => onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}>
|
<Button
|
||||||
|
onClick={() => onClickTariffDelete()}
|
||||||
|
sx={{ width: "40px", height: "25px" }}
|
||||||
|
>
|
||||||
Да
|
Да
|
||||||
</Button>
|
</Button>
|
||||||
{/* <Typography>Тариф:</Typography>
|
{/* <Typography>Тариф:</Typography>
|
@ -9,28 +9,24 @@ import axios from "axios";
|
|||||||
import { authStore } from "@root/stores/auth";
|
import { authStore } from "@root/stores/auth";
|
||||||
import { Privilege, Tariff } from "@root/model/tariff";
|
import { Privilege, Tariff } from "@root/model/tariff";
|
||||||
import { useTariffStore, updateTariff } from "@root/stores/tariffsStore";
|
import { useTariffStore, updateTariff } from "@root/stores/tariffsStore";
|
||||||
import { arrayBuffer } from "stream/consumers";
|
|
||||||
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
|
||||||
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
|
||||||
|
|
||||||
interface EditProps {
|
interface EditProps {
|
||||||
tarifIid: string,
|
tarifIid: string;
|
||||||
tariffName: string,
|
tariffName: string;
|
||||||
tariffPrice: number,
|
tariffPrice: number;
|
||||||
privilege: Privilege,
|
privilege: Privilege;
|
||||||
token: string
|
token: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const editTariff = ({
|
const editTariff = ({
|
||||||
tarifIid,
|
tarifIid,
|
||||||
tariffName,
|
tariffName,
|
||||||
tariffPrice,
|
tariffPrice,
|
||||||
privilege,
|
privilege,
|
||||||
token
|
token,
|
||||||
}:EditProps): Promise<unknown> => {
|
}: EditProps): Promise<unknown> => {
|
||||||
return axios({
|
return axios({
|
||||||
method: "put",
|
method: "put",
|
||||||
url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
|
url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
|
||||||
@ -41,120 +37,142 @@ const editTariff = ({
|
|||||||
name: tariffName,
|
name: tariffName,
|
||||||
price: tariffPrice,
|
price: tariffPrice,
|
||||||
isCustom: false,
|
isCustom: false,
|
||||||
privilegies: [privilege]
|
privilegies: [privilege],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
interface Props {
|
interface Props {
|
||||||
tariff: Tariff
|
tariff: Tariff;
|
||||||
|
requestTariffs: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function EditModal({tariff = undefined}:Props) {
|
export default function EditModal({
|
||||||
|
tariff = undefined,
|
||||||
|
requestTariffs,
|
||||||
|
}: 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 tariffs = useTariffStore((state) => state.tariffs);
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
const currentTariff = tariff ? tariffs[tariff.id] : undefined
|
const currentTariff = tariff ? tariffs[tariff.id] : undefined;
|
||||||
const { requestTariffs } = useGetTariffs()
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setOpen(tariff !== undefined)
|
setOpen(tariff !== undefined);
|
||||||
}, [tariff])
|
}, [tariff]);
|
||||||
|
|
||||||
return <Modal
|
return (
|
||||||
open={open}
|
<Modal
|
||||||
onClose={() => setOpen(false)}
|
open={open}
|
||||||
aria-labelledby="modal-modal-title"
|
onClose={() => setOpen(false)}
|
||||||
aria-describedby="modal-modal-description"
|
aria-labelledby="modal-modal-title"
|
||||||
|
aria-describedby="modal-modal-description"
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
top: "50%",
|
||||||
|
left: "50%",
|
||||||
|
transform: "translate(-50%, -50%)",
|
||||||
|
width: 400,
|
||||||
|
bgcolor: "background.paper",
|
||||||
|
border: "2px solid gray",
|
||||||
|
borderRadius: "6px",
|
||||||
|
boxShadow: 24,
|
||||||
|
p: 4,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Box
|
<Typography
|
||||||
sx={{
|
id="modal-modal-title"
|
||||||
position: "absolute",
|
variant="h6"
|
||||||
top: "50%",
|
component="h2"
|
||||||
left: "50%",
|
sx={{ whiteSpace: "nowrap" }}
|
||||||
transform: "translate(-50%, -50%)",
|
|
||||||
width: 400,
|
|
||||||
bgcolor: "background.paper",
|
|
||||||
border: "2px solid gray",
|
|
||||||
borderRadius: "6px",
|
|
||||||
boxShadow: 24,
|
|
||||||
p: 4,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Typography id="modal-modal-title" variant="h6" component="h2" sx={{ whiteSpace: "nowrap" }}>
|
Редактирование тариффа
|
||||||
Редактирование тариффа
|
</Typography>
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{currentTariff !== undefined && (
|
{currentTariff !== undefined && (
|
||||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
||||||
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
||||||
<TextField
|
<TextField
|
||||||
onChange={(event) => setName(event.target.value)}
|
onChange={(event) => setName(event.target.value)}
|
||||||
label="Имя"
|
label="Имя"
|
||||||
name="name"
|
name="name"
|
||||||
value={name}
|
value={name}
|
||||||
sx={{ marginBottom: "10px" }}
|
sx={{ marginBottom: "10px" }}
|
||||||
/>
|
/>
|
||||||
<Typography>Цена за единицу: {currentTariff.pricePerUnit}</Typography>
|
<Typography>
|
||||||
<TextField
|
Цена за единицу: {currentTariff.pricePerUnit}
|
||||||
onChange={(event) => setPrice(event.target.value)}
|
</Typography>
|
||||||
label="Цена за единицу"
|
<TextField
|
||||||
name="price"
|
onChange={(event) => setPrice(event.target.value)}
|
||||||
value={price}
|
label="Цена за единицу"
|
||||||
sx={{ marginBottom: "10px" }}
|
name="price"
|
||||||
/>
|
value={price}
|
||||||
<Button onClick={() => {
|
sx={{ marginBottom: "10px" }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
if (!currentTariff.isFront) {
|
if (!currentTariff.isFront) {
|
||||||
const privilege = findPrivilegeById(currentTariff.privilegeId);
|
const privilege = findPrivilegeById(
|
||||||
privilege.privilegeId = privilege.id
|
currentTariff.privilegeId
|
||||||
console.log(privilege)
|
);
|
||||||
|
privilege.privilegeId = privilege.id;
|
||||||
//back
|
console.log(privilege);
|
||||||
if (privilege !== null) {
|
|
||||||
|
|
||||||
privilege.amount = tariff.amount
|
|
||||||
privilege.privilegeName = privilege.name
|
|
||||||
privilege.privilegeId = privilege.id
|
|
||||||
privilege.serviceName = privilege.serviceKey
|
|
||||||
console.log(privilege)
|
|
||||||
|
|
||||||
editTariff({
|
|
||||||
tarifIid: currentTariff.id,
|
|
||||||
tariffName: name ? name : currentTariff.name,
|
|
||||||
tariffPrice: price ? Number(price) : currentTariff.price ? currentTariff.price : privilege.price,
|
|
||||||
isDeleted: currentTariff.isDeleted,
|
|
||||||
customPricePerUnit: currentTariff.price,
|
|
||||||
privilege: privilege,
|
|
||||||
token: token
|
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
setOpen(false)
|
|
||||||
requestTariffs()
|
|
||||||
})} else {
|
|
||||||
enqueueSnackbar(`Привилегия с id ${currentTariff.privilegeId} не найдена в тарифе ${currentTariff.name} с id ${currentTariff.id}`)
|
|
||||||
}
|
|
||||||
} else {//front/store
|
|
||||||
|
|
||||||
let array = tariffs
|
//back
|
||||||
let index
|
if (privilege !== null) {
|
||||||
tariffs.forEach((p:any, i:number) => {
|
privilege.amount = tariff.amount;
|
||||||
if (currentTariff.id == p.id) index = i
|
privilege.privilegeName = privilege.name;
|
||||||
})
|
privilege.privilegeId = privilege.id;
|
||||||
if (index !== undefined) {
|
privilege.serviceName = privilege.serviceKey;
|
||||||
array[index].name = name
|
console.log(privilege);
|
||||||
array[index].amount = Number(price)
|
|
||||||
updateTariffs(array)
|
editTariff({
|
||||||
setOpen(false)
|
tarifIid: currentTariff.id,
|
||||||
|
tariffName: name ? name : currentTariff.name,
|
||||||
|
tariffPrice: price
|
||||||
|
? Number(price)
|
||||||
|
: currentTariff.price
|
||||||
|
? currentTariff.price
|
||||||
|
: privilege.price,
|
||||||
|
isDeleted: currentTariff.isDeleted,
|
||||||
|
customPricePerUnit: currentTariff.price,
|
||||||
|
privilege: privilege,
|
||||||
|
token: token,
|
||||||
|
}).then(() => {
|
||||||
|
setOpen(false);
|
||||||
|
requestTariffs();
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.log("не нашел такой тариф в сторе")
|
enqueueSnackbar(
|
||||||
|
`Привилегия с id ${currentTariff.privilegeId} не найдена в тарифе ${currentTariff.name} с id ${currentTariff.id}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
}
|
//front/store
|
||||||
}}>Редактировать</Button>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Modal>
|
|
||||||
|
|
||||||
|
let array = tariffs;
|
||||||
|
let index;
|
||||||
|
tariffs.forEach((p: any, i: number) => {
|
||||||
|
if (currentTariff.id == p.id) index = i;
|
||||||
|
});
|
||||||
|
if (index !== undefined) {
|
||||||
|
array[index].name = name;
|
||||||
|
array[index].amount = Number(price);
|
||||||
|
updateTariffs(array);
|
||||||
|
setOpen(false);
|
||||||
|
} else {
|
||||||
|
console.log("не нашел такой тариф в сторе");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Редактировать
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import { GridColDef } from "@mui/x-data-grid";
|
import { GridColDef } from "@mui/x-data-grid";
|
||||||
import DataGrid from "@kitUI/datagrid";
|
import DataGrid from "@kitUI/datagrid";
|
||||||
import { Typography } from "@mui/material";
|
import { Tooltip, IconButton } from "@mui/material";
|
||||||
import { useCombinedPrivileges } from "@root/hooks/useCombinedPrivileges.hook";
|
|
||||||
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||||
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
{ field: "id", headerName: "id", width: 150 },
|
{ field: "id", headerName: "id", width: 150 },
|
||||||
@ -12,25 +12,31 @@ const columns: GridColDef[] = [
|
|||||||
{ field: "price", headerName: "Стоимость", width: 100 },
|
{ field: "price", headerName: "Стоимость", width: 100 },
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function Privileges() {
|
type Props = {
|
||||||
|
requestPrivilegies: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Privileges({ requestPrivilegies }: Props) {
|
||||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||||
// const { mergedPrivileges } = useCombinedPrivileges();
|
// const { mergedPrivileges } = useCombinedPrivileges();
|
||||||
const privilegesGridData = privileges
|
const privilegesGridData = privileges
|
||||||
.filter(privilege => (
|
.filter((privilege) => !privilege.isDeleted)
|
||||||
!privilege.isDeleted
|
.map((privilege) => ({
|
||||||
))
|
id: privilege.privilegeId,
|
||||||
.map((privilege) => ({
|
name: privilege.name,
|
||||||
id: privilege.privilegeId,
|
description: privilege.description,
|
||||||
name: privilege.name,
|
type: privilege.type,
|
||||||
description: privilege.description,
|
price: privilege.price,
|
||||||
type: privilege.type,
|
}));
|
||||||
price: privilege.price,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DataGrid
|
<>
|
||||||
rows={privilegesGridData}
|
<Tooltip title="обновить список привилегий">
|
||||||
columns={columns}
|
<IconButton onClick={requestPrivilegies}>
|
||||||
/>
|
<AutorenewIcon sx={{ color: "white" }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
<DataGrid rows={privilegesGridData} columns={columns} />
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,53 +1,30 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Container, IconButton, Tooltip, Typography } from "@mui/material";
|
import { Container, Typography } from "@mui/material";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
|
|
||||||
import Cart from "@root/kitUI/Cart/Cart";
|
import Cart from "@root/kitUI/Cart/Cart";
|
||||||
|
|
||||||
import axios from "axios";
|
import { useTariffs } from "@root/hooks/useTariffs.hook";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { usePrivilegies } from "@root/hooks/usePrivilegies.hook";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { useDiscounts } from "@root/hooks/useDiscounts.hook";
|
||||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
|
||||||
import { usePrivilegeStore, resetPrivilegeArray } 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 Privileges from "./Privileges/Privileges";
|
||||||
import ChangePriceModal from "./Privileges/ChangePriceModal";
|
import ChangePriceModal from "./Privileges/ChangePriceModal";
|
||||||
import {useRefreshPrivilegesStore} from "@root/hooks/useRefreshPrivilegesStore.hook"
|
|
||||||
import { Tariff } from "@root/model/tariff";
|
|
||||||
import AutorenewIcon from '@mui/icons-material/Autorenew';
|
|
||||||
import { RealPrivilege } from "@root/model/privilege";
|
|
||||||
import { Discount, GetDiscountResponse } from "@root/model/discount";
|
|
||||||
|
|
||||||
export default function Tariffs() {
|
export default function Tariffs() {
|
||||||
const token = authStore((state) => state.token);
|
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>(
|
||||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
[]
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
);
|
||||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>([]);
|
const { requestTariffs } = useTariffs();
|
||||||
const refreshStores = async () => {
|
const { requestPrivilegies } = usePrivilegies();
|
||||||
const priv = await axios<RealPrivilege[]>({
|
const { requestDiscounts } = useDiscounts();
|
||||||
method: "get",
|
|
||||||
url: "https://admin.pena.digital/strator/privilege/service",
|
useEffect(() => {
|
||||||
});
|
requestTariffs();
|
||||||
let extracted:RealPrivilege[] = []
|
requestPrivilegies();
|
||||||
for (let serviceKey in priv.data) { //Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
}, []);
|
||||||
extracted = extracted.concat(priv.data[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)
|
|
||||||
enqueueSnackbar("привилегии обновлены")
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container
|
<Container
|
||||||
@ -59,29 +36,30 @@ export default function Tariffs() {
|
|||||||
alignItems: "center",
|
alignItems: "center",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|
||||||
|
|
||||||
<button onClick={() => console.log(privileges)}>provileges</button>
|
|
||||||
<button onClick={() => console.log(tariffs)}>tariffs</button>
|
|
||||||
|
|
||||||
<Typography variant="h6">Список привилегий</Typography>
|
<Typography variant="h6">Список привилегий</Typography>
|
||||||
|
|
||||||
<Tooltip title="обновить список привилегий"><IconButton onClick={refreshStores}><AutorenewIcon sx={{color:"white"}}/></IconButton></Tooltip>
|
<Privileges requestPrivilegies={requestPrivilegies} />
|
||||||
<Privileges />
|
|
||||||
|
|
||||||
<ChangePriceModal />
|
<ChangePriceModal />
|
||||||
|
|
||||||
<CreateTariff />
|
<CreateTariff requestTariffs={requestTariffs} />
|
||||||
|
|
||||||
<Typography variant="h6" mt="20px">
|
<Typography variant="h6" mt="20px">
|
||||||
Список тарифов
|
Список тарифов
|
||||||
</Typography>
|
</Typography>
|
||||||
<TariffsDG
|
<TariffsDG
|
||||||
selectedTariffs={selectedTariffs}
|
selectedTariffs={selectedTariffs}
|
||||||
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
|
handleSelectionChange={(selectionModel) =>
|
||||||
|
setSelectedTariffs(selectionModel)
|
||||||
|
}
|
||||||
|
requestTariffs={requestTariffs}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Cart selectedTariffs={selectedTariffs} />
|
<Cart
|
||||||
|
requestPrivilegies={requestPrivilegies}
|
||||||
|
requestDiscounts={requestDiscounts}
|
||||||
|
selectedTariffs={selectedTariffs}
|
||||||
|
/>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
|
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
|
||||||
import { Box, Button, IconButton } from "@mui/material";
|
import { Box, Button, IconButton,Tooltip } from "@mui/material";
|
||||||
import BackspaceIcon from "@mui/icons-material/Backspace";
|
import BackspaceIcon from "@mui/icons-material/Backspace";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||||
@ -15,28 +15,33 @@ 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/pages/dashboard/Content/Tariffs/DeleteModal";
|
||||||
import EditModal from "./EditModal";
|
import EditModal from "./EditModal";
|
||||||
import { Tariff } from "@root/model/tariff";
|
import { Tariff } from "@root/model/tariff";
|
||||||
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedTariffs: GridSelectionModel;
|
selectedTariffs: GridSelectionModel;
|
||||||
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
||||||
|
requestTariffs: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) {
|
export default function TariffsDG({
|
||||||
const tariffs = Object.values(useTariffStore().tariffs)
|
selectedTariffs,
|
||||||
|
handleSelectionChange,
|
||||||
|
requestTariffs,
|
||||||
|
}: Props) {
|
||||||
|
const tariffs = Object.values(useTariffStore().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 | undefined>();
|
const [changingTariff, setChangingTariff] = useState<Tariff | undefined>();
|
||||||
const [tariffDelete, setTariffDelete] = useState(false);
|
const [tariffDelete, setTariffDelete] = useState(false);
|
||||||
|
|
||||||
|
console.log(selectedTariffs);
|
||||||
console.log(selectedTariffs)
|
|
||||||
|
|
||||||
const closeDeleteModal = () => {
|
const closeDeleteModal = () => {
|
||||||
setOpenDeleteModal(false)
|
setOpenDeleteModal(false);
|
||||||
}
|
};
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
{ field: "id", headerName: "ID", width: 100 },
|
{ field: "id", headerName: "ID", width: 100 },
|
||||||
@ -78,23 +83,27 @@ console.log(selectedTariffs)
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
||||||
const gridData = tariffs
|
const gridData = tariffs
|
||||||
?.map((tariff) => {
|
?.map((tariff) => {
|
||||||
console.log(tariff)
|
console.log(tariff);
|
||||||
const privilege = findPrivilegeById(tariff.privilegeId);
|
const privilege = findPrivilegeById(tariff.privilegeId);
|
||||||
return {
|
return {
|
||||||
id: tariff.id,
|
id: tariff.id,
|
||||||
name: tariff.name,
|
name: tariff.name,
|
||||||
serviceName: privilege?.serviceKey == "templategen" ? "Шаблонизатор" : privilege?.serviceKey,
|
serviceName:
|
||||||
|
privilege?.serviceKey == "templategen"
|
||||||
|
? "Шаблонизатор"
|
||||||
|
: privilege?.serviceKey,
|
||||||
privilegeName: privilege?.name,
|
privilegeName: privilege?.name,
|
||||||
amount: tariff.amount,
|
amount: tariff.amount,
|
||||||
pricePerUnit: tariff.isCustom
|
pricePerUnit: tariff.isCustom
|
||||||
? (tariff.customPricePerUnit || 0) / 100
|
? (tariff.customPricePerUnit || 0) / 100
|
||||||
: (tariff?.price || 0) / 100,
|
: (tariff?.price || 0) / 100,
|
||||||
type:
|
type:
|
||||||
findPrivilegeById(tariff.privilegeId)?.value === "шаблон" ? "штука" : findPrivilegeById(tariff.privilegeId)?.value,
|
findPrivilegeById(tariff.privilegeId)?.value === "шаблон"
|
||||||
customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
|
? "штука"
|
||||||
|
: findPrivilegeById(tariff.privilegeId)?.value,
|
||||||
|
customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
|
||||||
total: tariff.amount
|
total: tariff.amount
|
||||||
? (tariff.amount *
|
? (tariff.amount *
|
||||||
(tariff.isCustom
|
(tariff.isCustom
|
||||||
@ -106,10 +115,15 @@ console.log(selectedTariffs)
|
|||||||
})
|
})
|
||||||
.sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));
|
.sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));
|
||||||
|
|
||||||
// console.log(gridData)
|
// console.log(gridData)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<Tooltip title="обновить список тарифов">
|
||||||
|
<IconButton onClick={() => requestTariffs()}>
|
||||||
|
<AutorenewIcon sx={{ color: "white" }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
<DataGrid
|
<DataGrid
|
||||||
disableSelectionOnClick={true}
|
disableSelectionOnClick={true}
|
||||||
checkboxSelection={true}
|
checkboxSelection={true}
|
||||||
@ -120,8 +134,19 @@ console.log(selectedTariffs)
|
|||||||
onSelectionModelChange={handleSelectionChange}
|
onSelectionModelChange={handleSelectionChange}
|
||||||
/>
|
/>
|
||||||
{selectedTariffs.length ? (
|
{selectedTariffs.length ? (
|
||||||
<Box component="section" sx={{ width: "100%", display: "flex", justifyContent: "start", mb: "30px" }}>
|
<Box
|
||||||
<Button onClick={() => setOpenDeleteModal(true)} sx={{ mr: "20px", zIndex: "10000" }}>
|
component="section"
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "start",
|
||||||
|
mb: "30px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
onClick={() => setOpenDeleteModal(true)}
|
||||||
|
sx={{ mr: "20px", zIndex: "10000" }}
|
||||||
|
>
|
||||||
Удаление
|
Удаление
|
||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
@ -134,8 +159,9 @@ console.log(selectedTariffs)
|
|||||||
closeDeleteModal();
|
closeDeleteModal();
|
||||||
}}
|
}}
|
||||||
selectedTariffs={selectedTariffs}
|
selectedTariffs={selectedTariffs}
|
||||||
/>
|
requestTariffs={requestTariffs}
|
||||||
<EditModal tariff={changingTariff}/>
|
/>
|
||||||
|
<EditModal tariff={changingTariff} requestTariffs={requestTariffs} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,67 +1,66 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import {Outlet} from 'react-router-dom'
|
import { Outlet } from "react-router-dom";
|
||||||
import {useTheme} from '@mui/material/styles';
|
import { useTheme } from "@mui/material/styles";
|
||||||
import {Box} from "@mui/material";
|
import { Box } from "@mui/material";
|
||||||
import {ThemeProvider} from "@mui/material";
|
import { ThemeProvider } from "@mui/material";
|
||||||
import CssBaseline from '@mui/material/CssBaseline';
|
import CssBaseline from "@mui/material/CssBaseline";
|
||||||
import Menu from "./Menu";
|
import Menu from "./Menu";
|
||||||
import Header from "./Header";
|
import Header from "./Header";
|
||||||
import ModalAdmin from "./ModalAdmin";
|
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 theme = useTheme();
|
||||||
const {requestTariffs} = useGetTariffs()
|
return (
|
||||||
React.useEffect(() => {
|
<React.Fragment>
|
||||||
requestTariffs()
|
<Box
|
||||||
},[])
|
sx={{
|
||||||
const theme = useTheme()
|
backgroundColor: theme.palette.primary.main,
|
||||||
return (
|
color: theme.palette.secondary.main,
|
||||||
<React.Fragment>
|
height: "100%",
|
||||||
<Box sx={{
|
}}
|
||||||
backgroundColor: theme.palette.primary.main,
|
>
|
||||||
color: theme.palette.secondary.main,
|
<Box
|
||||||
height: "100%"
|
sx={{
|
||||||
|
backgroundColor: theme.palette.content.main,
|
||||||
|
display: "flex",
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu />
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
}}
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
height: "100vh",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
overflow: "auto",
|
||||||
|
overflowY: "auto",
|
||||||
|
padding: "160px 5px",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Box sx={{
|
<Outlet />
|
||||||
backgroundColor: theme.palette.content.main,
|
|
||||||
display: "flex",
|
|
||||||
width: "100%",
|
|
||||||
height: "100%"
|
|
||||||
}}>
|
|
||||||
|
|
||||||
<Menu/>
|
|
||||||
<Box sx={{
|
|
||||||
width: "100%",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center"
|
|
||||||
}}>
|
|
||||||
<Box sx={{
|
|
||||||
width: "100%",
|
|
||||||
height: "100vh",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
overflow: "auto",
|
|
||||||
overflowY: "auto",
|
|
||||||
padding: "160px 5px"
|
|
||||||
}}>
|
|
||||||
<Outlet/>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
<ModalAdmin open={useMatch('/modalAdmin') !== null}/>
|
<ModalAdmin open={useMatch("/modalAdmin") !== null} />
|
||||||
<ModalUser open={useMatch('/modalUser') !== null}/>
|
<ModalUser open={useMatch("/modalUser") !== null} />
|
||||||
<ModalEntities open={useMatch('/modalEntities') !== null}/>
|
<ModalEntities open={useMatch("/modalEntities") !== null} />
|
||||||
</React.Fragment>
|
</React.Fragment>
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
@ -1,31 +0,0 @@
|
|||||||
import { Discount, GetDiscountResponse } from "@root/model/discount";
|
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
import { useEffect } from "react";
|
|
||||||
|
|
||||||
|
|
||||||
const makeRequest = authStore.getState().makeRequest;
|
|
||||||
|
|
||||||
export default function useDiscounts({ onError, onNewDiscounts }: {
|
|
||||||
onNewDiscounts: (response: Discount[]) => void;
|
|
||||||
onError?: (error: any) => void;
|
|
||||||
}) {
|
|
||||||
useEffect(() => {
|
|
||||||
const controller = new AbortController();
|
|
||||||
|
|
||||||
makeRequest<never, GetDiscountResponse>({
|
|
||||||
url: "https://admin.pena.digital/price/discounts",
|
|
||||||
method: "get",
|
|
||||||
useToken: true,
|
|
||||||
bearer: true,
|
|
||||||
signal: controller.signal,
|
|
||||||
}).then(result => {
|
|
||||||
console.log("New discounts", result);
|
|
||||||
onNewDiscounts(result.Discounts);
|
|
||||||
}).catch(error => {
|
|
||||||
console.log("Error fetching discounts", error);
|
|
||||||
onError?.(error);
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => controller.abort();
|
|
||||||
}, [onError, onNewDiscounts]);
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user