Cleanup,dedup
This commit is contained in:
parent
29f4983a15
commit
0440003a02
12 changed files with 647 additions and 225 deletions
|
|
@ -25,6 +25,8 @@ export default async (req: Request, res: Response) => {
|
||||||
product.quantity = req.body.quantity || product.quantity;
|
product.quantity = req.body.quantity || product.quantity;
|
||||||
product.price = req.body.price || product.price;
|
product.price = req.body.price || product.price;
|
||||||
product.hidden = req.body.hidden || product.hidden;
|
product.hidden = req.body.hidden || product.hidden;
|
||||||
|
product.description = req.body.description || product.description;
|
||||||
|
product.images = req.body.images || product.images;
|
||||||
|
|
||||||
await product.save();
|
await product.save();
|
||||||
return res.status(200).json(product);
|
return res.status(200).json(product);
|
||||||
|
|
|
||||||
14
frontend/src/global/api.js
Normal file
14
frontend/src/global/api.js
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
export const uploadImage = async (file) => {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append('file', file);
|
||||||
|
const resp = await fetch('/api/v1/fileupload', { method: 'POST', body: fd });
|
||||||
|
const { output, error } = await resp.json();
|
||||||
|
if (error) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error(error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return `/api/v1/fileupload/${output}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default uploadImage;
|
||||||
|
|
@ -2,6 +2,8 @@ import LocalizedStrings from 'react-localization';
|
||||||
|
|
||||||
export const General = new LocalizedStrings({
|
export const General = new LocalizedStrings({
|
||||||
en: {
|
en: {
|
||||||
|
yes: 'Yes',
|
||||||
|
no: 'No',
|
||||||
close: 'Close',
|
close: 'Close',
|
||||||
save: 'Save',
|
save: 'Save',
|
||||||
openMenu: 'Open Menu',
|
openMenu: 'Open Menu',
|
||||||
|
|
@ -33,6 +35,9 @@ export const Product = new LocalizedStrings({
|
||||||
|
|
||||||
export const Manage = new LocalizedStrings({
|
export const Manage = new LocalizedStrings({
|
||||||
en: {
|
en: {
|
||||||
|
edit: {
|
||||||
|
title: (name) => `Editing ${name}`,
|
||||||
|
},
|
||||||
create: {
|
create: {
|
||||||
title: 'Create Product',
|
title: 'Create Product',
|
||||||
fileUpload: (count) => `${count || 'No'} ${count === 1 ? 'File' : 'Files'} Selected`,
|
fileUpload: (count) => `${count || 'No'} ${count === 1 ? 'File' : 'Files'} Selected`,
|
||||||
|
|
@ -40,14 +45,17 @@ export const Manage = new LocalizedStrings({
|
||||||
header: 'Item Added!',
|
header: 'Item Added!',
|
||||||
content: `Item created with ID ${id}`,
|
content: `Item created with ID ${id}`,
|
||||||
}),
|
}),
|
||||||
labels: {
|
},
|
||||||
name: 'Name',
|
labels: {
|
||||||
desc: 'Description (Supports Markdown)',
|
name: 'Name',
|
||||||
price: 'Price',
|
desc: 'Description',
|
||||||
qty: 'Quantity',
|
price: 'Price',
|
||||||
required: 'This Field is Required',
|
qty: 'Quantity',
|
||||||
save: 'Save Product',
|
rating: 'Rating',
|
||||||
},
|
hidden: 'Hidden',
|
||||||
|
required: 'This Field is Required',
|
||||||
|
save: 'Save Product',
|
||||||
|
saveChanges: 'Save Changes',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
6
frontend/src/global/search.js
Normal file
6
frontend/src/global/search.js
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
export default (term, all) => {
|
||||||
|
if (term.length) {
|
||||||
|
return all.filter((x) => x.name.toLowerCase().includes(term.toLowerCase()));
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
};
|
||||||
|
|
@ -9,22 +9,13 @@ import Card from './components/Card';
|
||||||
import { Home as i18n } from '../../global/i18n';
|
import { Home as i18n } from '../../global/i18n';
|
||||||
import Loading from '../../global/components/Loading';
|
import Loading from '../../global/components/Loading';
|
||||||
import InlineLabelInput from '../../global/components/FormControl/InlineLabelInput';
|
import InlineLabelInput from '../../global/components/FormControl/InlineLabelInput';
|
||||||
|
import search from '../../global/search';
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
const [hasLoaded, setLoaded] = useState(false);
|
const [hasLoaded, setLoaded] = useState(false);
|
||||||
const [allProducts, setAllProducts] = useState([]);
|
const [allProducts, setAllProducts] = useState([]);
|
||||||
const [products, setProducts] = useState([]);
|
const [products, setProducts] = useState([]);
|
||||||
|
|
||||||
const doSearch = (evt) => {
|
|
||||||
const terms = evt.target.value.toLowerCase();
|
|
||||||
if (terms.length) {
|
|
||||||
const filtered = products.filter((x) => x.name.toLowerCase().includes(terms));
|
|
||||||
setProducts(filtered);
|
|
||||||
} else {
|
|
||||||
setProducts(allProducts);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hasLoaded) return () => {};
|
if (hasLoaded) return () => {};
|
||||||
|
|
||||||
|
|
@ -55,7 +46,7 @@ export default () => {
|
||||||
</Heading>
|
</Heading>
|
||||||
<Box maxW="400px" m="auto">
|
<Box maxW="400px" m="auto">
|
||||||
<InlineLabelInput
|
<InlineLabelInput
|
||||||
propChangeEvt={doSearch}
|
propChangeEvt={(evt) => setProducts(search(evt.target.value, allProducts))}
|
||||||
propKeyPressEvt={() => {}}
|
propKeyPressEvt={() => {}}
|
||||||
propSubmitEvt={() => {}}
|
propSubmitEvt={() => {}}
|
||||||
type="text"
|
type="text"
|
||||||
|
|
|
||||||
36
frontend/src/pages/Manage/components/DeletableImage.jsx
Normal file
36
frontend/src/pages/Manage/components/DeletableImage.jsx
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Box, Flex, Heading, Image,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
|
import { BsTrash } from 'react-icons/bs';
|
||||||
|
|
||||||
|
export default ({ src, onClick }) => (
|
||||||
|
<div>
|
||||||
|
<Box position="relative" onClick={onClick}>
|
||||||
|
<Image
|
||||||
|
width="100%"
|
||||||
|
height="auto"
|
||||||
|
objectFit="cover"
|
||||||
|
src={src}
|
||||||
|
/>
|
||||||
|
<Box
|
||||||
|
position="absolute"
|
||||||
|
top={0}
|
||||||
|
left={0}
|
||||||
|
zIndex={1}
|
||||||
|
opacity={0}
|
||||||
|
backgroundColor="red.500"
|
||||||
|
width="100%"
|
||||||
|
height="100%"
|
||||||
|
transition="opacity ease-in-out 150ms"
|
||||||
|
_hover={{ opacity: 1 }}
|
||||||
|
cursor="pointer"
|
||||||
|
>
|
||||||
|
<Flex height="inherit" direction="column" justifyContent="center" alignItems="center">
|
||||||
|
<Heading size="2xl"><BsTrash /></Heading>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
27
frontend/src/pages/Manage/components/DynamicModal.jsx
Normal file
27
frontend/src/pages/Manage/components/DynamicModal.jsx
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Button, Modal, ModalBody,
|
||||||
|
ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
|
import { General as i18n } from '../../../global/i18n';
|
||||||
|
|
||||||
|
export default ({
|
||||||
|
open, header, superOnClose, size, children,
|
||||||
|
}) => (
|
||||||
|
<Modal isOpen={open} onClose={superOnClose} size={size || 'md'}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>{header}</ModalHeader>
|
||||||
|
<ModalCloseButton />
|
||||||
|
<ModalBody>
|
||||||
|
{children}
|
||||||
|
</ModalBody>
|
||||||
|
|
||||||
|
<ModalFooter>
|
||||||
|
<Button colorScheme="blue" mr={3} onClick={superOnClose}>
|
||||||
|
{i18n.close}
|
||||||
|
</Button>
|
||||||
|
</ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
|
@ -6,7 +6,7 @@ import {
|
||||||
import { FiFile } from 'react-icons/fi';
|
import { FiFile } from 'react-icons/fi';
|
||||||
import { Manage as i18n } from '../../../global/i18n';
|
import { Manage as i18n } from '../../../global/i18n';
|
||||||
|
|
||||||
export const FileUpload = ({
|
export default ({
|
||||||
name,
|
name,
|
||||||
placeholder,
|
placeholder,
|
||||||
propagateChange,
|
propagateChange,
|
||||||
|
|
@ -46,5 +46,3 @@ export const FileUpload = ({
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default FileUpload;
|
|
||||||
|
|
|
||||||
227
frontend/src/pages/Manage/components/modal/Edit.jsx
Normal file
227
frontend/src/pages/Manage/components/modal/Edit.jsx
Normal file
|
|
@ -0,0 +1,227 @@
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Box, Button, FormControl, FormLabel, Grid, GridItem, Heading,
|
||||||
|
InputGroup, InputLeftAddon, Text, Textarea, useColorModeValue,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
|
import CurrencyInput from 'react-currency-input-field';
|
||||||
|
import { AiOutlineFileText, AiOutlineNumber } from 'react-icons/ai';
|
||||||
|
import { BsCurrencyDollar, BsMarkdown } from 'react-icons/bs';
|
||||||
|
import InlineLabelInput from '../../../../global/components/FormControl/InlineLabelInput';
|
||||||
|
import IconTextDuo from '../../../../global/components/IconTextDuo';
|
||||||
|
import { Manage as i18n } from '../../../../global/i18n';
|
||||||
|
import store from '../../../../redux/store';
|
||||||
|
import FileUpload from '../FileUpload';
|
||||||
|
import DeletableImage from '../DeletableImage';
|
||||||
|
import { uploadImage } from '../../../../global/api';
|
||||||
|
|
||||||
|
const InputGroupStyle = {
|
||||||
|
marginTop: '1rem',
|
||||||
|
marginBottom: '1rem',
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ({ product }) => {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [state, setState] = useState({
|
||||||
|
name: product.name,
|
||||||
|
description: product.description,
|
||||||
|
quantity: product.quantity,
|
||||||
|
price: product.price,
|
||||||
|
images: product.images,
|
||||||
|
newImages: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
if (!state.name.length || !state.quantity || !state.price || !state.description) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Missing Info', content: 'Not all required fields have been filled. Please provide this info to proceed.' } });
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Step 1: Upload image files
|
||||||
|
// Join the old image files with the new ones as well
|
||||||
|
const imageUrls = (await Promise.all(state.newImages.map(uploadImage))).concat(state.images);
|
||||||
|
// Step 2: Upload the rest
|
||||||
|
// eslint-disable-next-line no-underscore-dangle
|
||||||
|
const resp = await fetch(`/api/v1/products/${product._id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
authorization: `Bearer ${window.localStorage.getItem('auth-token')}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
...state,
|
||||||
|
images: imageUrls.length,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Item Updated Successfully!', content: 'Your Changes have Been Saved and Will Be Reflected on the Management Page' } });
|
||||||
|
} else {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Item', content: JSON.stringify(data) } });
|
||||||
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Edit Item in Catch Block', content: ex } });
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Heading textAlign="center" marginBottom="1rem">
|
||||||
|
{i18n.title}
|
||||||
|
</Heading>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
borderRadius="2xl"
|
||||||
|
padding="2rem"
|
||||||
|
backgroundColor="blackAlpha.200"
|
||||||
|
w="100%"
|
||||||
|
maxW="768px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InlineLabelInput
|
||||||
|
required
|
||||||
|
type="text"
|
||||||
|
propSubmitEvt={save}
|
||||||
|
propChangeEvt={(e) => setState({ ...state, name: e.target.value })}
|
||||||
|
propKeyPressEvt={(e) => e.key === 'Enter' && save()}
|
||||||
|
value={state.name}
|
||||||
|
labelText={i18n.labels.name}
|
||||||
|
labelIcon={(<AiOutlineFileText />)}
|
||||||
|
labelBgColor="#fa6663"
|
||||||
|
labelFgColor="black"
|
||||||
|
error={!state.name.length ? i18n.labels.required : null}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={() => {}}
|
||||||
|
padding="0.5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
variant="floating"
|
||||||
|
>
|
||||||
|
<Textarea
|
||||||
|
id="manage-text-area"
|
||||||
|
value={state.description}
|
||||||
|
onChange={(e) => setState({ ...state, description: e.target.value })}
|
||||||
|
background={useColorModeValue('gray.50', 'gray.700')}
|
||||||
|
resize="vertical"
|
||||||
|
size="md"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{state.description.length === 0 && (
|
||||||
|
<FormLabel background="green.400" borderTopLeftRadius="8px" px={2} py={1}>
|
||||||
|
<IconTextDuo icon={(<BsMarkdown />)} text={i18n.labels.desc} />
|
||||||
|
</FormLabel>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.description.length ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<InputLeftAddon backgroundColor="#8a56c2" color="white">
|
||||||
|
<IconTextDuo icon={(<AiOutlineNumber />)} text="Qty" />
|
||||||
|
</InputLeftAddon>
|
||||||
|
{/* Use currency input to nicely handle whole numerical values */}
|
||||||
|
<CurrencyInput
|
||||||
|
prefix=""
|
||||||
|
allowDecimals={false}
|
||||||
|
className="chakra-input currency"
|
||||||
|
defaultValue={state.quantity}
|
||||||
|
onValueChange={(value) => setState({
|
||||||
|
...state, quantity: JSON.parse(value),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.quantity ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<InputLeftAddon backgroundColor="#fbb355" color="black"><IconTextDuo icon={(<BsCurrencyDollar />)} text="Price" /></InputLeftAddon>
|
||||||
|
<CurrencyInput
|
||||||
|
prefix="$"
|
||||||
|
decimalsLimit={2}
|
||||||
|
className="chakra-input currency"
|
||||||
|
defaultValue={state.price}
|
||||||
|
onValueChange={(value) => setState({
|
||||||
|
...state, price: JSON.parse(value),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.price ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<FileUpload
|
||||||
|
name="image"
|
||||||
|
acceptedFileTypes="image/*"
|
||||||
|
required
|
||||||
|
allowMultipleFiles
|
||||||
|
propagateChange={(evt) => setState({
|
||||||
|
...state,
|
||||||
|
newImages: Array.from(evt.target.files),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<Grid templateColumns="repeat(auto-fit, minmax(384px, 1fr));" rowGap={6} mt={2}>
|
||||||
|
{state.images.map((x) => (
|
||||||
|
<GridItem key={x}>
|
||||||
|
<DeletableImage
|
||||||
|
onClick={() => {
|
||||||
|
// eslint-disable-next-line no-alert
|
||||||
|
if (window.confirm('Do you want to delete this image?')) {
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
images: state.images.filter((i) => i !== x),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
src={x}
|
||||||
|
/>
|
||||||
|
</GridItem>
|
||||||
|
))}
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
display="block"
|
||||||
|
mx="auto"
|
||||||
|
mt={4}
|
||||||
|
colorScheme="green"
|
||||||
|
isLoading={loading}
|
||||||
|
type="submit"
|
||||||
|
onClick={save}
|
||||||
|
>
|
||||||
|
{i18n.labels.saveChanges}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
201
frontend/src/pages/Manage/components/modal/New.jsx
Normal file
201
frontend/src/pages/Manage/components/modal/New.jsx
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Box, Button, FormControl, FormLabel, Heading,
|
||||||
|
InputGroup, InputLeftAddon, Text, Textarea, useColorModeValue,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
|
import CurrencyInput from 'react-currency-input-field';
|
||||||
|
import { AiOutlineFileText, AiOutlineNumber } from 'react-icons/ai';
|
||||||
|
import { BsCurrencyDollar, BsMarkdown } from 'react-icons/bs';
|
||||||
|
import InlineLabelInput from '../../../../global/components/FormControl/InlineLabelInput';
|
||||||
|
import IconTextDuo from '../../../../global/components/IconTextDuo';
|
||||||
|
import { Manage as i18n } from '../../../../global/i18n';
|
||||||
|
import store from '../../../../redux/store';
|
||||||
|
import FileUpload from '../FileUpload';
|
||||||
|
import { uploadImage } from '../../../../global/api';
|
||||||
|
|
||||||
|
const InputGroupStyle = {
|
||||||
|
marginTop: '1rem',
|
||||||
|
marginBottom: '1rem',
|
||||||
|
};
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [state, setState] = useState({
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
quantity: null,
|
||||||
|
price: null,
|
||||||
|
images: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
if (!state.name.length || !state.quantity || !state.price || !state.description) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Missing Info', content: 'Not all required fields have been filled. Please provide this info to proceed.' } });
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Step 1: Upload image files
|
||||||
|
const imageUrls = await Promise.all(state.images.map(uploadImage));
|
||||||
|
// Step 2: Upload the rest
|
||||||
|
const resp = await fetch('/api/v1/products', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
authorization: `Bearer ${window.localStorage.getItem('auth-token')}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
...state,
|
||||||
|
images: imageUrls.length ? imageUrls : ['https://dv2ls.com/f/PpMcVb8gN'],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Added New Product!', content: 'Your New Product has Been Saved and Will Be Reflected on the Management Page' } });
|
||||||
|
} else {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Product', content: JSON.stringify(data) } });
|
||||||
|
}
|
||||||
|
} catch (ex) {
|
||||||
|
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Product', content: ex } });
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Heading textAlign="center" marginBottom="1rem">
|
||||||
|
{i18n.title}
|
||||||
|
</Heading>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
borderRadius="2xl"
|
||||||
|
padding="2rem"
|
||||||
|
backgroundColor="blackAlpha.200"
|
||||||
|
w="100%"
|
||||||
|
maxW="768px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InlineLabelInput
|
||||||
|
required
|
||||||
|
type="text"
|
||||||
|
propSubmitEvt={save}
|
||||||
|
propChangeEvt={(e) => setState({ ...state, name: e.target.value })}
|
||||||
|
propKeyPressEvt={(e) => e.key === 'Enter' && save()}
|
||||||
|
value={state.name}
|
||||||
|
labelText={i18n.labels.name}
|
||||||
|
labelIcon={(<AiOutlineFileText />)}
|
||||||
|
labelBgColor="#fa6663"
|
||||||
|
labelFgColor="black"
|
||||||
|
error={!state.name.length ? i18n.labels.required : null}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={() => {}}
|
||||||
|
padding="0.5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
variant="floating"
|
||||||
|
>
|
||||||
|
<Textarea
|
||||||
|
id="manage-text-area"
|
||||||
|
value={state.description}
|
||||||
|
onChange={(e) => setState({ ...state, description: e.target.value })}
|
||||||
|
background={useColorModeValue('gray.50', 'gray.700')}
|
||||||
|
resize="vertical"
|
||||||
|
size="md"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{state.description.length === 0 && (
|
||||||
|
<FormLabel background="green.400" borderTopLeftRadius="8px" px={2} py={1}>
|
||||||
|
<IconTextDuo icon={(<BsMarkdown />)} text={i18n.labels.desc} />
|
||||||
|
</FormLabel>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.description.length ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<InputLeftAddon backgroundColor="#8a56c2" color="white">
|
||||||
|
<IconTextDuo icon={(<AiOutlineNumber />)} text="Qty" />
|
||||||
|
</InputLeftAddon>
|
||||||
|
{/* Use currency input to nicely handle whole numerical values */}
|
||||||
|
<CurrencyInput
|
||||||
|
prefix=""
|
||||||
|
allowDecimals={false}
|
||||||
|
className="chakra-input currency"
|
||||||
|
onValueChange={(value) => setState({
|
||||||
|
...state, quantity: JSON.parse(value),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.quantity ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<InputLeftAddon backgroundColor="#fbb355" color="black"><IconTextDuo icon={(<BsCurrencyDollar />)} text="Price" /></InputLeftAddon>
|
||||||
|
<CurrencyInput
|
||||||
|
prefix="$"
|
||||||
|
decimalsLimit={2}
|
||||||
|
className="chakra-input currency"
|
||||||
|
onValueChange={(value) => setState({
|
||||||
|
...state, price: JSON.parse(value),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
<Text fontSize=".75rem" color="red.500">{!state.price ? i18n.labels.required : null}</Text>
|
||||||
|
</FormControl>
|
||||||
|
<FormControl
|
||||||
|
onSubmit={save}
|
||||||
|
onKeyPress={(e) => e.key === 'Enter' && save()}
|
||||||
|
isRequired
|
||||||
|
padding=".5rem"
|
||||||
|
borderRadius="8px"
|
||||||
|
margin="auto"
|
||||||
|
>
|
||||||
|
<InputGroup style={InputGroupStyle}>
|
||||||
|
<FileUpload
|
||||||
|
name="image"
|
||||||
|
acceptedFileTypes="image/*"
|
||||||
|
required
|
||||||
|
allowMultipleFiles
|
||||||
|
propagateChange={(evt) => setState({
|
||||||
|
...state,
|
||||||
|
images: Array.from(evt.target.files),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</InputGroup>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
display="block"
|
||||||
|
mx="auto"
|
||||||
|
mt={4}
|
||||||
|
colorScheme="green"
|
||||||
|
isLoading={loading}
|
||||||
|
type="submit"
|
||||||
|
onClick={save}
|
||||||
|
>
|
||||||
|
{i18n.labels.save}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
@ -1,225 +1,133 @@
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Box, Button, FormControl, FormLabel, Heading,
|
Table, Thead, Tbody, Tr, Th, Td, TableContainer, Box, Button, Flex,
|
||||||
InputGroup, InputLeftAddon, Text, Textarea, useColorModeValue,
|
|
||||||
} from '@chakra-ui/react';
|
} from '@chakra-ui/react';
|
||||||
import CurrencyInput from 'react-currency-input-field';
|
import { BiSearchAlt2 } from 'react-icons/bi';
|
||||||
import { AiOutlineFileText, AiOutlineNumber } from 'react-icons/ai';
|
import { Manage as i18n, General } from '../../global/i18n';
|
||||||
import { BsCurrencyDollar } from 'react-icons/bs';
|
import Loading from '../../global/components/Loading';
|
||||||
import InlineLabelInput from '../../global/components/FormControl/InlineLabelInput';
|
|
||||||
import IconTextDuo from '../../global/components/IconTextDuo';
|
|
||||||
import { Manage as i18n } from '../../global/i18n';
|
|
||||||
import store from '../../redux/store';
|
import store from '../../redux/store';
|
||||||
import { FileUpload } from './components/FileUpload';
|
import InlineLabelInput from '../../global/components/FormControl/InlineLabelInput';
|
||||||
|
import DynamicModal from './components/DynamicModal';
|
||||||
|
import New from './components/modal/New';
|
||||||
|
import Edit from './components/modal/Edit';
|
||||||
|
import search from '../../global/search';
|
||||||
|
|
||||||
const InputGroupStyle = {
|
const init = async (setProductsPt, setLoadedPt, setAllProductsPt) => {
|
||||||
marginTop: '1rem',
|
const resp = await fetch('/api/v1/products');
|
||||||
marginBottom: '1rem',
|
const data = await resp.json();
|
||||||
};
|
if (resp.ok) {
|
||||||
|
setProductsPt(data);
|
||||||
const uploadImage = async (file) => {
|
setAllProductsPt(data);
|
||||||
const fd = new FormData();
|
setLoadedPt(true);
|
||||||
fd.append('file', file);
|
} else {
|
||||||
const resp = await fetch('/api/v1/fileupload', { method: 'POST', body: fd });
|
store.dispatch({ type: 'SET_ALERT', data: { header: i18n.downloadFailedAlert.header, content: JSON.stringify(data.error) } });
|
||||||
const { output, error } = await resp.json();
|
|
||||||
if (error) {
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.error(error);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
return `/api/v1/fileupload/${output}`;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
const [loading, setLoading] = useState(false);
|
// New Product Modal management
|
||||||
const [state, setState] = useState({
|
const [newModal, setNewModal] = useState(false);
|
||||||
name: '',
|
const [editItem, setEditItem] = useState(null);
|
||||||
description: '',
|
|
||||||
quantity: null,
|
|
||||||
price: null,
|
|
||||||
images: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const save = async () => {
|
const [hasLoaded, setLoaded] = useState(false);
|
||||||
setLoading(true);
|
const [allProducts, setAllProducts] = useState([]);
|
||||||
if (!state.name.length || !state.quantity || !state.price) {
|
const [products, setProducts] = useState([]);
|
||||||
store.dispatch({ type: 'SET_ALERT', data: { header: 'Missing Info', content: 'Not all required fields have been filled. Please provide this info to proceed.' } });
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// Step 1: Upload image files
|
|
||||||
const imageUrls = await Promise.all(state.images.map(uploadImage));
|
|
||||||
// Step 2: Upload the rest
|
|
||||||
const resp = await fetch('/api/v1/products', {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: {
|
|
||||||
authorization: `Bearer ${window.localStorage.getItem('auth-token')}`,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
...state,
|
|
||||||
images: imageUrls.length ? imageUrls : ['https://dv2ls.com/f/PpMcVb8gN'],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await resp.json();
|
|
||||||
if (resp.ok) {
|
|
||||||
// Workaround for resetting this form as many custom inputs == VERY difficult to do
|
|
||||||
// eslint-disable-next-line no-underscore-dangle
|
|
||||||
window.location.href = `${window.location.href}?_id=${data._id}`;
|
|
||||||
} else {
|
|
||||||
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Item', content: JSON.stringify(data) } });
|
|
||||||
}
|
|
||||||
} catch (ex) {
|
|
||||||
store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Item in Catch Block', content: ex } });
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Workaround for resetting this form as many custom inputs == VERY difficult to do
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const params = new URLSearchParams(window.location.search);
|
if (hasLoaded) return () => {};
|
||||||
if (params.has('_id')) {
|
init(setProducts, setLoaded, setAllProducts);
|
||||||
store.dispatch({ type: 'SET_ALERT', data: { ...i18n.create.itemCreatedSuccess(params.get('_id')) } });
|
|
||||||
window.history.replaceState(null, null, window.location.pathname);
|
|
||||||
}
|
|
||||||
return () => {};
|
return () => {};
|
||||||
}, []);
|
}, [hasLoaded, setLoaded, setProducts, setAllProducts]);
|
||||||
|
|
||||||
|
if (!hasLoaded) {
|
||||||
|
return (<Loading />);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Heading textAlign="center" marginBottom="1rem">
|
<Flex justifyContent="center" alignItems="center">
|
||||||
{i18n.create.title}
|
<Box maxW="400px" m="auto">
|
||||||
</Heading>
|
<InlineLabelInput
|
||||||
|
propChangeEvt={(evt) => setProducts(search(evt.target.value, allProducts))}
|
||||||
<Box
|
propKeyPressEvt={() => {}}
|
||||||
borderRadius="2xl"
|
propSubmitEvt={() => {}}
|
||||||
padding="2rem"
|
type="text"
|
||||||
backgroundColor="blackAlpha.200"
|
labelBgColor="green.400"
|
||||||
w="100%"
|
labelFgColor="white"
|
||||||
maxW="768px"
|
labelIcon={(<BiSearchAlt2 />)}
|
||||||
margin="auto"
|
labelText="Search.."
|
||||||
>
|
error={null}
|
||||||
<InlineLabelInput
|
|
||||||
required
|
|
||||||
type="text"
|
|
||||||
propSubmitEvt={save}
|
|
||||||
propChangeEvt={(e) => setState({ ...state, name: e.target.value })}
|
|
||||||
propKeyPressEvt={(e) => e.key === 'Enter' && save()}
|
|
||||||
value={state.name}
|
|
||||||
labelText={i18n.create.labels.name}
|
|
||||||
labelIcon={(<AiOutlineFileText />)}
|
|
||||||
labelBgColor="#fa6663"
|
|
||||||
labelFgColor="black"
|
|
||||||
error={!state.name.length ? i18n.create.labels.required : null}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormControl
|
|
||||||
onSubmit={() => {}}
|
|
||||||
padding="0.5rem"
|
|
||||||
borderRadius="8px"
|
|
||||||
margin="auto"
|
|
||||||
variant="floating"
|
|
||||||
>
|
|
||||||
<Textarea
|
|
||||||
id="manage-text-area"
|
|
||||||
value={state.description}
|
|
||||||
onChange={(e) => setState({ ...state, description: e.target.value })}
|
|
||||||
background={useColorModeValue('gray.50', 'gray.700')}
|
|
||||||
resize="vertical"
|
|
||||||
size="md"
|
|
||||||
/>
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
{state.description.length === 0 && (
|
<Button backgroundColor="green.400" onClick={() => setNewModal(true)}>
|
||||||
<FormLabel background="green.400" borderTopLeftRadius="8px" px={2} py={1}>
|
Create
|
||||||
<IconTextDuo icon={(<AiOutlineFileText />)} text={i18n.create.labels.desc} />
|
|
||||||
</FormLabel>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Text fontSize=".75rem" color="red.500">{!state.description.length ? i18n.create.labels.required : null}</Text>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<FormControl
|
|
||||||
onSubmit={save}
|
|
||||||
onKeyPress={(e) => e.key === 'Enter' && save()}
|
|
||||||
isRequired
|
|
||||||
padding=".5rem"
|
|
||||||
borderRadius="8px"
|
|
||||||
margin="auto"
|
|
||||||
>
|
|
||||||
<InputGroup style={InputGroupStyle}>
|
|
||||||
<InputLeftAddon backgroundColor="#8a56c2" color="white">
|
|
||||||
<IconTextDuo icon={(<AiOutlineNumber />)} text="Qty" />
|
|
||||||
</InputLeftAddon>
|
|
||||||
{/* Use currency input to nicely handle whole numerical values */}
|
|
||||||
<CurrencyInput
|
|
||||||
prefix=""
|
|
||||||
allowDecimals={false}
|
|
||||||
className="chakra-input currency"
|
|
||||||
onValueChange={(value) => setState({
|
|
||||||
...state, quantity: JSON.parse(value),
|
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</InputGroup>
|
|
||||||
<Text fontSize=".75rem" color="red.500">{!state.quantity ? i18n.create.labels.required : null}</Text>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<FormControl
|
|
||||||
onSubmit={save}
|
|
||||||
onKeyPress={(e) => e.key === 'Enter' && save()}
|
|
||||||
isRequired
|
|
||||||
padding=".5rem"
|
|
||||||
borderRadius="8px"
|
|
||||||
margin="auto"
|
|
||||||
>
|
|
||||||
<InputGroup style={InputGroupStyle}>
|
|
||||||
<InputLeftAddon backgroundColor="#fbb355" color="black"><IconTextDuo icon={(<BsCurrencyDollar />)} text="Price" /></InputLeftAddon>
|
|
||||||
<CurrencyInput
|
|
||||||
prefix="$"
|
|
||||||
decimalsLimit={2}
|
|
||||||
className="chakra-input currency"
|
|
||||||
onValueChange={(value) => setState({
|
|
||||||
...state, price: JSON.parse(value),
|
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</InputGroup>
|
|
||||||
<Text fontSize=".75rem" color="red.500">{!state.price ? i18n.create.labels.required : null}</Text>
|
|
||||||
</FormControl>
|
|
||||||
<FormControl
|
|
||||||
onSubmit={save}
|
|
||||||
onKeyPress={(e) => e.key === 'Enter' && save()}
|
|
||||||
isRequired
|
|
||||||
padding=".5rem"
|
|
||||||
borderRadius="8px"
|
|
||||||
margin="auto"
|
|
||||||
>
|
|
||||||
<InputGroup style={InputGroupStyle}>
|
|
||||||
<FileUpload
|
|
||||||
name="image"
|
|
||||||
acceptedFileTypes="image/*"
|
|
||||||
required
|
|
||||||
allowMultipleFiles
|
|
||||||
propagateChange={(evt) => setState({
|
|
||||||
...state,
|
|
||||||
images: Array.from(evt.target.files),
|
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</InputGroup>
|
|
||||||
</FormControl>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
display="block"
|
|
||||||
mx="auto"
|
|
||||||
mt={4}
|
|
||||||
colorScheme="green"
|
|
||||||
isLoading={loading}
|
|
||||||
type="submit"
|
|
||||||
onClick={save}
|
|
||||||
>
|
|
||||||
{i18n.create.labels.save}
|
|
||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Flex>
|
||||||
|
|
||||||
|
<hr />
|
||||||
|
|
||||||
|
<TableContainer>
|
||||||
|
<Table>
|
||||||
|
<Thead>
|
||||||
|
<Tr>
|
||||||
|
<Th>{i18n.labels.name}</Th>
|
||||||
|
<Th>{i18n.labels.desc}</Th>
|
||||||
|
<Th>{i18n.labels.price}</Th>
|
||||||
|
<Th>{i18n.labels.qty}</Th>
|
||||||
|
<Th>{i18n.labels.hidden}</Th>
|
||||||
|
<Th>{i18n.labels.rating}</Th>
|
||||||
|
</Tr>
|
||||||
|
</Thead>
|
||||||
|
<Tbody>
|
||||||
|
{products.map((x) => (
|
||||||
|
<Tr
|
||||||
|
onClick={() => setEditItem(x)}
|
||||||
|
cursor="pointer"
|
||||||
|
_hover={{ backgroundColor: 'var(--chakra-colors-green-500)' }}
|
||||||
|
key={x.name}
|
||||||
|
>
|
||||||
|
<Td>{x.name}</Td>
|
||||||
|
<Td>
|
||||||
|
{x.description?.substring(0, 24)}
|
||||||
|
...
|
||||||
|
</Td>
|
||||||
|
<Td>
|
||||||
|
$
|
||||||
|
{x.price}
|
||||||
|
</Td>
|
||||||
|
<Td>{x.quantity}</Td>
|
||||||
|
<Td>{x.hidden ? General.yes : General.no}</Td>
|
||||||
|
<Td>{x.overallRating || 'No Reviews'}</Td>
|
||||||
|
</Tr>
|
||||||
|
))}
|
||||||
|
</Tbody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
|
||||||
|
<DynamicModal
|
||||||
|
open={newModal}
|
||||||
|
header={i18n.create.title}
|
||||||
|
superOnClose={() => {
|
||||||
|
setNewModal(false);
|
||||||
|
init(setProducts, setLoaded, setAllProducts);
|
||||||
|
}}
|
||||||
|
size="3xl"
|
||||||
|
>
|
||||||
|
<New />
|
||||||
|
</DynamicModal>
|
||||||
|
|
||||||
|
<DynamicModal
|
||||||
|
open={!!editItem}
|
||||||
|
header={i18n.edit.title(editItem?.name)}
|
||||||
|
superOnClose={() => {
|
||||||
|
setEditItem(null);
|
||||||
|
init(setProducts, setLoaded, setAllProducts);
|
||||||
|
}}
|
||||||
|
size="3xl"
|
||||||
|
>
|
||||||
|
<Edit product={editItem} />
|
||||||
|
</DynamicModal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { Box, Button, Heading } from '@chakra-ui/react';
|
import {
|
||||||
|
Box, Button, Code, Heading,
|
||||||
|
} from '@chakra-ui/react';
|
||||||
import ReactMarkdown from 'react-markdown';
|
import ReactMarkdown from 'react-markdown';
|
||||||
import Loading from '../../global/components/Loading';
|
import Loading from '../../global/components/Loading';
|
||||||
import { Product as i18n } from '../../global/i18n';
|
import { Product as i18n } from '../../global/i18n';
|
||||||
|
|
@ -70,7 +72,9 @@ export default () => {
|
||||||
|
|
||||||
<hr style={{ margin: '2rem auto' }} />
|
<hr style={{ margin: '2rem auto' }} />
|
||||||
|
|
||||||
<p>{JSON.stringify(product)}</p>
|
<Code colorScheme="cyan">
|
||||||
|
{JSON.stringify(product, null, 2)}
|
||||||
|
</Code>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue