adminFront/src/pages/dashboard/Content/Tariffs/tariffsDG.tsx

207 lines
6.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React from "react";
import { useEffect, useState } from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
import { Box, Button, IconButton } from "@mui/material";
import BackspaceIcon from "@mui/icons-material/Backspace";
import { enqueueSnackbar } from "notistack";
import DataGrid from "@kitUI/datagrid";
import { deleteTariffs, useTariffStore } from "@root/stores/tariffs";
import { SERVICE_LIST } from "@root/model/tariff";
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({ 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 ?? [])];
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 tariffDelete = async (tarifIid: string) => {
try {
await axios({
method: "delete",
url: "https://admin.pena.digital/strator/tariff",
headers: {
Authorization: `Bearer ${token}`,
},
data: { id: tarifIid },
});
setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]);
} catch (error: any) {
setErrorDelete(true);
enqueueSnackbar(error.message);
}
};
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("Ошибка получения тарифов");
}
};
axiosTariffs();
}, [deletedRows]);
const columns: GridColDef[] = [
{ field: "id", headerName: "ID", width: 100 },
{ field: "name", headerName: "Название тарифа", width: 150 },
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
{ field: "privilege", headerName: "Привелегия", width: 150 },
{ field: "amount", headerName: "Количество", width: 110 },
{ field: "type", headerName: "Единица", width: 100 },
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
{ field: "isCustomPrice", headerName: "Кастомная цена", width: 130 },
{ field: "total", headerName: "Сумма", width: 60 },
{ field: "isDeleted", headerName: "isDeleted", width: 60 },
{
field: "delete",
headerName: "Удаление",
width: 60,
renderCell: ({ row }) => {
return (
<IconButton
onClick={() => {
tariffDelete(row.id);
}}
>
<BackspaceIcon />
</IconButton>
);
},
},
];
const gridData = mergeTariffs.map(
(tariff: {
_id: string;
id: string;
name: string;
privilegeId: string;
amount: number;
price: number;
isDeleted: boolean;
customPricePerUnit: number;
}) => ({
id: tariff._id ? tariff._id : tariff.id,
name: tariff.name,
serviceName: SERVICE_LIST.find(
(service) => service.serviceKey === findPrivilegeById(tariff.privilegeId)?.serviceKey
)?.displayName,
privilege: `(${tariff.privilegeId}) ${
findPrivilegeById(tariff.privilegeId)?.description ?? "Привилегия не найдена"
}`,
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,
})
);
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}
/>
{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)}
/>
</>
);
}