From a1ddfa08e8c2198e63ac663fe9c7628ea25399f1 Mon Sep 17 00:00:00 2001 From: Nastya Date: Mon, 3 Jul 2023 13:55:43 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=D1=82=D0=B0=D1=80=D0=B8=D1=84=D1=8B=20?= =?UTF-8?q?=D1=85=D1=80=D0=B0=D0=BD=D1=8F=D1=82=D1=81=D1=8F=20=D0=B2=20?= =?UTF-8?q?=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82=D0=B5=20=D1=81=20=D0=BA?= =?UTF-8?q?=D0=BB=D1=8E=D1=87=D0=B0=D0=BC=D0=B8=20=D0=B0=D0=B9=D0=B4=D0=B8?= =?UTF-8?q?=D1=88=D0=BD=D0=B8=D0=BA=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useGetTariffs.hook.ts | 71 +++++++++++ src/hooks/useRefreshPrivilegesStore.hook.ts | 15 ++- src/kitUI/Cart/Cart.tsx | 11 +- src/model/tariff.ts | 41 +++---- .../Content/Tariffs/CreateTariff.tsx | 1 - .../dashboard/Content/Tariffs/EditModal.tsx | 6 +- .../Content/Tariffs/Privileges/Privileges.tsx | 6 +- src/pages/dashboard/Content/Tariffs/index.tsx | 65 ++-------- .../dashboard/Content/Tariffs/tariffsDG.tsx | 115 ++++++------------ src/stores/privilegesStore.ts | 5 +- src/stores/tariffs.ts | 50 -------- src/stores/tariffsStore.ts | 37 ++++++ 12 files changed, 190 insertions(+), 233 deletions(-) create mode 100644 src/hooks/useGetTariffs.hook.ts delete mode 100644 src/stores/tariffs.ts create mode 100644 src/stores/tariffsStore.ts diff --git a/src/hooks/useGetTariffs.hook.ts b/src/hooks/useGetTariffs.hook.ts new file mode 100644 index 0000000..3b60eb4 --- /dev/null +++ b/src/hooks/useGetTariffs.hook.ts @@ -0,0 +1,71 @@ +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 => { + console.log("ща запрошу список") + const token = authStore((state) => state.token); + const [allTariffs, setAllTariffs] = useState>({}); + const [isLoading, setIsLoading] = useState(false); + + const requestTariffs = async (page: number = 1): Promise => { + setIsLoading(true); + + let newSt:Record + try { + const { data } = await axios.get( + "https://admin.pena.digital/strator/tariff/", + { + params: { page, limit: 100 }, + headers: { Authorization: `Bearer ${token}` }, + } + ); + + if (!data.tariffs.length) { + setIsLoading(false); + + return; + } + const tariffsObj:Record = {} + data.tariffs.forEach((tariff) => { + tariffsObj[tariff._id] = { + id: tariff._id, + name: tariff.name, + amount: tariff.privilegies[0].amount, + isFront: false, + privilegeId: tariff.privilegies[0].privilegeId, + isDeleted: tariff.isDeleted, + customPricePerUnit: tariff.price + } + }) + + newSt = {...allTariffs, ...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..2464ccd 100644 --- a/src/hooks/useRefreshPrivilegesStore.hook.ts +++ b/src/hooks/useRefreshPrivilegesStore.hook.ts @@ -16,15 +16,20 @@ 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, + })) + resetPrivilegeArray(readyArray) }, [gotten.privilegies]); diff --git a/src/kitUI/Cart/Cart.tsx b/src/kitUI/Cart/Cart.tsx index 12c0f98..74f269c 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,7 +118,6 @@ 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); diff --git a/src/model/tariff.ts b/src/model/tariff.ts index ce082f9..bfe5d01 100644 --- a/src/model/tariff.ts +++ b/src/model/tariff.ts @@ -29,24 +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, - amount: number, - privilegeId: string, - customPricePerUnit?: number; -}; /** @deprecated */ export interface Privilege { @@ -60,14 +42,23 @@ export interface Privilege { 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; privilegeId: string; - /** Количество единиц привелегии */ - amount: number; - /** Кастомная цена, если есть, то используется вместо privilege.price */ - customPricePerUnit?: number; + amount: number; //Количество единиц привелегии + customPricePerUnit?: number; //Кастомная цена, если есть, то используется вместо privilege.price + isDeleted?: boolean, isFront?: boolean; -} +} \ No newline at end of file diff --git a/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx b/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx index 799b2b0..5041c79 100644 --- a/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx +++ b/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx @@ -6,7 +6,6 @@ import axios from "axios"; import { CustomTextField } from "@root/kitUI/CustomTextField"; -import { addTariffs } from "@root/stores/tariffs"; import { authStore } from "@root/stores/auth"; // import { mergedPrivilegeStore } from "@root/stores/mergedPrivileges"; import { Tariff_BACKEND } from "@root/model/tariff"; diff --git a/src/pages/dashboard/Content/Tariffs/EditModal.tsx b/src/pages/dashboard/Content/Tariffs/EditModal.tsx index 42bbca9..d8c3edf 100644 --- a/src/pages/dashboard/Content/Tariffs/EditModal.tsx +++ b/src/pages/dashboard/Content/Tariffs/EditModal.tsx @@ -7,9 +7,9 @@ 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 { Privilege, Tariff } from "@root/model/tariff"; import { findPrivilegeById } from "@root/stores/privilegesStore"; -import { useTariffStore, updateTariff } from "@root/stores/tariffs"; +import { useTariffStore, updateTariff } from "@root/stores/tariffsStore"; import { arrayBuffer } from "stream/consumers"; @@ -44,7 +44,7 @@ const editTariff = ({ }); } interface Props { - tariff: Tariff_FRONTEND, + tariff: Tariff, getTariffs: () => void } diff --git a/src/pages/dashboard/Content/Tariffs/Privileges/Privileges.tsx b/src/pages/dashboard/Content/Tariffs/Privileges/Privileges.tsx index f7ae229..143e5b3 100644 --- a/src/pages/dashboard/Content/Tariffs/Privileges/Privileges.tsx +++ b/src/pages/dashboard/Content/Tariffs/Privileges/Privileges.tsx @@ -2,6 +2,7 @@ import { GridColDef } from "@mui/x-data-grid"; import DataGrid from "@kitUI/datagrid"; import { Typography } from "@mui/material"; import { useCombinedPrivileges } from "@root/hooks/useCombinedPrivileges.hook"; +import { usePrivilegeStore } from "@root/stores/privilegesStore"; const columns: GridColDef[] = [ { field: "id", headerName: "id", width: 40 }, @@ -12,8 +13,9 @@ const columns: GridColDef[] = [ ]; export default function Privileges() { - const { mergedPrivileges } = useCombinedPrivileges(); - const privilegesGridData = mergedPrivileges + const privileges = usePrivilegeStore((state) => state.privileges); + // const { mergedPrivileges } = useCombinedPrivileges(); + const privilegesGridData = privileges .filter(privilege => ( !privilege.isDeleted )) diff --git a/src/pages/dashboard/Content/Tariffs/index.tsx b/src/pages/dashboard/Content/Tariffs/index.tsx index 891530d..d6c8402 100644 --- a/src/pages/dashboard/Content/Tariffs/index.tsx +++ b/src/pages/dashboard/Content/Tariffs/index.tsx @@ -7,15 +7,16 @@ import Cart from "@root/kitUI/Cart/Cart"; import axios from "axios"; import { enqueueSnackbar } from "notistack"; import { authStore } from "@root/stores/auth"; -import { Tariff_BACKEND } from "@root/model/tariff"; -import { updateTariff, useTariffStore } from "@root/stores/tariffs"; +import { useTariffStore } from "@root/stores/tariffsStore"; import { usePrivilegeStore } from "@root/stores/privilegesStore"; +import { useGetTariffs } from "@root/hooks/useGetTariffs.hook"; import TariffsDG from "./tariffsDG"; import CreateTariff from "./CreateTariff"; import Privileges from "./Privileges/Privileges"; import ChangePriceModal from "./Privileges/ChangePriceModal"; import {useRefreshPrivilegesStore} from "@root/hooks/useRefreshPrivilegesStore.hook" +import { Tariff } from "@root/model/tariff"; export default function Tariffs() { const token = authStore((state) => state.token); @@ -23,63 +24,14 @@ export default function Tariffs() { const privileges = usePrivilegeStore((state) => state.privileges); const tariffs = useTariffStore((state) => state.tariffs); const [selectedTariffs, setSelectedTariffs] = useState([]); - + const [allTariffs, setAllTariffs] = useState([]); + const {requestTariffs} = useGetTariffs() useRefreshPrivilegesStore() + - const getTariffs = (page: number = 1) => { - axios({ - method: "get", - url: "https://admin.pena.digital/strator/tariff", - params: { page, limit: 100 }, - headers: { - Authorization: `Bearer ${token}`, - }, - }) - .then((data: any) => { - //Получили список тарифов. Сразу убираем удалённые и записываем остальное в стор - data.data.tariffs.forEach((tariff: Tariff_BACKEND) => { - if (!tariff.isDeleted) { - let toFrontTariff = { - id: tariff._id, - name: tariff.name, - amount: tariff.privilegies[0].amount, - isFront: false, - privilegeId: tariff.privilegies[0].privilegeId, - customPricePerUnit: tariff.price, - }; - - console.log(data.data.tariffs) - console.log("reade") - updateTariff(toFrontTariff); - } - }); - if (page < data.totalPages) { - return getTariffs(page + 1); - } - // data.data.tariffs.forEach(async (t:any) => { - // if (t._id) { - // console.log(t._id) - // await axios({ - // method: "delete", - // url: "https://admin.pena.digital/strator/tariff/delete", - // headers: { - // Authorization: `Bearer ${token}`, - // }, - // data: { id: t._id }, - // }); - // } - - // }) - }) - .catch((error) => { - console.log(error) - enqueueSnackbar("Ошибка получения тарифов"); - }); - }; useEffect(() => { - getTariffs(); - - }, []); + requestTariffs() + },[]) return ( setSelectedTariffs(selectionModel)} - getTariffs={getTariffs} /> diff --git a/src/pages/dashboard/Content/Tariffs/tariffsDG.tsx b/src/pages/dashboard/Content/Tariffs/tariffsDG.tsx index cb146c7..073f3b6 100644 --- a/src/pages/dashboard/Content/Tariffs/tariffsDG.tsx +++ b/src/pages/dashboard/Content/Tariffs/tariffsDG.tsx @@ -9,7 +9,7 @@ import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutl import DataGrid from "@kitUI/datagrid"; -import { deleteTariffs, useTariffStore } from "@root/stores/tariffs"; +import { deleteTariffs, useTariffStore } from "@root/stores/tariffsStore"; import { SERVICE_LIST } from "@root/model/tariff"; import { findPrivilegeById } from "@root/stores/privilegesStore"; @@ -17,85 +17,26 @@ import axios from "axios"; import { authStore } from "@root/stores/auth"; import DeleteModal from "@root/kitUI/DeleteModal"; import EditModal from "./EditModal"; -import { Tariff_FRONTEND } from "@root/model/tariff"; +import { Tariff } from "@root/model/tariff"; interface Props { selectedTariffs: GridSelectionModel; handleSelectionChange: (selectionModel: GridSelectionModel) => void; - getTariffs: () => void; } /** @deprecated */ -export default function TariffsDG({ selectedTariffs, handleSelectionChange, getTariffs }: Props) { +export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) { const { token } = authStore(); - const tariffs = useTariffStore((state) => state.tariffs); + const tariffs = Object.values(useTariffStore().tariffs) const [deletedRows, setDeletedRows] = useState([]); const [openDeleteModal, setOpenDeleteModal] = useState(false); - const [changingTariff, setChangingTariff] = useState(); + const [changingTariff, setChangingTariff] = useState(); const [errorDelete, setErrorDelete] = useState(false); - const tariffDeleteDataGrid = async (tarifIid: string) => { - if (exampleTariffs.find((tariff) => tariff.id === tarifIid)) { - deleteTariffs(tarifIid); - enqueueSnackbar("Тариф удалён"); - return; - } - try { - await axios({ - method: "delete", - url: "https://admin.pena.digital/strator/tariff", - headers: { - Authorization: `Bearer ${token}`, - }, - data: { id: tarifIid }, - }); - setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]); - enqueueSnackbar("Тариф удалён"); - getTariffs(); - } catch (error: any) { - setErrorDelete(true); - enqueueSnackbar("Ошибка удаления :", error.message); - } - }; - - const tariffDelete = async (tarifIid: GridSelectionModel) => { - const deleted = []; - const notDeleted = []; - - for (let index = 0; index < tarifIid.length; index++) { - if (exampleTariffs.find((tariff) => tariff.id === (tarifIid[index] as string))) { - deleted.push(tarifIid[index]); - deleteTariffs(tarifIid[index] as string); - continue; - } - - try { - await axios({ - method: "delete", - url: "https://admin.pena.digital/strator/tariff", - headers: { - Authorization: `Bearer ${token}`, - }, - data: { id: tarifIid[index] }, - }); - setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid[index] as string]); - - deleted.push(tarifIid[index]); - } catch (error: any) { - notDeleted.push(tarifIid[index]); - - setErrorDelete(true); - enqueueSnackbar(error.message); - } - } - getTariffs(); - - enqueueSnackbar(`Deleted: ${deleted.join(", ")}`); - enqueueSnackbar(`Not deleted: ${notDeleted.join(", ")}`); - }; + const columns: GridColDef[] = [ { field: "id", headerName: "ID", width: 100 }, @@ -138,27 +79,45 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT }, ]; - // const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]); - // const selectedTariffPrivilege = selectedTariff ? selectedTariff.privilege : []; - const allName = () => { - const selectedNames = []; + const gridData = tariffs + ?.map((tariff) => { + const privilege = findPrivilegeById(tariff.privilegeId); - for (let index = 0; index < selectedTariffs.length; index++) { - const tariff = gridData.find((tariff) => tariff.id === selectedTariffs[index]); - const name = tariff ? tariff.name : ""; - selectedNames.push(name); - } + console.log(privilege) + return { + id: tariff.id, + name: tariff.name, + serviceName: privilege?.serviceKey, + privilegeName: privilege?.name, + amount: tariff.amount, + pricePerUnit: tariff.isCustom + ? (tariff.customPricePerUnit || 0) / 100 + : (tariff?.price || 0) / 100, + type: + findPrivilegeById(tariff.privilegeId)?.type === "count" + ? "день" + : "шт.", + isCustomPrice: tariff.isCustom ? "Да" : "Нет", + total: tariff.amount + ? (tariff.amount * + (tariff.isCustom + ? tariff.customPricePerUnit || 0 * tariff.amount + : findPrivilegeById(tariff.privilegeId)?.price || 0)) / + 100 + : 0, + }; + }) + .filter((tariff) => !tariff.isDelete) + .sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1)); - return selectedNames; - }; return ( <> row.id} components={{ Toolbar: GridToolbar }} @@ -184,7 +143,7 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT }} /> */} {console.log(changingTariff)} - + {/* */} ); } diff --git a/src/stores/privilegesStore.ts b/src/stores/privilegesStore.ts index d328545..82763e8 100644 --- a/src/stores/privilegesStore.ts +++ b/src/stores/privilegesStore.ts @@ -2,10 +2,10 @@ import { Privilege } from "@root/model/tariff"; import { create } from "zustand"; import { devtools } from "zustand/middleware"; import { exampleCartValues } from "./mocks/exampleCartValues"; -import { RealPrivilege } from "@root/model/privilege"; +import { mergedBackFrontPrivilege } from "@root/model/privilege"; interface RealPrivilegeStore { - privileges: RealPrivilege[]; + privileges: mergedBackFrontPrivilege[]; } export const usePrivilegeStore = create()( @@ -88,7 +88,6 @@ export const resetPrivilegeArray = (privileges: RealPrivilegeStore["privileges"] // }); // }; -/** @deprecated */ export const findPrivilegeById = (privilegeId: string) => { return usePrivilegeStore.getState().privileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null; }; diff --git a/src/stores/tariffs.ts b/src/stores/tariffs.ts deleted file mode 100644 index 8e3b45e..0000000 --- a/src/stores/tariffs.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { create } from "zustand"; -import { persist } from "zustand/middleware"; -import { Tariff_BACKEND, Tariff_FRONTEND } from "@root/model/tariff"; - - -interface TariffStore { - tariffs: Tariff_FRONTEND[] -} - -export const useTariffStore = create()( - persist( - (set, get) => ({ - tariffs: [], - // tariffs: exampleTariffs, - }), - { - name: "Tariff store", - } - ) -); - - -export const resetTariffs = (newTariff: Tariff_FRONTEND[]) => useTariffStore.setState((state) => ({ tariffs: newTariff })); - -export const updateTariff = (tariff: Tariff_FRONTEND) => { - let stateTariffs = useTariffStore.getState().tariffs - let index - stateTariffs.forEach((e,i) => { //ищем такой тариф для замены на новый - if (e.id == tariff.id) index = i - }) - if (index === undefined) {// не нашли. Добавляем - addTariffs([tariff]) - } else { //нашли. Заменяем - stateTariffs[index] = tariff - useTariffStore.setState(() => ({tariffs: stateTariffs})) - } -} - - -export const addTariffs = (newTariffs: Tariff_FRONTEND[]) => { - let stateTariffs = useTariffStore.getState().tariffs - let newArrayTariffs = [...stateTariffs, ...newTariffs] - newArrayTariffs.forEach((tariff) => { - updateTariff(tariff) - }) -} -export const deleteTariffs = (tariffId: string) => - useTariffStore.setState((state) => ({ - tariffs: state.tariffs.filter((tariff) => tariff.id !== tariffId), - })); diff --git a/src/stores/tariffsStore.ts b/src/stores/tariffsStore.ts new file mode 100644 index 0000000..afc1236 --- /dev/null +++ b/src/stores/tariffsStore.ts @@ -0,0 +1,37 @@ +import { create } from "zustand"; +import { persist } from "zustand/middleware"; +import { Tariff } from "@root/model/tariff"; + + +interface TariffStore { + tariffs: Record +} + +export const useTariffStore = create()( + persist( + (set, get) => ({ + tariffs: {}, + }), + { + name: "Tariff store", + } + ) +); + + + +export const updateTariffs = (newTariffs: Record) => { + useTariffStore.setState((state) => ({ + tariffs: {...state.tariffs, ...newTariffs}, + })); +}; + +export const deleteTariffs = (tariffId: string) => { + let tariffs = useTariffStore.getState().tariffs + delete tariffs[tariffId] + useTariffStore.setState(() => ({tariffs: tariffs})); +}; + +export const resetTariffsStore = (newTariffs: Record) => { + useTariffStore.setState(() => ({tariffs: newTariffs})); +}; From 80f63c04109ddfc78c13198e9b23fba6e1a9564e Mon Sep 17 00:00:00 2001 From: Nastya Date: Mon, 3 Jul 2023 14:28:42 +0300 Subject: [PATCH 2/6] =?UTF-8?q?=D0=BA=D0=BE=D1=80=D1=80=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useCombinedPrivileges.hook.ts | 4 +++- src/hooks/useGetTariffs.hook.ts | 9 ++++++--- src/hooks/useRefreshPrivilegesStore.hook.ts | 2 ++ src/model/privilege.ts | 2 +- src/model/tariff.ts | 2 ++ src/stores/privilegesStore.ts | 6 +++--- 6 files changed, 17 insertions(+), 8 deletions(-) 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 index 3b60eb4..ee4ca90 100644 --- a/src/hooks/useGetTariffs.hook.ts +++ b/src/hooks/useGetTariffs.hook.ts @@ -21,10 +21,10 @@ export const useGetTariffs = (): UseGetTariffs => { const [allTariffs, setAllTariffs] = useState>({}); const [isLoading, setIsLoading] = useState(false); + let newSt:Record const requestTariffs = async (page: number = 1): Promise => { setIsLoading(true); - let newSt:Record try { const { data } = await axios.get( "https://admin.pena.digital/strator/tariff/", @@ -44,15 +44,18 @@ export const useGetTariffs = (): UseGetTariffs => { 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 + customPricePerUnit: tariff.price, + } }) - newSt = {...allTariffs, ...tariffsObj} + newSt = {...newSt, ...tariffsObj} if (page < data.totalPages) { diff --git a/src/hooks/useRefreshPrivilegesStore.hook.ts b/src/hooks/useRefreshPrivilegesStore.hook.ts index 2464ccd..739302b 100644 --- a/src/hooks/useRefreshPrivilegesStore.hook.ts +++ b/src/hooks/useRefreshPrivilegesStore.hook.ts @@ -28,6 +28,8 @@ export const useRefreshPrivilegesStore = (): RefreshPrivilegesStore => { description: privilege.description, type: privilege.type, price: privilege.price, + value: privilege.value, + id: privilege._id, })) resetPrivilegeArray(readyArray) }, [gotten.privilegies]); diff --git a/src/model/privilege.ts b/src/model/privilege.ts index 44db7b8..180d8cf 100644 --- a/src/model/privilege.ts +++ b/src/model/privilege.ts @@ -34,7 +34,7 @@ export interface mergedBackFrontPrivilege { description: string; type: string; price: number; - isDeleted?: boolean + isDeleted?: boolean; } 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 bfe5d01..f090419 100644 --- a/src/model/tariff.ts +++ b/src/model/tariff.ts @@ -56,6 +56,8 @@ export type Tariff_BACKEND = { export type Tariff = { id: string; name: string; + isCustom?: boolean; + price?: number; privilegeId: string; amount: number; //Количество единиц привелегии customPricePerUnit?: number; //Кастомная цена, если есть, то используется вместо privilege.price diff --git a/src/stores/privilegesStore.ts b/src/stores/privilegesStore.ts index 82763e8..3f31532 100644 --- a/src/stores/privilegesStore.ts +++ b/src/stores/privilegesStore.ts @@ -4,11 +4,11 @@ import { devtools } from "zustand/middleware"; import { exampleCartValues } from "./mocks/exampleCartValues"; import { mergedBackFrontPrivilege } from "@root/model/privilege"; -interface RealPrivilegeStore { +interface PrivilegeStore { privileges: mergedBackFrontPrivilege[]; } -export const usePrivilegeStore = create()( +export const usePrivilegeStore = create()( devtools( (set, get) => ({ privileges: [], @@ -19,7 +19,7 @@ export const usePrivilegeStore = create()( ) ); -export const resetPrivilegeArray = (privileges: RealPrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges }); +export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges }); From 59bcf32b46960fc9808b7ab61b78408a38201a37 Mon Sep 17 00:00:00 2001 From: Nastya Date: Mon, 3 Jul 2023 18:06:27 +0300 Subject: [PATCH 3/6] =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B0=D0=BA=D1=82=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D1=82=D0=B0=D1=80?= =?UTF-8?q?=D0=B8=D1=84=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useGetTariffs.hook.ts | 6 +- src/kitUI/Cart/Cart.tsx | 12 -- src/kitUI/Cart/calc.ts | 4 - src/model/privilege.ts | 2 + .../DiscountManagement/CreateDiscount.tsx | 1 + .../dashboard/Content/ServiceUsersDG.tsx | 1 - .../dashboard/Content/Support/Chat/Chat.tsx | 1 - .../Content/Tariffs/CreateTariff.tsx | 173 +++++++++--------- .../dashboard/Content/Tariffs/EditModal.tsx | 52 +++--- src/pages/dashboard/Content/Tariffs/index.tsx | 7 - .../dashboard/Content/Tariffs/tariffsDG.tsx | 15 +- src/pages/dashboard/index.tsx | 7 + src/stores/discounts.ts | 3 - src/stores/privilegesStore.ts | 68 +------ src/utils/hooks/usePrivileges.ts | 2 - 15 files changed, 130 insertions(+), 224 deletions(-) diff --git a/src/hooks/useGetTariffs.hook.ts b/src/hooks/useGetTariffs.hook.ts index ee4ca90..faa72ae 100644 --- a/src/hooks/useGetTariffs.hook.ts +++ b/src/hooks/useGetTariffs.hook.ts @@ -16,7 +16,6 @@ type GetTariffsResponse = { }; export const useGetTariffs = (): UseGetTariffs => { - console.log("ща запрошу список") const token = authStore((state) => state.token); const [allTariffs, setAllTariffs] = useState>({}); const [isLoading, setIsLoading] = useState(false); @@ -34,11 +33,16 @@ export const useGetTariffs = (): UseGetTariffs => { } ); + + + + if (!data.tariffs.length) { setIsLoading(false); return; } + const tariffsObj:Record = {} data.tariffs.forEach((tariff) => { tariffsObj[tariff._id] = { diff --git a/src/kitUI/Cart/Cart.tsx b/src/kitUI/Cart/Cart.tsx index 74f269c..77a0ce0 100644 --- a/src/kitUI/Cart/Cart.tsx +++ b/src/kitUI/Cart/Cart.tsx @@ -120,10 +120,6 @@ export default function Cart({ selectedTariffs }: Props) { //рассчитать const cartItems = cartTariffs.map((tariff) => createCartItem(tariff)); - console.log(cartTariffs); - // console.log(cartItems); - // console.log("selectedTariffs"); - // console.log(selectedTariffs); let loyaltyValue = parseInt(loyaltyField); @@ -131,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/model/privilege.ts b/src/model/privilege.ts index 180d8cf..c77ed14 100644 --- a/src/model/privilege.ts +++ b/src/model/privilege.ts @@ -35,6 +35,8 @@ export interface mergedBackFrontPrivilege { type: string; price: number; isDeleted?: boolean; + value?: string + id?: string } export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"]; // export type PrivilegeMap = Record; diff --git a/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx b/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx index 6ffc5d0..6f72676 100644 --- a/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx +++ b/src/pages/dashboard/Content/DiscountManagement/CreateDiscount.tsx @@ -48,6 +48,7 @@ export default function CreateDiscount() { if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана"); try { + console.log("work") const createdDiscount = await createDiscountJSON({ cartPurchasesAmount, discountFactor, 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 5041c79..49c963b 100644 --- a/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx +++ b/src/pages/dashboard/Content/Tariffs/CreateTariff.tsx @@ -6,95 +6,98 @@ import axios from "axios"; import { CustomTextField } from "@root/kitUI/CustomTextField"; +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 d8c3edf..815385e 100644 --- a/src/pages/dashboard/Content/Tariffs/EditModal.tsx +++ b/src/pages/dashboard/Content/Tariffs/EditModal.tsx @@ -8,9 +8,11 @@ import TextField from "@mui/material/TextField"; import axios from "axios"; import { authStore } from "@root/stores/auth"; import { Privilege, Tariff } from "@root/model/tariff"; -import { findPrivilegeById } from "@root/stores/privilegesStore"; 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 { @@ -44,24 +46,22 @@ const editTariff = ({ }); } interface Props { - tariff: Tariff, - getTariffs: () => void + tariff: Tariff } -/** @deprecated */ -export default function EditModal({tariff, getTariffs}:Props) { - +export default function EditModal({tariff = undefined}:Props) { + console.log(tariff) 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 +97,7 @@ export default function EditModal({tariff, getTariffs}:Props) { value={name} sx={{ marginBottom: "10px" }} /> - Цена за единицу: {tariff.pricePerUnit} + Цена за единицу: {currentTariff.pricePerUnit} setPrice(event.target.value)} label="Цена за единицу" @@ -106,31 +106,33 @@ export default function EditModal({tariff, getTariffs}:Props) { sx={{ marginBottom: "10px" }} /> - Тариф: + {/* Тариф: {tariffName.map((name, index) => ( {name}; - ))} + ))} */} diff --git a/src/pages/dashboard/Content/Tariffs/EditModal.tsx b/src/pages/dashboard/Content/Tariffs/EditModal.tsx index 815385e..19b4424 100644 --- a/src/pages/dashboard/Content/Tariffs/EditModal.tsx +++ b/src/pages/dashboard/Content/Tariffs/EditModal.tsx @@ -50,7 +50,6 @@ interface Props { } export default function EditModal({tariff = undefined}:Props) { - console.log(tariff) const [open, setOpen] = useState(false); const [name, setName] = useState(""); const [price, setPrice] = useState(""); @@ -106,8 +105,7 @@ export default function EditModal({tariff = undefined}:Props) { sx={{ marginBottom: "10px" }} />