diff --git a/src/hooks/useCombinedPrivileges.hook.ts b/src/hooks/useCombinedPrivileges.hook.ts index 4a77ba6..c1a4c7a 100644 --- a/src/hooks/useCombinedPrivileges.hook.ts +++ b/src/hooks/useCombinedPrivileges.hook.ts @@ -8,7 +8,9 @@ import { mergedBackFrontPrivilege } from "@root/model/privilege"; interface UseCombinedPrivileges { mergedPrivileges: mergedBackFrontPrivilege[] } - +const translatorServiceKey = { + Шаблонизатор: "templategen" +} export const useCombinedPrivileges = ():UseCombinedPrivileges => { const [mergedPrivileges, setMergedPrivileges] = useState([]) diff --git a/src/hooks/useGetTariffs.hook.ts b/src/hooks/useGetTariffs.hook.ts new file mode 100644 index 0000000..f1df644 --- /dev/null +++ b/src/hooks/useGetTariffs.hook.ts @@ -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; + isLoading: boolean; +}; + +type GetTariffsResponse = { + totalPages: number; + tariffs: Tariff_BACKEND[]; +}; + +export const useGetTariffs = (): UseGetTariffs => { + const token = authStore((state) => state.token); + const [allTariffs, setAllTariffs] = useState>({}); + const [isLoading, setIsLoading] = useState(false); + + let newSt:Record + + + const requestTariffs = async (page: number = 1): Promise => { + setIsLoading(true); + + try { + const { data } = await axios.get( + "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 = {} + 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 }; +}; diff --git a/src/hooks/useRefreshPrivilegesStore.hook.ts b/src/hooks/useRefreshPrivilegesStore.hook.ts index 6c62dde..739302b 100644 --- a/src/hooks/useRefreshPrivilegesStore.hook.ts +++ b/src/hooks/useRefreshPrivilegesStore.hook.ts @@ -16,15 +16,22 @@ export const useRefreshPrivilegesStore = (): RefreshPrivilegesStore => { const [isError, setIsError] = useState(gotten.isError); const [errorMessage, setErrorMessage] = useState(gotten.errorMessage); - //Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор - - useEffect(() => { let extracted:RealPrivilege[] = [] - for (let serviceKey in gotten.privilegies) { + for (let serviceKey in gotten.privilegies) { //Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор extracted = extracted.concat(gotten.privilegies[serviceKey]) } - resetPrivilegeArray(extracted) + 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]); diff --git a/src/kitUI/Cart/Cart.tsx b/src/kitUI/Cart/Cart.tsx index 12c0f98..77a0ce0 100644 --- a/src/kitUI/Cart/Cart.tsx +++ b/src/kitUI/Cart/Cart.tsx @@ -27,7 +27,7 @@ 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/tariffs"; +import { useTariffStore } from "@root/stores/tariffsStore"; interface Props { selectedTariffs: GridSelectionModel; @@ -50,6 +50,7 @@ interface MergedTariff { } export default function Cart({ selectedTariffs }: Props) { + let cartTariffs = Object.values(useTariffStore().tariffs) const discounts = useMockDiscountStore((store) => store.discounts); const cartTotal = useCartStore((state) => state.cartTotal); const setCartTotal = useCartStore((store) => store.setCartTotal); @@ -58,13 +59,6 @@ export default function Cart({ selectedTariffs }: Props) { const [errorMessage, setErrorMessage] = useState(null); const [isNonCommercial, setIsNonCommercial] = useState(false); - const exampleTariffs = useTariffStore((state) => state.tariffs); - const [tariffs, setTariffs] = useState(); - const mergeTariffs: MergedTariff[] = [...exampleTariffs, ...(tariffs || [])]; - - console.log(cartTotal, "cartTotal"); - - const cartRows = cartTotal?.items.map((cartItemTotal) => { const privilege = findPrivilegeById(cartItemTotal.tariff.privilegeId); @@ -124,13 +118,8 @@ export default function Cart({ selectedTariffs }: Props) { function handleCalcCartClick() { //рассчитать - const cartTariffs = mergeTariffs.filter((tariff) => selectedTariffs.includes(tariff._id ? tariff._id : tariff.id)); const cartItems = cartTariffs.map((tariff) => createCartItem(tariff)); - console.log(cartTariffs); - // console.log(cartItems); - // console.log("selectedTariffs"); - // console.log(selectedTariffs); let loyaltyValue = parseInt(loyaltyField); @@ -138,14 +127,6 @@ export default function Cart({ selectedTariffs }: Props) { const activeDiscounts = discounts.filter((discount) => !discount.disabled); - console.log({ - user: testUser, - purchasesAmount: loyaltyValue, - cartItems, - discounts: activeDiscounts, - isNonCommercial, - coupon: couponField, - }); const cartData = calcCartData({ user: testUser, purchasesAmount: loyaltyValue, diff --git a/src/kitUI/Cart/calc.ts b/src/kitUI/Cart/calc.ts index c237fe0..65288e7 100644 --- a/src/kitUI/Cart/calc.ts +++ b/src/kitUI/Cart/calc.ts @@ -38,11 +38,7 @@ export function calcCartData({ }; cartItems.forEach((cartItem) => { - - console.log(cartItem) - console.log(cartItem.tariff.privilegeId) const privilege = findPrivilegeById(cartItem.tariff.privilegeId); - console.log(privilege) if (!privilege) throw new Error( `Привилегия с id ${cartItem.tariff.privilegeId} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}` diff --git a/src/kitUI/CustomWrapper.tsx b/src/kitUI/CustomWrapper.tsx index 6b2c18d..64b8bc6 100644 --- a/src/kitUI/CustomWrapper.tsx +++ b/src/kitUI/CustomWrapper.tsx @@ -90,9 +90,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps @@ -113,9 +113,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps )} diff --git a/src/kitUI/DeleteModal.tsx b/src/kitUI/DeleteModal.tsx index 7bd6340..cfcbaf1 100644 --- a/src/kitUI/DeleteModal.tsx +++ b/src/kitUI/DeleteModal.tsx @@ -4,36 +4,63 @@ import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; import Modal from "@mui/material/Modal"; 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 = { - open: boolean; + open: boolean | string; handleClose: () => void; - - tariffDelete: (tarifIid: GridSelectionModel) => Promise; - errorDelete: boolean; - tariffId: GridSelectionModel; - tariffName: string[]; + selectedTariffs: any; }; export default function DeleteModal({ open, handleClose, - tariffDelete, - errorDelete, - tariffId, - tariffName, + selectedTariffs }: DeleteModalProps) { - const onClickTariffDelete = () => { - if (errorDelete) { - return; + const { requestTariffs } = useGetTariffs() + const { token } = authStore(); + const tariffs = useTariffStore((state) => state.tariffs); + + const deleteTariff = async (id: string): Promise => { + 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(); + return + } + selectedTariffs.forEach((id:string) => { + deleteTariff(id) + }) handleClose(); + requestTariffs() }; return (
- Вы уверены, что хотите удалить тариф + Вы уверены, что хотите удалить {typeof open === 'string' ? "тариф" : "тарифы"} ? onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}> Да - Тариф: + {/* Тариф: {tariffName.map((name, index) => ( {name}; - ))} + ))} */} diff --git a/src/model/privilege.ts b/src/model/privilege.ts index 44db7b8..ffd4202 100644 --- a/src/model/privilege.ts +++ b/src/model/privilege.ts @@ -32,9 +32,12 @@ export interface mergedBackFrontPrivilege { privilegeId: string; name: string; description: string; - type: string; + type: "count" | "day" | "mb"; + amount?: number; price: number; - isDeleted?: boolean + isDeleted?: boolean; + value?: string + id?: string } export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"]; // export type PrivilegeMap = Record; diff --git a/src/model/tariff.ts b/src/model/tariff.ts index 4026a38..0d1e3f9 100644 --- a/src/model/tariff.ts +++ b/src/model/tariff.ts @@ -29,17 +29,6 @@ export interface Privilege_BACKEND { updatedAt: 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 = { id: string, name: string, @@ -54,20 +43,31 @@ export interface Privilege { name: PrivilegeType; privilegeId: string; description: string; - /** Единица измерения привилегии: время в днях/кол-во */ + /** Единица измерения привелегии: время в днях/кол-во */ type: "day" | "count"; - /** Стоимость одной единицы привилегии */ + /** Стоимость одной единицы привелегии */ price: number; } -/** @deprecated */ -export interface Tariff { +export type Tariff_BACKEND = { + _id: string, + name: string, + price: number, + isCustom: boolean, + isFront: false, + privilegies: Privilege_BACKEND[], + isDeleted: boolean, + createdAt: string, + updatedAt: string; +}; +export type Tariff = { id: string; name: string; + isCustom?: boolean; + price?: number; privilegeId: string; - /** Количество единиц привилегии */ - amount: number; - /** Кастомная цена, если есть, то используется вместо privilege.price */ - customPricePerUnit?: number; + amount: number; //Количество единиц привелегии + customPricePerUnit?: number; //Кастомная цена, если есть, то используется вместо privilege.price + isDeleted?: boolean, isFront?: boolean; } diff --git a/src/pages/Setting/CardPrivilegie.tsx b/src/pages/Setting/CardPrivilegie.tsx index 8703046..d5b2130 100644 --- a/src/pages/Setting/CardPrivilegie.tsx +++ b/src/pages/Setting/CardPrivilegie.tsx @@ -12,6 +12,7 @@ interface CardPrivilegie { value?: string; privilegeId: string; serviceKey: string; + amount: number } 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, serviceKey: serviceKey, description: description, + amount:1, type: type, value: value, - price: inputValue, + price: Number(inputValue), }, }) .then(() => { @@ -99,9 +101,9 @@ export const СardPrivilegie = ({ name, type, price, description, value, privile + {privileges.map(({ name, type, price, description, value, privilegeId, serviceKey, id, amount }) => ( + <СardPrivilegie + key={id} + name={name} + type={type} + amount={1} + price={price} + value={value} + privilegeId={privilegeId} + serviceKey={serviceKey} + description={description} + /> + )) + } + + ); +} diff --git a/src/pages/Setting/PrivilegiesWrapper.tsx b/src/pages/Setting/PrivilegiesWrapper.tsx index d259605..44b0a4d 100644 --- a/src/pages/Setting/PrivilegiesWrapper.tsx +++ b/src/pages/Setting/PrivilegiesWrapper.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { Box, SxProps, Theme, Typography, useMediaQuery, useTheme } from "@mui/material"; -// import ListPrivilegie from "./ListPrivilegie"; +import ListPrivilegie from "./ListPrivilegie"; interface CustomWrapperProps { text: string; @@ -90,9 +90,9 @@ export const PrivilegiesWrapper = ({ text, sx, result }: CustomWrapperProps) => @@ -113,15 +113,15 @@ export const PrivilegiesWrapper = ({ text, sx, result }: CustomWrapperProps) => )} - {/* {isExpanded && } */} + {isExpanded && } ); diff --git a/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx b/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx index 6cdabae..d7283ac 100644 --- a/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx +++ b/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx @@ -281,4 +281,4 @@ export default function CreateDiscount() { ); -} \ No newline at end of file +} diff --git a/src/pages/dashboard/Content/ServiceUsersDG.tsx b/src/pages/dashboard/Content/ServiceUsersDG.tsx index ad21e68..be71bc2 100644 --- a/src/pages/dashboard/Content/ServiceUsersDG.tsx +++ b/src/pages/dashboard/Content/ServiceUsersDG.tsx @@ -22,7 +22,6 @@ export default function ServiceUsersDG({ handleSelectionChange, users }: Props) if (!users) { return Loading...; } -console.log(users) const gridData = users.users.map((user:any) => ({ login: user.login, email: user.email, diff --git a/src/pages/dashboard/Content/Support/Chat/Chat.tsx b/src/pages/dashboard/Content/Support/Chat/Chat.tsx index a3184a8..be9dfab 100644 --- a/src/pages/dashboard/Content/Support/Chat/Chat.tsx +++ b/src/pages/dashboard/Content/Support/Chat/Chat.tsx @@ -45,7 +45,6 @@ export default function Chat() { body: getTicketsBody, signal: controller.signal, }).then(result => { - console.log("GetMessagesResponse", result); if (result?.length > 0) { if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1; addOrUpdateMessages(result); diff --git a/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx b/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx index 1157301..ebe2e32 100644 --- a/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx +++ b/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx @@ -6,96 +6,98 @@ import axios from "axios"; 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 { mergedPrivilegeStore } from "@root/stores/mergedPrivileges"; -import { Tariff_BACKEND } from "@root/model/tariff"; +import { findPrivilegeById, usePrivilegeStore } from "@root/stores/privilegesStore"; +import { useGetTariffs } from "@root/hooks/useGetTariffs.hook"; + +interface Props { + getTariffs: () => void +} export default function CreateTariff() { + + const { token } = authStore(); const theme = useTheme(); + + const privileges = usePrivilegeStore( store => store.privileges); + const [nameField, setNameField] = useState(""); const [amountField, setAmountField] = useState(""); const [customPriceField, setCustomPriceField] = useState(""); const [privilegeIdField, setPrivilegeIdField] = useState(""); - const { token } = authStore(); - const findPrivilegeById = (privilegeId: string) => { - // return mergedPrivileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null; - }; + const privilege = findPrivilegeById(privilegeIdField) - const privilege = findPrivilegeById(privilegeIdField); + const { requestTariffs } = useGetTariffs() + 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() { - // if (nameField === "") { - // enqueueSnackbar("Пустое название тарифа"); - // } - // if (amountField === "") { - // enqueueSnackbar("Пустое кол-во едениц привилегия"); - // } - // if (privilegeIdField === "") { - // enqueueSnackbar("Не выбрана привилегия"); - // } - - // const amount = Number(amountField); - // const customPrice = Number(customPriceField); - - // if (isNaN(amount) || !privilege) return; - - // const newTariff: Tariff = { + const createTariffBackend = () => { + if (checkFulledFields() && privilege !== null) { + 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), + }, + ], + }, + }) + .then(() => { + requestTariffs() + }) + .catch(() => { + enqueueSnackbar("что-то пошло не так") + }) + } + } + // const createTariffFrontend = () => { + // if (checkFulledFields() && privilege !== null) { + // updateTariffStore({ // id: nanoid(5), // name: nameField, - // amount:amount, - // isFront: true, + // amount: Number(amountField), + // isFront: true, // privilegeId: privilege.privilegeId, - // customPricePerUnit: customPrice ? customPrice / amount : undefined, - // }; - // addTariffs([newTariff]); - + // customPricePerUnit: customPriceField.length !== 0 ? Number(customPriceField)*100: undefined, + // }) // } - - // 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 ( - {/* {mergedPrivileges.map((privilege) => ( - + {privileges.map((privilege) => ( + {privilege.description} - ))} */} + ))} - - {/* {privilege && ( + {privilege && ( {privilege.price} - )} */} + )} diff --git a/src/pages/dashboard/Content/Tariffs/EditModal.tsx b/src/pages/dashboard/Content/Tariffs/EditModal.tsx index 42bbca9..50c2a92 100644 --- a/src/pages/dashboard/Content/Tariffs/EditModal.tsx +++ b/src/pages/dashboard/Content/Tariffs/EditModal.tsx @@ -7,10 +7,12 @@ import Modal from "@mui/material/Modal"; import TextField from "@mui/material/TextField"; import axios from "axios"; import { authStore } from "@root/stores/auth"; -import { Privilege, Tariff_FRONTEND } from "@root/model/tariff"; -import { findPrivilegeById } from "@root/stores/privilegesStore"; -import { useTariffStore, updateTariff } from "@root/stores/tariffs"; +import { Privilege, Tariff } from "@root/model/tariff"; +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 { enqueueSnackbar } from "notistack"; interface EditProps { @@ -38,30 +40,27 @@ const editTariff = ({ data: { name: tariffName, price: tariffPrice, - isCustom: true, + isCustom: false, privilegies: [privilege] }, }); } interface Props { - tariff: Tariff_FRONTEND, - getTariffs: () => void + tariff: Tariff } -/** @deprecated */ -export default function EditModal({tariff, getTariffs}:Props) { - +export default function EditModal({tariff = undefined}:Props) { const [open, setOpen] = useState(false); const [name, setName] = useState(""); const [price, setPrice] = useState(""); const { token } = authStore(); const tariffs = useTariffStore((state) => state.tariffs); + const currentTariff = tariff ? tariffs[tariff.id] : undefined + const { requestTariffs } = useGetTariffs() useEffect(() => { setOpen(tariff !== undefined) }, [tariff]) - console.log(tariff) - if (tariff?.privilege[0].privilegeId !== undefined) console.log(findPrivilegeById(tariff?.privilege[0].privilegeId)) return - {tariff !== undefined && ( + {currentTariff !== undefined && ( - Название Тарифа: {tariff.name} + Название Тарифа: {currentTariff.name} setName(event.target.value)} label="Имя" @@ -97,7 +96,7 @@ export default function EditModal({tariff, getTariffs}:Props) { value={name} sx={{ marginBottom: "10px" }} /> - Цена за единицу: {tariff.pricePerUnit} + Цена за единицу: {currentTariff.pricePerUnit} setPrice(event.target.value)} label="Цена за единицу" @@ -106,31 +105,41 @@ export default function EditModal({tariff, getTariffs}:Props) { sx={{ marginBottom: "10px" }} />