Parcourir la source

rtk_edit good yepp

Gennadysht il y a 2 ans
Parent
commit
4bca8790d6

+ 28 - 8
src/Components/EditableGood.js

@@ -1,14 +1,16 @@
 import React, { useState } from 'react';
 import Button from '@mui/material/Button';
 import { styled } from '@mui/material/styles';
-import { Container, Grid, Card, CardContent, CardMedia, AvatarGroup, CardActions, IconButton, TextField, InputAdornment, Box } from '@mui/material';
+import { Container, Grid, Card, CardContent, CardMedia, AvatarGroup, CardActions, IconButton, TextField, InputAdornment, Box, Modal } from '@mui/material';
 import { getFullImageUrl } from "./../utills";
 import { useDispatch } from 'react-redux';
 import { useGetGoodByIdQuery, useSaveGoodMutation, useUploadSingleFileMutation } from '../reducers';
 import { useParams } from 'react-router-dom';
 import { actionSetCurrentGood } from '../reducers/frontEndReducer';
 import { CSortedFileDropZone } from './SortedFileDropZone';
-import { MyDropzone } from './FileDropZone';
+import { saveImage } from '../utills/utils';
+import { CGood } from './Good';
+import { ModalContainer } from './ModalContainer';
 
 
 export const ExpandMore = styled(props => {
@@ -39,6 +41,7 @@ export const AvatarGroupOriented = styled((props) => {
 
 const EditableGood = ({ good: goodExt, maxWidth = 'md', saveGood, uploadFile }) => {
     let [good, setGood] = useState(goodExt);
+    let [showPreview, setShowPreview] = useState(false);
     let [imagesContainer, setImagesContainer] = useState({ images: goodExt.images });
     const setGoodData = (data) => {
         let goodData = { ...good, ...data };
@@ -48,13 +51,20 @@ const EditableGood = ({ good: goodExt, maxWidth = 'md', saveGood, uploadFile })
     const onChangeImages = images => {
         setImagesContainer({ images });
     }
+    const preview = show => {
+        let a = '';
+        setShowPreview(show);
+    }
 
-    const saveFullGood = () => {
-        for (let image of imagesContainer.images){
-            uploadFile(image);
+    const saveFullGood = async () => {
+        let addedImages = imagesContainer.images.filter(img => !img._id);
+        let results = await Promise.all(addedImages.map(img => saveImage(img)));
+        for (let i = 0; i < results.length; i++) {
+            addedImages[i]._id = results[i]._id;
+            addedImages[i].url = results[i].url;
         }
-        //saveGood({ good });
-
+        good = { ...good, images: imagesContainer.images };
+        saveGood({ good });
     }
 
     return good && (
@@ -117,6 +127,11 @@ const EditableGood = ({ good: goodExt, maxWidth = 'md', saveGood, uploadFile })
                         <CSortedFileDropZone items={good.images} onChange={items => onChangeImages(items)} />
                     </Grid>
                 </Grid>
+                {showPreview &&
+                    <ModalContainer onCloseClick={() => preview(false)}>
+                        <CGood good={good} editable={false} />
+                    </ModalContainer>
+                }
                 <CardActions>
                     <Button size='small' color='primary'
                         onClick={() => saveFullGood(good)}
@@ -128,6 +143,11 @@ const EditableGood = ({ good: goodExt, maxWidth = 'md', saveGood, uploadFile })
                     >
                         Cancel
                     </Button>
+                    <Button size='small' color='primary'
+                        onClick={() => preview(true)}
+                    >
+                        Preview
+                    </Button>
                 </CardActions>
             </Card>
         </Container>
@@ -144,7 +164,7 @@ const CEditableGood = ({ maxWidth = 'md' }) => {
     const [uploadSingleFileMutation, { }] = useUploadSingleFileMutation();
 
 
-    return <EditableGood good={good} saveGood={saveGoodMutation} uploadFile={uploadSingleFileMutation} maxWidth={maxWidth} />
+    return !isLoading && <EditableGood good={good} saveGood={saveGoodMutation} uploadFile={uploadSingleFileMutation} maxWidth={maxWidth} />
 }
 
 export { CEditableGood }

+ 8 - 7
src/Components/Good.js

@@ -38,7 +38,7 @@ export const AvatarGroupOriented = styled((props) => {
     },
     ".MuiAvatar-root": { /*width: 20, height: 20,*/ marginLeft: 1 }
 }));
-const Good = ({ good, maxWidth = 'md', showAddToCard = true, actionAddGoodToCart }) => {
+const Good = ({ good, maxWidth = 'md', showAddToCard = true, actionAddGoodToCart, editable }) => {
     let [currentImageIndex, setCurrentImageIndex] = useState(0);
     let [expanded, setExpanded] = useState(false);
     const handleExpandClick = () => setExpanded(!expanded);
@@ -102,10 +102,11 @@ const Good = ({ good, maxWidth = 'md', showAddToCard = true, actionAddGoodToCart
                         )
                     }
                     <MyLink to={`/editgood/${good._id}`}>
-
-                        <Button size='small' color='primary'>
-                            Edit
-                        </Button>
+                        {
+                            editable && <Button size='small' color='primary'>
+                                Edit
+                            </Button>
+                        }
                     </MyLink>
                 </CardActions>
                 <Collapse in={expanded} timeout='auto' unmountOnExit>
@@ -121,13 +122,13 @@ const Good = ({ good, maxWidth = 'md', showAddToCard = true, actionAddGoodToCart
     )
 }
 
-const CGood = ({maxWidth = 'md', showAddToCard = true}) => {
+const CGood = ({ maxWidth = 'md', showAddToCard = true, editable = true }) => {
     const { _id } = useParams();
     const { isLoading, data } = useGetGoodByIdQuery(_id);
     let good = isLoading ? { name: 'loading', goods: [] } : data?.GoodFindOne;
     const dispatch = useDispatch();
     dispatch(actionSetCurrentGood(_id));
 
-    return <Good good={good} maxWidth={maxWidth} showAddToCard={showAddToCard} actionAddGoodToCart={() => dispatch(actionAddGoodToCart(good))} />
+    return <Good good={good} maxWidth={maxWidth} showAddToCard={showAddToCard} editable={editable} actionAddGoodToCart={() => dispatch(actionAddGoodToCart(good))} />
 }
 export { CGood };

+ 75 - 0
src/Components/ModalContainer.js

@@ -0,0 +1,75 @@
+/*
+.modal-overlay {
+  position: absolute;
+  z-index: 9;
+  top: 0;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  background-color: rgba(0, 0, 0, 0.7);
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+
+.modal {
+  background-color: #ffffff;
+  border: 1px solid #bebebe;
+  border-radius: 2px;
+  padding: 12px 16px;
+  position: relative;
+  height: 200px;
+  width: 350px;
+}
+
+.modal-close {
+  position: absolute;
+  right: 8px;
+  top: 4px;
+  font-size: 24px;
+  cursor: pointer;
+}*/
+
+import { styled } from "@mui/material";
+
+const ModalOverlay = styled('div')({
+  position: "absolute",
+  zIndex: 9,
+  top: 0,
+  right: 0,
+  bottom: 0,
+  left: 0,
+  backgroundColor: "rgba(0, 0, 0, 0.7)",
+  display: "flex",
+  justifyContent: "center",
+  alignItems: "center",
+});
+
+const Modal = styled('div')({
+  backgroundColor: "#ffffff",
+  border: "1px solid #bebebe",
+  borderRadius: "2px",
+  padding: "12px 16px",
+  position: "relative",
+});
+
+const ModalClose = styled('div')({
+  position: "absolute",
+  right: "8px",
+  top: "4px",
+  fontSize: "24p",
+  cursor: "pointer"
+});
+
+const ModalContainer = ({ children, onCloseClick }) => 
+  <ModalOverlay>
+    <Modal>
+      <ModalClose onClick={onCloseClick}>
+        &#10005; {/* HTML code for a multiplication sign */}
+      </ModalClose>
+      {children}
+    </Modal>
+  </ModalOverlay>
+
+
+export { ModalContainer };

+ 1 - 0
src/Components/SortedFileDropZone.js

@@ -104,6 +104,7 @@ function SortedFileDropZone({ items: startItems, render, itemProp, keyField, onC
             if (overIndex === undefined) {
                 if (items.length === 1)
                     activeIndex = 0;
+                items = [...items]
                 items.splice(activeIndex, 1);
                 return items;
             }

+ 1 - 1
src/reducers/cartReducer.js

@@ -12,7 +12,7 @@ const cartReducerSlice = createSlice({ //promiseReducer
     },
     reducers: {
         restoreCart(state, action) {
-            let goods = localStorage.cart.goods;
+            let goods = localStorage.cart?.goods ?? [];
             if (!goods) {
                 goods = [];
                 localStorage.cart = { goods: goods };

+ 17 - 2
src/utills/utils.js

@@ -1,9 +1,24 @@
+import { useSelector } from "react-redux";
+
 const getFullImageUrl = (image) =>
-    `http://shop-roles.node.ed.asmer.org.ua/${image?.url}`;
+        `/${image?.url}`;
 
 const findObjectIndexById = (objs, goodId) => {
     return (objs.findIndex(g => g._id === goodId))
 }
 
-export { getFullImageUrl, findObjectIndexById };
+function saveImage(image) {
+    let formData = new FormData();
+    formData.append('photo', image.data);
+    let token = JSON.parse(JSON.parse(localStorage["persist:auth"]).token);
+    let res = fetch('/upload', {
+        method: "POST",
+        headers: token ? { Authorization: 'Bearer ' + token } : {},
+        body: formData
+    }).then(res => res.json());
+    return res;
+}
+
+export { getFullImageUrl, findObjectIndexById, saveImage };
+