FINALIZAÇAO DA IMPORTAÇÃO DE CSV PARA INSERIR CONTATOS EM MASSA

pull/20/head
adriano 2022-11-07 17:51:20 -03:00
parent f0714eb015
commit 9bf1850405
2 changed files with 311 additions and 53 deletions

View File

@ -0,0 +1,65 @@
import * as React from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
const Modal = (props) => {
const [open, setOpen] = React.useState(props.open);
const [scroll, /*setScroll*/] = React.useState('paper');
const handleClose = () => {
setOpen(false);
};
const descriptionElementRef = React.useRef(null);
React.useEffect(() => {
if (open) {
const { current: descriptionElement } = descriptionElementRef;
if (descriptionElement !== null) {
descriptionElement.focus();
}
}
}, [open]);
return (
<Dialog
open={open}
onClose={handleClose}
fullWidth={true}
maxWidth={'true'}
scroll={scroll}
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
<DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'paper'}>
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
</DialogContentText>
TESTANDO
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Ok</Button>
</DialogActions>
</Dialog>
);
}
export default Modal

View File

@ -36,14 +36,8 @@ import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
import apiBroker from "../../services/apiBroker";
import fileDownload from 'js-file-download'
import {
FormControlLabel,
Hidden,
Menu,
MenuItem,
Switch,
} from "@material-ui/core";
const reducer = (state, action) => {
@ -121,17 +115,94 @@ const Contacts = () => {
const [confirmOpen, setConfirmOpen] = useState(false);
const [hasMore, setHasMore] = useState(false);
const [file, setFile] = useState()
const [onQueueStatus, setOnQueueProcessStatus] = useState(undefined)
const [zipfile, setZipFile] = useState()
async function handleChange(event) {
function handleChange(event) {
try {
console.log('THE FILE: ', event.target.files[0])
setFile(event.target.files[0])
if (event.target.files[0].size > 1024 * 1024 * 4){
alert('Arquivo não pode ser maior que 4 MB!')
return
}
const formData = new FormData();
formData.append("adminId", user.id);
formData.append("baseURL", process.env.REACT_APP_BACKEND_URL_PRIVATE,);
formData.append("frontURL", process.env.REACT_APP_FRONTEND_URL);
formData.append("identifier", 'contacts_insert_csv');
formData.append("file", event.target.files[0]);
const config = {
headers: {
'content-type': 'multipart/form-data',
},
};
const bulk_contact_insert = await apiBroker.post("/contacts/bulk/insert", formData, config);
console.log(bulk_contact_insert.data)
const onQueueStatus = bulk_contact_insert.data.queueStatus
setOnQueueProcessStatus(onQueueStatus)
// history.go(0);
} catch (err) {
toastError(err);
}
}
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchReportOnQueue = async () => {
try {
const insertOnQueue = await apiBroker.get("/contacts/status/insert/onqueue", {
params: {
adminId: user.id,
baseURL: process.env.REACT_APP_BACKEND_URL_PRIVATE,
identifier: 'contacts_insert_csv'
}
});
if (insertOnQueue && insertOnQueue.data) {
console.log('insertOnQueue: ', insertOnQueue.data)
console.log('data.app.file: ', insertOnQueue.data.app.file)
setZipFile(insertOnQueue.data.app.file)
setOnQueueProcessStatus(insertOnQueue.data.app.status)
}
else {
setOnQueueProcessStatus('empty')
}
} catch (err) {
console.log(err);
}
};
fetchReportOnQueue();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [user])
useEffect(() => {
dispatch({ type: "RESET" });
@ -142,9 +213,6 @@ const Contacts = () => {
if (searchParam.trim().length > 0 && searchParam.endsWith(' ')) {
return
}
@ -180,6 +248,24 @@ const Contacts = () => {
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("contactsBulkInsertOnQueueStatus", (data) => {
if (data.action === 'update') {
if (String(data.insertOnQueue.adminId) === String(user.id)) {
// console.log('-----------------> THE FILE: ', data.insertOnQueue)
setZipFile(data.insertOnQueue.file)
setOnQueueProcessStatus(data.insertOnQueue.queueStatus)
if (data.insertOnQueue.queueStatus === "success") {
history.go(0);
}
}
}
})
socket.on("contact", (data) => {
if (data.action === "update" || data.action === "create") {
dispatch({ type: "UPDATE_CONTACTS", payload: data.contact });
@ -193,7 +279,7 @@ const Contacts = () => {
return () => {
socket.disconnect();
};
}, []);
}, [user, history]);
const removeExtraSpace = (str) => {
@ -258,32 +344,6 @@ const Contacts = () => {
}
};
const handleImportCSVContact = async () => {
console.log('kkkkkkkkkkk')
try {
const formData = new FormData();
const filename = `${new Date().getTime()}.mp3`;
formData.append("medias", filename);
formData.append("body", filename);
formData.append("fromMe", true);
const config = {
headers: {
'content-type': 'multipart/form-data',
},
};
const bulk_contact_insert = await apiBroker.post("/contacts/bulk/insert", formData, config);
// await api.post("/contacts/csv/import");
history.go(0);
} catch (err) {
toastError(err);
}
};
const loadMore = () => {
setPageNumber((prevState) => prevState + 1);
@ -300,6 +360,133 @@ const Contacts = () => {
}
};
const handleDownload = async () => {
setOnQueueProcessStatus('downloading')
try {
let res = await apiBroker.get(`/contacts/download/${zipfile}`, { responseType: 'blob' });
if (res) {
fileDownload(res.data, `${zipfile}`);
setOnQueueProcessStatus('empty')
}
} catch (err) {
console.log(err);
}
}
const handleError = async () => {
try {
alert('Não foi possível inserir a planilha de contatos! Tente novamente ou entre em contato com o suporte.')
let res = await apiBroker.get(`/contacts/error/insert/onqueue`, {
params: {
adminId: user.id,
baseURL: process.env.REACT_APP_BACKEND_URL_PRIVATE,
identifier: 'contacts_insert_csv'
}
});
if (res) {
setOnQueueProcessStatus('empty')
}
} catch (err) {
console.log(err);
}
}
const renderSwitch = (param) => {
switch (param) {
case 'empty':
return (
<>
<input
type="file"
accept=".csv"
style={{ display: 'none' }}
onChange={handleChange}
id="contained-button-file"
/>
<label htmlFor="contained-button-file">
<Button variant="contained" color="primary" component="span">
CSV UPLOAD
</Button>
</label>
{/* <Button
disabled={query && query.length > 0 ? false : true}
variant="contained"
color="primary"
onClick={(e) => {
handleCSVMessages()
}}
>
{"CSV ALL"}
</Button> */}
</>);
case 'pending' || 'processing':
return (
<>
<span>PROCESSING...</span>
</>);
case 'success':
return (
<>
<Button
variant="contained"
color="primary"
onClick={(e) => {
handleDownload(e)
}}
>
{'DOWNLOAD'}
</Button>
</>);
case 'error':
return (
<>
<Button
variant="contained"
color="primary"
onClick={(e) => {
handleError(e)
}}
>
{'ERROR'}
</Button>
</>);
case 'downloading':
return (
<>
<span>DOWNLOADING...</span>
</>);
default:
return (<><span>WAITING...</span></>);
}
}
return (
<MainContainer className={classes.mainContainer}>
<ContactModal
@ -348,14 +535,20 @@ const Contacts = () => {
role={user.profile}
perform="contacts-page:import-csv-contacts"
yes={() => (
<Button
variant="contained"
color="primary"
onClick={(e) => handleImportCSVContact()}
>
IMPORTAR CONTACTO CSV
{/* {i18n.t("contacts.buttons.import")} */}
</Button>
<>
{renderSwitch(onQueueStatus)}
</>
// <Button
// variant="contained"
// color="primary"
// onClick={(e) => handleImportCSVContact()}
// >
// IMPORTAR CONTACTO CSV
// {/* {i18n.t("contacts.buttons.import")} */}
// </Button>
)}
/>