import React, { useRef, useEffect, useState, useContext } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Table, Button, Form, Input, Tooltip, Modal } from 'antd'; import { read, utils } from 'xlsx'; import ExcelJS from 'exceljs'; import { emptyExcelData, excelDataSelector, excelFileSelector, excelFileErrorSelector, fileInputRefSelector, uploadExcel, } from '../../Features/ExcelUploadPage/ExcelUploadPage.js'; import '../../Components/Forms/main.scss'; import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx'; import { AiFillDelete } from 'react-icons/ai'; import upldimg from '../../Images/upldimg.png'; import { FiDelete, FiDownload } from 'react-icons/fi'; const allowedExcelTypes = [ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx 'application/vnd.ms-excel', // .xls ]; const ConfigExcel = ({ handleSubmit, CategoryNames, SubCatData }) => { const dispatch = useDispatch(); const fileInputRef = useRef(fileInputRefSelector); const excelData = useSelector(excelDataSelector); const excelFile = useSelector(excelFileSelector); const excelFileError = useSelector(excelFileErrorSelector); const [worksheet1, setWorksheet1] = useState(null); const [editdelete, seteditdelete] = useState(''); const [Datas, setDatas] = useState(); const [radioValue, setRadioValue] = useState('Category Name'); const [parcolumns, setparcolumns] = useState(); useEffect(() => { if (radioValue === 'Category Name') { setparcolumns([ { title: 'CATEGORY Name', dataIndex: 'CategoryName', key: 'CategoryName', editable: true, }, ]); } else if (radioValue === 'Sub-Category Name') { setparcolumns([ { title: 'CATEGORY Name', dataIndex: 'CategoryName', key: 'CategoryName', editable: true, }, { title: 'SUB-CATEGORY Name', dataIndex: 'SubCategoryName', key: 'SubCategoryName', editable: true, }, ]); } else if (radioValue === 'Brand Name') { setparcolumns([ { title: 'SUB-CATEGORY Name', dataIndex: 'SubCategoryName', key: 'SubCategoryName', editable: true, }, { title: 'BRAND Name', dataIndex: 'BrandName', key: 'BrandName', editable: true, }, ]); } }, [radioValue]); const handleTableChange = (pagination, filters, sorter) => { setCurrentPage(pagination.current); }; useEffect(() => { if (excelData && excelData?.length > 0) { let ExecelToJsConvertion = []; let slicedData = excelData?.slice(1); slicedData?.map((item, index) => { let convertedItem = { key: index, CategoryName: item?.['0'], TypeName: 'Product Category', }; if (radioValue === 'Category Name') { convertedItem = { ...convertedItem }; } else if (radioValue === 'Sub-Category Name') { convertedItem = { ...convertedItem, SubCategoryName: item?.['1'], TypeName: 'Product Sub-Category', }; } else if (radioValue === 'Brand Name') { convertedItem = { ...convertedItem, SubCategoryName: item?.['0'], BrandName: item?.['1'], TypeName: 'Product Brand', }; } ExecelToJsConvertion.push(convertedItem); }); setDatas(ExecelToJsConvertion); } }, [excelData, radioValue]); useEffect(() => { if (Datas) { handleSubmit(Datas); } }, [Datas, handleSubmit]); const handleFileUpload = (e) => { const file = e.target.files[0]; if (file) { const isAllowed = allowedExcelTypes.includes(file.type); if (!isAllowed) { Modal.error({ title: 'Invalid File Type', content: 'Only Excel files (.xls, .xlsx) are allowed.', }); handleCancelData(); } else { uploadAndProcessExcel(file); } } else { dispatch(emptyExcelData()); } }; const handleClick = () => { // Programmatically trigger the file input click event fileInputRef.current.click(); }; const uploadAndProcessExcel = (file) => { const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = read(data, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const jsonData = utils.sheet_to_json(worksheet, { header: 1, raw: false, dateNF: 'DD/MM/YY', }); const nonEmptyRows = jsonData.filter((row) => row.some((cell) => cell !== '') ); const header = nonEmptyRows[0]; const rows = nonEmptyRows.slice(1); const dateFields = ['Manufacture Date', 'Expire Date', 'Stock Date']; function convertToDisplayFormat(dateString) { const date = new Date(dateString); const day = date.getDate().toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const year = date.getFullYear().toString(); return `${day}-${month}-${year}`; } const formattedData = rows.map((row) => { let rowData = header.reduce((acc, col, columnIndex) => { if (dateFields.includes(col)) { acc[col] = convertToDisplayFormat(row[columnIndex]); } else { acc[col] = row[columnIndex]; } return acc; }, {}); return rowData; }); dispatch(uploadExcel({ file, jsonData: nonEmptyRows })); setWorksheet1(worksheet1); setDatas(formattedData); }; reader.readAsArrayBuffer(file); }; const handleDownload = async () => { const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Sheet1'); const headerStyle = { font: { bold: true }, border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' }, }, alignment: { horizontal: 'center', vertical: 'middle' }, }; worksheet.columns = [ { header: 'CATEGORY NAME', key: 'CATEGORY', width: 40, style: { ...headerStyle, font: { bold: true, color: { argb: '#000000' } }, }, }, ]; // const ProductNameHeaderCell = worksheet.getCell("A1"); // ProductNameHeaderCell.style = {...headerStyle,fill: { type: "pattern", pattern: "solid", fgColor: { argb: "FF2929" } }}; const CategoryNameHeaderCell = worksheet.getCell('A1'); CategoryNameHeaderCell.style = { ...headerStyle, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2929' } }, }; const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); const filename = 'CategoryDatas.xlsx'; if (typeof window !== 'undefined') { if (window.navigator && window.navigator.msSaveOrOpenBlob) { // For IE browser window.navigator.msSaveOrOpenBlob(blob, filename); } else { // For other browsers const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = filename; downloadLink.click(); } } }; const handleDownload1 = async () => { const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Sheet1'); const headerStyle = { font: { bold: true }, border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' }, }, alignment: { horizontal: 'center', vertical: 'middle' }, }; worksheet.columns = [ { header: 'CATEGORY NAME', key: 'CATEGORY', width: 40, style: { ...headerStyle, font: { bold: true, color: { argb: '#000000' } }, }, }, { header: 'Sub-Category NAME', key: 'Sub', width: 40, style: { ...headerStyle, font: { bold: true, color: { argb: '#000000' } }, }, }, ]; for (let i = 1; i <= 1000; i++) { worksheet.addRow({}); } const CategoryNameHeaderCell = worksheet.getCell('A1'); CategoryNameHeaderCell.style = { ...headerStyle, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2929' } }, }; worksheet .getColumn('A') .eachCell({ includeEmpty: true }, function (cell, rowNumber) { if (rowNumber > 1) { const dynamicValidValues = '"' + CategoryNames.join(',') + '"'; cell.dataValidation = { type: 'list', allowBlank: true, formulae: [dynamicValidValues], }; } }); const SubCategoryNameHeaderCell = worksheet.getCell('B1'); SubCategoryNameHeaderCell.style = { ...headerStyle, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2929' } }, }; const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); const filename = 'SubcatagoryDatas.xlsx'; if (typeof window !== 'undefined') { if (window.navigator && window.navigator.msSaveOrOpenBlob) { // For IE browser window.navigator.msSaveOrOpenBlob(blob, filename); } else { // For other browsers const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = filename; downloadLink.click(); } } }; const handleDownload2 = async () => { const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Sheet1'); // const hiddenWorksheet = workbook.addWorksheet('HiddenData'); // const dropdownDataSheet = workbook.addWorksheet('DropdownData'); const headerStyle = { font: { bold: true }, border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' }, }, alignment: { horizontal: 'center', vertical: 'middle' }, }; worksheet.columns = [ { header: 'Sub-Category Name', key: 'SubCategory', width: 40, style: { ...headerStyle, font: { bold: true, color: { argb: '#000000' } }, }, }, { header: 'Brand Name', key: 'Brand', width: 40, style: { ...headerStyle, font: { bold: true, color: { argb: '#000000' } }, }, }, ]; let sssss = [ "2,1,Hydserabadi 1s,Biryani2 ,ggie3,Natti4,Hybrid5,99 Dosa's6,super7,juice8,Hyderabadi Biryani9,iryaninks10,Non-ggie11, Clate12,American13,Natti14,Hybrid15,99 Dosa's16,superjuice17,superj18,uicesuperju19,icesuperj20,uice21,Hyderabadi22,Biryani23,iryaninks124", ]; for (let i = 1; i <= 100; i++) { worksheet.addRow(); } const SubCategoryNameHeaderCell = worksheet.getCell('A1'); SubCategoryNameHeaderCell.style = { ...headerStyle, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2929' } }, }; for (let i = 0; i < 100; i++) { worksheet.getCell(`A${i + 2}`).value = SubCatData[i]; } const dynamicValidValues = `'Sheet1'!$A$2:$A$101`; // Adjust range according to the length of your dropdown data array // Set data validation for each cell in column A (excluding header) worksheet .getColumn('A') .eachCell({ includeEmpty: true }, function (cell, rowNumber) { if (rowNumber > 1) { cell.dataValidation = { type: 'list', allowBlank: true, formulae: [dynamicValidValues], }; } }); // SubCatData.forEach((value, index) => { // dropdownDataSheet.getCell(`A${index + 1}`).value = value; // }); // const dataValidationRange = `'DropdownData'!$A$1:$A$${SubCatData.length}`; // Reference new sheet // worksheet.getColumn('A').eachCell((cell, rowNumber) => { // if (rowNumber > 1) { // Skip header // cell.dataValidation = { // type: 'list', // formulae: [dataValidationRange], // allowBlank: true // }; // } // }); const BrandNameHeaderCell = worksheet.getCell('B1'); BrandNameHeaderCell.style = { ...headerStyle, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2929' } }, }; const buffer = await workbook.xlsx.writeBuffer(); const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', }); const filename = 'BrandDatas.xlsx'; if (typeof window !== 'undefined') { if (window.navigator && window.navigator.msSaveOrOpenBlob) { // For IE browser window.navigator.msSaveOrOpenBlob(blob, filename); } else { // For other browsers const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = filename; downloadLink.click(); } } }; // for (let i = 0; i < SubCatData.length; i++) { // worksheet.getCell(`A${i + 2}`).value = SubCatData[i]; // } // const dynamicValidValues = `'Sheet1'!$A$2:$A$${SubCatData.length + 1}`; // console.log(dynamicValidValues,"dynamicValidValuesdynamicValidValuesdynamicValidValues") // worksheet.getColumn("A").eachCell({ includeEmpty: true }, function (cell, rowNumber) { // if (rowNumber > 1) { // cell.dataValidation = { // type: "list", // allowBlank: true, // formulae: [dynamicValidValues], // }; // } // }); //------------------------------------------------------------------------------------------------------- // worksheet.getColumn("A").eachCell({ includeEmpty: true }, function (cell, rowNumber) { // if (rowNumber > 1) { // const dynamicValidValues = '"' + sssss.join(",") + '"'; // console.log(dynamicValidValues,"dynamicValidValuesdynamicValidValuesdynamicValidValuesdynamicValidValues") // cell.dataValidation = { // type: "list", // allowBlank: true, // formulae: [dynamicValidValues], // }; // } // }); //------------------------------------------------------------------------------------------------------------------- // for (let i = 1; i <= 1000; i++) { // worksheet.addRow(); // } // worksheet.getColumn("A").eachCell({ includeEmpty: true }, function (cell, rowNumber) { // if (rowNumber > 1) { // const dynamicValidValues = '"' + SubCatData.join(",") + '"'; // cell.dataValidation = { // type: "list", // allowBlank: true, // formulae: [dynamicValidValues], // }; // } // }); //21 dataa with this dataaa // File upload submit handler const handleFileSubmit = (e) => { e.preventDefault(); if (excelFile === null) { excelFileError('Please select an Excel file.'); } else { handleSubmit(Datas); } }; const handleCancelData = () => { dispatch(emptyExcelData()); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const column = parcolumns?.map((col) => { if (!col.editable) { return col; } let onClickHandler = null; if (editdelete === 'Delete') { onClickHandler = (record) => removeFromTable(record); } return { ...col, onCell: (record) => ({ record, editable: col.editable, dataIndex: col.dataIndex, title: col.title, handleSave, onClick: () => onClickHandler(record), }), }; }); const EditableContext = React.createContext(null); const EditableRow = ({ index, dataIndex, ...props }) => { const [form] = Form.useForm(); return (
); }; const EditableCell = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => { const [editing, setEditing] = useState(false); const inputRef = useRef(null); const form = useContext(EditableContext); useEffect(() => { if (editing) { inputRef?.current?.focus(); } }, [editing]); const toggleEdit = () => { setEditing(!editing); form.setFieldsValue({ [dataIndex]: record[dataIndex], }); }; const save = async () => { try { const values = await form.validateFields(); toggleEdit(); handleSave({ ...record, ...values, }); } catch (errInfo) {} }; let childNode = children; if (editable) { childNode = editing ? ( ) : (
{children}
); } return {childNode}; }; const components = { body: { row: EditableRow, cell: EditableCell, }, }; const handleSave = (row) => { const newDatas = [...Datas]; const item = newDatas.filter((item) => item.key === row.key); const UpdatedData = { CategoryName: row?.CategoryName, SubCategoryName: row?.SubCategoryName, BrandName: row?.BrandName, }; newDatas.splice(item?.[0]?.key, 1, { ...item?.[0], ...UpdatedData, }); setDatas(newDatas); }; const handlechange22 = (index) => { if (editdelete === 'Delete') { seteditdelete(''); } else { seteditdelete('Delete'); } }; const removeFromTable = (record) => { const indexToRemove = Datas.findIndex((item) => item.key === record.key); if (indexToRemove !== -1) { const updatedDataSource = [...Datas]; updatedDataSource.splice(indexToRemove, 1); setDatas(updatedDataSource); } }; const handleRadioChange = (value) => { setRadioValue(value); }; return (
{ handleRadioChange(value); }} />
{excelData?.length > 0 && excelData && (
)}

{(!excelData || excelData?.length === 0) && ( <>
{/* */}
)} {/* {radioValue === 'Category Name' && ( )} {radioValue === 'Sub-Category Name' && ( )} {radioValue === 'Brand Name' && ( )} */} {excelFileError && (
{excelFileError}
)}
{excelData && excelData.length > 0 ? (
) : (

)}
{radioValue === 'Category Name' && (
Download
)} {radioValue === 'Sub-Category Name' && (
Download
)} {radioValue === 'Brand Name' && (
Download
)} {excelData && excelData?.length > 0 && (
Remove File
)}
); }; export default ConfigExcel;