fix after merge
This commit is contained in:
commit
16d7fefae7
@ -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<mergedBackFrontPrivilege[]>([])
|
||||
|
||||
82
src/hooks/useGetTariffs.hook.ts
Normal file
82
src/hooks/useGetTariffs.hook.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import axios from "axios";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
||||
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
||||
|
||||
|
||||
type UseGetTariffs = {
|
||||
requestTariffs: (page?: number, limit?: number) => Promise<void>;
|
||||
isLoading: boolean;
|
||||
};
|
||||
|
||||
type GetTariffsResponse = {
|
||||
totalPages: number;
|
||||
tariffs: Tariff_BACKEND[];
|
||||
};
|
||||
|
||||
export const useGetTariffs = (): UseGetTariffs => {
|
||||
const token = authStore((state) => state.token);
|
||||
const [allTariffs, setAllTariffs] = useState<Record<string, Tariff>>({});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
let newSt:Record<string, Tariff>
|
||||
|
||||
|
||||
const requestTariffs = async (page: number = 1): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const { data } = await axios.get<GetTariffsResponse>(
|
||||
"https://admin.pena.digital/strator/tariff/",
|
||||
{
|
||||
params: { page, limit: 100 },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
}
|
||||
);
|
||||
|
||||
// data.tariffs.forEach(async (t:any) => {
|
||||
// await axios({
|
||||
// method: "delete",
|
||||
// url: "https://admin.pena.digital/strator/tariff/delete",
|
||||
// headers: {
|
||||
// Authorization: `Bearer ${token}`,
|
||||
// },
|
||||
// data: { id: t._id },
|
||||
// });
|
||||
// })
|
||||
|
||||
|
||||
const tariffsObj:Record<string, Tariff> = {}
|
||||
data.tariffs.filter((tariff) => {return !tariff.isDeleted}).forEach((tariff) => {
|
||||
tariffsObj[tariff._id] = {
|
||||
id: tariff._id,
|
||||
name: tariff.name,
|
||||
isCustom: tariff.price ? true : false,
|
||||
amount: tariff.privilegies[0].amount,
|
||||
isFront: false,
|
||||
privilegeId: tariff.privilegies[0].privilegeId,
|
||||
price: tariff.privilegies[0].price,
|
||||
isDeleted: tariff.isDeleted,
|
||||
customPricePerUnit: tariff.price,
|
||||
|
||||
}
|
||||
})
|
||||
|
||||
newSt = {...newSt, ...tariffsObj}
|
||||
|
||||
|
||||
if (page < data.totalPages) {
|
||||
return requestTariffs(page + 1);
|
||||
}
|
||||
resetTariffsStore(newSt)
|
||||
setIsLoading(false);
|
||||
} catch {
|
||||
setIsLoading(false);
|
||||
|
||||
throw new Error("Ошибка при получении тарифов");
|
||||
}
|
||||
}
|
||||
|
||||
return { requestTariffs, isLoading };
|
||||
};
|
||||
@ -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]);
|
||||
|
||||
|
||||
|
||||
@ -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<string | null>(null);
|
||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||
|
||||
const exampleTariffs = useTariffStore((state) => state.tariffs);
|
||||
const [tariffs, setTariffs] = useState<any>();
|
||||
const mergeTariffs: MergedTariff[] = [...exampleTariffs, ...(tariffs || [])];
|
||||
|
||||
console.log(cartTotal, "cartTotal");
|
||||
|
||||
|
||||
const cartRows = cartTotal?.items.map((cartItemTotal) => {
|
||||
const 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,
|
||||
|
||||
@ -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}`
|
||||
|
||||
@ -90,9 +90,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps
|
||||
<path
|
||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||
stroke="#7E2AEA"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
@ -113,9 +113,9 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps
|
||||
<path
|
||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||
stroke="#fe9903"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
|
||||
@ -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<void>;
|
||||
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<void> => {
|
||||
const currentTariff = tariffs[id]
|
||||
|
||||
if (!currentTariff) {
|
||||
enqueueSnackbar("Тариф не найден");
|
||||
return
|
||||
}
|
||||
tariffDelete(tariffId);
|
||||
|
||||
try {
|
||||
await axios.delete("https://admin.pena.digital/strator/tariff/", {
|
||||
data: { id },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
} catch {
|
||||
|
||||
enqueueSnackbar("Ошибка при удалении тарифа на бэкэнде");
|
||||
}
|
||||
};
|
||||
|
||||
const onClickTariffDelete = () => {
|
||||
if (typeof open === 'string' ) {
|
||||
deleteTariff(open)
|
||||
requestTariffs()
|
||||
handleClose();
|
||||
return
|
||||
}
|
||||
selectedTariffs.forEach((id:string) => {
|
||||
deleteTariff(id)
|
||||
})
|
||||
handleClose();
|
||||
requestTariffs()
|
||||
};
|
||||
return (
|
||||
<div>
|
||||
<Modal
|
||||
open={open}
|
||||
open={Boolean(open)}
|
||||
onClose={handleClose}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
@ -53,7 +80,7 @@ export default function DeleteModal({
|
||||
}}
|
||||
>
|
||||
<Typography id="modal-modal-title" variant="h6" component="h2">
|
||||
Вы уверены, что хотите удалить тариф
|
||||
Вы уверены, что хотите удалить {typeof open === 'string' ? "тариф" : "тарифы"} ?
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{ mt: "20px", display: "flex", width: "332px", justifyContent: "space-between", alignItems: "center" }}
|
||||
@ -61,10 +88,10 @@ export default function DeleteModal({
|
||||
<Button onClick={() => onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}>
|
||||
Да
|
||||
</Button>
|
||||
<Typography>Тариф:</Typography>
|
||||
{/* <Typography>Тариф:</Typography>
|
||||
{tariffName.map((name, index) => (
|
||||
<Typography key={index}>{name};</Typography>
|
||||
))}
|
||||
))} */}
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
|
||||
@ -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<string, RealPrivilege[]>;
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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
|
||||
<path
|
||||
d="M9.25 9.25H10V14.5H10.75"
|
||||
stroke="#7E2AEA"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
|
||||
|
||||
27
src/pages/Setting/ListPrivilegie.tsx
Normal file
27
src/pages/Setting/ListPrivilegie.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import { Typography } from "@mui/material";
|
||||
import { СardPrivilegie } from "./CardPrivilegie";
|
||||
import { usePrivilegeStore } from "@root/stores/privilegesStore";
|
||||
|
||||
export default function ListPrivilegie() {
|
||||
const privileges = usePrivilegeStore().privileges;
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
{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}
|
||||
/>
|
||||
))
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -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) =>
|
||||
<path
|
||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||
stroke="#7E2AEA"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
@ -113,15 +113,15 @@ export const PrivilegiesWrapper = ({ text, sx, result }: CustomWrapperProps) =>
|
||||
<path
|
||||
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
|
||||
stroke="#fe9903"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
{/* {isExpanded && <ListPrivilegie />} */}
|
||||
{isExpanded && <ListPrivilegie />}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@ -281,4 +281,4 @@ export default function CreateDiscount() {
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -22,7 +22,6 @@ export default function ServiceUsersDG({ handleSelectionChange, users }: Props)
|
||||
if (!users) {
|
||||
return <Skeleton>Loading...</Skeleton>;
|
||||
}
|
||||
console.log(users)
|
||||
const gridData = users.users.map((user:any) => ({
|
||||
login: user.login,
|
||||
email: user.email,
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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<string>("");
|
||||
const [amountField, setAmountField] = useState<string>("");
|
||||
const [customPriceField, setCustomPriceField] = useState<string>("");
|
||||
const [privilegeIdField, setPrivilegeIdField] = useState<string>("");
|
||||
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 (
|
||||
<Container
|
||||
@ -153,15 +155,14 @@ export default function CreateTariff() {
|
||||
}}
|
||||
inputProps={{ sx: { pt: "12px" } }}
|
||||
>
|
||||
{/* {mergedPrivileges.map((privilege) => (
|
||||
<MenuItem key={privilege.description} value={privilege.privilegeId}>
|
||||
{privileges.map((privilege) => (
|
||||
<MenuItem key={privilege.description} value={privilege.id}>
|
||||
{privilege.description}
|
||||
</MenuItem>
|
||||
))} */}
|
||||
))}
|
||||
</Select>
|
||||
|
||||
</FormControl>
|
||||
{/* {privilege && (
|
||||
{privilege && (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
@ -181,7 +182,7 @@ export default function CreateTariff() {
|
||||
Стандартная цена за единицу: <span>{privilege.price}</span>
|
||||
</Typography>
|
||||
</Box>
|
||||
)} */}
|
||||
)}
|
||||
<CustomTextField
|
||||
id="tariff-name"
|
||||
label="Название тарифа"
|
||||
@ -203,16 +204,9 @@ export default function CreateTariff() {
|
||||
type="number"
|
||||
/>
|
||||
<Button
|
||||
// onClick={() => {
|
||||
// const privilege = findPrivilegeById(privilegeIdField);
|
||||
// if (true) {
|
||||
// //тариф создан на основе привилегии из БЕКЕНДА
|
||||
// createTariff();
|
||||
// } else {
|
||||
// //тариф создан на основе привилегии из ФРОНТА
|
||||
// handleCreateTariffClick();
|
||||
// }
|
||||
// }}
|
||||
onClick={() => {
|
||||
createTariffBackend()
|
||||
}}
|
||||
>
|
||||
Создать
|
||||
</Button>
|
||||
|
||||
@ -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 <Modal
|
||||
open={open}
|
||||
@ -87,9 +86,9 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
||||
Редактирование тариффа
|
||||
</Typography>
|
||||
|
||||
{tariff !== undefined && (
|
||||
{currentTariff !== undefined && (
|
||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
||||
<Typography>Название Тарифа: {tariff.name}</Typography>
|
||||
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
||||
<TextField
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
label="Имя"
|
||||
@ -97,7 +96,7 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
||||
value={name}
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Typography>Цена за единицу: {tariff.pricePerUnit}</Typography>
|
||||
<Typography>Цена за единицу: {currentTariff.pricePerUnit}</Typography>
|
||||
<TextField
|
||||
onChange={(event) => setPrice(event.target.value)}
|
||||
label="Цена за единицу"
|
||||
@ -106,31 +105,41 @@ export default function EditModal({tariff, getTariffs}:Props) {
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Button onClick={() => {
|
||||
if (tariff.privilege.length) {
|
||||
let privelege = tariff.privilege[0]
|
||||
if (!currentTariff.isFront) {
|
||||
const privilege = findPrivilegeById(currentTariff.privilegeId);
|
||||
privilege.privilegeId = privilege.id
|
||||
console.log(privilege)
|
||||
|
||||
mergedPrivileges.forEach((p:any) => {
|
||||
if (privelege.privilegeId == p.privilegeId) tariff.privilege[0].privilegeId = p._id
|
||||
})
|
||||
|
||||
//back
|
||||
editTariff({
|
||||
tarifIid: tariff.id,
|
||||
tariffName: name ? name : tariff.name,
|
||||
tariffPrice: price ? Number(price) : tariff.privilege[0].price,
|
||||
privilege: privelege,
|
||||
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)
|
||||
getTariffs()
|
||||
})
|
||||
requestTariffs()
|
||||
})} else {
|
||||
enqueueSnackbar(`Привилегия с id ${currentTariff.privilegeId} не найдена в тарифе ${currentTariff.name} с id ${currentTariff.id}`)
|
||||
}
|
||||
} else {//front/store
|
||||
|
||||
let array = tariffs
|
||||
let index
|
||||
tariffs.forEach((p:any, i:number) => {
|
||||
if (tariff.id == p.id) index = i
|
||||
if (currentTariff.id == p.id) index = i
|
||||
})
|
||||
if (index !== undefined) {
|
||||
array[index].name = name
|
||||
|
||||
@ -2,18 +2,20 @@ 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 },
|
||||
{ field: "name", headerName: "Привилегия", width: 150 },
|
||||
{ field: "id", headerName: "id", width: 150 },
|
||||
{ field: "name", headerName: "Привелегия", width: 150 },
|
||||
{ field: "description", headerName: "Описание", width: 550 }, //инфо из гитлаба.
|
||||
{ field: "type", headerName: "Тип", width: 150 },
|
||||
{ field: "price", headerName: "Стоимость", width: 100 },
|
||||
];
|
||||
|
||||
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
|
||||
))
|
||||
|
||||
@ -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,7 @@ export default function Tariffs() {
|
||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>([]);
|
||||
|
||||
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();
|
||||
|
||||
}, []);
|
||||
|
||||
|
||||
return (
|
||||
<Container
|
||||
@ -110,7 +55,6 @@ export default function Tariffs() {
|
||||
<TariffsDG
|
||||
selectedTariffs={selectedTariffs}
|
||||
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
|
||||
getTariffs={getTariffs}
|
||||
/>
|
||||
|
||||
<Cart selectedTariffs={selectedTariffs} />
|
||||
|
||||
@ -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,88 +17,38 @@ 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) {
|
||||
const { token } = authStore();
|
||||
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
|
||||
export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) {
|
||||
const tariffs = Object.values(useTariffStore().tariffs)
|
||||
const [deletedRows, setDeletedRows] = useState<string[]>([]);
|
||||
const [openDeleteModal, setOpenDeleteModal] = useState(false);
|
||||
const [changingTariff, setChangingTariff] = useState<Tariff_FRONTEND | undefined>();
|
||||
const [errorDelete, setErrorDelete] = useState(false);
|
||||
const [changingTariff, setChangingTariff] = useState<Tariff | undefined>();
|
||||
const [tariffDelete, setTariffDelete] = 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 closeDeleteModal = () => {
|
||||
setOpenDeleteModal(false)
|
||||
}
|
||||
|
||||
const columns: GridColDef[] = [
|
||||
{ field: "id", headerName: "ID", width: 100 },
|
||||
{
|
||||
field: "edit",
|
||||
headerName: "Изменение",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton onClick={() => setChangingTariff(row)}>
|
||||
<ModeEditOutlineOutlinedIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ field: "name", headerName: "Название тарифа", width: 150 },
|
||||
{ field: "amount", headerName: "Количество", width: 110 },
|
||||
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
|
||||
@ -115,7 +65,7 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
||||
return (
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
tariffDeleteDataGrid(row.id);
|
||||
setOpenDeleteModal(row.id);
|
||||
}}
|
||||
>
|
||||
<BackspaceIcon />
|
||||
@ -123,42 +73,47 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
field: "edit",
|
||||
headerName: "Изменение",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
// console.log(row)
|
||||
return (
|
||||
<IconButton onClick={() => setChangingTariff(row)}>
|
||||
<ModeEditOutlineOutlinedIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]);
|
||||
// const selectedTariffPrivilege = selectedTariff ? selectedTariff.privilege : [];
|
||||
|
||||
const allName = () => {
|
||||
const selectedNames = [];
|
||||
const gridData = tariffs
|
||||
?.map((tariff) => {
|
||||
const privilege = findPrivilegeById(tariff.privilegeId);
|
||||
console.log(tariff.privilegeId)
|
||||
console.log(privilege)
|
||||
return {
|
||||
id: tariff.id,
|
||||
name: tariff.name,
|
||||
serviceName: privilege?.serviceKey == "templategen" ? "Шаблонизатор" : 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"
|
||||
? "день"
|
||||
: "шт.",
|
||||
customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
|
||||
total: tariff.amount
|
||||
? (tariff.amount *
|
||||
(tariff.isCustom
|
||||
? tariff.customPricePerUnit || 0 * tariff.amount
|
||||
: findPrivilegeById(tariff.privilegeId)?.price || 0)) /
|
||||
100
|
||||
: 0,
|
||||
};
|
||||
})
|
||||
.sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
return selectedNames;
|
||||
};
|
||||
console.log(gridData)
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
checkboxSelection={true}
|
||||
rows={tariffs}
|
||||
rows={gridData}
|
||||
columns={columns}
|
||||
getRowId={(row) => row.id}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
@ -173,18 +128,14 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange, getT
|
||||
) : (
|
||||
<React.Fragment />
|
||||
)}
|
||||
{/* <DeleteModal
|
||||
tariffDelete={tariffDelete}
|
||||
errorDelete={errorDelete}
|
||||
tariffId={selectedTariffs}
|
||||
tariffName={allName()}
|
||||
<DeleteModal
|
||||
open={openDeleteModal}
|
||||
handleClose={() => {
|
||||
setOpenDeleteModal(false);
|
||||
closeDeleteModal();
|
||||
}}
|
||||
/> */}
|
||||
{console.log(changingTariff)}
|
||||
<EditModal tariff={changingTariff} getTariffs={getTariffs} />
|
||||
selectedTariffs={selectedTariffs}
|
||||
/>
|
||||
<EditModal tariff={changingTariff}/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@ -10,8 +10,15 @@ import ModalAdmin from "./ModalAdmin";
|
||||
import ModalUser from "./ModalUser";
|
||||
import ModalEntities from "./ModalEntities";
|
||||
import {useMatch} from "react-router-dom";
|
||||
import {useRefreshPrivilegesStore} from "@root/hooks/useRefreshPrivilegesStore.hook"
|
||||
import { useGetTariffs } from "@root/hooks/useGetTariffs.hook";
|
||||
|
||||
export default () => {
|
||||
useRefreshPrivilegesStore()
|
||||
const {requestTariffs} = useGetTariffs()
|
||||
React.useEffect(() => {
|
||||
requestTariffs()
|
||||
},[])
|
||||
const theme = useTheme()
|
||||
return (
|
||||
<React.Fragment>
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
import { Privilege } from "@root/model/tariff";
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { RealPrivilege } from "@root/model/privilege";
|
||||
import { exampleCartValues } from "./mocks/exampleCartValues";
|
||||
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
||||
|
||||
interface RealPrivilegeStore {
|
||||
privileges: RealPrivilege[];
|
||||
interface PrivilegeStore {
|
||||
privileges: mergedBackFrontPrivilege[];
|
||||
}
|
||||
|
||||
export const usePrivilegeStore = create<RealPrivilegeStore>()(
|
||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
privileges: [],
|
||||
@ -17,8 +19,9 @@ export const usePrivilegeStore = create<RealPrivilegeStore>()(
|
||||
)
|
||||
);
|
||||
|
||||
export const resetPrivilegeArray = (privileges: RealPrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||
|
||||
|
||||
export const findPrivilegeById = (privilegeId: string) => {
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null;
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege.id === privilegeId || privilege.privilegeId === privilegeId) ?? null;
|
||||
};
|
||||
|
||||
39
src/stores/tariffsStore.ts
Normal file
39
src/stores/tariffsStore.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
|
||||
|
||||
interface TariffStore {
|
||||
tariffs: Record<string, Tariff>
|
||||
}
|
||||
|
||||
export const useTariffStore = create<TariffStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
tariffs: {},
|
||||
}),
|
||||
{
|
||||
name: "Tariff store",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
|
||||
export const updateTariffs = (newTariffs: Record<string, Tariff>) => {
|
||||
useTariffStore.setState((state) => ({
|
||||
tariffs: {...state.tariffs, ...newTariffs},
|
||||
}));
|
||||
};
|
||||
|
||||
export const deleteTariffs = (tariffId: string) => {
|
||||
let tariffs = useTariffStore.getState().tariffs
|
||||
delete tariffs[tariffId]
|
||||
useTariffStore.setState(() => ({tariffs: tariffs}));
|
||||
};
|
||||
|
||||
export const resetTariffsStore = (newTariffs: Record<string, Tariff>) => {
|
||||
useTariffStore.setState(() => ({tariffs: {}}));
|
||||
console.log(newTariffs)
|
||||
useTariffStore.setState(() => ({tariffs: newTariffs}));
|
||||
};
|
||||
@ -19,10 +19,8 @@ export default function usePrivileges({ onError, onNewPrivileges }: {
|
||||
bearer: true,
|
||||
signal: controller.signal,
|
||||
}).then(result => {
|
||||
console.log("New privileges", result);
|
||||
onNewPrivileges(result);
|
||||
}).catch(error => {
|
||||
console.log("Error fetching privileges", error);
|
||||
onError?.(error);
|
||||
});
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user