This commit is contained in:
Nastya 2023-06-15 17:25:59 +03:00
parent da04d31591
commit b7f06fcf28
11 changed files with 298 additions and 237 deletions

@ -96,9 +96,13 @@ export default function Cart({ selectedTariffs }: Props) {
</Box>
);
function handleCalcCartClick() {
function handleCalcCartClick() { //рассчитать
const cartTariffs = tariffs.filter((tariff) => selectedTariffs.includes(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);
@ -106,6 +110,12 @@ 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,10 +38,12 @@ export function calcCartData({
};
cartItems.forEach((cartItem) => {
console.log(cartItem.tariff.privilegeId)
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
console.log(privilege)
if (!privilege)
throw new Error(
`Привилегия с id ${cartItem.tariff} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`
`Привилегия с id ${cartItem.tariff.privilegeId} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`
);
if (cartItem.tariff.customPricePerUnit === undefined)

@ -1,116 +0,0 @@
import React, { useState } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Modal from "@mui/material/Modal";
import TextField from "@mui/material/TextField";
interface Privilege {
name: string;
privilegeId: string;
serviceKey: string;
amount: number;
description: string;
price: number;
type: string;
value: string;
updatedAt: string;
_id: string;
}
type EditModalProps = {
open: boolean;
handleClose: () => void;
errorEdit: boolean;
tariffEdit: (tarifIid: string, tariffName: string, tariffPrice: string, privilege: Privilege) => Promise<void>;
selectedTariffPrivilege: string | Privilege[];
tariff?:
| {
id: string;
name: string;
serviceName: "Шаблонизатор документов" | "Опросник" | "Аналитика сокращателя" | undefined;
privilege: string | Privilege[];
amount: number | undefined;
type?: string;
value?: string;
pricePerUnit: number | undefined;
total: number;
}
| undefined;
};
export default function EditModal({
open,
handleClose,
errorEdit,
tariffEdit,
tariff,
selectedTariffPrivilege,
}: EditModalProps) {
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const [privilege] = selectedTariffPrivilege as Privilege[];
const updateTariffDetails = () => {
if (!tariff || errorEdit) {
return;
}
tariffEdit(tariff.id, name, price, privilege);
handleClose();
};
return (
<div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Typography id="modal-modal-title" variant="h6" component="h2" sx={{ whiteSpace: "nowrap" }}>
Редактирование тариффа
</Typography>
{tariff && (
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
<Typography>Название Тарифа: {tariff.name}</Typography>
<TextField
onChange={(event) => setName(event.target.value)}
label="Имя"
name="name"
value={name}
sx={{ marginBottom: "10px" }}
/>
<Typography>Цена за единицу: {tariff.pricePerUnit}</Typography>
<TextField
onChange={(event) => setPrice(event.target.value)}
label="Цена за единицу"
name="price"
value={price}
sx={{ marginBottom: "10px" }}
/>
<Button onClick={() => updateTariffDetails()}>Редактировать</Button>
</Box>
)}
</Box>
</Modal>
</div>
);
}

@ -36,4 +36,5 @@ export interface Tariff {
amount: number;
/** Кастомная цена, если есть, то используется вместо privilege.price */
customPricePerUnit?: number;
isFront?: boolean
}

@ -37,7 +37,7 @@ export default function CreateTariff() {
enqueueSnackbar("Пустое кол-во едениц привилегия");
}
if (privilegeIdField === "") {
enqueueSnackbar("Невыбрана привилегия");
enqueueSnackbar("Не выбрана привилегия");
}
const amount = Number(amountField);
@ -48,13 +48,14 @@ export default function CreateTariff() {
const newTariff: Tariff = {
id: nanoid(5),
name: nameField,
amount,
amount:amount,
isFront: true,
privilegeId: privilege.privilegeId,
customPricePerUnit: customPrice ? customPrice / amount : undefined,
};
addTariffs([newTariff]);
}
const createTariff = async () => {
@ -90,7 +91,7 @@ export default function CreateTariff() {
type: privilege.type,
value: privilege.value,
price: privilege.price,
amount: amountField,
amount: Number(amountField),
},
],
},
@ -210,10 +211,17 @@ export default function CreateTariff() {
/>
<Button
onClick={() => {
handleCreateTariffClick();
const privilege = findPrivilegeById(privilegeIdField);
if (true) {
//тариф создан на основе привилегии из БЕКЕНДА
createTariff();
} else {
//тариф создан на основе привилегии из ФРОНТА
handleCreateTariffClick();
}
}}
>
Создать
</Button>
</Container>

@ -0,0 +1,151 @@
import React, { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Modal from "@mui/material/Modal";
import TextField from "@mui/material/TextField";
import axios from "axios";
import { authStore } from "@root/stores/auth";
import {TariffDG, Privilege} from "./types"
import { findPrivilegeById } from "@root/stores/privileges";
import { mergedPrivilegeStore } from "@root/stores/mergedPrivileges";
import { useTariffStore, updateTariffs } from "@root/stores/tariffs";
import { arrayBuffer } from "stream/consumers";
interface EditProps {
tarifIid: string,
tariffName: string,
tariffPrice: number,
privilege: Privilege,
token: string
}
const editTariff = ({
tarifIid,
tariffName,
tariffPrice,
privilege,
token
}:EditProps): Promise<unknown> => {
return axios({
method: "put",
url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
headers: {
Authorization: `Bearer ${token}`,
},
data: {
name: tariffName,
price: tariffPrice,
isCustom: true,
privilegies: [privilege]
},
});
}
interface Props {
tariff: TariffDG | undefined,
getTariffs: () => void
}
export default function EditModal({tariff, getTariffs}: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);
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}
onClose={() => setOpen(false)}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Typography id="modal-modal-title" variant="h6" component="h2" sx={{ whiteSpace: "nowrap" }}>
Редактирование тариффа
</Typography>
{tariff !== undefined && (
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
<Typography>Название Тарифа: {tariff.name}</Typography>
<TextField
onChange={(event) => setName(event.target.value)}
label="Имя"
name="name"
value={name}
sx={{ marginBottom: "10px" }}
/>
<Typography>Цена за единицу: {tariff.pricePerUnit}</Typography>
<TextField
onChange={(event) => setPrice(event.target.value)}
label="Цена за единицу"
name="price"
value={price}
sx={{ marginBottom: "10px" }}
/>
<Button onClick={() => {
if (tariff.privilege.length) {
let privelege = tariff.privilege[0]
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,
token: token
})
.then(() => {
setOpen(false)
getTariffs()
})
} else {//front/store
let array = tariffs
let index
tariffs.forEach((p:any, i:number) => {
if (tariff.id == p.id) index = i
})
if (index !== undefined) {
array[index].name = name
array[index].amount = Number(price)
updateTariffs(array)
setOpen(false)
} else {
console.log("не нашел такой тариф в сторе")
}
}
}}>Редактировать</Button>
</Box>
)}
</Box>
</Modal>
}

@ -23,16 +23,24 @@ export default function Tariffs() {
}}
>
<Typography variant="h6">Список привелегий</Typography>
<Privileges />
<ChangePriceModal />
<CreateTariff />
<Typography variant="h6" mt="20px">
Список тарифов
</Typography>
<Typography variant="h6" mt="20px">Список тарифов</Typography>
<TariffsDG
selectedTariffs={selectedTariffs}
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
/>
<Cart selectedTariffs={selectedTariffs} />
</Container>
);

@ -15,26 +15,14 @@ import { findPrivilegeById } from "@root/stores/privileges";
import axios from "axios";
import { authStore } from "@root/stores/auth";
import DeleteModal from "@root/kitUI/DeleteModal";
import EditModal from "@root/kitUI/EditModal";
import EditModal from "./EditModal";
import {TariffDG, Privilege} from "./types"
interface Props {
selectedTariffs: GridSelectionModel;
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
}
interface Privilege {
name: string;
privilegeId: string;
serviceKey: string;
amount: number;
description: string;
price: number;
type: string;
value: string;
updatedAt: string;
_id: string;
}
interface MergedTariff {
_id: string;
id: string;
@ -48,52 +36,23 @@ interface MergedTariff {
amount?: number;
customPricePerUnit?: number;
privilegies: Privilege[];
isFront: boolean
}
export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) {
const { token } = authStore();
const exampleTariffs = useTariffStore((state) => state.tariffs);
const [tariffs, setTariffs] = useState<any>();
const [deletedRows, setDeletedRows] = useState<string[]>([]);
const [openDeleteModal, setOpenDeleteModal] = useState(false);
const [openEditModal, setOpenEditModal] = useState(false);
const { token } = authStore();
const [changedTariff, setChangedTariff] = useState<TariffDG | undefined>();
const [errorEdit, setErrorEdit] = useState(false);
const [errorDelete, setErrorDelete] = useState(false);
const mergeTariffs: MergedTariff[] = [...exampleTariffs, ...(tariffs?.tariffs ?? [])];
const tariffEdit = async (tarifIid: string, tariffName: string, tariffPrice: string, privilege: Privilege) => {
try {
await axios({
method: "put",
url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
headers: {
Authorization: `Bearer ${token}`,
},
data: {
name: tariffName,
price: tariffPrice,
isCustom: true,
privilegies: [
{
name: privilege.name,
privilegeId: privilege.privilegeId,
serviceKey: privilege.serviceKey,
description: privilege.description,
type: privilege.type,
value: privilege.value,
price: privilege.price,
amount: privilege.amount,
},
],
},
});
} catch (error: any) {
setErrorEdit(true);
enqueueSnackbar(error.message);
}
};
const mergeTariffs: MergedTariff[] = [...exampleTariffs, ...(tariffs || [])];
console.log("exampleTariffs")
console.log(exampleTariffs)
const tariffDeleteDataGrid = async (tarifIid: string) => {
if (exampleTariffs.find((tariff) => tariff.id === tarifIid)) {
@ -113,6 +72,7 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
});
setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]);
enqueueSnackbar("Тариф удалён");
getTariffs()
} catch (error: any) {
setErrorDelete(true);
enqueueSnackbar("Ошибка удаления :", error.message);
@ -149,27 +109,44 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
enqueueSnackbar(error.message);
}
}
getTariffs()
enqueueSnackbar(`Deleted: ${deleted.join(", ")}`);
enqueueSnackbar(`Not deleted: ${notDeleted.join(", ")}`);
};
useEffect(() => {
const axiosTariffs = async () => {
try {
const { data } = await axios({
method: "get",
url: "https://admin.pena.digital/strator/tariff",
});
setTariffs(data);
console.log(data);
} catch (error) {
enqueueSnackbar("Ошибка получения тарифов");
}
};
const getTariffs = () => {
axios({
method: "get",
url: "https://admin.pena.digital/strator/tariff",
})
.then((data:any) => {
setTariffs(data.data.tariffs)
axiosTariffs();
}, [deletedRows]);
// 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()
}, [])
const columns: GridColDef[] = [
{ field: "id", headerName: "ID", width: 100 },
@ -181,7 +158,6 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
{ field: "isCustomPrice", headerName: "Кастомная цена", width: 130 },
{ field: "total", headerName: "Сумма", width: 60 },
{ field: "isDeleted", headerName: "isDeleted", width: 60 },
{
field: "delete",
headerName: "Удаление",
@ -203,20 +179,12 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
headerName: "Изменение",
width: 60,
renderCell: ({ row }) => {
// console.log(row)
return (
<>
<IconButton onClick={() => setOpenEditModal(true)}>
<IconButton onClick={() => setChangedTariff(row)}>
<ModeEditOutlineOutlinedIcon />
</IconButton>
<EditModal
tariffEdit={tariffEdit}
errorEdit={errorEdit}
tariff={row}
selectedTariffPrivilege={row.pprivilege}
open={openEditModal}
handleClose={() => setOpenEditModal(false)}
/>
</>
);
},
},
@ -227,27 +195,35 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
return name[0];
};
const gridData = mergeTariffs.map((tariff) => ({
id: tariff._id ? tariff._id : tariff.id,
name: tariff.name,
serviceName: SERVICE_LIST.find(
(service) => service.serviceKey === findPrivilegeById(tariff.privilegeId)?.serviceKey
)?.displayName,
privilegeName: tariff.privilegies
? privilegiesName(tariff.privilegies)
: `(${tariff.privilegeId}) ${findPrivilegeById(tariff.privilegeId)?.description ?? "Привилегия не найдена"}`,
privilege: tariff.privilegies ? tariff.privilegies : [],
amount: tariff.amount,
type: findPrivilegeById(tariff.privilegeId)?.type === "count" ? "день" : "шт.",
pricePerUnit: tariff.customPricePerUnit
? tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price
: tariff.price,
isCustomPrice: tariff.customPricePerUnit === undefined ? "Нет" : "Да",
isDeleted: tariff.isDeleted,
total: tariff.amount
? tariff.amount * (tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price ?? 0)
: 0,
}));
console.log(mergeTariffs)
const gridData = mergeTariffs
.filter((tariff) => !tariff.isDeleted)
.map((tariff) => {
console.log(tariff)
return {
id: tariff._id ? tariff._id : tariff.id,
name: tariff.name,
serviceName: SERVICE_LIST.find(
(service) => service.serviceKey === findPrivilegeById(tariff.privilegeId)?.serviceKey
)?.displayName,
privilegeName: tariff.privilegies
? privilegiesName(tariff.privilegies)
: `(${tariff.privilegeId}) ${findPrivilegeById(tariff.privilegeId)?.description ?? "Привилегия не найдена"}`,
privilege: tariff.privilegies ? tariff.privilegies : [],
amount: tariff.amount,
type: findPrivilegeById(tariff.privilegeId)?.type === "count" ? "день" : "шт.",
pricePerUnit: tariff.customPricePerUnit
? tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price
: tariff.price,
isCustomPrice: tariff.customPricePerUnit === undefined ? "Нет" : "Да",
isDeleted: tariff.isDeleted,
total: tariff.amount
? tariff.amount * (tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price ?? 0)
: 0,
isFront: tariff.isFront ? tariff.isFront : false
}});
const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]);
const selectedTariffPrivilege = selectedTariff ? selectedTariff.privilege : [];
@ -265,6 +241,7 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
};
console.log(allName());
console.log(gridData);
return (
<>
@ -282,7 +259,6 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
<Button onClick={() => setOpenDeleteModal(true)} sx={{ mr: "20px", zIndex: "10000" }}>
Удаление
</Button>
<Button onClick={() => setOpenEditModal(true)}>Редактирование</Button>
</Box>
) : (
<React.Fragment />
@ -293,16 +269,10 @@ export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Pr
tariffId={selectedTariffs}
tariffName={allName()}
open={openDeleteModal}
handleClose={() => setOpenDeleteModal(false)}
/>
<EditModal
tariffEdit={tariffEdit}
errorEdit={errorEdit}
tariff={selectedTariff}
selectedTariffPrivilege={selectedTariffPrivilege}
open={openEditModal}
handleClose={() => setOpenEditModal(false)}
handleClose={() => {setOpenDeleteModal(false)}}
/>
{console.log(changedTariff)}
<EditModal tariff={changedTariff} getTariffs={getTariffs}/>
</>
);
}

@ -0,0 +1,23 @@
export interface TariffDG {
id: string;
name: string;
serviceName: "Шаблонизатор документов" | "Опросник" | "Аналитика сокращателя" | undefined;
privilege: Privilege[];
amount: number | undefined;
type?: string;
value?: string;
pricePerUnit: number | undefined;
total: number;
}
export interface Privilege {
name: string;
privilegeId: string;
serviceKey: string;
amount: number;
description: string;
price: number;
type: string;
value: string;
updatedAt: string;
_id: string;
}

@ -10,7 +10,8 @@ interface TariffStore {
export const useTariffStore = create<TariffStore>()(
persist(
(set, get) => ({
tariffs: exampleTariffs,
tariffs: [],
// tariffs: exampleTariffs,
}),
{
name: "Tariff store",
@ -21,6 +22,9 @@ export const useTariffStore = create<TariffStore>()(
export const addTariffs = (newTariffs: Tariff[]) =>
useTariffStore.setState((state) => ({ tariffs: [...state.tariffs, ...newTariffs] }));
export const updateTariffs = (newTariff: Tariff[]) =>
useTariffStore.setState((state) => ({ tariffs: newTariff }));
export const deleteTariffs = (tariffId: string) =>
useTariffStore.setState((state) => ({
tariffs: state.tariffs.filter((tariff) => tariff.id !== tariffId),

@ -8375,7 +8375,7 @@ mixin-deep@^1.2.0:
moment@^2.29.4:
version "2.29.4"
resolved "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.4.tgz#3dbe052889fe7c1b2ed966fcb3a77328964ef108"
integrity sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==
move-concurrently@^1.0.1: