Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup onetime csv upload #93

Merged
merged 4 commits into from
Apr 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 89 additions & 54 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@
"lint-staged": "^14.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^14.2.3",
"react-icons": "^5.0.1",
"yarn": "^1.22.21"
},
45 changes: 44 additions & 1 deletion src/components/BusinessTable/BusinessTable.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBackend } from '../../contexts/BackendContext';
import { Table, Thead, Tbody, Tr, Td, Checkbox, Button, Th } from '@chakra-ui/react';
import {
Table,
Thead,
Tbody,
Tr,
Td,
Checkbox,
Button,
Th,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalFooter,
ModalBody,
ModalCloseButton,
Heading,
Text,
useDisclosure} from '@chakra-ui/react';
import { ArrowDownIcon } from '@chakra-ui/icons';
import DownloadCSV from '../../utils/downloadCSV';
import DropZone from '../BusinessTable/DropZone';



const BusinessTable = businessData => {
const navigate = useNavigate();
const { backend } = useBackend();
const [data, setData] = useState([]);
const { isOpen, onOpen, onClose } = useDisclosure();
// const [selectedBusinessId, setBusinessId] = useState(null);

const TABLE_HEADERS = [
@@ -117,6 +139,9 @@ const BusinessTable = businessData => {
}
};




const handleDownloadCSV = () => {
const ids = Array.from(selectedBusinessIds);
var headers = [];
@@ -144,6 +169,24 @@ const BusinessTable = businessData => {
<h1>Loading ...</h1>
) : (
<div>
<Button onClick={onOpen}>Upload CSV</Button>

<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader marginBottom={0}>
<Heading size={'md'}>Upload existing data</Heading>
</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text fontFamily={'Inter'}>Transfer all business information into your new portal.</Text>
<DropZone onClose={onClose} />
</ModalBody>
<ModalFooter>

</ModalFooter>
</ModalContent>
</Modal>
<Button colorScheme="blue" onClick={handleSendReminders}>
Send Reminders
</Button>
61 changes: 61 additions & 0 deletions src/components/BusinessTable/DropZone.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { useDropzone } from 'react-dropzone';
import { useState } from 'react';
import { Flex, Text, Input, Button, Box } from '@chakra-ui/react';
import UploadCSV from '../../utils/uploadCSV';
import 'boxicons';
import { PropTypes } from 'prop-types';

const DropZone = ({ onClose }) => {
const [contents, setContents] = useState('');
const [file, setFile] = useState('');

const { getRootProps, getInputProps } = useDropzone({
accept: '.csv',
onDrop: async ( [file] ) => {
setFile(file);
var reader = new FileReader();
reader.onload = async function (e) {
setContents(e.target.result);
};
reader.readAsText(file);
}
});

const handleUpload = async () => {
await UploadCSV(contents);
}

return (
<Flex className="container" gap = {4} flexDirection={'column'}>
<Flex
{...getRootProps({ className: 'dropzone' })}
p={5}
bg="#f3fafa"
border={'1px dashed teal'}
borderRadius={4}
gap={4}
textAlign="center"
cursor="pointer"
flexDirection={'column'}
alignItems={'center'}
justifyContent={'center'}
>
<Input {...getInputProps()} />
<Text fontFamily={'Inter'} as={'b'} color={'gray.600'}>Drag files here, or</Text>
<Button colorScheme='teal' variant={'outline'} w={40}><box-icon name={'upload'} color={'teal'}></box-icon><Text marginLeft={2}>Upload File</Text></Button>

</Flex>
{file && <Box bg={'#f3fafa'} p={4} borderRadius={4} textAlign={'center'}>{file.name}</Box>}
<Flex gap={4} width={'100%'} justifyContent={'flex-end'}>
<Button colorScheme="teal" onClick={handleUpload}>Upload</Button>
<Button onClick={onClose}>Cancel</Button>
</Flex>
</Flex>
);
}

DropZone.propTypes = {
onClose: PropTypes.func.isRequired,
}

export default DropZone;
116 changes: 116 additions & 0 deletions src/utils/uploadCSV.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
async function UploadCSV( file ) {
const businessData = csvToArray(file);
const DUMMY_DATE = new Date().toLocaleString('en-US', { timeZone: 'America/Los_Angeles' })
for (const business of businessData) {
if (!business["name"]) continue;
try {
const DUMMY_STRING = "";
const DUMMY_INT = 0;
const DUMMY_BOOL = false;
const data = {
name: business["name"] || DUMMY_STRING,
contactName: business["contact_name"] || DUMMY_STRING,
street: business["street"] || DUMMY_STRING,
zipCode: business["zip_code"] || DUMMY_STRING,
state: business["state"] || DUMMY_STRING,
city: business["city"] || DUMMY_STRING,
website: business["website"] || DUMMY_STRING,
businessHours: DUMMY_STRING,
primaryPhone: business["primary_phone"] || DUMMY_STRING,
primaryEmail: business["email"] || DUMMY_STRING,
findOut: DUMMY_STRING,
food: DUMMY_BOOL,
donation: DUMMY_BOOL,
familyShelter: DUMMY_BOOL,
wellness: DUMMY_BOOL,
spayNeuter: DUMMY_BOOL,
financial: DUMMY_BOOL,
reHome: DUMMY_BOOL,
erBoarding: DUMMY_BOOL,
senior: DUMMY_BOOL,
cancer: DUMMY_BOOL,
dog: DUMMY_BOOL,
cat: DUMMY_BOOL,
fphPhone: DUMMY_INT,
webNotes: DUMMY_STRING,
internalNotes: DUMMY_STRING,
published: DUMMY_BOOL,
shelter: DUMMY_BOOL,
domesticViolence: DUMMY_BOOL,
webDateInit: DUMMY_DATE,
entQb: DUMMY_BOOL,
serviceRequest: DUMMY_BOOL,
inactive: true,
finalCheck: DUMMY_BOOL,
};
//console.log(data);
console.log(JSON.stringify(data));
await fetch(
`http://localhost:3001/business/`,
{
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
},
);
} catch (error) {
console.error('Error uploading business:', error);
}
}
}

function csvToArray( csv ) {
const csvToDB = {
Customer: "name",
State: "state",
City: "city",
Zip: "zip_code",
}
const [header, ...lines] = csv.split('\n');
const headers = header.split(',');
console.log(headers);
var businesses = [];
for (const line of lines) {
var business = {};
const values = line.split(',');
for (const [i, value] of values.entries()) {
if (!headers[i]) continue;
if (value == "") continue;
if (headers[i].replace(' ', '_') in csvToDB) {
business[csvToDB[headers[i]]] = value;
}
else if (headers[i] == "First Name") {
business["contact_name"] = value;
}
else if (headers[i] == "Last Name"){
business["contact_name"] += " " + value;
}
else if (headers[i] == "Main Phone"){
business["primary_phone"] = value.replace(/\D/g, '');
}
else if (headers[i] == "Street1"){
console.log(value);
business["street"] = value;
}
else if (headers[i] == "Street2"){
console.log(value);
business["street"] = value || business["street"];
}
else if (headers[i] == "Date Joined"){
business["join_date"] = value.split(/[^0-9]/).join('-');
}else if (headers[i] == "Website"){
business["website"] = business["website"] || value;
}else if (headers[i] == "Main Email"){
business["email"] = value;
}else if (headers[i] == "Customer Type"){
business["type"] = value;
}
}
businesses.push(business);
}
return businesses;
}

export default UploadCSV;