Vika 2 年之前
父节点
当前提交
92351d1533
共有 37 个文件被更改,包括 712 次插入291 次删除
  1. 31 8
      project/my-project/src/App.css
  2. 1 1
      project/my-project/src/App.js
  3. 22 0
      project/my-project/src/action/actionAddGoodToCat.js
  4. 3 3
      project/my-project/src/action/actionCatById.js
  5. 21 0
      project/my-project/src/action/actionChangeGoodsInCat.js
  6. 1 1
      project/my-project/src/action/actionChangeOneGood.js
  7. 2 0
      project/my-project/src/action/index.js
  8. 0 22
      project/my-project/src/components/aaaaa.js
  9. 9 8
      project/my-project/src/components/addCategory.js
  10. 8 1
      project/my-project/src/components/buttonExSite.js
  11. 22 11
      project/my-project/src/components/cCategory.js
  12. 42 0
      project/my-project/src/components/cNewGoodInCat.js
  13. 35 8
      project/my-project/src/components/cartChangeGood.js
  14. 40 17
      project/my-project/src/components/category.js
  15. 50 14
      project/my-project/src/components/changeOfGood.js
  16. 11 0
      project/my-project/src/components/emptyContent.js
  17. 1 2
      project/my-project/src/components/goodCardCharacteristic.js
  18. 61 0
      project/my-project/src/components/goodSearch.js
  19. 3 0
      project/my-project/src/components/index.js
  20. 17 26
      project/my-project/src/components/inputSearchGood.js
  21. 30 34
      project/my-project/src/components/listOrders.js
  22. 21 21
      project/my-project/src/components/switchRoute.js
  23. 1 1
      project/my-project/src/pages/cpageCategory.js
  24. 3 1
      project/my-project/src/pages/index.js
  25. 44 38
      project/my-project/src/pages/mainPage.js
  26. 24 18
      project/my-project/src/pages/pageAdmin.js
  27. 19 17
      project/my-project/src/pages/pageBasket.js
  28. 5 2
      project/my-project/src/pages/pageGood.js
  29. 20 0
      project/my-project/src/pages/pageSearch.js
  30. 28 1
      project/my-project/src/reducer/authReducer.js
  31. 2 1
      project/my-project/src/reducer/index.js
  32. 33 0
      project/my-project/src/reducer/promisePreloader.js
  33. 37 0
      project/my-project/src/route/cRoute.js
  34. 3 1
      project/my-project/src/route/index.js
  35. 15 15
      project/my-project/src/route/privateRoute.js
  36. 27 0
      project/my-project/src/route/routeSite.js
  37. 20 19
      project/my-project/src/route/useRoute.js

+ 31 - 8
project/my-project/src/App.css

@@ -1,4 +1,4 @@
-#components-layout-demo-top-side-2 .logo {
+#components-layout-demo-top-side-2 {
   float:  right;
   width: 120px;
   height: 31px;
@@ -20,22 +20,35 @@
     flex-wrap: wrap;
 }
 
-.ant-col-2 {
-  padding-top: 10px;
-}
-
 .ant-card {
   margin: 7px;
 }
 
 a:link, a:visited {
-  color: rgb(15, 8, 119);
+  color: black;
+}
+
+/* .ant-menu-vertical>.ant-menu-item {
+  background-color: #e6f7ff;
+}  */
+
+.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
+  background-color: #e6f7ff;
 }
 
-.ant-menu-vertical>.ant-menu-item {
+.ant-menu-item {
   background-color: #e6f7ff;
+  padding-right: 0px;
+  
 }
 
+.ant-menu-item-selected {
+  margin-right: -2px;
+}
+
+.ant-menu-inline .ant-menu-item-selected:after, .ant-menu-inline .ant-menu-selected:after  {
+  opacity: 0;
+}
 .subCategory {
   margin-left: 10px;
 }
@@ -56,4 +69,14 @@ a:link, a:visited {
 
 .ant-input-group-wrapper {
   margin-top: 15px;
-}
+}
+
+.example {
+  margin: 50% 0;
+  margin-bottom: 20px;
+  padding: 30px 50px;
+  text-align: center;
+  /* background: rgba(0, 0, 0, 0.05); */
+  border-radius: 4px;
+}
+

+ 1 - 1
project/my-project/src/App.js

@@ -1,6 +1,6 @@
 
 import 'antd/dist/antd.min.css';
-import MainPage from './pages/mainPage';
+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';

+ 22 - 0
project/my-project/src/action/actionAddGoodToCat.js

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

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

@@ -5,17 +5,17 @@ import gql from "../api";
 const actionCatById = (_id) =>  //добавить подкатегории
   actionPromise('catById', gql(`query catById($q: String){
       CategoryFindOne(query:$q){
-         name subCategories {
+         _id name subCategories {
           _id
           name 
           goods {
             _id name description price images{
-            url
+            url _id
             }
           }
        }goods {
          _id name price description images{
-           url
+           url _id
          }
        }
      }

+ 21 - 0
project/my-project/src/action/actionChangeGoodsInCat.js

@@ -0,0 +1,21 @@
+import { actionPromise } from ".";
+import gql from "../api";
+
+const actionChangeGoodsInCat = (_id, name, goods) => {
+  return actionPromise('changeGoodsInCat ', gql(`
+    mutation changeGoodsInCat($category:CategoryInput){
+      CategoryUpsert(category:$category){
+        _id name goods{
+          name _id
+        }
+      }
+    }`, {
+      "category":{
+        "_id": _id,
+        "name": name,
+        "goods": goods,
+      }
+    }))
+}
+
+export default actionChangeGoodsInCat; 

+ 1 - 1
project/my-project/src/action/actionChangeOneGood.js

@@ -12,7 +12,7 @@ const actionChangeOneGood = (_id, name, description, price, idImg) =>
           "_id": _id,
           "description": description,
           "name": name, 
-          "price": price,
+          "price": +price,
           "images": [{"_id": idImg}]
         } 
     })))

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

@@ -12,4 +12,6 @@ export { default as actionChangeCategName } from './actionChangeCategName';
 export { default as actionAddCategory } from './actionAddCategory';
 export { default as actionChangeOneGood } from './actionChangeOneGood';
 export { default as actionSearchGood } from './actionSearchGood';
+export { default as actionChangeGoodsInCat } from './actionChangeGoodsInCat';
+export { default as actionAddGoodToCat } from './actionAddGoodToCat';
 

+ 0 - 22
project/my-project/src/components/aaaaa.js

@@ -1,22 +0,0 @@
-const localStoredReducer = (reducer, localStorageName) =>
-  (state, action) => {
-
-    if(!state) {
-      const key = localStorage.getItem(localStorageName);
-      if(key) {
-       return JSON.parse(key);
-      } else {
-        let newState = reducer(state,action);
-        localStorage.setItem(localStorageName, JSON.stringify(newState))
-        return newState;
-      }
-
-    }
-   
-   
-
-  }
-combineReducers({cart: localStoredReducer(cartReducer, 'cart')})  
-
-
-

+ 9 - 8
project/my-project/src/components/addCategory.js

@@ -12,15 +12,16 @@ const ACategory = ({addCat}) => {
   
   return (
     <div >
-    <Card type="inner" title="Добавить категорию товара">
-      <Input onChange={ (e) => setNameCat(e.target.value)}/>
-      <Space>
-        <Button type="primary" onClick={() => addCat(nameCat)}>Сохранить изменения</Button>
-        <Button type="primary" onClick={clearInput} >Очистить поле</Button>
-      </Space>
+      <Card type="inner" title="Добавить категорию">
+        <div>Введите название категории</div>
+       <Input onChange={ (e) => setNameCat(e.target.value)}/>
+        <Space>
+         <Button type="primary" onClick={() => addCat(nameCat)}>Сохранить изменения</Button>
+         <Button type="primary" onClick={clearInput} >Очистить поле</Button>
+        </Space>
       
-    </Card>
-</div>
+      </Card>
+    </div>
   )
 }
 

+ 8 - 1
project/my-project/src/components/buttonExSite.js

@@ -2,10 +2,17 @@ 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';
 
 const ButtonExit = ({authLogaut}) => {
+  let history = useHistory();
+
+  const exit = () => {
+    authLogaut();
+    history.push("/");
+  }
   return (
-    <Button onClick={() => authLogaut()}><Link to = {'/'}>Выход</Link> </Button>
+    <Button onClick={exit}>Выход</Button>
   )
 }
 

+ 22 - 11
project/my-project/src/components/cCategory.js

@@ -1,23 +1,34 @@
 import { CGoodCard } from ".";
 import { connect } from "react-redux";
 import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
 import { Link } from "react-router-dom";
+import { CPromisePreloader } from '../reducer'
 
 const { SubMenu } = Menu;
 
-const Category = ({cat:{name, goods=[], subCategories}}) => { console.log('goods',goods)
+const Category = ({cat:{name, goods=[], subCategories}}) => { 
+  
   return (
-    <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} </Link></Menu.Item>)}
-     
+    <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} 
+                </Link>
+               
+              
+            </Menu.Item>)}
         
-    </Menu>
-</div>
+            
+        </Menu>
+      </div>
+    </CPromisePreloader>  
   )
 }
 

+ 42 - 0
project/my-project/src/components/cNewGoodInCat.js

@@ -0,0 +1,42 @@
+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 [_idCat, setIdCat] = useState('');
+  const [nameCat, setNameCat] = useState('');
+  const [nameGood, setNameGood] = useState('');
+
+  useEffect(() => {
+    if (cat) {
+      setIdCat(cat._id);
+      setNameCat(cat.name);
+    }                                            
+  }, [cat])
+
+  const addGoodClearInput = () => {
+    add(_idCat, nameCat, nameGood); 
+    setNameGood('');
+  }
+
+  console.log('_idCat', _idCat, nameCat, nameGood)  ;
+  return (
+    < >
+      <Card type="inner" title="Добавить товар в категорию">
+       <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;

+ 35 - 8
project/my-project/src/components/cartChangeGood.js

@@ -2,30 +2,41 @@ import { Select,Card } from 'antd';
 import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
 import { СhangeOfGood } from '.';
-import { actionChangeOneGood } from '../action';
+import { actionChangeOneGood, actionChangeGoodsInCat } from '../action';
 
 const { Option } = Select;
 
-const SelectGood = ({goods, changeGood}) => { console.log('ggggg',goods)
+const SelectGood = ({goods, changeGood, changeGoodsInCat}) => { console.log('ggggg',goods)
   
   const [goodsCat, setGoodsCat] = useState([]); 
   const [_id, setId] = useState('');
   const [selectGood, setSelectGood] = useState({}); 
-  console.log('RENDER======')
+  const [numbSelectGood, setNumbSelectGood] = useState('');
+  const [idCat, setIdCat] = useState('');
+  const [nameCat, setNameCat] =useState('');
+  
   useEffect(() => {
     if(goods && goods.goods && selectGood.name!== goods.goods.name ) {
       setSelectGood({});
+      setNumbSelectGood('')
     }
 
     if(goods && goods.goods){
-    setGoodsCat(goods.goods);
+      setGoodsCat(goods.goods);
+      setIdCat(goods._id);
+      setNameCat(goods.name)
     }
   }, [goods])
 
   function handleChange(value) {
       console.log(`selected ${value}`);
      
-      const good = goodsCat.filter((good) => good._id === value); 
+      const good = goodsCat.filter((good, index) => {
+        if (good._id === value) {
+          setNumbSelectGood(index+1);
+        }
+         
+        return good._id === value}); 
       setSelectGood(...good);
       setId(value);
     }
@@ -34,26 +45,42 @@ const SelectGood = ({goods, changeGood}) => { console.log('ggggg',goods)
       console.log("----", typeof name, typeof description, typeof price, typeof imgId )
       changeGood(_id, 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 (
      < >{goods &&
       <Card type="inner" title="Изменить товар">
         <Select value={selectGood.name || null} placeholder='Выбирите товар' style={{ width: 272 }} onChange={handleChange}>
-          {goodsCat.map((item) => <Option value={item._id} key={item._id}>{item.name}</Option>)}
+          {goodsCat.map((item, index) => <Option value={item._id} key={item._id}>{`${index+1} ${item.name}`}</Option>)}
         </Select>
-        <СhangeOfGood good={selectGood} changeGood={() => changeGoodInSer}/>
+        <СhangeOfGood good={selectGood} changeGood={changeGoodInSer} number={numbSelectGood} changeIndexGoodInSer={changeIndexGoodInSer}/>
+        {/* <div>
+          <p>№ в категории</p>
+        </div> */}
       </Card>
     }</>
    )
 }
 
 const mapStateToProps = (state) => ({
-  goods: state.promise.catById?.payload
+  goods: state.promise.catById?.payload,
+  
 })
 
 const mapDispatchToProps = {
   changeGood : actionChangeOneGood,
+  changeGoodsInCat: actionChangeGoodsInCat, 
 }
 
 

+ 40 - 17
project/my-project/src/components/category.js

@@ -1,30 +1,53 @@
 import { store } from "../store";
 import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { actionRootCats } from "../action";
+import { AppstoreOutlined, MenuUnfoldOutlined, MenuFoldOutlined, PieChartOutlined, DesktopOutlined, ContainerOutlined, MailOutlined } from '@ant-design/icons';
 import {Provider, connect} from 'react-redux';
-import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
-import { useEffect } from "react";
+import { Button, Menu  } from 'antd';
+import { useEffect, useState } from "react";
+import React from 'react';
+import { jwtDecode } from "../utils";
 
 const { SubMenu } = Menu;
 
-const CategoryListItem = ({_id, name}) =>
-  // <li> 
-    
-      <Menu.Item><Link to={`/category/${_id}`}>{name} </Link></Menu.Item>
+const CategoryListItem = ({_id, name}) => {
+  const [userName, setUserName] = useState('user');
+  
+  useEffect( () => {
+    const token = localStorage.getItem('authToken'); 
+    //
+    if (token) { 
+      const name = jwtDecode(token)['sub']['acl']; 
+      name.includes('admin') ? setUserName('admin'):  setUserName('user'); 
+     
+    }
+  }, [localStorage.getItem('authToken')]);  
+  
+  return (
+    < > 
+
+
+      { userName === 'user' ? 
+        <Menu.Item icon={<PieChartOutlined />}><Link to={`/category/${_id}`}>{name} </Link></Menu.Item>
+        :
+        <Menu.Item><Link to={`/admin/${_id}`}>{name} </Link></Menu.Item>
+      } 
+    </>
     
-  {/* </li> */}
+     
+  )  
+  
 
-const CategoryList = ({cats}) =>{console.log('cats', cats)
-  // useEffect(() => {
-  //   getCategoryList()
-  // }, [])
+}
 
+const CategoryList = ({cats}) =>{console.log('cats', cats)
+ 
   return (
-    <Menu>
-      {/* <Menu.Item>Категории товаров</Menu.Item> */}
-      {cats.map((item) => <CategoryListItem key={item._id} {...item} />)}
-    </Menu>
-)
+    <div >
+     
+        {cats.map((item) => <CategoryListItem key={item._id} {...item} />)}
+     
+    </div>
+  ) 
 }
 
 const mapStateToProps = state => ({cats:state.promise.rootCats?.payload || []})

+ 50 - 14
project/my-project/src/components/changeOfGood.js

@@ -1,45 +1,81 @@
 import { Input, Card, Button, Space, Image, Row } from 'antd';
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
 import { connect } from 'react-redux';
 import { InputUpLoadFile } from '.';
 import { backURL } from '../api'; 
 
 const { TextArea } = Input;
 
-const CharacterfGood =({ good, good:{ _id, name, description, images, price }, upLoad, changeGood }) => {    console.log('gooood',good)
+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 [ img, setImg ] = useState(''); 
+    const [ imag, setImag ] = useState(''); 
     const [ cost, setCost ] = useState(price);
+    const [inputNumber, setInputNumber] = useState(number);
 
     useEffect( () => {
       setInputName(name);
       setInputDescrip(description);
 
-      if(images && images[0].url) {
-        setImg(images[0].url); 
+      if (images && images[0].url) {
+        setImag(images[0].url); 
+        setInputIdImg(images[0]._id);
+      }
+
+      if (Object.keys(good).length === 0) { console.log('gfergergrthetrhrthyrty')
+        setImag(''); 
+        setInputIdImg('');
+      }
+      if(images && !images[0].url) {
+        setImag(''); 
+        setInputIdImg(''); 
       }
               
-      setCost(price);           
+      setCost(price); 
+      setInputNumber(number); 
+          
 
     }, [good])
 
+    
+
     useEffect(() => {
-      if(upLoad && upLoad.status === 'RESOLVED' ) { console.log('',)
-        setImg(upLoad.payload.url);
-        setInputIdImg(upLoad.payload._id);  //61e304d8f9be102f49b2aa5c
+      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 saveChange = () => {
+      changeGood(inputName, inputDescrip, cost, inputIdImg );
+      changeIndexGoodInSer(inputNumber);
+      clearInput();
+    }
+                                                                        console.log('imag', imag); console.log('good',good)
   return (
     <div >
+        <div>№ в категории</div>
+          <Input value={inputNumber} onChange={(e) => setInputNumber(e.target.value)}/>
+          <Button type="primary" onClick={() => setInputNumber('')}>Очистить поле</Button>
+
       <div>Название</div>
         <Input value={inputName} onChange={(e) => setInputName(e.target.value)}/>
-        <Button type="primary" >Очистить поле</Button>
+        <Button type="primary" onClick={() => setInputName('')}>Очистить поле</Button>
       <div>Характеристика</div>
         <TextArea
             value={inputDescrip}
@@ -47,11 +83,11 @@ const CharacterfGood =({ good, good:{ _id, name, description, images, price }, u
             
             autoSize={{ minRows: 3, maxRows: 5 }}
           />
-        <Button type="primary" >Очистить поле</Button>
+        <Button type="primary" onClick={() => setInputDescrip('')}>Очистить поле</Button>
       <div>Цена</div>
         <Row>
           <Input value={cost} onChange={(e) => setCost(e.target.value)}/>
-          <Button type="primary" >Очистить поле</Button>
+          <Button type="primary" onClick={() => setCost('')}>Очистить поле</Button>
         </Row>
        
         
@@ -62,12 +98,12 @@ const CharacterfGood =({ good, good:{ _id, name, description, images, price }, u
             {Object.keys(good).length === 0 ?
               <div style={{height:"150px", width:"150px"}}> </div>
               :
-              <Image width={150} height={150} src={`${backURL}/${img}`} style={{ objectFit: 'cover' }}/>}
+              <Image width={150} height={150} src={`${backURL}/${imag}`} style={{ objectFit: 'cover' }}/>}
               <InputUpLoadFile/>
            {/* </div> */}
         </Space>
         <Space size={2}></Space>
-        <Button type="primary" block onClick={() => changeGood(inputName, inputDescrip, cost, inputIdImg )}>
+        <Button type="primary" block onClick={saveChange}>
           Сохранить изменения
         </Button>     
   </div>

+ 11 - 0
project/my-project/src/components/emptyContent.js

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

+ 1 - 2
project/my-project/src/components/goodCardCharacteristic.js

@@ -1,6 +1,5 @@
-import { Card, Image } from 'antd';
+import { Card, Image, Button  } from 'antd';
 import { connect } from 'react-redux';
-import { Button } from 'antd';
 import { actionCartAdd } from '../action';
 
 const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';

+ 61 - 0
project/my-project/src/components/goodSearch.js

@@ -0,0 +1,61 @@
+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';
+
+const ContentSearch = ({value, onAdd}) => { console.log('value', value)
+  const [good, setGood] = useState(value); 
+  let history = useHistory();
+
+  useEffect(() => {
+    if(value.length) {
+      setGood(value[0]);
+    }
+  }, [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} />}
+          <p>{good.description}</p>
+          <p>{good.price} грн</p>
+          <Button onClick={() => onAdd({
+                                        _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}
+          />
+        </>
+        }
+    </>
+  )
+}
+
+const mapStateToProps = (state) => ({
+  value: state.promise.searchGood?.payload || [],
+})
+const mapDispatchToProps = {
+  onAdd: actionCartAdd,
+}
+
+const GoodSearch = connect(mapStateToProps, mapDispatchToProps)(ContentSearch);
+
+export default GoodSearch;

+ 3 - 0
project/my-project/src/components/index.js

@@ -15,5 +15,8 @@ export { default as AddCategory } from './addCategory';
 export { default as СhangeOfGood } from './changeOfGood';
 export { default as CartChangeGood} from './cartChangeGood';
 export { default as InputSearchGood } from './inputSearchGood';
+export { default as CNewGoodInCat } from './cNewGoodInCat';
+export { default as EmptyContent } from './emptyContent';
+export { default as GoodSearch } from './goodSearch';
 
 

+ 17 - 26
project/my-project/src/components/inputSearchGood.js

@@ -1,44 +1,35 @@
-import { Input  } from 'antd';
+import { Input, Button  } from 'antd';
+import { SearchOutlined } from '@ant-design/icons';
 import { useEffect, useState } from 'react';
 import { connect } from 'react-redux';
-import { actionSearchGood } from '../action';
-import {useHistory} from 'react-router-dom';
+import {Link} from 'react-router-dom';
 
-const { Search } = Input;
-
-const InputSearchG = ({good:{_id}, search}) => { 
-  let history = useHistory();
-  const [idGood, setIdGood] = useState(_id);
+const InputSearchG = ({nick}) => { 
   const [inputValue, setInputValue] = useState('');
+  const [user, setUser] = useState(nick);
   
-  useEffect(() => {
-    if(_id) {
-      setIdGood(_id);
-      history.push(`/good/${_id}`);
+  useEffect(() => { 
+
+    if(nick && nick.acl && nick.acl.includes('admin')) {
+      setUser('admin')
     }
 
-  }, [_id])
+  }, [nick])
 
-  const onSearch = value => {
-    console.log(value);
-    search(value);
-    setInputValue(''); console.log('setInputValue',)
-   
-  } 
   
   return (
-    <Search placeholder="Найти товар " allowClear onSearch={onSearch} style={{ width: 250 }} value={inputValue} 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) => ({
-  good: state.promise.searchGood?.payload[0] || '',
+  nick: state.auth.payload?.sub || '',
 }) 
 
-const mapDispatchToProps = {
-  search: actionSearchGood,
-}
-
-const InputSearchGood = connect(mapStateToProps, mapDispatchToProps)(InputSearchG);
+const InputSearchGood = connect(mapStateToProps)(InputSearchG);
 
 export default InputSearchGood;

+ 30 - 34
project/my-project/src/components/listOrders.js

@@ -1,7 +1,7 @@
-import { connect } from "react-redux";
+import { connect } from 'react-redux';
 import { Card, Row, Col } from 'antd';
-import { actionMyOrders } from "../action";
-import { useEffect, useState } from "react";
+import { useEffect, useState } from 'react';
+import { CPromisePreloader } from '../reducer';
 
 const Orders = ({allOrders, status}) => {
   const [ord, setOrd] = useState(allOrders); 
@@ -13,37 +13,33 @@ const Orders = ({allOrders, status}) => {
   }, [allOrders])
 
   return (
-    <Card title="История заказов">
-
-    { ord.length0 === 0 && status['status'] &&  <Card>Вы не совершали покупки</Card>}
-       { ord.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) => 
-              <Card key={item._id}>
-                <Row>
-                  <Col span={9}>{item.good.name}</Col>
-                  <Col span={5}>{`${item.count} шт.`}</Col>
-                  <Col span={5}>{`${item.price} грн.`}</Col>
-                  <Col span={5}>{`${item.total}`}</Col>
-                </Row>
-              </Card>
-            )}
-          </Card>
-
-
-      ) 
-      
-    
-    }
-
-   
-  </Card>
+    <CPromisePreloader myOrders='myOrders'>
+
+      <Card title="История заказов">
+
+      { ord.length0 === 0 && status['status'] &&  <Card>Вы не совершали покупки</Card>}
+        { ord.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) => 
+                <Card key={item._id}>
+                  <Row>
+                    <Col span={9}>{item.good.name}</Col>
+                    <Col span={5}>{`${item.count} шт.`}</Col>
+                    <Col span={5}>{`${item.price} грн.`}</Col>
+                    <Col span={5}>{`${item.total}`}</Col>
+                  </Row>
+                </Card>
+              )}
+        </Card>
+       )}
+      </Card>
+    </CPromisePreloader> 
   )
 }
 

+ 21 - 21
project/my-project/src/components/switchRoute.js

@@ -1,26 +1,26 @@
-import { useEffect, useState } from "react";
-import { UseRoute } from "../route";
-import { jwtDecode } from "../utils";
-import { PrivateRoute } from "../route";
+// import { useEffect, useState } from "react";
+// import { UseRoute } from "../route";
+// import { jwtDecode } from "../utils";
+// import { PrivateRoute } from "../route";
 
-const SwitchRoute = () => {
-  const [userName, setUserName] = useState('user');
+// const SwitchRoute = () => {
+//   const [userName, setUserName] = useState('user');
 
-  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'); 
+//   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'); 
      
-    }
-  }, [localStorage.getItem('authToken')])
+//     }
+//   }, [localStorage.getItem('authToken')])
 
-  return ( 
-    < >
-    {userName === 'user' ? <UseRoute/>: <PrivateRoute/>}
-    </>
-  )
-}
+//   return ( 
+//     < >
+//     {userName === 'user' ? <UseRoute/>: <PrivateRoute/>}
+//     </>
+//   )
+// }
 
-export default SwitchRoute; 
+// export default SwitchRoute; 

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

@@ -3,7 +3,7 @@ import { CCategory } from "../components";
 import { connect } from "react-redux";
 import { actionCatById } from "../action";
 
-const PageCategory = ({match, match: {params: {_id}}, getData}) => {console.log('match',match, _id); 
+export const PageCategory = ({match: {params: {_id}}, getData}) => {
   useEffect(() => { 
       getData(_id)
   },[_id])

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

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

+ 44 - 38
project/my-project/src/pages/mainPage.js

@@ -6,6 +6,7 @@ import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
 import { actionRootCats } from "../action";
 
 
+
 import {SignIn, ListOrders, Page404} from '../components';
 import { CCategoryList, SwitchRoute } from '../components';
 import { useEffect } from 'react';
@@ -14,7 +15,7 @@ import CreatePageGood from './pageGood';
 import { HeaderSite } from '../components';
 import PageBasket from './pageBasket';
 import { RegisterIn } from '../components';
-import { UseRoute } from '../route'
+import { UseRoute, RouteSite } from '../route'
 
 
 const { SubMenu } = Menu;
@@ -26,57 +27,62 @@ const IconFont = createFromIconfontCN({
 function MainPage () {
 
   return (
-    <>
-     <Layout>
-      <HeaderSite/>
+    <Layout>
+     <HeaderSite/>
     <Content style={{ padding: '0 50px' }}>
-      <Layout className="site-layout-background" style={{ padding: '24px 0' }}>
-        <Sider className="site-layout-background" width={200}>
-          {/* <Menu
+      <Breadcrumb style={{ margin: '16px 0' }}/>
+      <Layout className="site-layout-background" style={{ marginTop: '-2px 0' }}>
+        <Sider className="site-layout-background" width={230}>
+          <Menu
             mode="inline"
             defaultSelectedKeys={['1']}
             defaultOpenKeys={['sub1']}
             style={{ height: '100%' }}
-          /> */}
+          >
             <CCategoryList/>
-            {/* <SubMenu key="sub1" icon={<UserOutlined />} title="subnav 1"> */}
-              {/* <Menu.Item key="1">option1</Menu.Item>
-              <Menu.Item key="2">option2</Menu.Item>
-              <Menu.Item key="3">option3</Menu.Item>
-              <Menu.Item key="4">option4</Menu.Item> */}
-            {/* </SubMenu>
-            <SubMenu key="sub2" icon={<LaptopOutlined />} title="subnav 2">
-              <Menu.Item key="5">option5</Menu.Item>
-              <Menu.Item key="6">option6</Menu.Item>
-              <Menu.Item key="7">option7</Menu.Item>
-              <Menu.Item key="8">option8</Menu.Item>
-            </SubMenu>
-            <SubMenu key="sub3" icon={<NotificationOutlined />} title="subnav 3">
-              <Menu.Item key="9">option9</Menu.Item>
-              <Menu.Item key="10">option10</Menu.Item>
-              <Menu.Item key="11">option11</Menu.Item>
-              <Menu.Item key="12">option12</Menu.Item>
-            </SubMenu> */}
-          {/* </Menu> */}
+          </Menu>
         </Sider>
         <Content style={{ padding: '0 24px', minHeight: 280 }}>Content
           <Switch>
-            <SwitchRoute/>
+            <RouteSite/>
           </Switch>
+        </Content>  
+      </Layout>
+    </Content>
+    <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
+  </Layout>
+
+
+
+    // <>
+    //  <Layout>
+    //   <HeaderSite/>
+    // <Content style={{ padding: '0 50px' }}>
+    //   <Layout className="site-layout-background" style={{ padding: '24px 0' }}>
+    //     <Sider >
+         
+    //         <CCategoryList/>
+      
+    //     </Sider>
+    //     <Content style={{ padding: '0 24px', minHeight: 280 }}>Content
+          // <Switch>
+          //   {/* <SwitchRoute/> */}
+          //   <RouteSite/>
+          // </Switch>
 
           
 
 
-        </Content>
-      </Layout>
-    </Content>
-    <Footer style={{ textAlign: 'center' }}><div className="icons-list">
-      <IconFont type="icon-facebook"  style={{color: 'black', fontSize:'30px'}}/>
-      <IconFont type="icon-twitter" style={{fontSize:'30px', marginLeft:'10px'}} />
-    </div>
-    </Footer>
-    </Layout> 
-    </>
+    //     </Content>
+    //   </Layout>
+    // </Content>
+    // <Footer style={{ textAlign: 'center' }}><div className="icons-list">
+    //   <IconFont type="icon-facebook"  style={{color: 'black', fontSize:'30px'}}/>
+    //   <IconFont type="icon-twitter" style={{fontSize:'30px', marginLeft:'10px'}} />
+    // </div>
+    // </Footer>
+    // </Layout> 
+    // </>
   )
   
 }

+ 24 - 18
project/my-project/src/pages/pageAdmin.js

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

+ 19 - 17
project/my-project/src/pages/pageBasket.js

@@ -4,6 +4,7 @@ import { actionCartAdd,  actionCartRemove, actionCartChange, actionCartClear, ac
 import { connect } from 'react-redux';
 import {PlusSquareTwoTone, MinusSquareTwoTone, CloseSquareTwoTone, CheckSquareTwoTone, RestTwoTone} from '@ant-design/icons';
 import { useEffect, useState } from 'react';
+import { CPromisePreloader } from '../reducer';
 
 
 
@@ -72,23 +73,24 @@ const GoodsInBasket = ({cart = {}, orderPayload, cartMin, cartClear, cartChange,
   }
 
   return (
-    <Card title="Ваш заказ">
-     <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>
-      }
-     </Space> 
-    </Row>
-
-       {goods.map((item) => <CartBasket key={item.good._id} {...item} clickButton={{cartMin, cartChange, cartRemove, cartAdd}}/>)}
-    </Card>
-   
+    <CPromisePreloader name='order'>
+      <Card title="Ваш заказ">
+      <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>
+        }
+      </Space> 
+      </Row>
+
+        {goods.map((item) => <CartBasket key={item.good._id} {...item} clickButton={{cartMin, cartChange, cartRemove, cartAdd}}/>)}
+      </Card>
+      </CPromisePreloader>
   )
 
 }

+ 5 - 2
project/my-project/src/pages/pageGood.js

@@ -2,14 +2,17 @@ import { useEffect } from "react";
 import { connect } from "react-redux";
 import { GoodCardCharacteristic } from "../components";
 import { actionGoodById } from "../action";
+import { CPromisePreloader } from "../reducer"
 
-const PageGood = ({match, match: {params: {_id}}, getData}) => { console.log('matchGood', match)
+const PageGood = ({match: {params: {_id}}, getData}) => { 
   useEffect( () =>{
     getData(_id)
   }, [_id])
 
   return (
-    <GoodCardCharacteristic/>
+    <CPromisePreloader name='goodById'>
+      <GoodCardCharacteristic/>
+    </CPromisePreloader>
   )
 }
 

+ 20 - 0
project/my-project/src/pages/pageSearch.js

@@ -0,0 +1,20 @@
+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(()=>{
+    searchGood(value);
+  }, [value])
+
+   return (
+    <CPromisePreloader>  
+      <GoodSearch value={value}/>
+    </CPromisePreloader>
+   )
+}
+const PageSearch = connect(null, {searchGood:actionSearchGood})(PageSearchGood);
+
+export default PageSearch;

+ 28 - 1
project/my-project/src/reducer/authReducer.js

@@ -1,9 +1,35 @@
 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 на наличие
-        return {
+        state = {
         'type': 'AUTH_LOGIN',
         'token':localStorage.authToken,
         };                         //если есть - сделать так, что бы следующий if сработал
@@ -26,4 +52,5 @@ function authReducer(state, {type, token}){
   return state
 }
 
+
 export default authReducer;

+ 2 - 1
project/my-project/src/reducer/index.js

@@ -1,3 +1,4 @@
 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'; 

+ 33 - 0
project/my-project/src/reducer/promisePreloader.js

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

+ 37 - 0
project/my-project/src/route/cRoute.js

@@ -0,0 +1,37 @@
+import { useEffect, useState } from "react";
+import { useHistory, Route, Redirect}  from 'react-router-dom';
+import { connect } from "react-redux";
+
+
+const ProtectedRoute = ({fallback='/', 
+                      roles=["admin"], 
+                      auth,
+                      ...routeProps}) => {
+ 
+    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');                                                             
+                                                                                        
+      const newAcl = roles.filter((item) => acl.includes(item));                     
+      if (newAcl.length) {
+        setAccess(true);
+      }
+    })
+
+    return (
+      < >
+        { access? <Route {...routeProps}/> : <Redirect to='/'/>}
+      </>
+    )  
+}
+//<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}))(ProtectedRoute);
+
+export default CRoute; 

+ 3 - 1
project/my-project/src/route/index.js

@@ -1,2 +1,4 @@
 export { default as UseRoute } from './useRoute';
-export { default as PrivateRoute } from './privateRoute';
+export { default as PrivateRoute } from './privateRoute';
+export { default as RouteSite } from './routeSite';
+export { default as CRoute } from './cRoute';

+ 15 - 15
project/my-project/src/route/privateRoute.js

@@ -1,19 +1,19 @@
-import { Route, Switch } from "react-router-dom";
-import { SignIn } from "../components";
-import { PageCategoryAdmin } from "../pages";
+// import { Route, Switch } from "react-router-dom";
+// import { SignIn } from "../components";
+// import { PageCategoryAdmin } from "../pages";
 
 
 
-const PrivateRoute = () => {
-  return (
-    <>
-      <Route path = "/login" component = {SignIn}/>
-      <Route path = "/category/:_id" component = {PageCategoryAdmin}/>
-      {/* <Route path = "/good/:_id" component = {CreatePageGood}/>
-      <Route path = "/basket" component={PageBasket}/> 
-      <Route path = "/listOrders" component={ListOrders}/> */}
-    </>
-  )
-}
+// const PrivateRoute = () => {
+//   return (
+//     <>
+//       <Route path = "/login" component = {SignIn}/>
+//       <Route path = "/category/:_id" component = {PageCategoryAdmin}/>
+//       {/* <Route path = "/good/:_id" component = {CreatePageGood}/>
+//       <Route path = "/basket" component={PageBasket}/> 
+//       <Route path = "/listOrders" component={ListOrders}/> */}
+//     </>
+//   )
+// }
 
-export default PrivateRoute;
+// export default PrivateRoute;

+ 27 - 0
project/my-project/src/route/routeSite.js

@@ -0,0 +1,27 @@
+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';
+
+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;

+ 20 - 19
project/my-project/src/route/useRoute.js

@@ -1,24 +1,25 @@
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import { SignIn, RegisterIn, ListOrders } from '../components';
-import { PageBasket, CPageCategory, CreatePageGood}  from '../pages';
+// 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';
 
 
 
 
-const UseRoute = () => {
-  return (
-    <>
-      {/* <Redirect from="/main" to='/' /> */}
-      {/* <Route path="/" component={PageMain} 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 = "/listOrders" component={ListOrders}/>
-      {/* <Route path = "/*" component= {Page404}/> */}
-    </>
-  )
-}
+// 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 = "/listOrders" component={ListOrders}/>
+//       <Route path = "/search/:value" component = {PageSearch}/>
+//       {/* <Route path = "*" component={Page404}/> */}
+//     </>
+//   )
+// }
 
-export default UseRoute;
+// export default UseRoute;