import React, { useEffect, useState } from "react";
import { LicenseInfo } from "@mui/x-license-pro";
import DetailsIcon from "@mui/icons-material/Details";
import DeleteDialog from "@/components/common/DeleteAlert/DeleteDialog";
import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import {
SellerCatgoryThName,
SellerCatgoryValue,
BoxText,
SellerCatgoryStatus,
CategoryTable,
ParentCategoryBox,
MainBox,
MainBox1,
SecondSkeletonBox,
MainBox3,
} from "./styles";
import { ProfileHeader } from "../common/profileheader";
import { apiClient, getPermission } from "../common/common";
import Auth from "@/auth/Auth";
LicenseInfo.setLicenseKey(
"e25aea50a43f724c2a50c717a29c3f54Tz01MDc2NixFPTE2OTQ2OTY3MTk4MjUsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI="
);
import * as Yup from "yup";
import { Box, Skeleton, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tooltip, Typography, Grid, Drawer } from "@mui/material";
import PropTypes from "prop-types";
import Tabs from "@mui/material/Tabs";
import {
Mainbox,
Tabtext,
SelectedCategories,
DeletSelected,
DeleteIcon,
Categories,
Header1,
} from "./styles";
import { DataGridPro } from "@mui/x-data-grid-pro";
import { DataGridStyle } from "../common/commonStyle";
import { useFormik } from "formik";
import ProductApplicationComponent from "./productApplicationComponent";
import ProductUseCaseComponent from "./productUseCase";
import { useSelector } from "react-redux";
import { LightTooltip } from "../common/Tooltip/tooltip";
import { IconsStyle } from "../CompanySettings/CompanyDetail/commonStyles";
import Image from "next/image";
import MyCategorySkeleton from "./MyCategorySkeleton";
import { Redoutlinebtn } from "../common/buttons/ButtonsVariations";
import { fetchCatelogue } from "@/hooks/UseProductListContext";
import AddBrand from "./AddCategory";
function CustomTabPanel(props) {
const { children, value, index, ...other } = props;
return (
{value === index && (
{children}
)}
);
}
CustomTabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.number.isRequired,
value: PropTypes.number.isRequired,
};
export default function MyCategory() {
const [newCategory, setNewCategory] = useState([]);
const [addMore, setAddMore] = useState("");
const { role } = useSelector((state) => state.userData);
const [state, setState] = React.useState({
top: false,
left: false,
bottom: false,
right: false,
});
const toggleDrawer = (anchor, open) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setState({ ...state, [anchor]: open });
};
const list = (anchor) => (
);
let List = [1, 2, 3, 4, 5];
const columns = [
{
field: "serialNo",
headerName: "Sr. No.",
minWidth: 100,
flex: 0.5,
renderCell: (params) => {
const rowIndex = params.rowIndex;
const serialNumber = rowIndex + 1;
return (
<>
{categoryList.length}
>
);
},
},
{
field: "id",
headerName: "Id",
minWidth: 60,
flex: 1,
sortable: false,
filterable: false,
disableColumnMenu: true,
renderHeader: (params) => {
return (
{params?.colDef?.headerName}
);
},
renderCell: (cellValues) => {
return (
<>
{cellValues?.row?.id}
>
);
},
},
{
field: "sector",
headerName: "Sector",
minWidth: 200,
flex: 1,
sortable: false,
filterable: false,
disableColumnMenu: true,
renderHeader: (params) => {
return (
{params?.colDef?.headerName}
);
},
renderCell: (cellValues) => {
let newParent = extractDataRecursive(cellValues?.row)
?.reverse()
?.find((ele) => ele.parent_name == null);
return (
<>
{newParent?.name}
>
);
},
},
{
field: "parent_id",
headerName: "Parent Category",
minWidth: 500,
flex: 1,
sortable: false,
filterable: false,
disableColumnMenu: true,
renderHeader: (params) => {
return (
{params?.colDef?.headerName}
);
},
renderCell: (cellValues) => {
let newParent = extractDataRecursive(cellValues?.row)?.reverse();
return (
{newParent?.length > 0 &&
newParent?.map(
(ele, index) =>
ele?.parent_name != null && (
<>
{ele?.name}
{index !== newParent.length - 1 && (
)}
>
)
)}
);
},
},
{
field: "approval_status",
headerName: "Status",
minWidth: 100,
flex: 1,
sortable: false,
filterable: false,
disableColumnMenu: true,
renderHeader: (params) => {
return (
{params?.colDef?.headerName}
);
},
renderCell: (cellValues) => {
return (
<>
{cellValues?.row?.approval_status == 0 ? (
Pending
) : cellValues?.row?.approval_status == 1 ? (
Approved
) : (
Rejected
)}
>
);
},
},
{
field: "action",
headerName: "Action",
width: 80,
sortable: false,
filterable: false,
disableColumnMenu: true,
renderHeader: (params) => {
return (
{params?.colDef?.headerName}
);
},
renderCell: (cellValues) => {
return (
<>
{(role == "seller" ||
(role == "subuser" && getPermission("Category", "Edit"))) && (
{
setState({ ...state, right: true });
setEditColumn(params.row);
setAddMore("edit");
}}
/>
)}
{(role == "seller" ||
(role == "subuser" &&
getPermission("Category", "Delete"))) && (
{
setOpenDialog(true);
setMultipleDeleteID([cellValues?.id]);
}}
style={{
width: "21px",
height: "20px",
color: "#DD484E",
zIndex: "9999",
"& .MuiSvgIcon-root": {
marginTop: "10px",
}
}}
/>
)}
>
);
},
},
];
const [multipleDeleteID, setMultipleDeleteID] = useState([]);
const [categoryName, setCategoryName] = useState([]);
const [pendingList, setPendingList] = useState([]);
const [productList, setProductList] = useState([]);
const [categoryList, setCategoryList] = useState([]);
const [value, setValue] = React.useState(0);
const [renderComponent, setRenderComponent] = React.useState(false);
const [openDialog, setOpenDialog] = React.useState(false);
const [loader, setLoader] = React.useState(false);
const [errorText, setErrorText] = useState([]);
const handleChange = (even, newValue) => {
setValue(newValue);
};
const PendingCategoryList = async () => {
let response = await apiClient("category/pending_approval", "get");
if (response.status == 201) {
setPendingList(response.data);
}
};
const UseCasesList = async () => {
let response = await apiClient("use_cases/list", "get");
if (response.status == 200) {
setProductList(response.data);
}
};
useEffect(() => {
setRenderComponent(true);
PendingCategoryList();
getCategoryList();
UseCasesList();
}, []);
const [description, setDescription] = useState("");
const handleDescriptionChange = (event) => {
const newValue = event.target.value;
setDescription(newValue);
};
const [category, setCategory] = useState();
const [useCase, setRelateduseCase] = useState();
const [keywords, setKeywords] = useState();
const [productname, setProductName] = useState();
const handleCategory = (event, values) => {
setCategory(values);
};
const validation = Yup.object().shape({
productname: Yup.string().required("Please enter product name"),
description: Yup.string().required("Please enter description"),
});
const formik = useFormik({
enableReinitialize: true,
validationSchema: validation,
validateOnBlur: true,
validateOnChange: true,
initialValues: {
productname: productname,
description: description,
},
onSubmit: async (values) => {
const { productname, description } = values;
let payload = {
name: productname,
related_categories: category,
related_use_cases: useCase,
keywords: keywords,
description: description,
type: "product application",
};
setLoader(true);
const response = await apiClient("use_cases/create", "post", {
body: payload,
});
if (response.status === true || response.status == 200) {
}
},
});
const getCategoryList = async (parentId = 0, level = 0, type = "new") => {
setLoader(true);
let response = await apiClient("category/list", "post", {
body: { fetch: "all", parent: parentId, user_id: Auth?.userData()?.id },
});
if (response.status === 200) {
setLoader(false);
if (type === "update") {
let index = categoryList.findIndex((v) => v.level === level);
let list = [...categoryList];
list[index] = { level, data: response.data, parentId };
setCategoryList(list);
let selectedValue = response.data.find(
(v) => (v.name = newCategory[level - 1])
);
if (selectedValue) {
SelectedOptionHandler(selectedValue.id, level, selectedValue.name);
}
setNewCategory([]);
return;
} else {
let listExist = categoryList.filter((v) => v.level <= level);
let updateList = [
...listExist,
{ level: level + 1, data: response.data, parentId },
];
setCategoryList(updateList);
}
return response;
}
};
const deleteAfterC = (arr, index) => {
if (index !== -1) {
arr.splice(index + 1);
}
return arr;
};
const handleOptionChange = (event, newValue, index, level) => {
setCategoryName((prev) => {
let name = deleteAfterC([...prev], index);
name[index] = newValue;
return name;
});
if (newValue) {
setErrorText([]);
getCategoryList(newValue.value, level);
}
};
const DeleteActionHandler = async () => {
setLoader(true);
await apiClient("category/delete", "post", {
body: { id: multipleDeleteID },
});
setLoader(false);
setOpenDialog(false);
PendingCategoryList();
getCategoryList();
};
const createNewCategory = async (index, level) => {
if (newCategory[index]) {
let index = categoryName.findIndex((v) => v.value == "new");
let parentIndex = index <= 0 ? 0 : index - 1;
let response = await apiClient("category/create", "post", {
body: {
parent_id: level > 1 ? categoryName[parentIndex].value : 0,
name: newCategory[index],
user_id: `${Auth?.userData()?.id}`,
},
});
if (response.status === 200) {
let list = [...categoryList];
list[index].data = [
...list[index].data,
{
icon: "",
id: response.data,
level: 0,
name: response.name,
parent_id: 0,
parent_name: "",
},
];
let indexCheck = categoryList.findIndex((v) => v.level == level + 1);
if (indexCheck < 0) {
setCategoryList([
...list,
{ level: level + 1, data: [], parentId: response.data },
]);
} else {
setCategoryList(list);
}
setCategoryName((prev) => {
let name = [...prev];
name[index].value = response.data;
return name;
});
setNewCategory([]);
PendingCategoryList();
} else {
setErrorText((prev) => {
let error = [...prev];
error[index] = response.message[0];
return error;
});
}
}
};
function CustomTabPanel(props) {
const { children, value, index, ...other } = props;
return (
{value === index && (
{children}
)}
);
}
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
"aria-controls": `simple-tabpanel-${index}`,
};
}
const [value1, setValue1] = React.useState(0);
const handleChange1 = (event, newValue) => {
setValue1(newValue);
};
function extractParentNames(obj, result = []) {
if (obj && typeof obj === "object") {
if (obj.parent_name !== null) {
result.push(obj.parent_name);
}
for (let key in obj) {
extractParentNames(obj[key], result);
}
}
return result;
}
function extractDataRecursive(data, result = []) {
if (data && typeof data === "object") {
result.push({
id: data.id,
name: data.name,
parent_id: data.parent_id,
parent_name: data.parent_name,
icon: data.icon,
});
if (data.children_recursive) {
extractDataRecursive(data.children_recursive, result);
}
}
return result;
}
return (
<>
{openDialog && (
)}
{['left', 'right', 'top', 'bottom'].map((anchor) => (
Add Categories
{list(anchor)}
))}
{renderComponent ? (
{(role == "seller" ||
(role == "subuser" &&
getPermission("Category", "View"))) && (
)}
{(role == "seller" ||
(role == "subuser" &&
getPermission("Product Application", "View"))) && (
)}
{(role == "seller" ||
(role == "subuser" &&
getPermission("Product Use Cases", "View"))) && (
)}
{(role == "seller" ||
(role == "subuser" && getPermission("Category", "View"))) && (
{multipleDeleteID.length > 0 && (
Selected Categories ({multipleDeleteID.length})
{
e.stopPropagation();
setOpenDialog(true);
}}
>
Delete Selected
)}
{loader ? (
) : (
setMultipleDeleteID(newSelectionModel)
}
loading={loader}
localeText={{
columnMenuShowColumns: "Manage Columns",
}}
rows={categoryList?.[0]?.data || []}
selectionModel={multipleDeleteID}
columns={columns}
rowHeight={40}
pagination
pageSize={10}
initialState={{
pagination: {
paginationModel: { page: 0, pageSize: 5 },
},
}}
pageSizeOptions={[5, 10]}
checkboxSelection
/>
)}
)}
{(role == "seller" ||
(role == "subuser" && getPermission("Product Application", "View"))) && (
)}
{(role == "seller" ||
(role == "subuser" && getPermission("Product Use Cases", "View"))) && (
)}
) : (
"loading"
)}
>
);
}