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