Ver código fonte

fix userOrderForm

ilya_shyian 2 anos atrás
pai
commit
d43723d220

+ 1 - 1
src/actions/actionCatAll.js

@@ -7,7 +7,7 @@ export const actionCatAll =
         dispatch(
             actionPromise(
                 promiseName,
-                fetch('/categories/', {
+                fetch(`/categories/?limit=${limit}&skip=${skip}`, {
                     method: 'GET',
                     headers: {
                         'Content-Type': 'application/json',

+ 1 - 1
src/actions/actionGoodsAll.js

@@ -7,7 +7,7 @@ export const actionGoodsAll =
         dispatch(
             actionPromise(
                 promiseName,
-                fetch('/goods/', {
+                fetch(`/goods/?limit=${limit}&skip=${skip}`, {
                     method: 'GET',
                     headers: {
                         'Content-Type': 'application/json',

+ 7 - 107
src/actions/actionGoodsPopular.js

@@ -6,115 +6,15 @@ export const actionGoodsPopular = () => async (dispatch, getState) => {
     dispatch(
         actionPromise(
             'goodsPopular',
-            new Promise((resolve) => {
-                setTimeout(
-                    Math.random() > 0.01
-                        ? resolve({
-                              data: [
-                                  {
-                                      _id: 1,
-                                      name: 'Good 1',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: [
-                                          {
-                                              _id: 1,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                          {
-                                              _id: 2,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                      ],
-                                  },
-                                  {
-                                      _id: 2,
-                                      name: 'Good 2',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: [
-                                          {
-                                              _id: 1,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                          {
-                                              _id: 2,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                      ],
-                                  },
-                                  {
-                                      _id: 3,
-                                      name: 'Good 3',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: null,
-                                  },
-                                  {
-                                      _id: 4,
-                                      name: 'Good 4',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: [
-                                          {
-                                              _id: 1,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                          {
-                                              _id: 2,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                      ],
-                                  },
-                                  {
-                                      _id: 5,
-                                      name: 'Good 5',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: [
-                                          {
-                                              _id: 1,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                          {
-                                              _id: 2,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                      ],
-                                  },
-                                  {
-                                      _id: 6,
-                                      name: 'Good 6',
-                                      description: 'adaadasda asasd asd asd asd asd ',
-                                      price: '999',
-                                      amount: 9999,
-                                      images: [
-                                          {
-                                              _id: 1,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                          {
-                                              _id: 2,
-                                              url: 'https://content2.rozetka.com.ua/goods/images/big/183546719.jpg',
-                                          },
-                                      ],
-                                  },
-                              ],
-                          })
-                        : resolve({
-                              errors: [{ message: 'Error adsasdadas' }],
-                          }),
-                    400
-                );
+            fetch(`/goods/?limit=20&skip=0&popular=1`, {
+                method: 'GET',
+                headers: {
+                    'Content-Type': 'application/json',
+                    ...(localStorage.authToken ? { Authorization: 'Bearer ' + localStorage.authToken } : {}),
+                },
             })
-                // .then((res) => res.json())
+                .then((res) => res.json())
                 .then((data) => {
-                    console.log(data);
                     if (data.errors) {
                         throw new Error(JSON.stringify(data.errors));
                     } else return data.data;

+ 2 - 2
src/actions/actionOrderUpdate.js

@@ -1,7 +1,7 @@
 import { actionOrdersAll } from './actionOrdersAll';
 import { actionOrderUpsert } from './actionOrderUpsert';
 
-export const actionOrderUpdate = (good) => async (dispatch, getState) => {
-    await dispatch(actionOrderUpsert(good));
+export const actionOrderUpdate = (order) => async (dispatch, getState) => {
+    await dispatch(actionOrderUpsert(order));
     await dispatch(actionOrdersAll());
 };

+ 21 - 29
src/actions/actionOrderUpsert.js

@@ -1,39 +1,31 @@
 import { actionPromise } from '../reducers';
 
 export const actionOrderUpsert = (order) => async (dispatch) => {
+    const formData = new FormData();
+    order._id && formData.append('_id', order._id);
+    formData.append('orderGoods', JSON.stringify(order.orderGoods));
+    formData.append('email', order.email);
+    formData.append('phoneNumber', order.phoneNumber);
+    formData.append('adress', order.padress);
+    formData.append('delivery', order.delivery);
+    formData.append('name', order.name);
+    formData.append('surname', order.surname);
     dispatch(
         actionPromise(
             'orderUpsert',
-            new Promise((resolve) => {
-                setTimeout(
-                    Math.random() > 0.01
-                        ? resolve({
-                              data: {
-                                  _id: 4,
-                                  email: 'example@gmail.com',
-                                  phoneNumber: '0667213260',
-                                  orderGoods: [
-                                      {
-                                          _id: 1,
-                                          price: 999,
-                                          count: 1,
-                                          good: {
-                                              _id: 1,
-                                              name: 'Good 1',
-                                              price: '999',
-                                          },
-                                      },
-                                  ],
-                                  price: 999,
-                                  status: 3,
-                              },
-                          })
-                        : resolve({
-                              errors: [{ message: 'Error adsasdadas' }],
-                          }),
-                    400
-                );
+            fetch(`/order/`, {
+                method: 'POST',
+                headers: {
+                    ...(localStorage.authToken ? { Authorization: 'Bearer ' + localStorage.authToken } : {}),
+                },
+                body: formData,
             })
+                .then((res) => res.json())
+                .then((data) => {
+                    if (data.errors) {
+                        throw new Error(JSON.stringify(data.errors));
+                    } else return data.data;
+                })
         )
     );
 };

+ 8 - 31
src/actions/actionRootCats.js

@@ -6,41 +6,18 @@ export const actionRootCats = () => async (dispatch, getState) => {
     dispatch(
         actionPromise(
             'rootCats',
-            new Promise((resolve) => {
-                setTimeout(
-                    Math.random() > 0.01
-                        ? resolve({
-                              data: [
-                                  {
-                                      _id: 1,
-                                      name: 'Category 1',
-                                  },
-                                  {
-                                      _id: 2,
-                                      name: 'Category 2',
-                                  },
-                                  {
-                                      _id: 3,
-                                      name: 'Category 3',
-                                  },
-                                  {
-                                      _id: 4,
-                                      name: 'Category 4',
-                                  },
-                              ],
-                          })
-                        : resolve({
-                              errors: [{ message: 'Error adsasdadas' }],
-                          }),
-                    400
-                );
+            fetch(`/categories/?isRoot=1`, {
+                method: 'GET',
+                headers: {
+                    'Content-Type': 'application/json',
+                    ...(localStorage.authToken ? { Authorization: 'Bearer ' + localStorage.authToken } : {}),
+                },
             })
-                // .then((res) => res.json())
+                .then((res) => res.json())
                 .then((data) => {
-                    console.log(data);
                     if (data.errors) {
                         throw new Error(JSON.stringify(data.errors));
-                    } else return Object.values(data.data);
+                    } else return data.data;
                 })
         )
     );

+ 45 - 3
src/components/CartPage/OrderForm/index.js

@@ -1,6 +1,10 @@
-import { Box, Grid, TextField, MenuItem, Button } from '@mui/material';
+import { Box, Grid, TextField, MenuItem, Button, Alert, Snackbar } from '@mui/material';
 import * as Yup from 'yup';
 import { useFormik } from 'formik';
+import { connect } from 'react-redux';
+import { actionPromiseClear } from '../../../reducers';
+import { actionOrderUpdate } from '../../../actions/actionOrderUpdate';
+import { useEffect, useState } from 'react';
 
 const deliveryOptions = [
     { label: 'Нова пошта', value: 'nova-poshta' },
@@ -23,7 +27,7 @@ const orderSchema = Yup.object().shape({
         ),
 });
 
-export const OrderForm = ({ onSubmit = null }) => {
+export const OrderForm = ({ onSubmit = null, promiseStatus = null, serverErrors = [] } = {}) => {
     const formik = useFormik({
         initialValues: {
             name: '',
@@ -39,6 +43,20 @@ export const OrderForm = ({ onSubmit = null }) => {
             onSubmit(formik.values);
         },
     });
+    const [snackbar, setSnackbar] = useState({ isOpen: false, message: '', type: 'success' });
+
+    useEffect(() => {
+        if (promiseStatus === 'FULFILLED') {
+            formik.setSubmitting(false);
+            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
+        }
+        if (promiseStatus === 'REJECTED') {
+            const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
+            console.log(serverErrors);
+            formik.setSubmitting(false);
+            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
+        }
+    }, [promiseStatus]);
 
     return (
         <Box className="OrderForm" component="form" onSubmit={formik.handleSubmit}>
@@ -140,8 +158,22 @@ export const OrderForm = ({ onSubmit = null }) => {
                         ))}
                     </TextField>
                 </Grid>
+                <Snackbar
+                    severity={snackbar.type}
+                    message={snackbar.message}
+                    autoHideDuration={3000}
+                    open={snackbar.isOpen}
+                    onClose={() => setSnackbar({ ...snackbar, isOpen: false })}
+                    sx={{
+                        width: 400,
+                    }}
+                >
+                    <Alert severity={snackbar.type} sx={{ width: '100%' }} open={snackbar.isOpen}>
+                        {snackbar.message}
+                    </Alert>
+                </Snackbar>
                 <Grid item xs={12} display="flex" justifyContent="flex-end">
-                    <Button variant="contained" type="submit" disabled={formik.isSubmitting || !formik.isValid}>
+                    <Button variant="contained" type="submit" disabled={!formik.isValid || formik.isSubmitting}>
                         Підтвердити
                     </Button>
                 </Grid>
@@ -149,3 +181,13 @@ export const OrderForm = ({ onSubmit = null }) => {
         </Box>
     );
 };
+
+export const COrderForm = connect(
+    (state) => ({
+        promiseStatus: state.promise.orderUpsert?.status || null,
+        serverErrors: state.promise?.orderUpsert?.error || [],
+    }),
+    {
+        onClose: () => actionPromiseClear('orderUpsert'),
+    }
+)(OrderForm);

+ 16 - 4
src/components/CartPage/index.js

@@ -3,9 +3,10 @@ import { useEffect } from 'react';
 import { useDispatch, useSelector } from 'react-redux';
 import { useNavigate } from 'react-router-dom';
 import { actionNewOrder } from '../../actions/actionNewOrder';
+import { actionOrderUpdate } from '../../actions/actionOrderUpdate';
 import { actionCartDelete } from '../../reducers';
 import { CartItem } from './CartItem';
-import { OrderForm } from './OrderForm';
+import { COrderForm, OrderForm } from './OrderForm';
 
 export const CartPage = () => {
     const cart = useSelector((state) => state.cart || {});
@@ -18,6 +19,7 @@ export const CartPage = () => {
             navigate('/');
         }
     }, []);
+    console.log(cart);
 
     return (
         <Box className="CartPage">
@@ -26,7 +28,11 @@ export const CartPage = () => {
                 <Table className="table">
                     <TableBody>
                         {Object.entries(cart).map(([_id, order]) => (
-                            <CartItem order={order} onDeleteClick={(good) => dispatch(actionCartDelete(good))} />
+                            <CartItem
+                                order={order}
+                                onDeleteClick={(good) => dispatch(actionCartDelete(good))}
+                                key={_id}
+                            />
                         ))}
 
                         <TableRow>
@@ -43,8 +49,14 @@ export const CartPage = () => {
                     </TableBody>
                 </Table>
 
-                <OrderForm />
-                
+                <COrderForm
+                    onSubmit={(order) => {
+                        const orderToSubmit = order;
+                        orderToSubmit.orderGoods = Object.values(cart);
+                        console.log(orderToSubmit);
+                        dispatch(actionOrderUpdate(orderToSubmit));
+                    }}
+                />
             </Stack>
         </Box>
     );

+ 12 - 0
src/components/GoodsPage/SubCategories/index.js

@@ -0,0 +1,12 @@
+import { Box, Paper } from '@mui/material';
+import { Link } from 'react-router-dom';
+
+export const SubCategories = ({ categories }) => (
+    <Box className="SubCategories">
+        {(categories || []).map((cat) => (
+            <Paper className="SubCategory Link" component={Link} to={`/category/${cat._id}`}>
+                {cat.name}
+            </Paper>
+        ))}
+    </Box>
+);

+ 22 - 4
src/components/GoodsPage/index.js

@@ -1,16 +1,34 @@
-import { Grid } from '@mui/material';
+import { Grid, Stack, Typography } from '@mui/material';
 import { Box } from '@mui/system';
 import { connect } from 'react-redux';
 import { useParams } from 'react-router-dom';
 import { GoodCard } from '../common/GoodCard';
 import { GoodList } from '../common/GoodList';
+import { SubCategories } from './SubCategories';
 
 const GoodsPage = ({ category = {} }) => {
-    const { goods = [], name = '' } = category || {};
+    const { goods = [], name = '', subcategories = [] } = category || {};
 
     return (
-        <Box className="MainPage">
-            <GoodList goods={goods} />
+        <Box className="GoodsPage">
+            <Stack>
+                {!!subcategories.length ? (
+                    <Box>
+                        <Typography variant="h6" color="#79747E" textAlign="left">
+                            Категорії
+                        </Typography>
+                        <SubCategories categories={subcategories} />
+                    </Box>
+                ) : null}
+                {!!goods.length ? (
+                    <Box>
+                        <Typography paddingBottom={1} variant="h6" color="#79747E" textAlign="left">
+                            Товари
+                        </Typography>
+                        <GoodList goods={goods} />
+                    </Box>
+                ) : null}
+            </Stack>
         </Box>
     );
 };

+ 2 - 1
src/components/LayoutPage/index.js

@@ -20,7 +20,8 @@ import { MainPage } from '../MainPage';
 const GoodsPageContainer = () => {
     const params = useParams();
     const dispatch = useDispatch();
-    dispatch(actionCatById(params._id));
+    console.log(params);
+    dispatch(actionCatById({ _id: params._id }));
 
     return <CGoodsPage />;
 };

+ 3 - 3
src/components/admin/AdminCategoryPage/CategoryForm.js

@@ -61,12 +61,12 @@ const CategoryForm = ({
         console.log(promiseStatus);
         if (promiseStatus === 'FULFILLED') {
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', severity: 'succes' });
+            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
         }
         if (promiseStatus === 'REJECTED') {
-            const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr, '');
+            const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, severity: 'error' });
+            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
         }
     }, [promiseStatus]);
 

+ 4 - 5
src/components/admin/AdminGoodPage/GoodForm.js

@@ -78,15 +78,14 @@ export const GoodForm = ({
     });
 
     useEffect(() => {
-        console.log(promiseStatus);
         if (promiseStatus === 'FULFILLED') {
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', severity: 'succes' });
+            setSnackbar({ ...snackbar, isOpen: true, message: 'Готово', type: 'success' });
         }
         if (promiseStatus === 'REJECTED') {
-            const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr, '');
+            const errorMessage = serverErrors.reduce((prev, curr) => prev + '\n' + curr.message, '');
             formik.setSubmitting(false);
-            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, severity: 'error' });
+            setSnackbar({ ...snackbar, isOpen: true, message: errorMessage, type: 'error' });
         }
     }, [promiseStatus]);
 
@@ -219,7 +218,7 @@ export const CGoodForm = connect(
         catList: state.promise.catAll?.payload || [],
         promiseStatus: state.promise.goodUpsert?.status || null,
         good: state.promise?.adminGoodById?.payload || {},
-        serverErrors: state.promise?.adminGoodById?.errors || [],
+        serverErrors: state.promise?.goodUpsert?.errors || [],
     }),
     {
         onSave: (good) => actionGoodUpdate(good),

+ 5 - 1
src/components/common/DrawerCart/DrawerCart.js

@@ -42,7 +42,11 @@ export const DrawerCart = ({ isOpen = false, onClose = null } = {}) => {
 
                     <Divider />
                     {Object.entries(cart).map(([_id, order]) => (
-                        <DrawerCartItem order={order} onDeleteClick={(good) => dispatch(actionCartDelete(good))} />
+                        <DrawerCartItem
+                            order={order}
+                            onDeleteClick={(good) => dispatch(actionCartDelete(good))}
+                            key={_id}
+                        />
                     ))}
 
                     {!!Object.keys(cart).length && (

+ 18 - 1
src/index.scss

@@ -272,7 +272,7 @@
     & .MainPage{
       padding: 10px;
       & .MainPageImage{
-        width: 1005;
+        width: 100%;
         border-radius: 10px;
       }
 
@@ -292,6 +292,23 @@
       }
 
     }
+
+    & .GoodsPage{
+      padding:10px;
+      & .SubCategories{
+        padding-top: 10px;
+        padding-bottom: 10px;
+        display: flex;
+        & .SubCategory{
+          width: 250px;
+          padding: 15px 7px;
+          margin-right: 15px;
+          margin-bottom: 15px;
+          cursor: pointer;
+        }
+
+      }
+    }
   }
 
   & .Footer{