Browse Source

update code style

Vika 2 years ago
parent
commit
80e5f9ecfd
78 changed files with 2659 additions and 2129 deletions
  1. 4 0
      project/my-project/.eslintignore
  2. 54 0
      project/my-project/.eslintrc.js
  3. 1402 729
      project/my-project/package-lock.json
  4. 10 0
      project/my-project/package.json
  5. 33 1
      project/my-project/src/App.css
  6. 4 7
      project/my-project/src/App.js
  7. 6 8
      project/my-project/src/action/actionAddCategory.js
  8. 14 13
      project/my-project/src/action/actionAddGoodToCat.js
  9. 5 5
      project/my-project/src/action/actionCart.js
  10. 5 6
      project/my-project/src/action/actionCatById.js
  11. 8 9
      project/my-project/src/action/actionChangeArrImgGood.js
  12. 12 12
      project/my-project/src/action/actionChangeCategName.js
  13. 10 10
      project/my-project/src/action/actionChangeGoodsInCat.js
  14. 13 14
      project/my-project/src/action/actionChangeOneGood.js
  15. 2 5
      project/my-project/src/action/actionClearFirstImg.js
  16. 5 5
      project/my-project/src/action/actionGoodById.js
  17. 13 14
      project/my-project/src/action/actionImg.js
  18. 2 2
      project/my-project/src/action/actionImgClear.js
  19. 14 14
      project/my-project/src/action/actionLogin.js
  20. 5 5
      project/my-project/src/action/actionMyOrders.js
  21. 10 15
      project/my-project/src/action/actionOrder.js
  22. 13 14
      project/my-project/src/action/actionPromise.js
  23. 21 21
      project/my-project/src/action/actionRegister.js
  24. 3 3
      project/my-project/src/action/actionRootCats.js
  25. 15 17
      project/my-project/src/action/actionSearchGood.js
  26. 16 21
      project/my-project/src/action/actionUploadFile.js
  27. 13 14
      project/my-project/src/action/actionUploadFirstImg.js
  28. 16 21
      project/my-project/src/action/actionUploadImg.js
  29. 3 4
      project/my-project/src/action/index.js
  30. 17 17
      project/my-project/src/api/index.js
  31. 12 13
      project/my-project/src/components/addCategory.js
  32. 28 35
      project/my-project/src/components/additionalImages.js
  33. 9 10
      project/my-project/src/components/buttonExSite.js
  34. 18 26
      project/my-project/src/components/cCategory.js
  35. 15 30
      project/my-project/src/components/cGoodCard.js
  36. 16 16
      project/my-project/src/components/cNewGoodInCat.js
  37. 60 59
      project/my-project/src/components/cartChangeGood.js
  38. 16 24
      project/my-project/src/components/cartGoodAdmin.js
  39. 20 28
      project/my-project/src/components/category.js
  40. 82 91
      project/my-project/src/components/changeOfGood.js
  41. 2 4
      project/my-project/src/components/emptyContent.js
  42. 34 21
      project/my-project/src/components/goodCardCharacteristic.js
  43. 31 30
      project/my-project/src/components/goodSearch.js
  44. 45 58
      project/my-project/src/components/header.js
  45. 6 13
      project/my-project/src/components/imgGood.js
  46. 2 4
      project/my-project/src/components/index.js
  47. 23 20
      project/my-project/src/components/inputSearchGood.js
  48. 14 15
      project/my-project/src/components/inputUploadFile.js
  49. 16 24
      project/my-project/src/components/listOrders.js
  50. 18 19
      project/my-project/src/components/nameCategory.js
  51. 2 2
      project/my-project/src/components/pege404.js
  52. 21 34
      project/my-project/src/components/registerIn.js
  53. 26 36
      project/my-project/src/components/signIn.js
  54. 39 38
      project/my-project/src/components/sortTableComponent.js
  55. 14 16
      project/my-project/src/components/switchRoute.js
  56. 0 2
      project/my-project/src/index.js
  57. 12 12
      project/my-project/src/pages/cpageCategory.js
  58. 1 1
      project/my-project/src/pages/index.js
  59. 11 15
      project/my-project/src/pages/mainPage.js
  60. 15 17
      project/my-project/src/pages/pageAdmin.js
  61. 55 59
      project/my-project/src/pages/pageBasket.js
  62. 13 13
      project/my-project/src/pages/pageGood.js
  63. 14 13
      project/my-project/src/pages/pageSearch.js
  64. 13 27
      project/my-project/src/pages/pageUser.js
  65. 22 49
      project/my-project/src/reducer/authReducer.js
  66. 50 58
      project/my-project/src/reducer/cartReducer.js
  67. 3 3
      project/my-project/src/reducer/index.js
  68. 9 11
      project/my-project/src/reducer/promiseImg.js
  69. 12 17
      project/my-project/src/reducer/promisePreloader.js
  70. 7 20
      project/my-project/src/reducer/promiseReducer.js
  71. 8 11
      project/my-project/src/reducer/uploaderReducer.js
  72. 31 33
      project/my-project/src/route/cRoute.js
  73. 7 9
      project/my-project/src/route/privateRoute.js
  74. 22 24
      project/my-project/src/route/routeSite.js
  75. 9 12
      project/my-project/src/route/useRoute.js
  76. 22 45
      project/my-project/src/store/index.js
  77. 1 1
      project/my-project/src/utils/index.js
  78. 5 5
      project/my-project/src/utils/jwtDecode.js

+ 4 - 0
project/my-project/.eslintignore

@@ -0,0 +1,4 @@
+node_modules/
+build
+**/*.test.js
+babel.config.js

+ 54 - 0
project/my-project/.eslintrc.js

@@ -0,0 +1,54 @@
+module.exports = {
+  env: {
+    browser: true,
+    es2021: true
+  },
+  extends: [
+    'plugin:react/recommended',
+    'standard'
+  ],
+  parser: '@babel/eslint-parser',
+  parserOptions: {
+    ecmaFeatures: {
+      jsx: true
+    },
+    ecmaVersion: 'latest',
+    sourceType: 'module',
+    requireConfigFile: false,
+    babelOptions: {
+      presets: ['@babel/preset-react']
+    }
+  },
+  settings: {
+    react: {
+      version: 'detect'
+    }
+  },
+  plugins: [
+    'react'
+  ],
+  overrides: [
+    {
+      files: ['**/*.js', '**/*.jsx'],
+      rules: {
+        'no-unused-vars': ['off'],
+        'no-undef': ['off'],
+        'react/prop-types': ['off'],
+        'react/display-name': ['off'],
+        'no-var': 'warn',
+        'max-len': ['warn', { code: 120 }],
+        'jest/valid-expect': ['off'],
+        'react/react-in-jsx-scope': 'off',
+        'comma-dangle': ['warn', {
+          arrays: 'never',
+          objects: 'never',
+          imports: 'never',
+          exports: 'never',
+          functions: 'never'
+        }],
+        semi: [2, 'always'],
+        'semi-spacing': ['warn', { before: false, after: true }]
+      }
+    }
+  ]
+};

File diff suppressed because it is too large
+ 1402 - 729
project/my-project/package-lock.json


+ 10 - 0
project/my-project/package.json

@@ -45,5 +45,15 @@
       "last 1 firefox version",
       "last 1 safari version"
     ]
+  },
+  "devDependencies": {
+    "@babel/eslint-parser": "^7.16.5",
+    "@babel/preset-react": "^7.16.7",
+    "eslint": "^7.32.0",
+    "eslint-config-standard": "^16.0.3",
+    "eslint-plugin-import": "^2.25.4",
+    "eslint-plugin-node": "^11.1.0",
+    "eslint-plugin-promise": "^5.2.0",
+    "eslint-plugin-react": "^7.28.0"
   }
 }

+ 33 - 1
project/my-project/src/App.css

@@ -81,11 +81,17 @@ a:link, a:visited {
 }
 
 .additionalImg {
-  outline: 2px solid rgb(117, 9, 103);;
+  /* outline: 2px solid rgb(117, 9, 103);; */
   display: inline-block;
   margin-left: 3px;
+  width: 100%;
+  display: inline-block;
+  text-align: center;
+  margin-top: 10px;
 }
 
+
+
 .sortTablelist {
   display: flex;
   flex-direction: row;
@@ -94,4 +100,30 @@ a:link, a:visited {
 
 .liSortTable {
   display: block;
+}
+
+.ant-carousel {
+  line-height: 7;
+  font-feature-settings: "tnum";
+}
+
+.ant-carousel .slick-dots li button {
+
+  
+  height: 15px;
+  color: black;
+  background: rgb(58, 165, 236);
+  border-radius: 50%;
+  opacity: 0.8;
+ 
+}
+
+.slick-active button {
+  background: blue;
+}
+
+.ant-carousel .slick-dots li.slick-active button {
+    background: rgb(14, 80, 141);
+    opacity: 1;
+    border-radius: 50%;
 }

+ 4 - 7
project/my-project/src/App.js

@@ -1,16 +1,15 @@
+import { Router } from 'react-router-dom';
+import createHistory from 'history/createBrowserHistory';
+import { Provider } from 'react-redux';
 
 import 'antd/dist/antd.min.css';
 import { MainPage } from './pages';
-import { Router, Route, Link, Redirect, Switch } from 'react-router-dom';
-import createHistory from "history/createBrowserHistory";
-import { Provider, connect } from 'react-redux';
 import { store } from './store';
 import './App.css';
-import { InputUpLoadFile} from './components';
 
 const history = createHistory();
 
-function App() {
+function App () {
   return (
     <Router history={history}>
       <Provider store={store}>
@@ -19,8 +18,6 @@ function App() {
       </div>
       </Provider>
     </Router>
-
-    
   );
 }
 

+ 6 - 8
project/my-project/src/action/actionAddCategory.js

@@ -1,15 +1,13 @@
-import _default from "antd/lib/checkbox/Group"
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
-const actionAddCategory = (name) => 
+const actionAddCategory = (name) =>
   actionPromise('addCat', gql(`mutation addCategory ($add:CategoryInput) {
     CategoryUpsert(category:$add){
       _id name
       }
     }`, {
-      "add": {"name": name}
-    }))
+    add: { name }
+  }));
 
-
-export default actionAddCategory; 
+export default actionAddCategory;

+ 14 - 13
project/my-project/src/action/actionAddGoodToCat.js

@@ -1,22 +1,23 @@
-import { actionCatById, actionPromise } from ".";
-import gql from "../api";
+import { actionCatById, actionPromise } from '.';
+import gql from '../api';
 
-const actionAddGoodToCat = (_idCat, nameCat, nameGood) => 
- async (dispatch) => {
-  await  dispatch(actionPromise('addGoodToCat', gql(` mutation addGood($good:GoodInput){
+const actionAddGoodToCat = (_idCat, nameCat, nameGood) =>
+  async (dispatch) => {
+    await dispatch(actionPromise('addGoodToCat', gql(` mutation addGood($good:GoodInput){
       GoodUpsert(good:$good){
         _id name 
       }
     }`, {
-      "good": {"name":nameGood,
-              "categories":[{
-                  "name":nameCat,
-                  "_id": _idCat,
-              }]
+      good: {
+        name: nameGood,
+        categories: [{
+          name: nameCat,
+          _id: _idCat
+        }]
       }
-    })))
+    })));
 
     dispatch(actionCatById(_idCat));
-}
+  };
 
-export default actionAddGoodToCat;
+export default actionAddGoodToCat;

+ 5 - 5
project/my-project/src/action/actionCart.js

@@ -1,5 +1,5 @@
-export const actionCartAdd = (good, count = 1) => ({type: 'CART_ADD', good, count});
-export const actionCartRemove = (good) =>({type: 'CART_REMOVE', good});
-export const actionCartChange = (good, count) =>({type: 'CART_CHANGE', good, count});
-export const actionCartClear = () => ({type: 'CART_CLEAR'})
-export const actionCartMin = (good, count = 1) =>({type: 'CART_MINUS', good, count});
+export const actionCartAdd = (good, count = 1) => ({ type: 'CART_ADD', good, count });
+export const actionCartRemove = (good) => ({ type: 'CART_REMOVE', good });
+export const actionCartChange = (good, count) => ({ type: 'CART_CHANGE', good, count });
+export const actionCartClear = () => ({ type: 'CART_CLEAR' });
+export const actionCartMin = (good, count = 1) => ({ type: 'CART_MINUS', good, count });

+ 5 - 6
project/my-project/src/action/actionCatById.js

@@ -1,8 +1,7 @@
-import _default from "antd/lib/checkbox/Group";
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
-const actionCatById = (_id) =>  //добавить подкатегории
+const actionCatById = (_id) =>
   actionPromise('catById', gql(`query catById($q: String){
       CategoryFindOne(query:$q){
          _id name subCategories {
@@ -19,6 +18,6 @@ const actionCatById = (_id) =>  //добавить подкатегории
          }
        }
      }
-   }`, {"q": JSON.stringify([{_id}])}))
+   }`, { q: JSON.stringify([{ _id }]) }));
 
-   export default actionCatById;
+export default actionCatById;

+ 8 - 9
project/my-project/src/action/actionChangeArrImgGood.js

@@ -1,21 +1,20 @@
-import { actionPromise } from "."
-import { actionGoodById } from "./index";
-import gql from "../api"
+import { actionPromise, actionGoodById } from '.';
+import gql from '../api';
 
-const actionChangeArrInGood = (_id, arr) => 
+const actionChangeArrInGood = (_id, arr) =>
   async (dispatch) => {
     await dispatch(actionPromise('changeArrInGood', gql(`mutation changeArrImgInGood ($good:GoodInput){
       GoodUpsert(good:$good){
         _id name
       }
     }`, {
-      "good": {
-        "_id": _id,
-        "images": arr,
+      good: {
+        _id,
+        images: arr
       }
     })));
 
     dispatch(actionGoodById(_id));
-  }
+  };
 
-export default actionChangeArrInGood; 
+export default actionChangeArrInGood;

+ 12 - 12
project/my-project/src/action/actionChangeCategName.js

@@ -1,20 +1,20 @@
-import { actionPromise } from ".";
-import gql from "../api";
-import { actionRootCats } from ".";
+import { actionPromise, actionRootCats } from '.';
+import gql from '../api';
 
-const actionChangeCategName = (_id, name) => 
-  async (dispatch) => { 
+const actionChangeCategName = (_id, name) =>
+  async (dispatch) => {
     await dispatch(actionPromise('newCategoryName', gql(`mutation categoryChange($category:CategoryInput){
     CategoryUpsert(category:$category){
       _id name
       }
     }`, {
-      "category": {
-        "_id": _id,
-        "name": name}
-    })))
+      category: {
+        _id,
+        name
+      }
+    })));
 
-    dispatch(actionRootCats())
-  }
+    dispatch(actionRootCats());
+  };
 
-export default actionChangeCategName;
+export default actionChangeCategName;

+ 10 - 10
project/my-project/src/action/actionChangeGoodsInCat.js

@@ -1,5 +1,5 @@
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
 const actionChangeGoodsInCat = (_id, name, goods) => {
   return actionPromise('changeGoodsInCat ', gql(`
@@ -10,12 +10,12 @@ const actionChangeGoodsInCat = (_id, name, goods) => {
         }
       }
     }`, {
-      "category":{
-        "_id": _id,
-        "name": name,
-        "goods": goods,
-      }
-    }))
-}
+    category: {
+      _id,
+      name,
+      goods
+    }
+  }));
+};
 
-export default actionChangeGoodsInCat; 
+export default actionChangeGoodsInCat;

+ 13 - 14
project/my-project/src/action/actionChangeOneGood.js

@@ -1,5 +1,5 @@
-import { actionPromise, actionCatById } from ".";
-import gql from "../api";
+import { actionPromise, actionCatById } from '.';
+import gql from '../api';
 
 const actionChangeOneGood = (_id, _idCat, name, description, price, idImg) =>
   async (dispatch) => {
@@ -8,17 +8,16 @@ const actionChangeOneGood = (_id, _idCat, name, description, price, idImg) =>
         _id name
       }
     }`, {
-          "good":{
-          "_id": _id,
-          "description": description,
-          "name": name, 
-          "price": +price,
-          // "images": [{"_id": idImg}]
-          "images": idImg,
-        } 
-    })))
+      good: {
+        _id,
+        description,
+        name,
+        price: +price,
+        images: idImg
+      }
+    })));
 
-    dispatch(actionCatById(_idCat)); console.log('_idCattttttt', _idCat)
-}
+    dispatch(actionCatById(_idCat));
+  };
 
-export default actionChangeOneGood; 
+export default actionChangeOneGood;

+ 2 - 5
project/my-project/src/action/actionClearFirstImg.js

@@ -1,6 +1,3 @@
-const actionClearFirstImg = () => {
-  console.log('ACTION ON DELETE UPLOAD')
-   return {type: 'UPLOAD_IMG_CLEAR'}
-};
+const actionClearFirstImg = () => ({ type: 'UPLOAD_IMG_CLEAR' });
 
-export default actionClearFirstImg;
+export default actionClearFirstImg;

+ 5 - 5
project/my-project/src/action/actionGoodById.js

@@ -1,13 +1,13 @@
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
 const actionGoodById = (_id) =>
-   actionPromise('goodById', gql(`query goodById($goodId:String){
+  actionPromise('goodById', gql(`query goodById($goodId:String){
     GoodFindOne(query:$goodId){
         _id name description price images{
         _id text url
       }
     }
-  }`, {"goodId": JSON.stringify([{_id}])}))
+  }`, { goodId: JSON.stringify([{ _id }]) }));
 
-export default actionGoodById;
+export default actionGoodById;

+ 13 - 14
project/my-project/src/action/actionImg.js

@@ -1,18 +1,17 @@
-const actionPend  = name => ({type: 'IMG', status: 'PENDING', name})
-const actionResolv = (name, payload) => ({type: 'IMG', status: 'RESOLVED', name, payload})
-const actionReject = (name, error) => ({type: 'IMG', status: 'REJECTED', name,  error})
+const actionPend = name => ({ type: 'IMG', status: 'PENDING', name });
+const actionResolv = (name, payload) => ({ type: 'IMG', status: 'RESOLVED', name, payload });
+const actionReject = (name, error) => ({ type: 'IMG', status: 'REJECTED', name, error });
 
 const actionImg = (name, promise) =>
   async (dispatch) => {
-      dispatch(actionPend(name)) 
-      try{
-          let payload = await promise
-          dispatch(actionResolv(name, payload))
-          return payload;
-      }
-      catch(error){
-          dispatch(actionReject(name, error))
-      }
-  }
+    dispatch(actionPend(name));
+    try {
+      const payload = await promise;
+      dispatch(actionResolv(name, payload));
+      return payload;
+    } catch (error) {
+      dispatch(actionReject(name, error));
+    }
+  };
 
- export default actionImg; 
+export default actionImg;

+ 2 - 2
project/my-project/src/action/actionImgClear.js

@@ -1,3 +1,3 @@
-const actionImgClear = () => ({type:'IMG_CLEAR'});
+const actionImgClear = () => ({ type: 'IMG_CLEAR' });
 
-export default actionImgClear;
+export default actionImgClear;

+ 14 - 14
project/my-project/src/action/actionLogin.js

@@ -1,26 +1,26 @@
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
 const actionLogin = (login, password) =>
   actionPromise('login', gql(`query authorize ($login:String, $password:String){
     login(login:$login, password:$password)}`
-  , 
-    {
-      "login": `${login}`,
-      "password":`${password}`
-    }
+  ,
+  {
+    login: `${login}`,
+    password: `${password}`
+  }
   )
-)
+  );
 
-const actionAuthLogin  = token => ({type: 'AUTH_LOGIN', token})
+const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token });
 
 const actionFullLogin = (login, password) =>
   async dispatch => {
-    let token = await dispatch(actionLogin(login, password)); 
+    const token = await dispatch(actionLogin(login, password));
 
-    if (token){
-        dispatch(actionAuthLogin(token))
+    if (token) {
+      dispatch(actionAuthLogin(token));
     }
-  }
+  };
 
-export default actionFullLogin;  
+export default actionFullLogin;

+ 5 - 5
project/my-project/src/action/actionMyOrders.js

@@ -1,5 +1,5 @@
-import { actionPromise } from ".";
-import gql from "../api";
+import { actionPromise } from '.';
+import gql from '../api';
 
 const actionMyOrders = () =>
   async (dispatch, getState) => {
@@ -7,7 +7,7 @@ const actionMyOrders = () =>
       OrderFind(query:"[{}]"){
         orderGoods {price, count, good{name, _id}, total, _id}
       }
-    }`)))
-  }
+    }`)));
+  };
 
- export default  actionMyOrders;
+export default actionMyOrders;

+ 10 - 15
project/my-project/src/action/actionOrder.js

@@ -1,23 +1,18 @@
-import gql from "../api";
-import { store} from '../store';
-import { actionPromise } from ".";
+import gql from '../api';
+import { store } from '../store';
+import { actionPromise } from '.';
 
 const actionOrder = () =>
   async (dispatch, getState) => {
-      let {cart} = store.getState()
-                                                                          //магия по созданию структуры вида
-                                                                      //let orderGoods = [{good: {_id}, count}, {good: {_id}, count} .......]
-                                                                      //из структуры вида
-                                                                          //{_id1: {good, count},
-                                                                          //_id2: {good, count}}
-      const orderGoods = Object.entries(cart).map(([_id, {good, count}]) => ({good: {_id}, count}))
+    const { cart } = store.getState();
+    const orderGoods = Object.entries(cart).map(([_id, { good, count }]) => ({ good: { _id }, count }));
 
-      await dispatch(actionPromise('order', gql(`
+    await dispatch(actionPromise('order', gql(`
                   mutation newOrder($order:OrderInput){
                     OrderUpsert(order:$order)
-                      { _id total 	}
+                      { _id total }
                   }
-          `, {order: {orderGoods}})))
-}
+          `, { order: { orderGoods } })));
+  };
 
-export default actionOrder;
+export default actionOrder;

+ 13 - 14
project/my-project/src/action/actionPromise.js

@@ -1,18 +1,17 @@
-const actionPending  = name => ({type: 'PROMISE', status: 'PENDING', name})
-const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
-const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name,  error})
+const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name });
+const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload });
+const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error });
 
 const actionPromise = (name, promise) =>
   async (dispatch) => {
-      dispatch(actionPending(name)) 
-      try{
-          let payload = await promise
-          dispatch(actionResolved(name, payload))
-          return payload;
-      }
-      catch(error){
-          dispatch(actionRejected(name, error))
-      }
-  }
+    dispatch(actionPending(name));
+    try {
+      const payload = await promise;
+      dispatch(actionResolved(name, payload));
+      return payload;
+    } catch (error) {
+      dispatch(actionRejected(name, error));
+    }
+  };
 
- export default actionPromise; 
+export default actionPromise;

+ 21 - 21
project/my-project/src/action/actionRegister.js

@@ -1,27 +1,27 @@
-import { actionPromise } from ".";
-import gql from "../api";
-import { actionFullLogin } from ".";
+import { actionPromise, actionFullLogin } from '.';
+import gql from '../api';
 
-export const actionRegister = (login, password) =>                  //const actionRegister //actionPromise
+export const actionRegister = (login, password) =>
   actionPromise('register', gql(`mutation register($user:UserInput){
     UserUpsert(user:$user){
       _id login
     }
-  }`, {"user":{
-        "login": `${login}`,
-        "password": `${password}`
-        }
-      }
-    )
+  }`, {
+    user: {
+      login: `${login}`,
+      password: `${password}`
+    }
+  }
   )
-  
-export const actionAuthLogout = ()    => ({type: 'AUTH_LOGOUT'}); 
-  
-export const actionFullRegister = (login, password) =>   //const actionFullRegister = (login, password) => //actionRegister + actionFullLogin
-  async dispatch => {      
-    await dispatch(actionAuthLogout());                      //+ интерфейс к этому - форму логина, регистрации, может повесить это на #/login #/register 
-    let reg = await dispatch(actionRegister(login, password)); 
-    if(reg){
-      dispatch(actionFullLogin(login, password))
-    }                                                    //+ #/orders показывает ваши бывшие заказы:
-  }
+  );
+
+export const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' });
+
+export const actionFullRegister = (login, password) =>
+  async dispatch => {
+    await dispatch(actionAuthLogout());
+    const reg = await dispatch(actionRegister(login, password));
+    if (reg) {
+      dispatch(actionFullLogin(login, password));
+    }
+  };

+ 3 - 3
project/my-project/src/action/actionRootCats.js

@@ -1,12 +1,12 @@
 import actionPromise from './actionPromise';
 import gql from '../api';
 
-const actionRootCats = () => 
+const actionRootCats = () =>
   actionPromise('rootCats', gql(`query {
       CategoryFind(query: "[{\\"parent\\":null}]"){
           _id name subCategories {
             _id name}
       }
-  }`))
+  }`));
 
-export default actionRootCats;  
+export default actionRootCats;

+ 15 - 17
project/my-project/src/action/actionSearchGood.js

@@ -1,10 +1,9 @@
-import { actionPromise } from ".";
-import  gql  from '../api';
-
+import { actionPromise } from '.';
+import gql from '../api';
 
 const actionSearchGood = (name) =>
-  
-    actionPromise('searchGood', gql(`
+
+  actionPromise('searchGood', gql(`
       query gf($query: String){
           GoodFind(query: $query){
               _id, name, description, price, images{
@@ -12,17 +11,16 @@ const actionSearchGood = (name) =>
               }
           }
       }`, {
-        query: JSON.stringify([
-                  {
-                      $or: [{name}, {description: name}]
-                  },
-                  {
-                      sort: [{name: 1}]
-                  }
-                  ])
-          }
-      )
-    )
-  
+    query: JSON.stringify([
+      {
+        $or: [{ name }, { description: name }]
+      },
+      {
+        sort: [{ name: 1 }]
+      }
+    ])
+  }
+  )
+  );
 
 export default actionSearchGood;

+ 16 - 21
project/my-project/src/action/actionUploadFile.js

@@ -1,28 +1,23 @@
-import { connect } from "react-redux";
-import { actionUploadFirstImg  } from "./";
+import { actionUploadFirstImg } from './';
 import { backURL } from '../api';
-import { Upload, message, Button } from 'antd';
-import { UploadOutlined } from '@ant-design/icons';
 
 const actionUploadFile = (file) => {
-  const fileJson = JSON.stringify(file[0]);
   const formData = new FormData();
-  formData.append("photo", file[0]);
-  
-   return actionUploadFirstImg ('upLoad',  fetch(`${backURL}/upload`, {
-    method: "POST",
-    headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
+  formData.append('photo', file[0]);
+
+  return actionUploadFirstImg('upLoad', fetch(`${backURL}/upload`, {
+    method: 'POST',
+    headers: localStorage.authToken ? { Authorization: 'Bearer ' + localStorage.authToken } : {},
     body: formData
   })
-  .then(res => {
-    console.log('file', res)
-    return res.json();
-  }). then (data => {
-        if (data.errors && !data._id)
-            throw new Error(JSON.stringify(data.errors))
-        return data;
-})
-  )
-}
+    .then(res => {
+      console.log('file', res);
+      return res.json();
+    }).then(data => {
+      if (data.errors && !data._id) { throw new Error(JSON.stringify(data.errors)); };
+      return data;
+    })
+  );
+};
 
-export default actionUploadFile;
+export default actionUploadFile;

+ 13 - 14
project/my-project/src/action/actionUploadFirstImg.js

@@ -1,18 +1,17 @@
-const actionPend  = name => ({type: 'UPLOAD', status: 'PENDING', name})
-const actionResolv = (name, payload) => ({type: 'UPLOAD', status: 'RESOLVED', name, payload})
-const actionReject = (name, error) => ({type: 'UPLOAD', status: 'REJECTED', name,  error})
+const actionPend = name => ({ type: 'UPLOAD', status: 'PENDING', name });
+const actionResolv = (name, payload) => ({ type: 'UPLOAD', status: 'RESOLVED', name, payload });
+const actionReject = (name, error) => ({ type: 'UPLOAD', status: 'REJECTED', name, error });
 
 const actionUploadFirstImg = (name, promise) =>
   async (dispatch) => {
-      dispatch(actionPend(name)) 
-      try{
-          let payload = await promise
-          dispatch(actionResolv(name, payload))
-          return payload;
-      }
-      catch(error){
-          dispatch(actionReject(name, error))
-      }
-  }
+    dispatch(actionPend(name));
+    try {
+      const payload = await promise;
+      dispatch(actionResolv(name, payload));
+      return payload;
+    } catch (error) {
+      dispatch(actionReject(name, error));
+    }
+  };
 
- export default actionUploadFirstImg; 
+export default actionUploadFirstImg;

+ 16 - 21
project/my-project/src/action/actionUploadImg.js

@@ -1,28 +1,23 @@
-import { connect } from "react-redux";
-import { actionImg } from "./";
+import { actionImg } from './';
 import { backURL } from '../api';
-import { Upload, message, Button } from 'antd';
-import { UploadOutlined } from '@ant-design/icons';
 
 const actionUploadImg = (file, name) => {
-  const fileJson = JSON.stringify(file[0]);
   const formData = new FormData();
-  formData.append("photo", file[0]);
-  
-   return actionImg(name,  fetch(`${backURL}/upload`, {
-    method: "POST",
-    headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
+  formData.append('photo', file[0]);
+
+  return actionImg(name, fetch(`${backURL}/upload`, {
+    method: 'POST',
+    headers: localStorage.authToken ? { Authorization: 'Bearer ' + localStorage.authToken } : {},
     body: formData
   })
-  .then(res => {
-    console.log('file', res)
-    return res.json();
-  }). then (data => {
-        if (data.errors && !data._id)
-            throw new Error(JSON.stringify(data.errors))
-        return data;
-})
-  )
-}
+    .then(res => {
+      console.log('file', res);
+      return res.json();
+    }).then(data => {
+      if (data.errors && !data._id) { throw new Error(JSON.stringify(data.errors)); };
+      return data;
+    })
+  );
+};
 
-export default actionUploadImg;
+export default actionUploadImg;

+ 3 - 4
project/my-project/src/action/index.js

@@ -4,10 +4,10 @@ export { default as actionCatById } from './actionCatById';
 export { actionCartAdd, actionCartRemove, actionCartChange, actionCartClear, actionCartMin } from './actionCart';
 export { default as actionGoodById } from './actionGoodById';
 export { default as actionFullLogin } from './actionLogin';
-export {actionAuthLogout, actionFullRegister,} from './actionRegister';
+export { actionAuthLogout, actionFullRegister } from './actionRegister';
 export { default as actionOrder } from './actionOrder';
 export { default as actionMyOrders } from './actionMyOrders';
-export { default as actionUploadFile} from './actionUploadFile';
+export { default as actionUploadFile } from './actionUploadFile';
 export { default as actionChangeCategName } from './actionChangeCategName';
 export { default as actionAddCategory } from './actionAddCategory';
 export { default as actionChangeOneGood } from './actionChangeOneGood';
@@ -19,5 +19,4 @@ export { default as actionUploadImg } from './actionUploadImg';
 export { default as actionChangeArrInGood } from './actionChangeArrImgGood';
 export { default as actionImgClear } from './actionImgClear';
 export { default as actionUploadFirstImg } from './actionUploadFirstImg';
-export {default as actionClearFirstImg } from './actionClearFirstImg';
-
+export { default as actionClearFirstImg } from './actionClearFirstImg';

+ 17 - 17
project/my-project/src/api/index.js

@@ -1,26 +1,26 @@
 const getGQL = url =>
   (query, variables = {}) =>
-      fetch(url, {
-      //метод
+    fetch(url, {
+
       method: 'POST',
       headers: {
-          //заголовок content-type
-          "Content-Type": "application/json",
-          ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} :
-                                       {})
+
+        'Content-Type': 'application/json',
+        ...(localStorage.authToken
+          ? { Authorization: 'Bearer ' + localStorage.authToken }
+          : {})
       },
-      //body с ключами query и variables 
-      body: JSON.stringify({query, variables})
-      })
+
+      body: JSON.stringify({ query, variables })
+    })
       .then(res => res.json())
       .then(data => {
-          if (data.errors && !data.data)
-              throw new Error(JSON.stringify(data.errors))
-          return data.data[Object.keys(data.data)[0]]
-      })
+        if (data.errors && !data.data) { throw new Error(JSON.stringify(data.errors)); };
+        return data.data[Object.keys(data.data)[0]];
+      });
+
+export const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
 
-export const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
-  
-const gql = getGQL(`${backURL}/graphql`)
+const gql = getGQL(`${backURL}/graphql`);
 
-export default gql;
+export default gql;

+ 12 - 13
project/my-project/src/components/addCategory.js

@@ -1,15 +1,14 @@
 import { Input, Card, Button, Space } from 'antd';
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
 import { connect } from 'react-redux';
 import { actionAddCategory } from '../action';
 
-const ACategory = ({addCat}) => {
-  const [nameCat, setNameCat] =useState('');
-  
-  const clearInput = () => { 
-    setNameCat(''); 
-  }
-  
+const ACategory = ({ addCat }) => {
+  const [nameCat, setNameCat] = useState('');
+  const clearInput = () => {
+    setNameCat('');
+  };
+
   return (
     <div >
       <Card type="inner" title="Добавить категорию">
@@ -19,12 +18,12 @@ const ACategory = ({addCat}) => {
          <Button type="primary" onClick={() => addCat(nameCat)}>Сохранить изменения</Button>
          <Button type="primary" onClick={clearInput} >Очистить поле</Button>
         </Space>
-      
+
       </Card>
     </div>
-  )
-}
+  );
+};
 
-const AddCategory = connect(null, {addCat: actionAddCategory})(ACategory);
+const AddCategory = connect(null, { addCat: actionAddCategory })(ACategory);
 
-export default AddCategory;
+export default AddCategory;

+ 28 - 35
project/my-project/src/components/additionalImages.js

@@ -1,27 +1,23 @@
 import React, { useEffect, useState } from 'react';
 import { Upload, Button, Space } from 'antd';
-import ImgCrop from 'antd-img-crop'; 
-import { connect } from 'react-redux'; 
-import { backURL } from '../api'; 
-import { actionUploadImg, actionGoodById , actionChangeArrInGood, actionImgClear } from '../action';
+import ImgCrop from 'antd-img-crop';
+import { connect } from 'react-redux';
+import { actionUploadImg, actionGoodById, actionChangeArrInGood, actionImgClear } from '../action';
 import { Link } from 'react-router-dom';
 
-
-const Additional = ({imgs, upload, _id, goodById, good, saveImg, imgClear}) => { 
+const Additional = ({ imgs, upload, _id, goodById, good, saveImg, imgClear }) => {
   const [fileList, setFileList] = useState([]);
-  //const [selectGood, setSelectGood] = useState(good);
-  
+
   useEffect(() => {
     goodById(_id);
-                               
-  }, [_id])
-                                                            console.log('gooood', good);
+  }, [_id]);
+
   const onChange = ({ fileList: newFileList }) => {
-    setFileList(newFileList); console.log('newFileList', newFileList)
+    setFileList(newFileList); console.log('newFileList', newFileList);
   };
 
   const onPreview = async file => {
-    let src = file.url; console.log('file', file)
+    let src = file.url; console.log('file', file);
     if (!src) {
       src = await new Promise(resolve => {
         const reader = new FileReader();
@@ -35,24 +31,21 @@ const Additional = ({imgs, upload, _id, goodById, good, saveImg, imgClear}) => {
     imgWindow.document.write(image.outerHTML);
   };
   const onChangeArrImg = () => {
-    
-    const newArrImg = [... good.images].map((item) => ({"_id": item._id}));        
+    const newArrImg = [...good.images].map((item) => ({ _id: item._id }));
     for (let i = 0; i < Object.keys(imgs).length; i++) {
       const newImgId = imgs[`${i}`].payload._id;
-      
-      newArrImg.push({"_id":newImgId});           
+
+      newArrImg.push({ _id: newImgId });
       saveImg(good._id, newArrImg);
     }
-  }
+  };
 
   const onSave = async () => {
-    const newF = [...fileList].map((item) => [item.originFileObj]); 
-    const newFF = await  newF.map((item, index) => [upload(item, index)]); 
-    // await onChangeArrImg();
+    const newF = [...fileList].map((item) => [item.originFileObj]);
+    await newF.map((item, index) => [upload(item, index)]);
+
     setFileList([]);
-    // imgClear(); 
-    
-  }
+  };
 
   return (
     <div>
@@ -67,30 +60,30 @@ const Additional = ({imgs, upload, _id, goodById, good, saveImg, imgClear}) => {
           {fileList.length < 4 && '+ Добавить фото'}
         </Upload>
       </ImgCrop>
-     
+
       <Space direction="vertical">
         <Button type="primary" onClick={onSave}>Закачать</Button>
-        <Button type="primary" onClick={() => {onChangeArrImg(); imgClear()}}>Сохранить</Button>
+        <Button type="primary" onClick={() => { onChangeArrImg(); imgClear(); }}>Сохранить</Button>
         <Link to={`/goodAdmin/${_id}`}>
-          <Button type="primary" >Просмотреть карточку товара</Button> 
-        </Link> 
+          <Button type="primary" >Просмотреть карточку товара</Button>
+        </Link>
       </Space>
-      
-    </div>  
+
+    </div>
   );
 };
 
 const mapStateToProps = (state) => ({
   imgs: state.img || [],
-  good: state.promise.goodById?.payload || {},
-})
+  good: state.promise.goodById?.payload || {}
+});
 
 const mapDispatchToProps = {
   upload: actionUploadImg,
   goodById: actionGoodById,
-  saveImg: actionChangeArrInGood, 
-  imgClear: actionImgClear,
-}
+  saveImg: actionChangeArrInGood,
+  imgClear: actionImgClear
+};
 
 const AdditionalImages = connect(mapStateToProps, mapDispatchToProps)(Additional);
 

+ 9 - 10
project/my-project/src/components/buttonExSite.js

@@ -1,21 +1,20 @@
 import { Button } from 'antd';
 import { actionAuthLogout } from '../action';
 import { connect } from 'react-redux';
-import { Link } from 'react-router-dom/cjs/react-router-dom.min';
-import {useHistory} from 'react-router-dom';
+import { useHistory } from 'react-router-dom';
 
-const ButtonExit = ({authLogaut}) => {
-  let history = useHistory();
+const ButtonExit = ({ authLogaut }) => {
+  const history = useHistory();
 
   const exit = () => {
     authLogaut();
-    history.push("/");
-  }
+    history.push('/');
+  };
   return (
     <Button onClick={exit}>Выход</Button>
-  )
-}
+  );
+};
 
-const ButtonExSite = connect(null, {authLogaut:actionAuthLogout})(ButtonExit);
+const ButtonExSite = connect(null, { authLogaut: actionAuthLogout })(ButtonExit);
 
-export default ButtonExSite;
+export default ButtonExSite;

+ 18 - 26
project/my-project/src/components/cCategory.js

@@ -1,39 +1,31 @@
-import { CGoodCard } from ".";
-import { connect } from "react-redux";
-import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
-import { useEffect, useState } from "react";
-import { Link } from "react-router-dom";
-import { CPromisePreloader } from '../reducer'
+import { CGoodCard } from '.';
+import { connect } from 'react-redux';
+import { Menu } from 'antd';
+import { Link } from 'react-router-dom';
+import { CPromisePreloader } from '../reducer';
 
-const { SubMenu } = Menu;
-
-const Category = ({cat:{name, goods=[], subCategories}}) => { 
-  
+const Category = ({ cat: { name, goods = [], subCategories } }) => {
   return (
     <CPromisePreloader name='catById'>
       <div className='category'>
         <h1>{name}</h1>
         <Menu>
             {goods?.map(good => <CGoodCard key={good._id} good={good} />)}
-          
-            {subCategories?.map(subCateg =><Menu.Item className="subCategory" key= {subCateg._id}> 
-              
-                <Link  to={`/category/${subCateg._id}`}> 
-                  {subCateg.name} 
+
+            {subCategories?.map(subCateg => <Menu.Item className="subCategory" key= {subCateg._id}>
+
+                <Link to={`/category/${subCateg._id}`}>
+                  {subCateg.name}
                 </Link>
-               
-              
+
             </Menu.Item>)}
-        
-            
+
         </Menu>
       </div>
-    </CPromisePreloader>  
-  )
-}
-
+    </CPromisePreloader>
+  );
+};
 
-const CCategory = connect(state => ({cat:state.promise.catById?.payload || {}}))
-                              (Category)
+const CCategory = connect(state => ({ cat: state.promise.catById?.payload || {} }))(Category);
 
-export default CCategory;                              
+export default CCategory;

+ 15 - 30
project/my-project/src/components/cGoodCard.js

@@ -1,46 +1,31 @@
-import { Card, Image, Space } from 'antd';
+import { Card, Image, Space, Button } from 'antd';
 import { connect } from 'react-redux';
-import { Button, Radio } from 'antd';
 import { actionCartAdd } from '../action';
 import { Link } from 'react-router-dom';
 
-
 const { Meta } = Card;
-const backendURL = "http://shop-roles.asmer.fs.a-level.com.ua" ;
+const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
 
-const GoodCard = ({good:{_id, name, price, images}, onAdd}) =>
-  <Card 
-    
+const GoodCard = ({ good: { _id, name, price, images }, onAdd }) =>
+  <Card
     hoverable
     style={{ width: 240 }}
-    // cover={images && images[0] && images[0].url &&<Link to={`/good/${_id}`}> <img src={backendURL + '/' + images[0].url} /></Link>}
     >
     <Meta title={name} />
     <Space direction="vertical">
-      {images && images[0] && images[0].url &&<Link to={`/good/${_id}`}> <Image width={200} height={200} style={{objectFit: 'cover'}} src={backendURL + '/' + images[0].url} /></Link>}
+      {
+        images &&
+        images[0] &&
+        images[0].url &&
+        <Link to={`/good/${_id}`}>
+          <Image width={200} height={200} style={{ objectFit: 'cover' }} src={backendURL + '/' + images[0].url} />
+        </Link>}
       <strong>{price} грн.</strong>
-      <Button size="middle" onClick={() => onAdd({_id, name, price, images})}>Купить</Button>
+      <Button size="middle" onClick={() => onAdd({ _id, name, price, images })}>Купить</Button>
     </Space>
-   
-     
-    
-    
-
-  </Card>
-
-
-
 
-{/* <li className='GoodCard'>
-    <Link to={`/good/${_id}`}> 
-        <h2>{name}</h2>
-        {images && images[0] && images[0].url && <img src={backendURL + '/' + images[0].url} />}
-    </Link>    
-    <strong>{price}</strong>
-    <button onClick={() => onAdd({_id, name, price, images})}>+</button>
-    
-</li> */}
+  </Card>;
 
-const CGoodCard = connect(null, {onAdd: actionCartAdd})(GoodCard)
+const CGoodCard = connect(null, { onAdd: actionCartAdd })(GoodCard);
 
-export default CGoodCard;
+export default CGoodCard;

+ 16 - 16
project/my-project/src/components/cNewGoodInCat.js

@@ -1,9 +1,9 @@
-import { Card, Input, Space, Button } from "antd";
-import { useEffect, useState } from "react";
-import { connect } from "react-redux";
+import { Card, Input, Space, Button } from 'antd';
+import { useEffect, useState } from 'react';
+import { connect } from 'react-redux';
 import { actionAddGoodToCat } from '../action';
 
-const NewGoodInCat = ({cat, add}) => {
+const NewGoodInCat = ({ cat, add }) => {
   const [_idCat, setIdCat] = useState('');
   const [nameCat, setNameCat] = useState('');
   const [nameGood, setNameGood] = useState('');
@@ -12,30 +12,30 @@ const NewGoodInCat = ({cat, add}) => {
     if (cat) {
       setIdCat(cat._id);
       setNameCat(cat.name);
-    }                                            
-  }, [cat])
+    }
+  }, [cat]);
 
   const addGoodClearInput = () => {
-    add(_idCat, nameCat, nameGood); 
+    add(_idCat, nameCat, nameGood);
     setNameGood('');
-  }
+  };
 
   return (
     < >
       <Card type="inner" title="Добавить товар в категорию">
-       <div>Введите название товара </div> 
-       <Input  value={nameGood} onChange={(e) => setNameGood(e.target.value)}/>
+       <div>Введите название товара </div>
+       <Input value={nameGood} onChange={(e) => setNameGood(e.target.value)}/>
         <Space>
          <Button type="primary" onClick={() => addGoodClearInput()}>Сохранить изменения</Button>
          <Button type="primary" onClick={setNameGood}>Очистить поле</Button>
         </Space>
       </Card>
     </>
-  )
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
-  cat: state.promise.catById?.payload, 
-})
-const CNewGoodInCat = connect(mapStateToProps, {add: actionAddGoodToCat})(NewGoodInCat);
-export default CNewGoodInCat;
+  cat: state.promise.catById?.payload
+});
+const CNewGoodInCat = connect(mapStateToProps, { add: actionAddGoodToCat })(NewGoodInCat);
+export default CNewGoodInCat;

+ 60 - 59
project/my-project/src/components/cartChangeGood.js

@@ -1,4 +1,4 @@
-import { Select,Card } from 'antd';
+import { Select, Card } from 'antd';
 import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
 import { СhangeOfGood } from '.';
@@ -6,88 +6,89 @@ import { actionChangeOneGood, actionChangeGoodsInCat, actionImgClear, actionClea
 
 const { Option } = Select;
 
-const SelectGood = ({goods, changeGood, changeGoodsInCat, imgClear, firstImgClear, _idCat}) => { console.log('_idCat',_idCat)
-  
-  const [goodsCat, setGoodsCat] = useState([]); 
+const SelectGood = ({ goods, changeGood, changeGoodsInCat, imgClear, firstImgClear, _idCat }) => {
+  const [goodsCat, setGoodsCat] = useState([]);
   const [_id, setId] = useState('');
-  const [selectGood, setSelectGood] = useState({}); 
+  const [selectGood, setSelectGood] = useState({});
   const [numbSelectGood, setNumbSelectGood] = useState('');
   const [idCat, setIdCat] = useState('');
-  const [nameCat, setNameCat] =useState('');
-  
+  const [nameCat, setNameCat] = useState('');
+
   useEffect(() => {
-    if(goods && goods.goods && selectGood.name!== goods.goods.name ) {
+    if (goods && goods.goods && selectGood.name !== goods.goods.name) {
       setSelectGood({});
-      setNumbSelectGood('')
+      setNumbSelectGood('');
     }
 
-    if(goods && goods.goods){
+    if (goods && goods.goods) {
       setGoodsCat(goods.goods);
       setIdCat(goods._id);
-      setNameCat(goods.name)
+      setNameCat(goods.name);
     }
-  }, [goods])
+  }, [goods]);
 
-  function handleChange(value) {
-      console.log(`selected ${value}`);
-     
-      const good = goodsCat.filter((good, index) => {
-        if (good._id === value) {
-          setNumbSelectGood(index+1);
-        }
-         
-        return good._id === value}); 
-      setSelectGood(...good);
-      setId(value);
-      imgClear(); 
-      firstImgClear();
-    }
+  function handleChange (value) {
+    const good = goodsCat.filter((good, index) => {
+      if (good._id === value) {
+        setNumbSelectGood(index + 1);
+      }
 
-    function changeGoodInSer (name, description, price, imgId) {
-                                                               
-      changeGood(_id, _idCat, name, description,price, imgId);
-    }
-    function changeIndexGoodInSer (number) {              
-      if (numbSelectGood !== number && number > 0 ){                  
-        const newGoodsCat = [...goodsCat];             
-        const goodRemuve = newGoodsCat.splice(numbSelectGood-1, 1)[0];   
-        newGoodsCat.splice(number-1,0, goodRemuve);        
-        const newGCat = newGoodsCat.map((item) => { console.log('itemmmm',item)
-          return ({_id: item._id});
-        })
-        changeGoodsInCat(idCat, nameCat, newGCat);
-      }  
-    }
+      return good._id === value;
+    });
+    setSelectGood(...good);
+    setId(value);
+    imgClear();
+    firstImgClear();
+  }
 
+  function changeGoodInSer (name, description, price, imgId) {
+    changeGood(_id, _idCat, name, description, price, imgId);
+  }
+  function changeIndexGoodInSer (number) {
+    if (numbSelectGood !== number && number > 0) {
+      const newGoodsCat = [...goodsCat];
+      const goodRemuve = newGoodsCat.splice(numbSelectGood - 1, 1)[0];
+      newGoodsCat.splice(number - 1, 0, goodRemuve);
+      const newGCat = newGoodsCat.map((item) => {
+        console.log('itemmmm', item);
+        return ({ _id: item._id });
+      });
+      changeGoodsInCat(idCat, nameCat, newGCat);
+    }
+  }
 
-   return (
+  return (
      < >{goods &&
       <Card type="inner" title="Изменить товар">
-        <Select value={selectGood.name || null} placeholder='Выбирите товар' style={{ width: 272 }} onChange={handleChange}>
-          {goodsCat.map((item, index) => <Option value={item._id} key={item._id}>{`${index+1} ${item.name}`}</Option>)}
+        <Select
+          value={selectGood.name || null}
+          placeholder='Выбирите товар'
+          style={{ width: 272 }} onChange={handleChange}>
+          {goodsCat.map((item, index) =>
+          <Option value={item._id} key={item._id}>{`${index + 1} ${item.name}`}</Option>)}
         </Select>
-        <СhangeOfGood good={selectGood} changeGood={changeGoodInSer} number={numbSelectGood} changeIndexGoodInSer={changeIndexGoodInSer}/>
-        {/* <div>
-          <p>№ в категории</p>
-        </div> */}
+        <СhangeOfGood
+          good={selectGood}
+          changeGood={changeGoodInSer}
+          number={numbSelectGood}
+          changeIndexGoodInSer={changeIndexGoodInSer}/>
       </Card>
     }</>
-   )
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
-  goods: state.promise.catById?.payload,
-  
-})
+  goods: state.promise.catById?.payload
+
+});
 
 const mapDispatchToProps = {
-  changeGood : actionChangeOneGood,
-  changeGoodsInCat: actionChangeGoodsInCat, 
+  changeGood: actionChangeOneGood,
+  changeGoodsInCat: actionChangeGoodsInCat,
   imgClear: actionImgClear,
-  firstImgClear: actionClearFirstImg,
-}
-
+  firstImgClear: actionClearFirstImg
+};
 
 const CartChangeGood = connect(mapStateToProps, mapDispatchToProps)(SelectGood);
 
-export default CartChangeGood;
+export default CartChangeGood;

+ 16 - 24
project/my-project/src/components/cartGoodAdmin.js

@@ -1,45 +1,37 @@
 import { connect } from 'react-redux';
-import { useState, useEffect } from 'react';
-import { GoodCardCharacteristic, SortableComponent  } from './index';
+import { GoodCardCharacteristic, SortableComponent } from './index';
 import { Card } from 'antd';
 import { actionClearFirstImg, actionChangeArrInGood } from '../action';
 
-
-const CartGoodAdmin = ({good:{_id, images}, upLoad, clearUpLoad, onChangeArrInGood}) => {
-  const [arrImages, setArrImages] = useState(images);  
-  const [upl, setUpl] = useState(upLoad);
-
-  // useEffect(() => {
-  //    setArrImages(images);                       
-  // }, [images])
-    
-  // useEffect(() => {
-  //   setUpl(upLoad);
-  // }, [upLoad])
-    console.log('upLoad===========', upLoad)
-   return (
+const CartGoodAdmin = ({ good: { _id, images }, upLoad, clearUpLoad, onChangeArrInGood }) => {
+  return (
     <Card>
       <GoodCardCharacteristic/>
-      <div style={{textAlign:"center"}}>
+      <div style={{ textAlign: 'center' }}>
         <strong >Фото можно поменять местами</strong>
       </div>
       <div>
-      <SortableComponent images={images} idGood={_id} upLoad={upLoad} clearUpLoad={clearUpLoad} onChangeArrInGood={onChangeArrInGood} />
+      <SortableComponent
+       images={images}
+       idGood={_id}
+       upLoad={upLoad}
+       clearUpLoad={clearUpLoad}
+       onChangeArrInGood={onChangeArrInGood} />
       </div>
     </Card>
-  )
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
-  good: state.promise.goodById?.payload || [],  
-  upLoad: state.upLoad.upLoad?.payload || '',
+  good: state.promise.goodById?.payload || [],
+  upLoad: state.upLoad.upLoad?.payload || ''
 });
 
 const mapDispatchToProps = {
   clearUpLoad: actionClearFirstImg,
-  onChangeArrInGood: actionChangeArrInGood,
+  onChangeArrInGood: actionChangeArrInGood
 };
 
 const CCartGoodAdmin = connect(mapStateToProps, mapDispatchToProps)(CartGoodAdmin);
 
-export default CCartGoodAdmin;
+export default CCartGoodAdmin;

+ 20 - 28
project/my-project/src/components/category.js

@@ -1,43 +1,35 @@
-import { store } from "../store";
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { AppstoreOutlined, MenuUnfoldOutlined, MenuFoldOutlined, PieChartOutlined, DesktopOutlined, ContainerOutlined, MailOutlined } from '@ant-design/icons';
-import {Provider, connect} from 'react-redux';
-import { Button, Menu  } from 'antd';
-import { useEffect, useState } from "react";
+import { Link } from 'react-router-dom';
+import { PieChartOutlined } from '@ant-design/icons';
+import { connect } from 'react-redux';
+import { Menu } from 'antd';
 import React from 'react';
-import { jwtDecode } from "../utils";
-
-const { SubMenu } = Menu;
-
-const CategoryListItem = ({_id, name, auth}) => {
 
+const CategoryListItem = ({ _id, name, auth }) => {
   return (
-    < > 
+    < >
       <Menu.Item icon={<PieChartOutlined />}><Link to={`/category/${_id}`}>{name} </Link></Menu.Item>
     </>
-    
-     
-  )  
-  
 
-}
+  );
+};
+
+const CategoryList = ({ cats, auth }) => {
+  console.log('cats', cats);
 
-const CategoryList = ({cats, auth}) =>{console.log('cats', cats)
- 
   return (
     <div >
-     
-        {cats.map((item) => <CategoryListItem key={item._id} {...item} auth={auth} />)}
-     
+
+      {cats.map((item) => <CategoryListItem key={item._id} {...item} auth={auth} />)}
+
     </div>
-  ) 
-}
+  );
+};
 
 const mapStateToProps = state => ({
-  cats:state.promise.rootCats?.payload || [],
-  auth: state.auth,
-})
+  cats: state.promise.rootCats?.payload || [],
+  auth: state.auth
+});
 
-const CCategoryList = connect(mapStateToProps)(CategoryList)
+const CCategoryList = connect(mapStateToProps)(CategoryList);
 
 export default CCategoryList;

+ 82 - 91
project/my-project/src/components/changeOfGood.js

@@ -1,86 +1,81 @@
-import { Input, Card, Button, Space, Image, Row } from 'antd';
-import { useEffect, useRef, useState } from 'react';
+import { Input, Button, Space, Image, Row } from 'antd';
+import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
-import { InputUpLoadFile } from '.';
-import { backURL } from '../api'; 
-import { AdditionalImages } from './index';
+import { InputUpLoadFile, AdditionalImages } from '.';
+import { backURL } from '../api';
 
 const { TextArea } = Input;
 
-const CharacterfGood =({ good, good:{ _id, name, description, images, price }, upLoad, changeGood, number, changeIndexGoodInSer }) => {    
-    const [ inputIdImg, setInputIdImg] = useState(''); 
-    const [ inputName, setInputName ] = useState(name); 
-    const [ inputDescrip, setInputDescrip] = useState(description);
-    const [ imag, setImag ] = useState(''); 
-    const [ cost, setCost ] = useState(price);
-    const [inputNumber, setInputNumber] = useState(number);
-
-    useEffect( () => {
-      setInputName(name);
-      setInputDescrip(description);
-
-      if (images && images.length >=1 &&images[0].url) {
-        setImag(images[0].url); 
-        setInputIdImg(images[0]._id);
-      }
-
-      if (Object.keys(good).length === 0) { 
-        setImag(''); 
-        setInputIdImg('');
-      }
-      if(images && images.length >=1 &&!images[0].url) {
-        setImag(''); 
-        setInputIdImg(''); 
-      }
-              
-      setCost(price); 
-      setInputNumber(number); 
-          
-
-    }, [good]);                                       console.log('good',good)
-
-                                                      
-
-    useEffect(() => {
-      if(upLoad && upLoad.status === 'RESOLVED' ) { 
-        setImag(upLoad.payload.url); console.log('39', imag)
-        setInputIdImg(upLoad.payload._id);  
-      }
-
-    }, [upLoad])
-
-    // onChange = ({ target: { value } }) => {
-    //   setInputDescrip(value);
-    // };
-
-    const clearInput = () => {
-      setInputName('');
-      setInputDescrip('');
-      setCost('');
-      setImag ('');
-      setInputIdImg('');
+const CharacterfGood = ({
+  good,
+  good: { _id, name, description, images, price },
+  upLoad, changeGood, number, changeIndexGoodInSer
+}) => {
+  const [inputIdImg, setInputIdImg] = useState('');
+  const [inputName, setInputName] = useState(name);
+  const [inputDescrip, setInputDescrip] = useState(description);
+  const [imag, setImag] = useState('');
+  const [cost, setCost] = useState(price);
+  const [inputNumber, setInputNumber] = useState(number);
+
+  useEffect(() => {
+    setInputName(name);
+    setInputDescrip(description);
+
+    if (images && images.length >= 1 && images[0].url) {
+      setImag(images[0].url);
+      setInputIdImg(images[0]._id);
+    }
 
+    if (Object.keys(good).length === 0) {
+      setImag('');
+      setInputIdImg('');
     }
+    if (images && images.length >= 1 && !images[0].url) {
+      setImag('');
+      setInputIdImg('');
+    }
+
+    setCost(price);
+    setInputNumber(number);
+  }, [good]); console.log('good', good);
 
-    const saveChange = () => {
-       let goodImages = [{"_id": inputIdImg}];
-
-      if (good.images && good.images.length > 1) {
-        goodImages = [...good.images].map((state) => ({"_id": state._id})); 
-        goodImages.shift();
-        goodImages.unshift({"_id": inputIdImg}); 
-      }
-      // if (!good.images) {
-      //   goodImages = [{"_id": inputIdImg}]
-      // }          
-      changeGood(inputName, inputDescrip, cost, goodImages);
-      changeIndexGoodInSer(inputNumber);
-      clearInput();
+  useEffect(() => {
+    if (upLoad && upLoad.status === 'RESOLVED') {
+      setImag(upLoad.payload.url); console.log('39', imag);
+      setInputIdImg(upLoad.payload._id);
     }
-                                       console.log('inputIdImg', inputIdImg)  ;           
-                                       console.log('good',good); console.log('iinputIdImg.length === 0',  inputIdImg.length === 0 );
-                                       console.log('Object.keys(good).length === 0',Object.keys(good).length === 0);
-                                       console.log('good.images == null',good.images == null);
+  }, [upLoad]);
+
+  // onChange = ({ target: { value } }) => {
+  //   setInputDescrip(value);
+  // };
+
+  const clearInput = () => {
+    setInputName('');
+    setInputDescrip('');
+    setCost('');
+    setImag('');
+    setInputIdImg('');
+  };
+
+  const saveChange = () => {
+    let goodImages = [{ _id: inputIdImg }];
+
+    if (good.images && good.images.length > 1) {
+      goodImages = [...good.images].map((state) => ({ _id: state._id }));
+      goodImages.shift();
+      goodImages.unshift({ _id: inputIdImg });
+    }
+
+    changeGood(inputName, inputDescrip, cost, goodImages);
+    changeIndexGoodInSer(inputNumber);
+    clearInput();
+  };
+  console.log('inputIdImg', inputIdImg);
+  console.log('good', good); console.log('iinputIdImg.length === 0', inputIdImg.length === 0);
+  console.log('Object.keys(good).length === 0', Object.keys(good).length === 0);
+  console.log('good.images == null', good.images == null);
 
   return (
     <div >
@@ -95,7 +90,7 @@ const CharacterfGood =({ good, good:{ _id, name, description, images, price }, u
         <TextArea
             value={inputDescrip}
             onChange={(e) => setInputDescrip(e.target.value)}
-            
+
             autoSize={{ minRows: 3, maxRows: 5 }}
           />
         <Button type="primary" onClick={() => setInputDescrip('')}>Очистить поле</Button>
@@ -104,33 +99,29 @@ const CharacterfGood =({ good, good:{ _id, name, description, images, price }, u
           <Input value={cost} onChange={(e) => setCost(e.target.value)}/>
           <Button type="primary" onClick={() => setCost('')}>Очистить поле</Button>
         </Row>
-       
-        
+
         <Space size={12} direction="vertical">
-          
-            {/* <div  className="imgWrapper"> */}
+
               <div>Фото основное</div>
-            {(Object.keys(good).length === 0 && good.images == null )|| inputIdImg.length === 0   ?
-              <div style={{height:"150px", width:"150px"}}> </div>
-              :
-              <Image width={150} height={150} src={`${backURL}/${imag}`} style={{ objectFit: 'cover' }}/>}
+            {(Object.keys(good).length === 0 && good.images == null) || inputIdImg.length === 0
+              ? <div style={{ height: '150px', width: '150px' }}> </div>
+              : <Image width={150} height={150} src={`${backURL}/${imag}`} style={{ objectFit: 'cover' }}/>}
               <InputUpLoadFile/>
            {/* </div> */}
         </Space>
         <Space size={2}></Space>
         <Button type="primary" block onClick={saveChange}>
           Сохранить изменения
-        </Button>  
+        </Button>
         <div> Загрузить дополнительные фото</div>
-        <AdditionalImages imag={imag} _id={_id}/>   
+        <AdditionalImages imag={imag} _id={_id}/>
   </div>
-  )
-}
+  );
+};
 
-const mapStateToProps = ((state) => ({
+const mapStateToProps = (state) => ({
   upLoad: state.upLoad.upLoad
-}))
+});
 const СhangeOfGood = connect(mapStateToProps)(CharacterfGood);
 
 export default СhangeOfGood;
-

+ 2 - 4
project/my-project/src/components/emptyContent.js

@@ -1,11 +1,9 @@
 const EmptyContent = () => {
-
   return (
     < div>
 
     </div>
-  )
-}
+  );
+};
 
 export default EmptyContent;
-

+ 34 - 21
project/my-project/src/components/goodCardCharacteristic.js

@@ -1,40 +1,53 @@
-import { Card, Image, Button, Space  } from 'antd';
+import { Card, Image, Button, Carousel } from 'antd';
 import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
 import { actionCartAdd } from '../action';
 
 const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
 
-const Good = ({good: {name, images, description, price, _id}, onAdd}) => { 
+const Good = ({ good: { name, images, description, price, _id }, onAdd }) => {
   const [dopImg, setDopImg] = useState([]);
-  
+
   useEffect(() => {
-    if (images && images.length > 1) {         
-      const newImages = [...images]; 
-      newImages.shift();                    
+    if (images && images.length > 1) {
+      const newImages = [...images];
+      newImages.shift();
       setDopImg(newImages);
     }
-  }, [images])
-                                             
+  }, [images]);
+  function onChange (a, b, c) {
+    console.log(a, b, c);
+  }
+
+  const contentStyle = {
+    height: '160px',
+    color: '#fff',
+    lineHeight: '160px',
+    textAlign: 'center',
+    background: '#364d79'
+  };
+
   return (
-    <Card title={name} style={{ width: 400}} hoverable>
+    <Card title={name} style={{ width: 400 }} hoverable>
     {images && images[0] && images[0].url && <Image width={350} src={backendURL + '/' + images[0].url} />}
-    {(dopImg.length >= 1) &&  dopImg.map((item) =>
-      
-        <div key={item._id} className='additionalImg'> 
-          <Image width={110} height={110} src={backendURL + '/' + item.url} />
+    <Carousel afterChange={onChange}>
+    {(dopImg.length >= 1) && dopImg.map((item) =>
+
+        <div key={item._id} className='additionalImg' style={contentStyle}>
+          <Image width={160} height={160} src={backendURL + '/' + item.url} />
         </div>
-     
-        )}
+
+    )}
+    </Carousel>
     <p>{description}</p>
     <p>{price} грн</p>
-    <Button onClick={() => onAdd({_id, name, price, images})}>Купить</Button>
+    <Button onClick={() => onAdd({ _id, name, price, images })}>Купить</Button>
   </Card>
-  )
-}
+  );
+};
 
-const mapStateToProps = state => ({good: state.promise.goodById?.payload || {}})
+const mapStateToProps = state => ({ good: state.promise.goodById?.payload || {} });
 
-const GoodCardCharacteristic = connect(mapStateToProps, {onAdd: actionCartAdd})(Good);
+const GoodCardCharacteristic = connect(mapStateToProps, { onAdd: actionCartAdd })(Good);
 
-export default GoodCardCharacteristic;
+export default GoodCardCharacteristic;

+ 31 - 30
project/my-project/src/components/goodSearch.js

@@ -1,44 +1,45 @@
-import { useEffect, useState } from "react";
-import { Card, Image, Button,  Alert } from 'antd';
+import { useEffect, useState } from 'react';
+import { Card, Image, Button, Alert } from 'antd';
 import { connect } from 'react-redux';
-import { backURL } from "../api";
-import { actionCartAdd } from "../action";
-import {Router, Route, Link, Redirect, Switch, useHistory} from 'react-router-dom';
+import { backURL } from '../api';
+import { actionCartAdd } from '../action';
+import { useHistory } from 'react-router-dom';
 
-const ContentSearch = ({value, onAdd}) => { console.log('value', value)
-  const [good, setGood] = useState(value); 
-  let history = useHistory();
+const ContentSearch = ({ value, onAdd }) => {
+  console.log('value', value);
+  const [good, setGood] = useState(value);
+  const history = useHistory();
 
   useEffect(() => {
-    if(value.length) {
+    if (value.length) {
       setGood(value[0]);
     }
-  }, [value])
+  }, [value]);
 
   const onClose = (e) => {
     console.log(e, 'I was closed.');
     history.push('/');
-    
-  }
+  };
 
   return (
-    <> { value.length?
-        <Card title={good.name} style={{ width: 350 }} hoverable>
-          {good.images && good.images[0] && good.images[0].url && <Image width={300} src={backURL + '/' + good.images[0].url} />}
+    <> { value.length
+      ? <Card title={good.name} style={{ width: 350 }} hoverable>
+          {good.images &&
+          good.images[0] &&
+          good.images[0].url &&
+          <Image width={300} src={backURL + '/' + good.images[0].url} />}
           <p>{good.description}</p>
           <p>{good.price} грн</p>
           <Button onClick={() => onAdd({
-                                        _id: good._id, 
-                                        name: good.name, 
-                                        price: good.price,
-                                        images: good.images
-                                      })}>Купить</Button>
+            _id: good._id,
+            name: good.name,
+            price: good.price,
+            images: good.images
+          })}>Купить</Button>
         </Card>
-        :
-        <>
+      : <>
          <Alert
             message="Товара с таким названием не существует"
-            // description="Error Description Error Description Error Description Error Description Error Description Error Description"
             type="error"
             closable
             onClose={onClose}
@@ -46,16 +47,16 @@ const ContentSearch = ({value, onAdd}) => { console.log('value', value)
         </>
         }
     </>
-  )
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
-  value: state.promise.searchGood?.payload || [],
-})
+  value: state.promise.searchGood?.payload || []
+});
 const mapDispatchToProps = {
-  onAdd: actionCartAdd,
-}
+  onAdd: actionCartAdd
+};
 
 const GoodSearch = connect(mapStateToProps, mapDispatchToProps)(ContentSearch);
 
-export default GoodSearch;
+export default GoodSearch;

+ 45 - 58
project/my-project/src/components/header.js

@@ -1,92 +1,81 @@
-import { Layout, Menu, Breadcrumb, Row, Col, Avatar, Badge, Button, Input  } from 'antd';
+import { Layout, Row, Col, Avatar, Badge, Button } from 'antd';
 import { useEffect, useState } from 'react';
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
+import { Link } from 'react-router-dom';
 import { createFromIconfontCN, FileTwoTone } from '@ant-design/icons';
 import { connect } from 'react-redux';
 import { jwtDecode } from '../utils';
-import {default as ButtonExSite } from './buttonExSite';
+import ButtonExSite from './buttonExSite';
 import { actionMyOrders } from '../action';
 import { InputSearchGood } from '.';
 
-const { Header, Content, Footer, Sider } = Layout;
+const { Header } = Layout;
 
 const IconFont = createFromIconfontCN({
   scriptUrl: [
     '//at.alicdn.com/t/font_1788044_0dwu4guekcwr.js', // icon-javascript, icon-java, icon-shoppingcart (overrided)
-    '//at.alicdn.com/t/font_1788592_a5xf2bdic3u.js', // icon-shoppingcart, icon-python
-  ],
+    '//at.alicdn.com/t/font_1788592_a5xf2bdic3u.js' // icon-shoppingcart, icon-python
+  ]
 });
 
-const HeaderComponent = ({login, cart, getOrders}) => { 
-  
-  console.log('cartHeader', cart)
+const HeaderComponent = ({ login, cart, getOrders }) => {
+  console.log('cartHeader', cart);
   const [nike, setNike] = useState('');
-  const [countBasket, setCountBasket] = useState(0); console.log('CountBasket',countBasket );
+  const [countBasket, setCountBasket] = useState(0); console.log('CountBasket', countBasket);
 
-  useEffect (
+  useEffect(
     () => {
       if (login) {
-        // console.log('loginHeader', login)
-        // const base64Url = login.split('.')[1];
-        // const base64 = atob(base64Url);
-        // const b = JSON.parse(base64);
-        setNike(jwtDecode(login)['sub']['login']); 
-        
-        
+        setNike(jwtDecode(login).sub.login);
       }
-      
-      if(!login) { console.log('logauthhhhhh')
+
+      if (!login) {
         setNike(false);
-       
       }
 
       const arrCount = Object.values(cart);
-      const count = arrCount.reduce((accum, item) => accum + item.count, 0 );
+      const count = arrCount.reduce((accum, item) => accum + item.count, 0);
       setCountBasket(count);
-      
-      console.log('arrCount', arrCount)  ;
-      console.log('CountBasket',countBasket )
-    } 
-  , [login, cart])
-
-    
-   
-  return(
+
+      console.log('arrCount', arrCount);
+      console.log('CountBasket', countBasket);
+    }
+    , [login, cart]);
+
+  return (
     <Header className="header">
-    {/* <div className="logo" /> */}
-    
+
       <Row>
         <Col span={12}>
         </Col>
 
         <Col span={15}>
-          <InputSearchGood/> 
-        </Col>  
+          <InputSearchGood/>
+        </Col>
 
-       { nike? 
-        < >
+       { nike
+         ? < >
           <Col span={1}>
           <div className="icons-list">
-           <Avatar size={40}>{nike}</Avatar> 
+           <Avatar size={40}>{nike}</Avatar>
           </div>
           </Col>
           <Col span={1}></Col>
           <Col span={1}>
           <ButtonExSite/>
           </Col>
-        </>:
-        <>
+        </>
+         : <>
           <Col span={2}>
           <Button>
-            <Link to = {`/login`}> Вход</Link>
+            <Link to = {'/login'}> Вход</Link>
           </Button>
-           
+
           </Col>
           <Col span={2}>
             <Button>
-              <Link to = {`/registration`}>Регистрация</Link>
+              <Link to = {'/registration'}>Регистрация</Link>
             </Button>
-            
+
           </Col>
         </>
         }
@@ -94,33 +83,31 @@ const HeaderComponent = ({login, cart, getOrders}) => {
         <Col span={1}></Col>
         <Col span={1}>
         <Link to='/basket'>
-          <Badge count={countBasket} size="small" style={{marginTop: "11px"}}>
-            <IconFont type="icon-shoppingcart" style={{color:'blue', fontSize: "40px", marginTop: "14px"}}/>
-          </Badge>  
+          <Badge count={countBasket} size="small" style={{ marginTop: '11px' }}>
+            <IconFont type="icon-shoppingcart" style={{ color: 'blue', fontSize: '40px', marginTop: '14px' }}/>
+          </Badge>
         </Link>
         </Col>
 
         <Col span={1}> <Link to='/listOrders'>
-          <FileTwoTone twoToneColor="blue" style={{fontSize: "35px", marginTop: "15px", }} onClick={()=> getOrders()}/>
+          <FileTwoTone twoToneColor="blue" style={{ fontSize: '35px', marginTop: '15px' }} onClick={() => getOrders()}/>
         </Link></Col>
-       
-
 
       </Row>
-    
+
   </Header>
-  )
-} 
+  );
+};
 
 const mapStateToProps = (state) => ({
   login: state.auth?.token,
   cart: state?.cart
-})
+});
 
 const mapDispatchToProps = {
-  getOrders: actionMyOrders,
-}
+  getOrders: actionMyOrders
+};
 
-const HeaderSite = connect(mapStateToProps, mapDispatchToProps)(HeaderComponent)
+const HeaderSite = connect(mapStateToProps, mapDispatchToProps)(HeaderComponent);
 
-export default HeaderSite;
+export default HeaderSite;

+ 6 - 13
project/my-project/src/components/imgGood.js

@@ -1,25 +1,18 @@
-import { upload } from '@testing-library/user-event/dist/upload';
-import { Image , Card, Button} from 'antd';
-import { useEffect, useState } from 'react';
-import { connect } from 'react-redux';
+import { Image } from 'antd';
 import { backURL } from '../api';
 import { InputUpLoadFile } from './index';
 
-
-const ImgGood = ({url, _id}) => {
-
+const ImgGood = ({ url, _id }) => {
   return (
-    < > 
-      <Image height={200} style={{objectFit: 'cover'}}
+    < >
+      <Image height={200} style={{ objectFit: 'cover' }}
         width={200}
         src={backURL + '/' + url}
       />
       <InputUpLoadFile/>
-      {/* <Button onClick={() => onSave()}>Сохранить</Button> */}
     </>
 
-  )
-}
+  );
+};
 
 export default ImgGood;
-

+ 2 - 4
project/my-project/src/components/index.js

@@ -6,14 +6,14 @@ export { default as GoodCardCharacteristic } from './goodCardCharacteristic';
 // export { default as ButtonExSite } from './buttonExSite';
 export { default as HeaderSite } from './header';
 export { default as RegisterIn } from './registerIn';
-export { default as ListOrders }  from './listOrders';
+export { default as ListOrders } from './listOrders';
 export { default as Page404 } from './pege404';
 export { default as InputUpLoadFile } from './inputUploadFile';
 export { default as SwitchRoute } from './switchRoute';
 export { default as NameCategory } from './nameCategory';
 export { default as AddCategory } from './addCategory';
 export { default as СhangeOfGood } from './changeOfGood';
-export { default as CartChangeGood} from './cartChangeGood';
+export { default as CartChangeGood } from './cartChangeGood';
 export { default as InputSearchGood } from './inputSearchGood';
 export { default as CNewGoodInCat } from './cNewGoodInCat';
 export { default as EmptyContent } from './emptyContent';
@@ -22,5 +22,3 @@ export { default as AdditionalImages } from './additionalImages';
 export { default as CCartGoodAdmin } from './cartGoodAdmin';
 export { default as SortableComponent } from './sortTableComponent';
 export { default as ImgGood } from './imgGood';
-
-

+ 23 - 20
project/my-project/src/components/inputSearchGood.js

@@ -1,35 +1,38 @@
-import { Input, Button  } from 'antd';
+import { Input, Button } from 'antd';
 import { SearchOutlined } from '@ant-design/icons';
-import { useEffect, useState } from 'react';
+import { useState } from 'react';
+// import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
-import {Link} from 'react-router-dom';
+import { Link } from 'react-router-dom';
 
-const InputSearchG = ({nick}) => { 
+const InputSearchG = ({ nick }) => {
   const [inputValue, setInputValue] = useState('');
-  const [user, setUser] = useState(nick);
-  
-  useEffect(() => { 
+  // const [user, setUser] = useState(nick);
 
-    if(nick && nick.acl && nick.acl.includes('admin')) {
-      setUser('admin')
-    }
+  // useEffect(() => {
+  //   if (nick && nick.acl && nick.acl.includes('admin')) {
+  //     setUser('admin');
+  //   }
+  // }, [nick]);
 
-  }, [nick])
-
-  
   return (
     < >
-      <Input placeholder="Найти товар " value={inputValue} size="middle" style={{ width: '40%' }} onChange={(e) => setInputValue(e.target.value)}/>
+      <Input
+        placeholder="Найти товар "
+        value={inputValue}
+        size="middle"
+        style={{ width: '40%' }}
+        onChange={(e) => setInputValue(e.target.value)}/>
       <Link to={`/search/${inputValue}`}><Button icon={<SearchOutlined />} onClick={() => setInputValue('')}/></Link>
-     
+
     </>
-  )
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
-  nick: state.auth.payload?.sub || '',
-}) 
+  nick: state.auth.payload?.sub || ''
+});
 
 const InputSearchGood = connect(mapStateToProps)(InputSearchG);
 
-export default InputSearchGood;
+export default InputSearchGood;

+ 14 - 15
project/my-project/src/components/inputUploadFile.js

@@ -1,31 +1,30 @@
-import React, {useCallback} from 'react';
-import {useDropzone} from 'react-dropzone';
-import { Upload, message, Button } from 'antd';
+import React, { useCallback } from 'react';
+import { useDropzone } from 'react-dropzone';
+import { Button } from 'antd';
 import { UploadOutlined } from '@ant-design/icons';
 
-import { store} from '../store';
+import { store } from '../store';
 import { actionUploadFile } from '../action';
 
 const InputUpLoadFile = () => {
-  
   const onDrop = useCallback(acceptedFiles => {
     console.log('acceptedFiles', acceptedFiles);
 
-    store.dispatch(actionUploadFile(acceptedFiles ))
-  }, [])
-  
-  const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop})
+    store.dispatch(actionUploadFile(acceptedFiles));
+  }, []);
+
+  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
 
   return (
     <div {...getRootProps()}>
       <input {...getInputProps()} />
       {
-        isDragActive ?
-          <p>Drop the files here ...</p> :
-          <Button icon={<UploadOutlined />}> Выбрать файл</Button>
+        isDragActive
+          ? <p>Drop the files here ...</p>
+          : <Button icon={<UploadOutlined />}> Выбрать файл</Button>
       }
     </div>
-  )
-}
+  );
+};
 
-export default InputUpLoadFile;
+export default InputUpLoadFile;

+ 16 - 24
project/my-project/src/components/listOrders.js

@@ -1,32 +1,24 @@
 import { connect } from 'react-redux';
 import { Card, Row, Col } from 'antd';
-import { useEffect, useState } from 'react';
 import { CPromisePreloader } from '../reducer';
+import { Redirect } from 'react-router-dom';
 
-const Orders = ({allOrders, status}) => {
-  const [ord, setOrd] = useState(allOrders); 
-
-  useEffect( () => {
-
-    setOrd(allOrders);
-
-  }, [allOrders])
-
+const Orders = ({ allOrders, status, arrUsers }) => {
   return (
     <CPromisePreloader myOrders='myOrders'>
+      {arrUsers?.acl?.includes('user')
+        ? <Card title="История заказов">
 
-      <Card title="История заказов">
-
-      { ord.length === 0 && status['status'] === 'RESOLVD' &&  <Card>Вы не совершали покупки</Card>}
-        { ord.map( (item, index) => 
-            <Card  key={index} type="inner" title={`Заказ №  ${index + 1}`} style={{ marginTop: 16 }} >
+      { allOrders.length === 0 && status.status === 'RESOLVD' && <Card>Вы не совершали покупки</Card>}
+        { allOrders.map((item, index) =>
+            <Card key={index} type="inner" title={`Заказ №  ${index + 1}`} style={{ marginTop: 16 }} >
               <Row>
                 <Col span={9}>Название</Col>
                 <Col span={5}>Количество</Col>
                 <Col span={4}>Цена</Col>
                 <Col span={4}>Сумма</Col>
               </Row>
-              {item.orderGoods.map( (item) => 
+              {item.orderGoods.map((item) =>
                 <Card key={item._id}>
                   <Row>
                     <Col span={9}>{item.good.name}</Col>
@@ -37,21 +29,21 @@ const Orders = ({allOrders, status}) => {
                 </Card>
               )}
         </Card>
-       )}
+        )}
       </Card>
-    </CPromisePreloader> 
-  )
-}
+        : <Redirect to='/'/> }
+    </CPromisePreloader>
+  );
+};
 
 const mapStateToProps = (state) => (
   {
     allOrders: state.promise.myOrders?.payload || [],
     status: state.promise?.myOrders,
+    arrUsers: state.auth.payload?.sub || []
   }
-)
-
-
+);
 
 const ListOrders = connect(mapStateToProps)(Orders);
 
-export default ListOrders;
+export default ListOrders;

+ 18 - 19
project/my-project/src/components/nameCategory.js

@@ -3,22 +3,21 @@ import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
 import { actionChangeCategName } from '../action';
 
-const CategoryAdmin = ({category, _id, changeCategName }) => { 
+const CategoryAdmin = ({ category, _id, changeCategName }) => {
+  const [nameCat, setNameCat] = useState(category.name);
 
-  const [nameCat, setNameCat] = useState(category.name); 
-  
-  useEffect ( () => {
-    setNameCat(category.name)
-  }, [category])
+  useEffect(() => {
+    setNameCat(category.name);
+  }, [category]);
 
   const renewCategory = () => {
     changeCategName(_id, nameCat);// console.log('zzz', typeof _id)
     setNameCat('');
-  }
+  };
 
-  const clearInput = () => { 
-    setNameCat(''); 
-  }
+  const clearInput = () => {
+    setNameCat('');
+  };
 
   return (
    <div >
@@ -28,18 +27,18 @@ const CategoryAdmin = ({category, _id, changeCategName }) => {
           <Button type="primary" onClick={renewCategory}>Сохранить изменения</Button>
           <Button type="primary" onClick={clearInput} >Очистить поле</Button>
         </Space>
-        
+
       </Card>
   </div>
-    
-  )
-}
+
+  );
+};
 
 const mapStateToProps = (state) => ({
-  category: state.promise. catById?.payload || {},
-  allcategory: state.promise.rootCats?.payload || [],
-})
+  category: state.promise.catById?.payload || {},
+  allcategory: state.promise.rootCats?.payload || []
+});
 
-const NameCategory = connect(mapStateToProps, { changeCategName :actionChangeCategName })(CategoryAdmin);
+const NameCategory = connect(mapStateToProps, { changeCategName: actionChangeCategName })(CategoryAdmin);
 
-export default NameCategory;
+export default NameCategory;

+ 2 - 2
project/my-project/src/components/pege404.js

@@ -1,4 +1,4 @@
 
-const Page404 = () => <h1 align="center" style={{fontSize: '50px'}}>Error 404</h1>;
+const Page404 = () => <h1 align="center" style={{ fontSize: '50px' }}>Error 404</h1>;
 
-export default Page404;
+export default Page404;

+ 21 - 34
project/my-project/src/components/registerIn.js

@@ -1,39 +1,27 @@
-import { Form, Input, Button, Checkbox, Row, Col, Alert } from 'antd';
+import { Form, Input, Button, Row, Col, Alert } from 'antd';
 import { connect } from 'react-redux';
-import { actionFullRegister} from '../action';
-import {Router, Route, Link, Redirect, Switch, useHistory} from 'react-router-dom';
-
-
-
-
+import { actionFullRegister } from '../action';
+import { useHistory } from 'react-router-dom';
 import { useEffect, useState } from 'react';
 
-const Register = ({getState, auth}) => { console.log('auth', auth); 
-
-  const  [regMessage, setRegMessage] = useState(false);
-  
-  let history = useHistory();
+const Register = ({ getState, auth }) => {
+  const [regMessage, setRegMessage] = useState(false);
 
-  
+  const history = useHistory();
 
   useEffect(
     () => {
-      
-      if((auth).length !== 0) { 
-        history.push('/')
-      } 
-    } , [auth]) 
-
+      if ((auth).length !== 0) {
+        history.push('/');
+      }
+    }, [auth]);
 
   const onFinish = (values) => {
     console.log('Success:', values);
     getState(values.username, values.password);
-  
-    setRegMessage(!regMessage);
-    
-
 
-   };
+    setRegMessage(!regMessage);
+  };
 
   const onFinishFailed = (errorInfo) => {
     console.log('Failed:', errorInfo);
@@ -41,7 +29,7 @@ const Register = ({getState, auth}) => { console.log('auth', auth);
 
   return (
 
-    <Row> 
+    <Row>
       <Col span ={7}>
 
      </Col>
@@ -76,26 +64,25 @@ const Register = ({getState, auth}) => { console.log('auth', auth);
           </Button>
         </Form.Item>
 
-        { regMessage && (auth).length == 0 && <Form.Item wrapperCol={{ offset: 8, span: 16 }}> {console.log('куп')}
+        { regMessage && (auth).length === 0 && <Form.Item wrapperCol={{ offset: 8, span: 16 }}> {console.log('куп')}
         <Alert
           message="Ошибка"
           description="Такой пользователь существует"
           type="error"
-      
-          
+
          />
         </Form.Item>}
 
       </Form>
     </Row>
-  )
+  );
 };
 
 const mapStateToProps = state => ({
-  auth: state.auth?.token || '',
- 
-})
+  auth: state.auth?.token || ''
+
+});
 
-const RegisterIn = connect(mapStateToProps, {getState: actionFullRegister})(Register)
+const RegisterIn = connect(mapStateToProps, { getState: actionFullRegister })(Register);
 
-export default RegisterIn;
+export default RegisterIn;

+ 26 - 36
project/my-project/src/components/signIn.js

@@ -1,43 +1,31 @@
-import { Form, Input, Button, Checkbox, Row, Col, Alert } from 'antd';
+import { Form, Input, Button, Row, Col, Alert } from 'antd';
 import { connect } from 'react-redux';
 import { actionFullLogin } from '../action';
-import {Router, Route, Link, Redirect, Switch, useHistory} from 'react-router-dom';
-
-
-
-
+import { useHistory } from 'react-router-dom';
 import { useEffect, useState } from 'react';
 
-const Sign = ({getState, auth, logStatus, user}) => { console.log('auth', auth); 
+const Sign = ({ getState, auth, logStatus, user }) => {
+  const [logMessage, setLogMessage] = useState(false);
 
-  const  [logMessage, setLogMessage] = useState(false);
-  
-  let history = useHistory();
-
-  
+  const history = useHistory();
 
   useEffect(
     () => {
-      
-      if((auth).length !== 0) { 
-        history.push('/');             
-      } 
-
-      if(user.payload && user.payload.sub && user.payload.sub.acl.includes('admin') ) {
-        history.push('/admin'); 
+      if ((auth).length !== 0) {
+        history.push('/');
       }
-    } , [auth]) 
 
+      if (user.payload && user.payload.sub && user.payload.sub.acl.includes('admin')) {
+        history.push('/admin');
+      }
+    }, [auth]);
 
   const onFinish = (values) => {
     console.log('Success:', values);
     getState(values.username, values.password);
-  
-    setLogMessage(!logMessage);
-    
-
 
-   };
+    setLogMessage(!logMessage);
+  };
 
   const onFinishFailed = (errorInfo) => {
     console.log('Failed:', errorInfo);
@@ -45,7 +33,7 @@ const Sign = ({getState, auth, logStatus, user}) => { console.log('auth', auth);
 
   return (
 
-    <Row> 
+    <Row>
       <Col span ={7}>
 
      </Col>
@@ -80,28 +68,30 @@ const Sign = ({getState, auth, logStatus, user}) => { console.log('auth', auth);
           </Button>
         </Form.Item>
 
-        { logMessage && logStatus == 'RESOLVED' && (auth).length == 0 && <Form.Item wrapperCol={{ offset: 8, span: 16 }}> {console.log('tttt')}
+        { logMessage &&
+        logStatus === 'RESOLVED' &&
+        (auth).length === 0 &&
+         <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
         <Alert
           message="Ошибка"
           description="Неправильно введен логин или пароль"
           type="error"
-      
-          
+
          />
         </Form.Item>}
 
       </Form>
     </Row>
-  )
+  );
 };
 
 const mapStateToProps = state => ({
   auth: state.auth?.token || '',
-  logStatus: state.promise.login?.status || '', 
-  user: state.auth || '',
- 
-})
+  logStatus: state.promise.login?.status || '',
+  user: state.auth || ''
+
+});
 
-const SignIn = connect(mapStateToProps, {getState:actionFullLogin})(Sign)
+const SignIn = connect(mapStateToProps, { getState: actionFullLogin })(Sign);
 
-export default SignIn;
+export default SignIn;

+ 39 - 38
project/my-project/src/components/sortTableComponent.js

@@ -1,29 +1,27 @@
-import React, {Component} from 'react';
-import {render} from 'react-dom';
+import React, { Component } from 'react';
 import { SortableContainer, SortableElement } from 'react-sortable-hoc';
 import { arrayMoveImmutable } from 'array-move';
-import { Image , Card, Button} from 'antd';
-// import { arrayMove } from 'react-sortable-hoc';
+import { Card, Button } from 'antd';
 import { ImgGood } from '.';
 
-const SortableItem = SortableElement(({value:{_id, url, onSave}}) =>  
+const SortableItem = SortableElement(({ value: { _id, url, onSave } }) =>
   <li className='liSortTable'>
-    <Card>    {console.log('onSave',onSave)}
+    <Card>
       <ImgGood url={url} />
       <Button onClick={onSave}>Сохранить</Button>
-    </Card>  
+    </Card>
   </li>);
 
-const SortableList = SortableContainer(({items, idGood, onSave, onChangeImagesOnSer}) => {
-  
+const SortableList = SortableContainer(({ items, idGood, onSave, onChangeImagesOnSer }) => {
   return (
     <>
-      <ul className='sortTablelist' > 
+      <ul className='sortTablelist' >
         {items.map((value, index) => (
-          <SortableItem  key={`item-${index}`} index={index} value={
-            {"_id": value._id, 
-            "url":value.url, 
-            "onSave": () => onSave(value._id)
+          <SortableItem key={`item-${index}`} index={index} value={
+            {
+              _id: value._id,
+              url: value.url,
+              onSave: () => onSave(value._id)
             }
         } />
         ))}
@@ -36,49 +34,52 @@ const SortableList = SortableContainer(({items, idGood, onSave, onChangeImagesOn
 class SortableComponent extends Component {
   state = {
     items: this.props.images,
-    idGood: this.props.idGood,   
-    clearUpLoad: this.props.clearUpLoad,
+    idGood: this.props.idGood,
+    clearUpLoad: this.props.clearUpLoad
   };
 
-  getState =() => console.log('this.state',this.state)
+  getState =() => console.log('this.state', this.state)
 
-  onSortEnd = ({oldIndex, newIndex}) => {
-    this.setState(({items}) => ({
-      items: arrayMoveImmutable(items, oldIndex, newIndex),
+  onSortEnd = ({ oldIndex, newIndex }) => {
+    this.setState(({ items }) => ({
+      items: arrayMoveImmutable(items, oldIndex, newIndex)
     }));
-    this.getState();  
+    this.getState();
   };
 
   onChangeImagesOnSer = () => {
-    const arrImagesForSave = this.state.items.map((item) => ({_id: item._id}));
+    const arrImagesForSave = this.state.items.map((item) => ({ _id: item._id }));
     this.props.onChangeArrInGood(this.state.idGood, arrImagesForSave);
-                
-  } 
+  }
 
   onSave = (idImg) => {
-    const newArrImgs = this.state.items.map((item) => {    
-
+    const newArrImgs = this.state.items.map((item) => {
       if (idImg === item._id) {
         return {
           _id: this.props.upLoad._id,
-          url: this.props.upLoad.url,
-        }
+          url: this.props.upLoad.url
+        };
       };
+
       return item;
-    });                               
-                                                    //console.log('newArrImgs ', newArrImgs )
-    this.setState(() => ({items: newArrImgs}));
-    
-    this.state.clearUpLoad();     
+    });
 
+    this.setState(() => ({ items: newArrImgs }));
+
+    this.state.clearUpLoad();
   }
 
-  render() {
-    return <SortableList axis="xy" items={this.state.items} idGood={this.state.idGood} onSortEnd={this.onSortEnd} onSave={this.onSave} 
-      onChangeImagesOnSer={this.onChangeImagesOnSer}
-    />;
+  render () {
+    return (
+      <SortableList
+        axis="xy"
+        items={this.state.items}
+        idGood={this.state.idGood}
+        onSortEnd={this.onSortEnd}
+        onSave={this.onSave}
+        onChangeImagesOnSer={this.onChangeImagesOnSer}
+    />);
   }
 }
 
 export default SortableComponent;
-

+ 14 - 16
project/my-project/src/components/switchRoute.js

@@ -1,26 +1,24 @@
-import { useEffect, useState } from "react";
-import { UseRoute } from "../route";
-import { jwtDecode } from "../utils";
-import { PrivateRoute } from "../route";
+import { useEffect, useState } from 'react';
+import { UseRoute, PrivateRoute } from '../route';
+import { jwtDecode } from '../utils';
 
 const SwitchRoute = () => {
   const [userName, setUserName] = useState('user');
 
-  useEffect( () => {
-    const token = localStorage.getItem('authToken'); 
+  useEffect(() => {
+    const token = localStorage.getItem('authToken');
     //
-    if (token) { 
-      const name = jwtDecode(token)['sub']['acl']; //console.log('name', jwtDecode(token)['sub']);
-      name.includes('admin') ? setUserName(name ):  setUserName('user'); 
-     
+    if (token) {
+      const name = jwtDecode(token).sub.acl;
+      name.includes('admin') ? setUserName(name) : setUserName('user');
     }
-  }, [localStorage.getItem('authToken')])
+  }, [localStorage.getItem('authToken')]);
 
-  return ( 
+  return (
     < >
-    {userName === 'user' ? <UseRoute/>: <PrivateRoute/>}
+    {userName === 'user' ? <UseRoute/> : <PrivateRoute/>}
     </>
-  )
-}
+  );
+};
 
-export default SwitchRoute; 
+export default SwitchRoute;

+ 0 - 2
project/my-project/src/index.js

@@ -3,7 +3,6 @@ import ReactDOM from 'react-dom';
 import './index.css';
 import App from './App';
 
-
 ReactDOM.render(
   <React.StrictMode>
     <App />
@@ -14,4 +13,3 @@ ReactDOM.render(
 // If you want to start measuring performance in your app, pass a function
 // to log results (for example: reportWebVitals(console.log))
 // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
-

+ 12 - 12
project/my-project/src/pages/cpageCategory.js

@@ -1,17 +1,17 @@
-import { useEffect } from "react";
-import { CCategory } from "../components";
-import { connect } from "react-redux";
-import { actionCatById } from "../action";
+import { useEffect } from 'react';
+import { CCategory } from '../components';
+import { connect } from 'react-redux';
+import { actionCatById } from '../action';
 
-export const PageCategory = ({match: {params: {_id}}, getData}) => {
-  useEffect(() => { 
-      getData(_id)
-  },[_id])
+export const PageCategory = ({ match: { params: { _id } }, getData }) => {
+  useEffect(() => {
+    getData(_id);
+  }, [_id]);
   return (
     <CCategory />
-  )
-}
+  );
+};
 
-const CPageCategory = connect(null, {getData: actionCatById})(PageCategory)
+const CPageCategory = connect(null, { getData: actionCatById })(PageCategory);
 
-export default CPageCategory;
+export default CPageCategory;

+ 1 - 1
project/my-project/src/pages/index.js

@@ -3,4 +3,4 @@ export { default as CreatePageGood } from './pageGood';
 export { default as CPageCategory } from './cpageCategory';
 export { default as PageCategoryAdmin } from './pageAdmin';
 export { default as MainPage } from './mainPage';
-export { default as PageSearch } from './pageSearch';
+export { default as PageSearch } from './pageSearch';

+ 11 - 15
project/my-project/src/pages/mainPage.js

@@ -1,19 +1,16 @@
-import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
-import { createFromIconfontCN } from '@ant-design/icons';
+import { Layout, Menu, Breadcrumb } from 'antd';
+// import { createFromIconfontCN } from '@ant-design/icons';
 import '../App.css';
 import 'antd/dist/antd.min.css';
-import {Switch} from 'react-router-dom';
-import { CCategoryList, SwitchRoute } from '../components';
-import { HeaderSite } from '../components';
+import { Switch } from 'react-router-dom';
+import { CCategoryList, SwitchRoute, HeaderSite } from '../components';
 
-const { SubMenu } = Menu;
-const { Header, Content, Footer, Sider } = Layout;
-const IconFont = createFromIconfontCN({
-  scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
-});
+const { Content, Footer, Sider } = Layout;
+// const IconFont = createFromIconfontCN({
+//   scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js'
+// });
 
 function MainPage () {
-
   return (
     <Layout>
      <HeaderSite/>
@@ -34,13 +31,12 @@ function MainPage () {
           <Switch>
             <SwitchRoute/>
           </Switch>
-        </Content>  
+        </Content>
       </Layout>
     </Content>
     <Footer style={{ textAlign: 'center' }}>Viktoriia Yurchenko 2022</Footer>
   </Layout>
-  )
-  
+  );
 }
 
-export default MainPage;
+export default MainPage;

+ 15 - 17
project/my-project/src/pages/pageAdmin.js

@@ -1,17 +1,17 @@
-import { useEffect } from "react";
-import { connect } from "react-redux";
-import { actionCatById } from "../action";
-import { NameCategory, AddCategory, CartChangeGood, CNewGoodInCat } from "../components";
+import { useEffect } from 'react';
+import { connect } from 'react-redux';
+import { actionCatById } from '../action';
+import { NameCategory, AddCategory, CartChangeGood, CNewGoodInCat } from '../components';
 import { CPromisePreloader } from '../reducer';
 
- 
-const PCategoryAdmin = ({match, match: {params: {_id}}, getData}) => { console.log('match', match)
-  useEffect( () => {
+const PCategoryAdmin = ({ match, match: { params: { _id } }, getData }) => {
+  console.log('match', match);
+  useEffect(() => {
     getData(_id);
-  }, [_id]);                            console.log('======id', _id)
+  }, [_id]); console.log('======id', _id);
 
   return (
-    <> 
+    <>
       <CPromisePreloader name={'catById'}>
         {/* Изменить категорию товара */}
         <div>
@@ -24,18 +24,16 @@ const PCategoryAdmin = ({match, match: {params: {_id}}, getData}) => { console.l
           {/* Добавить товар в категорию */}
         <div>
           <CNewGoodInCat/>
-        </div>  
+        </div>
         {/* Изменить товар */}
         <div>
           <CartChangeGood _idCat={_id}/>
         </div>
       </CPromisePreloader>
-    </> 
-  )
-}
-
-
+    </>
+  );
+};
 
-const PageCategoryAdmin = connect(null, {getData: actionCatById})(PCategoryAdmin)
+const PageCategoryAdmin = connect(null, { getData: actionCatById })(PCategoryAdmin);
 
-export default PageCategoryAdmin;
+export default PageCategoryAdmin;

+ 55 - 59
project/my-project/src/pages/pageBasket.js

@@ -1,20 +1,21 @@
-import { Card, Button, Image, Space, Row , Col} from 'antd';
-import { defaultIconPrefixCls } from 'antd/lib/config-provider';
-import { actionCartAdd,  actionCartRemove, actionCartChange, actionCartClear, actionCartMin, actionOrder} from '../action';
+import { Card, Button, Image, Space, Row } from 'antd';
+import {
+  actionCartAdd, actionCartRemove, actionCartChange,
+  actionCartClear, actionCartMin, actionOrder
+} from '../action';
 import { connect } from 'react-redux';
-import {PlusSquareTwoTone, MinusSquareTwoTone, CloseSquareTwoTone, CheckSquareTwoTone, RestTwoTone} from '@ant-design/icons';
+import {
+  PlusSquareTwoTone, MinusSquareTwoTone,
+  CloseSquareTwoTone, CheckSquareTwoTone,
+  RestTwoTone
+} from '@ant-design/icons';
 import { useEffect, useState } from 'react';
 import { CPromisePreloader } from '../reducer';
 
+const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
 
-
-
-const backendURL = "http://shop-roles.asmer.fs.a-level.com.ua" ;
-
-const CartBasket = ({good, good:{name, price, images}, count, clickButton:{cartMin, cartChange, cartRemove, cartAdd}}) => {
-  
+const CartBasket = ({ good, good: { name, price, images }, count, clickButton: { cartMin, cartRemove, cartAdd } }) => {
   return (
-   
 
     <Card
       style={{ marginTop: 16 }}
@@ -23,54 +24,51 @@ const CartBasket = ({good, good:{name, price, images}, count, clickButton:{cartM
     >
     <Space>
       <Row>
-        {images && images[0] && images[0].url &&<Image  width={100} height={70} src={backendURL + '/' + images[0].url} />}
+        {images && images[0] &&
+         images[0].url &&
+          <Image width={100} height={70} src={backendURL + '/' + images[0].url} />}
         <Space align="center">
-        <Button size ='large' icon={<PlusSquareTwoTone />} onClick={()=>cartAdd(good)}></Button>
-        <Button size ='large' icon={<MinusSquareTwoTone />} onClick={()=>cartMin(good)}></Button>
-        <Button size ='large' icon={<CloseSquareTwoTone />} onClick={()=>cartRemove(good)}></Button>
+        <Button size ='large' icon={<PlusSquareTwoTone />} onClick={() => cartAdd(good)}></Button>
+        <Button size ='large' icon={<MinusSquareTwoTone />} onClick={() => cartMin(good)}></Button>
+        <Button size ='large' icon={<CloseSquareTwoTone />} onClick={() => cartRemove(good)}></Button>
         </Space>
 
-        
-
         <Space align="center">
-          
+
             <p>{`Цена       ${price}  грн.`}</p>
             <p>{`Количество ${count}  шт.`}</p>
             <p>{`Всего:     ${price * count}  грн.`}</p>
-          
+
         </Space>
       </Row>
-        
-
 
       </Space>
 
-
     </Card>
-  
-  )
-}
 
+  );
+};
 
-const GoodsInBasket = ({cart = {}, orderPayload, cartMin, cartClear, cartChange, cartRemove, cartAdd, order, auth}) => {
-  const goods = Object.values(cart); console.log("csrt", goods);
-  const costOrder= goods.reduce((acumm, item) => acumm + item.good.price * item.count, 0 ); 
+const GoodsInBasket = ({
+  cart = {}, cartMin, cartClear,
+  cartChange, cartRemove, cartAdd, order, auth
+}) => {
+  const goods = Object.values(cart);
+  const costOrder = goods.reduce((acumm, item) => acumm + item.good.price * item.count, 0);
   const [messageForOrder, setmessageForOrder] = useState(false);
 
-  useEffect (() => {
-
-    if((auth).length !== 0) { 
+  useEffect(() => {
+    if ((auth).length !== 0) {
       setmessageForOrder(!messageForOrder);
-    } 
+    }
   }
-  ,[auth]) 
-  
-  const oderPlusclearOrder = () => { 
+  , [auth]);
+
+  const oderPlusclearOrder = () => {
     order();
 
     cartClear();
-    
-  }
+  };
 
   return (
     <CPromisePreloader name='order'>
@@ -78,39 +76,37 @@ const GoodsInBasket = ({cart = {}, orderPayload, cartMin, cartClear, cartChange,
       <Row>
       <p>{`Всего:  ${costOrder} грн.`}</p>
       <Space align="center">
-        {messageForOrder ? 
-          < >
-            <Button size ='large' icon={<CheckSquareTwoTone />} onClick={()=> oderPlusclearOrder() }>Оформить</Button> 
-            <Button size ='large' icon={<RestTwoTone />} onClick={()=> cartClear()} >Очистить</Button> 
-          </>  
-        : <p style={{color:'red'}}> Для оформления заказа нужно авторизоваться</p>
+        {messageForOrder
+          ? < >
+            <Button size ='large' icon={<CheckSquareTwoTone />} onClick={() => oderPlusclearOrder() }>Оформить</Button>
+            <Button size ='large' icon={<RestTwoTone />} onClick={() => cartClear()} >Очистить</Button>
+          </>
+          : <p style={{ color: 'red' }}> Для оформления заказа нужно авторизоваться</p>
         }
-      </Space> 
+      </Space>
       </Row>
 
-        {goods.map((item) => <CartBasket key={item.good._id} {...item} clickButton={{cartMin, cartChange, cartRemove, cartAdd}}/>)}
+        {goods.map((item) =>
+        <CartBasket key={item.good._id} {...item} clickButton={{ cartMin, cartChange, cartRemove, cartAdd }}/>)}
       </Card>
       </CPromisePreloader>
-  )
-
-}
+  );
+};
 
 const mapStateToProps = (state) => ({
   cart: state?.cart,
   orderPayload: state.promise.order?.payload || {},
-  auth: state.auth?.token || '',
+  auth: state.auth?.token || ''
 });
 const mapDispatchToProps = {
-  cartAdd: actionCartAdd, 
-  cartRemove: actionCartRemove, 
-  cartChange: actionCartChange, 
-  cartClear: actionCartClear, 
-  cartMin: actionCartMin, 
-  order: actionOrder,
-}
-
-
+  cartAdd: actionCartAdd,
+  cartRemove: actionCartRemove,
+  cartChange: actionCartChange,
+  cartClear: actionCartClear,
+  cartMin: actionCartMin,
+  order: actionOrder
+};
 
 const PageBasket = connect(mapStateToProps, mapDispatchToProps)(GoodsInBasket);
 
-export default PageBasket;
+export default PageBasket;

+ 13 - 13
project/my-project/src/pages/pageGood.js

@@ -1,21 +1,21 @@
-import { useEffect } from "react";
-import { connect } from "react-redux";
-import { GoodCardCharacteristic } from "../components";
-import { actionGoodById } from "../action";
-import { CPromisePreloader } from "../reducer"
+import { useEffect } from 'react';
+import { connect } from 'react-redux';
+import { GoodCardCharacteristic } from '../components';
+import { actionGoodById } from '../action';
+import { CPromisePreloader } from '../reducer';
 
-const PageGood = ({match: {params: {_id}}, getData}) => { 
-  useEffect( () =>{
-    getData(_id)
-  }, [_id])
+const PageGood = ({ match: { params: { _id } }, getData }) => {
+  useEffect(() => {
+    getData(_id);
+  }, [_id]);
 
   return (
     <CPromisePreloader name='goodById'>
       <GoodCardCharacteristic/>
     </CPromisePreloader>
-  )
-}
+  );
+};
 
-const CreatePageGood = connect(null, {getData: actionGoodById} )(PageGood);
+const CreatePageGood = connect(null, { getData: actionGoodById })(PageGood);
 
-export default CreatePageGood;
+export default CreatePageGood;

+ 14 - 13
project/my-project/src/pages/pageSearch.js

@@ -1,20 +1,21 @@
-import { useEffect } from "react";
-import { connect } from "react-redux";
-import { actionSearchGood } from "../action";
-import { GoodSearch } from "../components";
+import { useEffect } from 'react';
+import { connect } from 'react-redux';
+import { actionSearchGood } from '../action';
+import { GoodSearch } from '../components';
 import { CPromisePreloader } from '../reducer';
 
-const PageSearchGood = ({match ,match: {params: {value}}, searchGood}) => { console.log('search', match)
-  useEffect(()=>{
+const PageSearchGood = ({ match, match: { params: { value } }, searchGood }) => {
+  console.log('search', match);
+  useEffect(() => {
     searchGood(value);
-  }, [value])
+  }, [value]);
 
-   return (
-    <CPromisePreloader>  
+  return (
+    <CPromisePreloader>
       <GoodSearch value={value}/>
     </CPromisePreloader>
-   )
-}
-const PageSearch = connect(null, {searchGood:actionSearchGood})(PageSearchGood);
+  );
+};
+const PageSearch = connect(null, { searchGood: actionSearchGood })(PageSearchGood);
 
-export default PageSearch;
+export default PageSearch;

+ 13 - 27
project/my-project/src/pages/pageUser.js

@@ -1,31 +1,18 @@
-import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
-import { UserOutlined, LaptopOutlined, NotificationOutlined, createFromIconfontCN  } from '@ant-design/icons';
+import { Layout, Menu, Breadcrumb } from 'antd';
+// import { createFromIconfontCN } from '@ant-design/icons';
 import '../App.css';
 import 'antd/dist/antd.min.css';
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { actionRootCats } from "../action";
+import { Switch } from 'react-router-dom';
+import { CCategoryList, HeaderSite } from '../components';
+import { RouteSite } from '../route';
 
-
-
-import {SignIn, ListOrders, Page404} from '../components';
-import { CCategoryList, SwitchRoute } from '../components';
-import { useEffect } from 'react';
-import CPageCategory from './cpageCategory';
-import CreatePageGood from './pageGood';
-import { HeaderSite } from '../components';
-import PageBasket from './pageBasket';
-import { RegisterIn } from '../components';
-import { UseRoute, RouteSite } from '../route'
-
-
-const { SubMenu } = Menu;
-const { Header, Content, Footer, Sider } = Layout;
-const IconFont = createFromIconfontCN({
-  scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
-});
+// const { SubMenu } = Menu;
+const { Content, Footer, Sider } = Layout;
+// const IconFont = createFromIconfontCN({
+//   scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js'
+// });
 
 function PageUser () {
-
   return (
     <Layout>
      <HeaderSite/>
@@ -46,13 +33,12 @@ function PageUser () {
           <Switch>
             <RouteSite/>
           </Switch>
-        </Content>  
+        </Content>
       </Layout>
     </Content>
     <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
   </Layout>
-  )
-  
+  );
 }
 
-export default PageUser;
+export default PageUser;

+ 22 - 49
project/my-project/src/reducer/authReducer.js

@@ -1,56 +1,29 @@
-import { jwtDecode } from '../utils'
+import { jwtDecode } from '../utils';
 
-// function authReducer(state, {type, token}){
-//   if (!state){
-//       if(localStorage.authToken){  //проверить localStorage.authToken на наличие
-//         return {
-//         'type': 'AUTH_LOGIN',
-//         'token':localStorage.authToken,
-//         };                         //если есть - сделать так, что бы следующий if сработал
-//       }  else { return state = {}}                            //если нет - вернуть {}
-//   }
-//   if (type === 'AUTH_LOGIN'){
-//     const bigToken =  jwtDecode(token);   //взять токен из action
-//     if (bigToken) {                                //попытаться его jwtDecode
-//       localStorage.setItem('authToken', token);                              //если удалось, то:
-//       return { 
-//         token,
-//         payload: bigToken,
-//       }
-//     }                                              //сохранить токен в localStorage
-//   }                                                //вернуть объект вида {токен, payload: раскодированный токен}
-//   if (type === 'AUTH_LOGOUT'){
-//     localStorage.clear();                          //почистить localStorage
-//     return {};                                     //вернуть пустой объект
-//   }
-//   return state
-// }
-
-function authReducer(state, {type, token}){
-  if (!state){
-      if(localStorage.authToken){  //проверить localStorage.authToken на наличие
-        state = {
-        'type': 'AUTH_LOGIN',
-        'token':localStorage.authToken,
-        };                         //если есть - сделать так, что бы следующий if сработал
-      }  else { return state = {}}                            //если нет - вернуть {}
+function authReducer (state, { type, token }) {
+  if (!state) {
+    if (localStorage.authToken) {
+      state = {
+        type: 'AUTH_LOGIN',
+        token: localStorage.authToken
+      };
+    } return {};
   }
-  if (type === 'AUTH_LOGIN'){
-    const bigToken =  jwtDecode(token);   //взять токен из action
-    if (bigToken) {                                //попытаться его jwtDecode
-      localStorage.setItem('authToken', token);                              //если удалось, то:
-      return { 
+  if (type === 'AUTH_LOGIN') {
+    const bigToken = jwtDecode(token);
+    if (bigToken) {
+      localStorage.setItem('authToken', token);
+      return {
         token,
-        payload: bigToken,
-      }
-    }                                              //сохранить токен в localStorage
-  }                                                //вернуть объект вида {токен, payload: раскодированный токен}
-  if (type === 'AUTH_LOGOUT'){
-    localStorage.clear();                          //почистить localStorage
-    return {};                                     //вернуть пустой объект
+        payload: bigToken
+      };
+    }
+  }
+  if (type === 'AUTH_LOGOUT') {
+    localStorage.clear();
+    return {};
   }
-  return state
+  return state;
 }
 
-
 export default authReducer;

+ 50 - 58
project/my-project/src/reducer/cartReducer.js

@@ -1,65 +1,57 @@
-function cartReducer(state={}, {type, good = {}, count=1}){
-  //{
-  //  _id1: {good, count}
-  //  _id2: {good, count}
-  //}
+function cartReducer (state = {}, { type, good = {}, count = 1 }) {
   const types = {
-    
-      CART_ADD(){ //как CHANGE, только если ключ раньше был, то достать из count и добавить
-        const {_id} = good;   
-                               //к count из action. Если не было, достать 0 и добавить к count из action
-        return {
-         ...state,
-         [_id]:{good, count:count +(state[_id]?.count || 0)}
-       }
-      },
-      CART_MINUS(){ //как CHANGE, только если ключ раньше был, то достать из count и добавить
-        const {_id} = good;   
-                               //к count из action. Если не было, достать 0 и добавить к count из action
-        return {
-         ...state,
-         [_id]:{good, count: (-count +(state[_id]?.count || 0)) < 1 ? 0: -count +(state[_id]?.count || 0)}
-       }
-      },
-      CART_REMOVE(){ //смочь скопировать объект и выкинуть ключ. как вариант через
-                      //деструктуризацию
-        const {_id} = good; 
-        let newState = {...state};
-        const arrKeys = Object.keys(newState);
-        for (let key of arrKeys) {
-          if(_id === key) {
-            delete newState[_id];
-          }
-        } 
-        
-        return {
-          ... newState,
-        }  
-      },
-      CART_CHANGE(){
-        const {_id} = good;
-          return {
-            ...state, //по аналогии с promiseReducer дописать
-            [_id]:{good, count}
-          }
-      },
-      CART_CLEAR(){
-      
-        return {
-          
-        };
-      },
-      AUTH_LOGOUT () {
-        localStorage.clear();                          //почистить localStorage
-        return {};                                     //вернуть пустой объект
+
+    CART_ADD () {
+      const { _id } = good;
+
+      return {
+        ...state,
+        [_id]: { good, count: count + (state[_id]?.count || 0) }
+      };
+    },
+    CART_MINUS () {
+      const { _id } = good;
+
+      return {
+        ...state,
+        [_id]: { good, count: (-count + (state[_id]?.count || 0)) < 1 ? 0 : -count + (state[_id]?.count || 0) }
+      };
+    },
+    CART_REMOVE () {
+      const { _id } = good;
+      const newState = { ...state };
+      const arrKeys = Object.keys(newState);
+      for (const key of arrKeys) {
+        if (_id === key) {
+          delete newState[_id];
+        }
       }
-  }
 
-  if (type in types)
-      return types[type]()
+      return {
+        ...newState
+      };
+    },
+    CART_CHANGE () {
+      const { _id } = good;
+      return {
+        ...state,
+        [_id]: { good, count }
+      };
+    },
+    CART_CLEAR () {
+      return {
+
+      };
+    },
+    AUTH_LOGOUT () {
+      localStorage.clear();
+      return {};
+    }
+  };
 
+  if (type in types) { return types[type](); };
 
-  return state
+  return state;
 }
 
-export default cartReducer;
+export default cartReducer;

+ 3 - 3
project/my-project/src/reducer/index.js

@@ -1,6 +1,6 @@
 export { default as authReducer } from './authReducer';
 export { default as promiseReducer } from './promiseReducer';
-export { default as cartReducer} from './cartReducer';
+export { default as cartReducer } from './cartReducer';
 export { default as CPromisePreloader } from './promisePreloader';
-export { default as promiseImg } from './promiseImg'; 
-export { default as upLoaderReducer } from './uploaderReducer';
+export { default as promiseImg } from './promiseImg';
+export { default as upLoaderReducer } from './uploaderReducer';

+ 9 - 11
project/my-project/src/reducer/promiseImg.js

@@ -1,16 +1,14 @@
-function promiseImg(state={}, {type, name, status, payload, error}){
+function promiseImg (state = {}, { type, name, status, payload, error }) {
   if (type === 'IMG_CLEAR') {
-    return {}
+    return {};
   }
-  if (type === 'IMG'){
-      return {
-        ...state,
-        [name]:{status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error}
-      }
+  if (type === 'IMG') {
+    return {
+      ...state,
+      [name]: { status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error }
+    };
   }
-  return state
+  return state;
 }
 
-
-
-export default promiseImg;
+export default promiseImg;

+ 12 - 17
project/my-project/src/reducer/promisePreloader.js

@@ -2,32 +2,27 @@ import { Spin } from 'antd';
 import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
 
-const PromisePreloader = ({children, name, reduxPromises}) => {
+const PromisePreloader = ({ children, name, reduxPromises }) => {
   const [status, setStatus] = useState('');
 
   useEffect(() => {
-     if (reduxPromises && reduxPromises[name]) {
-      setStatus(reduxPromises[name].status)
-     }
-  }, [reduxPromises])
+    if (reduxPromises && reduxPromises[name]) {
+      setStatus(reduxPromises[name].status);
+    }
+  }, [reduxPromises]);
 
   return (
     < >
-    { (status === 'RESOLVED' || !reduxPromises[name]) ? children 
-      :
-      <div className="example">
-       <Spin size="large"  delay={500}/>
+    { (status === 'RESOLVED' || !reduxPromises[name])
+      ? children
+      : <div className="example">
+       <Spin size="large" delay={500}/>
       </div>
     }
     </>
-  )
-}
+  );
+};
 
-const CPromisePreloader = connect(state => ({reduxPromises: state.promise}))(PromisePreloader);
+const CPromisePreloader = connect(state => ({ reduxPromises: state.promise }))(PromisePreloader);
 
 export default CPromisePreloader;
-
-
-
-
-

+ 7 - 20
project/my-project/src/reducer/promiseReducer.js

@@ -1,24 +1,11 @@
-// function promiseReducer(state={}, {type, name, status, payload, error}){
-//   if (type === 'PROMISE'){
-//       return {
-//         ...state,
-//         [name]:{status, payload, error}
-//       }
-//   }
-//   return state
-// }
-
-
-function promiseReducer(state={}, {type, name, status, payload, error}){
-  if (type === 'PROMISE'){
-      return {
-        ...state,
-        [name]:{status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error}
-      }
+function promiseReducer (state = {}, { type, name, status, payload, error }) {
+  if (type === 'PROMISE') {
+    return {
+      ...state,
+      [name]: { status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error }
+    };
   }
-  return state
+  return state;
 }
 
-
-
 export default promiseReducer;

+ 8 - 11
project/my-project/src/reducer/uploaderReducer.js

@@ -1,17 +1,14 @@
-function upLoaderReducer(state={}, {type, name, status, payload, error}){
+function upLoaderReducer (state = {}, { type, name, status, payload, error }) {
   if (type === 'UPLOAD_IMG_CLEAR') {
-    return {}
+    return {};
   }
-  if (type === 'UPLOAD'){
-      return {
-        ...state,
-        [name]:{status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error}
-      }
+  if (type === 'UPLOAD') {
+    return {
+      ...state,
+      [name]: { status, payload: (status === 'PENDING' && state[name] && state[name].payload) || payload, error }
+    };
   }
-  return state
+  return state;
 }
 
-
-
 export default upLoaderReducer;
-

+ 31 - 33
project/my-project/src/route/cRoute.js

@@ -1,39 +1,37 @@
-// import { useEffect, useState } from "react";
-// import { useHistory, Route, Redirect}  from 'react-router-dom';
-// import { connect } from "react-redux";
+// import { useEffect, useState } from 'react';
+// import { useHistory, Route, Redirect } from 'react-router-dom';
+// import { connect } from 'react-redux';
 
+// const ProtectedRoute = ({
+//   fallback = '/',
+//   roles = ['admin'],
+//   auth,
+//   path, component
+// }) => {
+//   const [acl, setAcl] = useState([]);
+//   const [access, setAccess] = useState(false);
+//   const history = useHistory();
 
-// const ProtectedRoute = ({fallback='/', 
-//                       roles=["admin"], 
-//                       auth,
-//                       path, component}) => {
- 
-//     const [acl, setAcl] = useState([]);
-//     const [access, setAccess] = useState(false);    
-    // let history = useHistory();
-
-//     useEffect(() => {
-//       if (auth && auth.payload && auth.payload.sub.acl.length !== 0) {            
-//         setAcl(auth.payload.sub.acl);                                                    
-//       } else {
-//         setAcl('anon'); 
-//         setAccess(false);                                                            
-//       }                                                                                
-//       const newAcl = roles.filter((item) => acl.includes(item));                  
-//       if (newAcl.length) {
-//         setAccess(true); console.log('access24', access)
-//       }
-//     }, [auth])
-//                                console.log('acl', acl); console.log('roles', roles) ;  
-//     return (
+//   useEffect(() => {
+//     if (auth && auth.payload && auth.payload.sub.acl.length !== 0) {
+//       setAcl(auth.payload.sub.acl);
+//     } else {
+//       setAcl('anon');
+//       setAccess(false);
+//     }
+//     const newAcl = roles.filter((item) => acl.includes(item));
+//     if (newAcl.length) {
+//       setAccess(true); console.log('access24', access);
+//     }
+//   }, [auth]);
+//   console.log('acl', acl); console.log('roles', roles);
+//   return (
 //       < >
-//         { access? <Route path={path} component={component}/> : <Redirect to={fallback}/>}
+//         { access ? <Route path={path} component={component}/> : <Redirect to={fallback}/>}
 //       </>
-//     )  
-// }
-//<CRoute roles={["anon", "user", "admin"]} path="/category/:_id" component={PageCategory} />
-//<CRoute roles={["admin"]} path="/good/:_id" component={PageGood} />
+//   );
+// };
 
-// const CRoute = connect(state => ({auth: state.auth.payload}))(ProtectedRoute);
+// const CRoute = connect(state => ({ auth: state.auth.payload }))(ProtectedRoute);
 
-// export default CRoute; 
+// export default CRoute;

+ 7 - 9
project/my-project/src/route/privateRoute.js

@@ -1,8 +1,6 @@
-import { Route, Switch } from "react-router-dom";
-import { SignIn, CCartGoodAdmin  } from "../components";
-import { PageCategoryAdmin, CreatePageGood, PageSearch } from "../pages";
-
-
+import { Route } from 'react-router-dom';
+import { SignIn, CCartGoodAdmin } from '../components';
+import { PageCategoryAdmin, PageSearch } from '../pages';
 
 const PrivateRoute = () => {
   return (
@@ -11,10 +9,10 @@ const PrivateRoute = () => {
       <Route path = "/category/:_id" component = {PageCategoryAdmin}/>
       <Route path = "/goodAdmin/:_id" component = {CCartGoodAdmin}/>
       <Route path = "/search/:value" component = {PageSearch}/>
-      {/* <Route path = "/basket" component={PageBasket}/> 
+      {/* <Route path = "/basket" component={PageBasket}/>
       <Route path = "/listOrders" component={ListOrders}/>  */}
     </>
-  )
-}
+  );
+};
 
-export default PrivateRoute;
+export default PrivateRoute;

+ 22 - 24
project/my-project/src/route/routeSite.js

@@ -1,27 +1,25 @@
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { SignIn, RegisterIn, ListOrders, EmptyContent, Page404} from '../components';
-import { PageBasket, CPageCategory, CreatePageGood, PageSearch, PageCategoryAdmin}  from '../pages';
-import { CRoute  } from './index';
+// import { SignIn, RegisterIn, ListOrders, EmptyContent, Page404 } from '../components';
+// import { PageBasket, CPageCategory, CreatePageGood, PageSearch, PageCategoryAdmin } from '../pages';
+// import { CRoute } from './index';
 
-const RouteSite = () => {
-  return (
-    < >
-     
-      {/* <Redirect from="/main" to='/' /> */}
-      <CRoute roles={["anon", "user", "admin"]} path="/" component={EmptyContent} exact />
-      <CRoute roles={["anon", "user", "admin"]} path ="/login" component = {SignIn}/>
-      <CRoute roles={["anon"]} path = "/registration" component = {RegisterIn} />
-      <CRoute roles={["anon", "user", "admin"]} path = "/category/:_id" component = {CPageCategory}/>
-      <CRoute roles={["anon", "user", "admin"]} path = "/good/:_id" component = {CreatePageGood}/>
-      <CRoute roles={["anon", "user", "admin"]} path = "/basket" component={PageBasket}/> 
-      <CRoute roles={["user", "admin"]} path = "/listOrders" component={ListOrders}/>
-      <CRoute roles={["anon", "user", "admin"]} path = "/search/:value" component = {PageSearch}/>
-      <CRoute roles={["admin"]} path = "/admin/:_id" component = {PageCategoryAdmin}/>
-      {/* <CRoute path = "*" component={Page404}/>  */}
-      
+// const RouteSite = () => {
+//   return (
+//     < >
 
-    </>
-  )
-}
+//       {/* <Redirect from="/main" to='/' /> */}
+//       <CRoute roles={['anon', 'user', 'admin']} path="/" component={EmptyContent} exact />
+//       <CRoute roles={['anon', 'user', 'admin']} path ="/login" component = {SignIn}/>
+//       <CRoute roles={['anon']} path = "/registration" component = {RegisterIn} />
+//       <CRoute roles={['anon', 'user', 'admin']} path = "/category/:_id" component = {CPageCategory}/>
+//       <CRoute roles={['anon', 'user', 'admin']} path = "/good/:_id" component = {CreatePageGood}/>
+//       <CRoute roles={['anon', 'user', 'admin']} path = "/basket" component={PageBasket}/>
+//       <CRoute roles={['user', 'admin']} path = "/listOrders" component={ListOrders}/>
+//       <CRoute roles={['anon', 'user', 'admin']} path = "/search/:value" component = {PageSearch}/>
+//       <CRoute roles={['admin']} path = "/admin/:_id" component = {PageCategoryAdmin}/>
+//       {/* <CRoute path = "*" component={Page404}/>  */}
 
-export default RouteSite;
+//     </>
+//   );
+// };
+
+// export default RouteSite;

+ 9 - 12
project/my-project/src/route/useRoute.js

@@ -1,25 +1,22 @@
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { SignIn, RegisterIn, ListOrders, EmptyContent, Page404} from '../components';
-import { PageBasket, CPageCategory, CreatePageGood, PageSearch}  from '../pages';
-
-
-
+import { Route } from 'react-router-dom';
+import { SignIn, RegisterIn, ListOrders, EmptyContent } from '../components';
+import { PageBasket, CPageCategory, CreatePageGood, PageSearch } from '../pages';
 
 const UseRoute = () => {
   return (
     <>
-      {/* <Redirect from="/main" to='/' /> */}
+
       <Route path="/" component={EmptyContent} exact />
       <Route path = "/login" component = {SignIn}/>
       <Route path = "/registration" component = {RegisterIn} />
       <Route path = "/category/:_id" component = {CPageCategory}/>
       <Route path = "/good/:_id" component = {CreatePageGood}/>
-      <Route path = "/basket" component={PageBasket}/> 
+      <Route path = "/basket" component={PageBasket}/>
       <Route path = "/listOrders" component={ListOrders}/>
       <Route path = "/search/:value" component = {PageSearch}/>
-      {/* <Route path = "*" component={Page404}/> */}
+
     </>
-  )
-}
+  );
+};
 
-export default UseRoute;
+export default UseRoute;

+ 22 - 45
project/my-project/src/store/index.js

@@ -2,55 +2,32 @@
 import thunk from 'redux-thunk';
 import { createStore, combineReducers, applyMiddleware } from 'redux';
 import { authReducer, promiseReducer, cartReducer, promiseImg, upLoaderReducer } from '../reducer';
-import { actionRootCats, actionSearchGood } from "../action";
-
-// export const store = createStore(combineReducers({
-//   promise: promiseReducer, 
-//   auth: authReducer, 
-//   cart: cartReducer
-// }), applyMiddleware(thunk));
- 
-// store.subscribe(() => console.log(store.getState()));
-// store.dispatch(actionRootCats());
-
-
-
-const localStoredReducer = (reducer, localStorageName) => 
-  (state, action) => { 
-
-    if(!state) {
-      const key = localStorage.getItem(localStorageName); 
-      if(key) { 
-       return JSON.parse(key);
+import { actionRootCats } from '../action';
+
+const localStoredReducer = (reducer, localStorageName) =>
+  (state, action) => {
+    if (!state) {
+      const key = localStorage.getItem(localStorageName);
+      if (key) {
+        return JSON.parse(key);
       } else {
-       return reducer(state, action);
-      }  
-    }       
-    if(state) {
-      let newState = reducer(state, action);  
+        return reducer(state, action);
+      }
+    }
+    if (state) {
+      const newState = reducer(state, action);
       localStorage.setItem(localStorageName, JSON.stringify(newState));
       return newState;
-    }   
-  }
-
-
- 
-
-
-  export const store = createStore(combineReducers({
-    promise: localStoredReducer(promiseReducer, 'promise'), 
-    auth: localStoredReducer(authReducer, 'auth'), 
-    cart: localStoredReducer(cartReducer, 'cart'),
-    img: localStoredReducer(promiseImg, 'img'),
-    upLoad: localStoredReducer(upLoaderReducer, 'upLoad'),
-  }), applyMiddleware(thunk));
-
-
-  
+    }
+  };
 
+export const store = createStore(combineReducers({
+  promise: localStoredReducer(promiseReducer, 'promise'),
+  auth: localStoredReducer(authReducer, 'auth'),
+  cart: localStoredReducer(cartReducer, 'cart'),
+  img: localStoredReducer(promiseImg, 'img'),
+  upLoad: localStoredReducer(upLoaderReducer, 'upLoad')
+}), applyMiddleware(thunk));
 
 store.subscribe(() => console.log(store.getState()));
 store.dispatch(actionRootCats());
-// setTimeout(() => {
-//   store.dispatch(actionSearchGood("iPhone 11"));
-// }, 2000)

+ 1 - 1
project/my-project/src/utils/index.js

@@ -1 +1 @@
-export { default as jwtDecode } from './jwtDecode';
+export { default as jwtDecode } from './jwtDecode';

+ 5 - 5
project/my-project/src/utils/jwtDecode.js

@@ -1,11 +1,11 @@
-function jwtDecode(token){
+function jwtDecode (token) {
   try {
-    let base64Url = token.split('.')[1];
-    let base64 = atob(base64Url);
-    return JSON.parse(base64); 
+    const base64Url = token.split('.')[1];
+    const base64 = atob(base64Url);
+    return JSON.parse(base64);
   } catch (err) {
     console.log(err);
   }
 }
 
-export default jwtDecode;
+export default jwtDecode;