удаление и редактирование тарифов в таблице

This commit is contained in:
ArtChaos189 2023-06-12 16:48:06 +03:00
parent f2437ce6a3
commit aeb6a879eb
5 changed files with 444 additions and 168 deletions

69
src/kitUI/DeleteModal.tsx Normal file

@ -0,0 +1,69 @@
import * as React 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";
type DeleteModalProps = {
open: boolean;
handleClose: () => void;
tariffDelete: (tarifIid: string) => Promise<void>;
errorDelete: boolean;
tariffId: string;
tariffName: string;
};
export default function DeleteModal({
open,
handleClose,
tariffDelete,
errorDelete,
tariffId,
tariffName,
}: DeleteModalProps) {
const onClickTariffDelete = () => {
if (errorDelete) {
return;
}
tariffDelete(tariffId);
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">
Вы уверены, что хотите удалить тариф
</Typography>
<Box
sx={{ mt: "20px", display: "flex", width: "332px", justifyContent: "space-between", alignItems: "center" }}
>
<Button onClick={() => onClickTariffDelete()} sx={{ width: "40px", height: "25px" }}>
Да
</Button>
<Typography>Тариф: {tariffName}</Typography>
</Box>
</Box>
</Modal>
</div>
);
}

99
src/kitUI/EditModal.tsx Normal file

@ -0,0 +1,99 @@
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";
type EditModalProps = {
open: boolean;
handleClose: () => void;
errorEdit: boolean;
tariffEdit: (tarifIid: string, tariffName: string, tariffPrice: string) => Promise<void>;
tariff:
| {
id: string;
name: string;
serviceName: "Шаблонизатор документов" | "Опросник" | "Аналитика сокращателя" | undefined;
privilege: string;
amount: number;
type: string;
pricePerUnit: number;
isCustomPrice: string;
isDeleted: boolean;
total: number;
}
| undefined;
};
export default function EditModal({ open, handleClose, errorEdit, tariffEdit, tariff }: EditModalProps) {
const [editOpen, setEditOpen] = useState(false);
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const updateTariffDetails = () => {
if (!tariff || errorEdit) {
return;
}
tariffEdit(tariff.id, name, price);
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>
<Button
onClick={() => setEditOpen(true)}
sx={{ width: "45px", height: "25px", mt: "20px", display: editOpen ? "none" : "" }}
>
да
</Button>
{editOpen && 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>
);
}

@ -1,165 +1,197 @@
import { Box, Button, styled, useTheme } from "@mui/material";
import { DataGrid, GridColDef, GridRowsProp, GridToolbar } from "@mui/x-data-grid";
import { findDiscountFactor, formatDiscountFactor } from "@root/kitUI/Cart/calc";
import { activateDiscounts, deactivateDiscounts, setSelectedDiscountIds, useDiscountStore } from "@root/stores/discounts";
import {
activateDiscounts,
deactivateDiscounts,
setSelectedDiscountIds,
useDiscountStore,
} from "@root/stores/discounts";
import axios from "axios";
import { enqueueSnackbar } from "notistack";
import { useEffect, useState } from "react";
const BoxButton = styled('div')(({ theme }) => ({
[theme.breakpoints.down(400)]: {
justifyContent: 'center'
},
const BoxButton = styled("div")(({ theme }) => ({
[theme.breakpoints.down(400)]: {
justifyContent: "center",
},
}));
const columns: GridColDef[] = [
{
field: "id",
headerName: "ID",
width: 70,
sortable: false,
},
{
field: "name",
headerName: "Название скидки",
width: 150,
sortable: false,
},
{
field: "description",
headerName: "Описание",
width: 120,
sortable: false,
},
{
field: "conditionType",
headerName: "Тип условия",
width: 120,
sortable: false,
},
{
field: "factor",
headerName: "Процент скидки",
width: 120,
sortable: false,
},
{
field: "value",
headerName: "Значение",
width: 120,
sortable: false,
},
{
field: "active",
headerName: "Активна",
width: 120,
sortable: false,
},
{
field: "id",
headerName: "ID",
width: 70,
sortable: false,
},
{
field: "name",
headerName: "Название скидки",
width: 150,
sortable: false,
},
{
field: "description",
headerName: "Описание",
width: 120,
sortable: false,
},
{
field: "conditionType",
headerName: "Тип условия",
width: 120,
sortable: false,
},
{
field: "factor",
headerName: "Процент скидки",
width: 120,
sortable: false,
},
{
field: "value",
headerName: "Значение",
width: 120,
sortable: false,
},
{
field: "active",
headerName: "Активна",
width: 120,
sortable: false,
},
];
export default function DiscountDataGrid() {
const theme = useTheme();
const discounts = useDiscountStore(state => state.discounts);
const selectedDiscountIds = useDiscountStore(state => state.selectedDiscountIds);
const theme = useTheme();
const discounts = useDiscountStore((state) => state.discounts);
const selectedDiscountIds = useDiscountStore((state) => state.selectedDiscountIds);
const discountsGridData: GridRowsProp = discounts.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 ??
"-";
const [discount, setDiscount] = useState();
return {
id: discount._id,
name: discount.name,
description: discount.description,
conditionType: discount.conditionType,
factor: formatDiscountFactor(findDiscountFactor(discount)),
active: discount.disabled ? "🚫" : "✅",
value,
};
});
useEffect(() => {
const axiosDiscount = async () => {
try {
const { data } = await axios({
method: "get",
url: "https://penahub.gitlab.yandexcloud.net/price/discount/all",
});
setDiscount(data);
console.log(data);
} catch (error) {
enqueueSnackbar("Ошибка получения скидок");
}
};
return (
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
<Box sx={{ height: 600 }}>
<DataGrid
checkboxSelection={true}
rows={discountsGridData}
columns={columns}
selectionModel={selectedDiscountIds}
onSelectionModelChange={setSelectedDiscountIds}
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none"
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main
},
"& .MuiButton-text": {
color: theme.palette.secondary.main
},
}}
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={deactivateDiscounts}
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={activateDiscounts}
sx={{
backgroundColor: theme.palette.menu.main,
width: "200px",
height: "48px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main
}
}}>
Активировать
</Button>
</BoxButton>
</Box>
</Box>
);
}
axiosDiscount();
}, []);
const discountsGridData: GridRowsProp = discounts.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,
};
});
return (
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
<Box sx={{ height: 600 }}>
<DataGrid
checkboxSelection={true}
rows={discountsGridData}
columns={columns}
selectionModel={selectedDiscountIds}
onSelectionModelChange={setSelectedDiscountIds}
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none",
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main,
},
"& .MuiButton-text": {
color: theme.palette.secondary.main,
},
}}
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={deactivateDiscounts}
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={activateDiscounts}
sx={{
backgroundColor: theme.palette.menu.main,
width: "200px",
height: "48px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Активировать
</Button>
</BoxButton>
</Box>
</Box>
);
}

@ -29,7 +29,10 @@ export default function Tariffs() {
<Typography variant="h6" mt="20px">
Список тарифов
</Typography>
<TariffsDG handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)} />
<TariffsDG
selectedTariffs={selectedTariffs}
handleSelectionChange={(selectionModel) => setSelectedTariffs(selectionModel)}
/>
<Cart selectedTariffs={selectedTariffs} />
</Container>
);

@ -1,6 +1,7 @@
import React from "react";
import { useEffect, useState } from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
import { IconButton } from "@mui/material";
import { Box, Button, IconButton } from "@mui/material";
import BackspaceIcon from "@mui/icons-material/Backspace";
import { enqueueSnackbar } from "notistack";
@ -12,22 +13,60 @@ 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";
interface Props {
selectedTariffs: GridSelectionModel;
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
}
export default function TariffsDG({ handleSelectionChange }: Props) {
export default function TariffsDG({ selectedTariffs, handleSelectionChange }: Props) {
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 [errorEdit, setErrorEdit] = useState(false);
const [errorDelete, setErrorDelete] = useState(false);
const mergeTariffs = [...exampleTariffs, ...(tariffs?.tariffs ?? [])];
console.log(mergeTariffs);
const tariffEdit = async (tarifIid: string, tariffName: string, tariffPrice: string) => {
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: "Количество попыток использования",
privilegeId: "507f1f77bcf86cd799439011",
serviceKey: "docx-templater-service",
description: "Количество попыток использования",
type: "count",
value: "200",
price: 12300,
amount: 300,
},
],
},
});
} catch (error: any) {
setErrorEdit(true);
enqueueSnackbar(error.message);
}
};
const tariffsDelete = async (tarifIid: string) => {
const tariffDelete = async (tarifIid: string) => {
try {
await axios({
method: "delete",
@ -38,8 +77,9 @@ export default function TariffsDG({ handleSelectionChange }: Props) {
data: { id: tarifIid },
});
setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]);
} catch (error) {
enqueueSnackbar("Ошибка удаления тарифов");
} catch (error: any) {
setErrorDelete(true);
enqueueSnackbar(error.message);
}
};
@ -79,7 +119,7 @@ export default function TariffsDG({ handleSelectionChange }: Props) {
return (
<IconButton
onClick={() => {
tariffsDelete(row.id);
tariffDelete(row.id);
}}
>
<BackspaceIcon />
@ -120,14 +160,47 @@ export default function TariffsDG({ handleSelectionChange }: Props) {
: 0,
})
);
const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]);
const selectedTariffName = selectedTariff ? selectedTariff.name : "";
console.log(selectedTariff);
return (
<DataGrid
checkboxSelection={true}
rows={gridData}
columns={columns}
getRowId={(row) => row.id}
components={{ Toolbar: GridToolbar }}
onSelectionModelChange={handleSelectionChange}
/>
<>
<DataGrid
checkboxSelection={true}
rows={gridData}
columns={columns}
getRowId={(row) => row.id}
components={{ Toolbar: GridToolbar }}
onSelectionModelChange={handleSelectionChange}
/>
{selectedTariffs.length ? (
<Box component="section" sx={{ width: "100%", display: "flex", justifyContent: "start", mb: "30px" }}>
<Button onClick={() => setOpenDeleteModal(true)} sx={{ mr: "20px" }}>
Удаление
</Button>
<Button onClick={() => setOpenEditModal(true)}>Редактирование</Button>
</Box>
) : (
<React.Fragment />
)}
<DeleteModal
tariffDelete={tariffDelete}
errorDelete={errorDelete}
tariffId={String(selectedTariffs[0])}
tariffName={selectedTariffName}
open={openDeleteModal}
handleClose={() => setOpenDeleteModal(false)}
/>
<EditModal
tariffEdit={tariffEdit}
errorEdit={errorEdit}
tariff={selectedTariff}
open={openEditModal}
handleClose={() => setOpenEditModal(false)}
/>
</>
);
}