Vika 3 years ago
parent
commit
45ae9c7874
51 changed files with 31175 additions and 0 deletions
  1. 23 0
      project/my-project/.gitignore
  2. 70 0
      project/my-project/README.md
  3. 29687 0
      project/my-project/package-lock.json
  4. 45 0
      project/my-project/package.json
  5. 43 0
      project/my-project/public/index.html
  6. 3 0
      project/my-project/public/robots.txt
  7. 45 0
      project/my-project/src/App.css
  8. 30 0
      project/my-project/src/App.js
  9. 8 0
      project/my-project/src/App.test.js
  10. 5 0
      project/my-project/src/action/actionCart.js
  11. 24 0
      project/my-project/src/action/actionCatById.js
  12. 13 0
      project/my-project/src/action/actionGoodById.js
  13. 26 0
      project/my-project/src/action/actionLogin.js
  14. 13 0
      project/my-project/src/action/actionMyOrders.js
  15. 23 0
      project/my-project/src/action/actionOrder.js
  16. 18 0
      project/my-project/src/action/actionPromise.js
  17. 27 0
      project/my-project/src/action/actionRegister.js
  18. 12 0
      project/my-project/src/action/actionRootCats.js
  19. 27 0
      project/my-project/src/action/actionUploadFile.js
  20. 11 0
      project/my-project/src/action/index.js
  21. 26 0
      project/my-project/src/api/index.js
  22. 14 0
      project/my-project/src/components/buttonExSite.js
  23. 28 0
      project/my-project/src/components/cCategory.js
  24. 46 0
      project/my-project/src/components/cGoodCard.js
  25. 34 0
      project/my-project/src/components/category.js
  26. 23 0
      project/my-project/src/components/goodCardCharacteristic.js
  27. 120 0
      project/my-project/src/components/header.js
  28. 13 0
      project/my-project/src/components/index.js
  29. 27 0
      project/my-project/src/components/inputUploadFile.js
  30. 60 0
      project/my-project/src/components/listOrders.js
  31. 4 0
      project/my-project/src/components/pege404.js
  32. 101 0
      project/my-project/src/components/registerIn.js
  33. 101 0
      project/my-project/src/components/signIn.js
  34. 14 0
      project/my-project/src/index.css
  35. 17 0
      project/my-project/src/index.js
  36. 1 0
      project/my-project/src/logo.svg
  37. 17 0
      project/my-project/src/pages/cpageCategory.js
  38. 3 0
      project/my-project/src/pages/index.js
  39. 80 0
      project/my-project/src/pages/mainPage.js
  40. 115 0
      project/my-project/src/pages/pageBasket.js
  41. 18 0
      project/my-project/src/pages/pageGood.js
  42. 29 0
      project/my-project/src/reducer/authReducer.js
  43. 61 0
      project/my-project/src/reducer/cartReducer.js
  44. 3 0
      project/my-project/src/reducer/index.js
  45. 11 0
      project/my-project/src/reducer/promiseReducer.js
  46. 1 0
      project/my-project/src/route/index.js
  47. 24 0
      project/my-project/src/route/useRoute.js
  48. 5 0
      project/my-project/src/setupTests.js
  49. 14 0
      project/my-project/src/store/index.js
  50. 1 0
      project/my-project/src/utils/index.js
  51. 11 0
      project/my-project/src/utils/jwtDecode.js

+ 23 - 0
project/my-project/.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

+ 70 - 0
project/my-project/README.md

@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
+
+You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

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


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

@@ -0,0 +1,45 @@
+{
+  "name": "my-project",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.16.1",
+    "@testing-library/react": "^12.1.2",
+    "@testing-library/user-event": "^13.5.0",
+    "antd": "^4.18.2",
+    "bootstrap": "^5.1.3",
+    "react": "^17.0.2",
+    "react-bootstrap": "^2.0.4",
+    "react-dom": "^17.0.2",
+    "react-dropzone": "^11.5.1",
+    "react-redux": "^7.2.6",
+    "react-router-dom": "^5.3.0",
+    "react-scripts": "5.0.0",
+    "redux-thunk": "^2.4.1",
+    "web-vitals": "^2.1.2"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}

+ 43 - 0
project/my-project/public/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <!-- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> -->
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>

+ 3 - 0
project/my-project/public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 45 - 0
project/my-project/src/App.css

@@ -0,0 +1,45 @@
+#components-layout-demo-top-side-2 .logo {
+  float:  right;
+  width: 120px;
+  height: 31px;
+  margin: 16px 24px 16px 0;
+  background: rgba(255, 255, 255, 0.3);
+}
+
+.ant-row-rtl #components-layout-demo-top-side-2 .logo {
+  float: right;
+  margin: 16px 0 16px 24px;
+}
+
+.site-layout-background {
+  background: #fff;
+}
+
+.category ul {
+    display: flex;
+    flex-wrap: wrap;
+}
+
+.ant-col-2 {
+  padding-top: 10px;
+}
+
+.ant-card {
+  margin: 7px;
+}
+
+a:link, a:visited {
+  color: rgb(15, 8, 119);
+}
+
+.ant-menu-vertical>.ant-menu-item {
+  background-color: #e6f7ff;
+}
+
+.subCategory {
+  margin-left: 10px;
+}
+
+.ant-layout-header {
+  background:  #728892; 
+}

+ 30 - 0
project/my-project/src/App.js

@@ -0,0 +1,30 @@
+
+import 'antd/dist/antd.min.css';
+import MainPage from './pages/mainPage';
+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() {
+  return (
+    <Router history={history}>
+      <Provider store={store}>
+        <div className="App">
+          <MainPage></MainPage>
+      </div>
+      </Provider>
+
+<InputUpLoadFile/>
+
+    </Router>
+
+    
+  );
+}
+
+export default App;

+ 8 - 0
project/my-project/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

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

@@ -0,0 +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});

+ 24 - 0
project/my-project/src/action/actionCatById.js

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

+ 13 - 0
project/my-project/src/action/actionGoodById.js

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

+ 26 - 0
project/my-project/src/action/actionLogin.js

@@ -0,0 +1,26 @@
+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}`
+    }
+  )
+)
+
+const actionAuthLogin  = token => ({type: 'AUTH_LOGIN', token})
+
+const actionFullLogin = (login, password) =>
+  async dispatch => {
+    let token = await dispatch(actionLogin(login, password)); 
+
+    if (token){
+        dispatch(actionAuthLogin(token))
+    }
+  }
+
+export default actionFullLogin;  

+ 13 - 0
project/my-project/src/action/actionMyOrders.js

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

+ 23 - 0
project/my-project/src/action/actionOrder.js

@@ -0,0 +1,23 @@
+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}))
+
+      await dispatch(actionPromise('order', gql(`
+                  mutation newOrder($order:OrderInput){
+                    OrderUpsert(order:$order)
+                      { _id total 	}
+                  }
+          `, {order: {orderGoods}})))
+}
+
+export default actionOrder;

+ 18 - 0
project/my-project/src/action/actionPromise.js

@@ -0,0 +1,18 @@
+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))
+      }
+  }
+
+ export default actionPromise; 

+ 27 - 0
project/my-project/src/action/actionRegister.js

@@ -0,0 +1,27 @@
+import { actionPromise } from ".";
+import gql from "../api";
+import { actionFullLogin } from ".";
+
+export const actionRegister = (login, password) =>                  //const actionRegister //actionPromise
+  actionPromise('register', gql(`mutation register($user:UserInput){
+    UserUpsert(user:$user){
+      _id login
+    }
+  }`, {"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 показывает ваши бывшие заказы:
+  }

+ 12 - 0
project/my-project/src/action/actionRootCats.js

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

+ 27 - 0
project/my-project/src/action/actionUploadFile.js

@@ -0,0 +1,27 @@
+import { connect } from "react-redux";
+import { actionPromise } from "./";
+import { backURL } from '../api';
+
+const actionUploadFile = (file) => {
+  const fileJson = JSON.stringify(file[0]);
+  const formData = new FormData();
+  formData.append("photo", file[0]);
+  
+   return actionPromise('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;
+})
+  )
+}
+
+
+export default actionUploadFile;

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

@@ -0,0 +1,11 @@
+export { default as actionRootCats } from './actionRootCats';
+export { default as actionPromise } from './actionPromise';
+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 { default as actionOrder } from './actionOrder';
+export { default as actionMyOrders } from './actionMyOrders';
+export { default as actionUploadFile} from './actionUploadFile';
+

+ 26 - 0
project/my-project/src/api/index.js

@@ -0,0 +1,26 @@
+const getGQL = url =>
+  (query, variables = {}) =>
+      fetch(url, {
+      //метод
+      method: 'POST',
+      headers: {
+          //заголовок content-type
+          "Content-Type": "application/json",
+          ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} :
+                                       {})
+      },
+      //body с ключами 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]]
+      })
+
+export const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
+  
+const gql = getGQL(`${backURL}/graphql`)
+
+export default gql;

+ 14 - 0
project/my-project/src/components/buttonExSite.js

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

+ 28 - 0
project/my-project/src/components/cCategory.js

@@ -0,0 +1,28 @@
+import { CGoodCard } from ".";
+import { connect } from "react-redux";
+import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
+import { useEffect } from "react";
+import { Link } from "react-router-dom";
+
+const { SubMenu } = Menu;
+
+const Category = ({cat:{name, goods=[], subCategories}}) => { console.log('goods',goods)
+  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>)}
+     
+        
+    </Menu>
+</div>
+  )
+}
+
+
+const CCategory = connect(state => ({cat:state.promise.catById?.payload || {}}))
+                              (Category)
+
+export default CCategory;                              

+ 46 - 0
project/my-project/src/components/cGoodCard.js

@@ -0,0 +1,46 @@
+import { Card, Image, Space } 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 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} src={backendURL + '/' + images[0].url} /></Link>}
+      <strong>{price} грн.</strong>
+      <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> */}
+
+const CGoodCard = connect(null, {onAdd: actionCartAdd})(GoodCard)
+
+export default CGoodCard;

+ 34 - 0
project/my-project/src/components/category.js

@@ -0,0 +1,34 @@
+import { store } from "../store";
+import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
+import { actionRootCats } from "../action";
+import {Provider, connect} from 'react-redux';
+import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
+import { useEffect } from "react";
+
+const { SubMenu } = Menu;
+
+const CategoryListItem = ({_id, name}) =>
+  // <li> 
+    
+      <Menu.Item><Link to={`/category/${_id}`}>{name} </Link></Menu.Item>
+    
+  {/* </li> */}
+
+const CategoryList = ({cats}) =>{console.log('cats', cats)
+  // useEffect(() => {
+  //   getCategoryList()
+  // }, [])
+
+  return (
+    <Menu>
+      {/* <Menu.Item>Категории товаров</Menu.Item> */}
+      {cats.map((item) => <CategoryListItem key={item._id} {...item} />)}
+    </Menu>
+)
+}
+
+const mapStateToProps = state => ({cats:state.promise.rootCats?.payload || []})
+
+const CCategoryList = connect(mapStateToProps)(CategoryList)
+
+export default CCategoryList;

+ 23 - 0
project/my-project/src/components/goodCardCharacteristic.js

@@ -0,0 +1,23 @@
+import { Card, Image } 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';
+
+const Good = ({good: {name, images, description, price, _id}, onAdd}) => { console.log(name)
+  return (
+    <Card title={name} style={{ width: 350 }} hoverable>
+    {images && images[0] && images[0].url && <Image width={300} src={backendURL + '/' + images[0].url} />}
+    <p>{description}</p>
+    <p>{price} грн</p>
+    <Button onClick={() => onAdd({_id, name, price, images})}>Купить</Button>
+  </Card>
+  )
+}
+
+const mapStateToProps = state => ({good: state.promise.goodById?.payload || {}})
+
+const GoodCardCharacteristic = connect(mapStateToProps, {onAdd: actionCartAdd})(Good);
+
+export default GoodCardCharacteristic;

+ 120 - 0
project/my-project/src/components/header.js

@@ -0,0 +1,120 @@
+import { Layout, Menu, Breadcrumb, Row, Col, Avatar, Badge, Button  } from 'antd';
+import { useEffect, useState } from 'react';
+import {Router, Route, Link, Redirect, Switch} 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 { actionMyOrders } from '../action';
+
+const { Header, Content, Footer, Sider } = 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
+  ],
+});
+
+const HeaderComponent = ({login, cart, getOrders}) => { 
+  
+  console.log('cartHeader', cart)
+  const [nike, setNike] = useState('');
+  const [countBasket, setCountBasket] = useState(0); console.log('CountBasket',countBasket );
+
+  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']); 
+        
+        
+      }
+      
+      if(!login) { console.log('logauthhhhhh')
+        setNike(false);
+       
+      }
+
+      const arrCount = Object.values(cart);
+      const count = arrCount.reduce((accum, item) => accum + item.count, 0 );
+      setCountBasket(count);
+      
+      console.log('arrCount', arrCount)  ;
+      console.log('CountBasket',countBasket )
+    } 
+  , [login, cart])
+
+    
+
+  return(
+    <Header className="header">
+    {/* <div className="logo" /> */}
+    
+      <Row>
+        <Col span={17}>
+        </Col>
+
+       { nike? 
+        < >
+          <Col span={1}>
+          <div className="icons-list">
+           <Avatar size={40}>{nike}</Avatar> 
+          </div>
+          </Col>
+          <Col span={1}></Col>
+          <Col span={1}>
+          <ButtonExSite/>
+          </Col>
+        </>:
+        <>
+          <Col span={2}>
+          <Button>
+            <Link to = {`/login`}> Вход</Link>
+          </Button>
+           
+          </Col>
+          <Col span={2}>
+            <Button>
+              <Link to = {`/registration`}>Регистрация</Link>
+            </Button>
+            
+          </Col>
+        </>
+        }
+
+        <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>  
+        </Link>
+        </Col>
+
+        <Col span={1}> <Link to='/listOrders'>
+          <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,
+}
+
+const HeaderSite = connect(mapStateToProps, mapDispatchToProps)(HeaderComponent)
+
+export default HeaderSite;

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

@@ -0,0 +1,13 @@
+export { default as CCategoryList } from './category';
+export { default as SignIn } from './signIn';
+export { default as CCategory } from './cCategory';
+export { default as CGoodCard } from './cGoodCard';
+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 Page404 } from './pege404';
+export { default as InputUpLoadFile } from './inputUploadFile';
+
+

+ 27 - 0
project/my-project/src/components/inputUploadFile.js

@@ -0,0 +1,27 @@
+import React, {useCallback} from 'react';
+import {useDropzone} from 'react-dropzone';
+
+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})
+
+  return (
+    <div {...getRootProps()}>
+      <input {...getInputProps()} />
+      {
+        isDragActive ?
+          <p>Drop the files here ...</p> :
+          <p>Выбрать файл</p>
+      }
+    </div>
+  )
+}
+
+export default InputUpLoadFile;

+ 60 - 0
project/my-project/src/components/listOrders.js

@@ -0,0 +1,60 @@
+import { connect } from "react-redux";
+import { Card, Row, Col } from 'antd';
+import { actionMyOrders } from "../action";
+import { useEffect, useState } from "react";
+
+const Orders = ({allOrders}) => {
+  const [ord, setOrd] = useState(allOrders); 
+
+  useEffect( () => {
+
+    setOrd(allOrders);
+
+  }, [allOrders])
+
+  return (
+    <Card title="История заказов">
+
+    { ord.length ? 
+        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>Вы не совершали покупки</Card>
+    
+    }
+
+   
+  </Card>
+  )
+}
+
+const mapStateToProps = (state) => (
+  {
+    allOrders: state.promise.myOrders?.payload || [],
+  }
+)
+
+
+
+const ListOrders = connect(mapStateToProps)(Orders);
+
+export default ListOrders;

+ 4 - 0
project/my-project/src/components/pege404.js

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

+ 101 - 0
project/my-project/src/components/registerIn.js

@@ -0,0 +1,101 @@
+import { Form, Input, Button, Checkbox, 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 { useEffect, useState } from 'react';
+
+const Register = ({getState, auth}) => { console.log('auth', auth); 
+
+  const  [regMessage, setRegMessage] = useState(false);
+  
+  let history = useHistory();
+
+  
+
+  useEffect(
+    () => {
+      
+      if((auth).length !== 0) { 
+        history.push('/')
+      } 
+    } , [auth]) 
+
+
+  const onFinish = (values) => {
+    console.log('Success:', values);
+    getState(values.username, values.password);
+  
+    setRegMessage(!regMessage);
+    
+
+
+   };
+
+  const onFinishFailed = (errorInfo) => {
+    console.log('Failed:', errorInfo);
+  };
+
+  return (
+
+    <Row> 
+      <Col span ={7}>
+
+     </Col>
+      <Form
+      name="basic"
+      labelCol={{ span: 8 }}
+      wrapperCol={{ span: 16 }}
+      initialValues={{ remember: true }}
+      onFinish={onFinish}
+      onFinishFailed={onFinishFailed}
+      autoComplete="off"
+       >
+      <Form.Item
+        label="Имя"
+        name="username"
+        rules={[{ required: true, message: 'Please input your username!' }]}
+      >
+        <Input />
+      </Form.Item>
+
+      <Form.Item
+        label="Пароль"
+        name="password"
+        rules={[{ required: true, message: 'Please input your password!' }]}
+      >
+        <Input.Password />
+      </Form.Item>
+
+      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
+          <Button type="primary" htmlType="submit">
+            Войти
+          </Button>
+        </Form.Item>
+
+        { 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 || '',
+ 
+})
+
+const RegisterIn = connect(mapStateToProps, {getState: actionFullRegister})(Register)
+
+export default RegisterIn;

+ 101 - 0
project/my-project/src/components/signIn.js

@@ -0,0 +1,101 @@
+import { Form, Input, Button, Checkbox, 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 { useEffect, useState } from 'react';
+
+const Sign = ({getState, auth}) => { console.log('auth', auth); 
+
+  const  [logMessage, setLogMessage] = useState(false);
+  
+  let history = useHistory();
+
+  
+
+  useEffect(
+    () => {
+      
+      if((auth).length !== 0) { 
+        history.push('/')
+      } 
+    } , [auth]) 
+
+
+  const onFinish = (values) => {
+    console.log('Success:', values);
+    getState(values.username, values.password);
+  
+    setLogMessage(!logMessage);
+    
+
+
+   };
+
+  const onFinishFailed = (errorInfo) => {
+    console.log('Failed:', errorInfo);
+  };
+
+  return (
+
+    <Row> 
+      <Col span ={7}>
+
+     </Col>
+      <Form
+      name="basic"
+      labelCol={{ span: 8 }}
+      wrapperCol={{ span: 16 }}
+      initialValues={{ remember: true }}
+      onFinish={onFinish}
+      onFinishFailed={onFinishFailed}
+      autoComplete="off"
+       >
+      <Form.Item
+        label="Имя"
+        name="username"
+        rules={[{ required: true, message: 'Please input your username!' }]}
+      >
+        <Input />
+      </Form.Item>
+
+      <Form.Item
+        label="Пароль"
+        name="password"
+        rules={[{ required: true, message: 'Please input your password!' }]}
+      >
+        <Input.Password />
+      </Form.Item>
+
+      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
+          <Button type="primary" htmlType="submit">
+            Войти
+          </Button>
+        </Form.Item>
+
+        { logMessage && (auth).length == 0 && <Form.Item wrapperCol={{ offset: 8, span: 16 }}> {console.log('tttt')}
+        <Alert
+          message="Ошибка"
+          description="Неправильно введен логин или пароль"
+          type="error"
+      
+          
+         />
+        </Form.Item>}
+
+      </Form>
+    </Row>
+  )
+};
+
+const mapStateToProps = state => ({
+  auth: state.auth?.token || '',
+ 
+})
+
+const SignIn = connect(mapStateToProps, {getState:actionFullLogin})(Sign)
+
+export default SignIn;

+ 14 - 0
project/my-project/src/index.css

@@ -0,0 +1,14 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}
+

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

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.css';
+import App from './App';
+
+
+ReactDOM.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+  document.getElementById('root')
+);
+
+// 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
+

File diff suppressed because it is too large
+ 1 - 0
project/my-project/src/logo.svg


+ 17 - 0
project/my-project/src/pages/cpageCategory.js

@@ -0,0 +1,17 @@
+import { useEffect } from "react";
+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); 
+  useEffect(() => { 
+      getData(_id)
+  },[_id])
+  return (
+    <CCategory />
+  )
+}
+
+const CPageCategory = connect(null, {getData: actionCatById})(PageCategory)
+
+export default CPageCategory;

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

@@ -0,0 +1,3 @@
+export { default as PageBasket } from './pageBasket';
+export { default as CreatePageGood } from './pageGood';
+export { default as CPageCategory } from './cpageCategory';

+ 80 - 0
project/my-project/src/pages/mainPage.js

@@ -0,0 +1,80 @@
+import { Layout, Menu, Breadcrumb, Row, Col, Avatar  } from 'antd';
+import { UserOutlined, LaptopOutlined, NotificationOutlined, 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 {SignIn, ListOrders, Page404} from '../components';
+import { CCategoryList } 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 } from '../route'
+
+
+const { SubMenu } = Menu;
+const { Header, Content, Footer, Sider } = Layout;
+const IconFont = createFromIconfontCN({
+  scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
+});
+
+function MainPage () {
+
+  return (
+    <>
+     <Layout>
+      <HeaderSite/>
+    <Content style={{ padding: '0 50px' }}>
+      <Layout className="site-layout-background" style={{ padding: '24px 0' }}>
+        <Sider className="site-layout-background" width={200}>
+          {/* <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> */}
+        </Sider>
+        <Content style={{ padding: '0 24px', minHeight: 280 }}>Content
+          <UseRoute/>
+
+
+        </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> 
+    </>
+  )
+  
+}
+
+export default MainPage;

+ 115 - 0
project/my-project/src/pages/pageBasket.js

@@ -0,0 +1,115 @@
+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 { connect } from 'react-redux';
+import {PlusSquareTwoTone, MinusSquareTwoTone, CloseSquareTwoTone, CheckSquareTwoTone, RestTwoTone} from '@ant-design/icons';
+import { useEffect, useState } from 'react';
+
+
+
+
+const backendURL = "http://shop-roles.asmer.fs.a-level.com.ua" ;
+
+const CartBasket = ({good, good:{name, price, images}, count, clickButton:{cartMin, cartChange, cartRemove, cartAdd}}) => {
+  
+  return (
+   
+
+    <Card
+      style={{ marginTop: 16 }}
+      type="inner"
+      title={`${name}`}
+    >
+    <Space>
+      <Row>
+        {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>
+        </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 [messageForOrder, setmessageForOrder] = useState(false);
+
+  useEffect (() => {
+
+    if((auth).length !== 0) { 
+      setmessageForOrder(!messageForOrder);
+    } 
+  }
+  ,[auth]) 
+  
+  const oderPlusclearOrder = () => { 
+    order();
+
+    if (Object.values(orderPayload).length !== 0) { console.log('clearOrder')
+      cartClear();
+    }
+  }
+
+  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>
+   
+  )
+
+}
+
+const mapStateToProps = (state) => ({
+  cart: state?.cart,
+  orderPayload: state.promise.order?.payload || {},
+  auth: state.auth?.token || '',
+});
+const mapDispatchToProps = {
+  cartAdd: actionCartAdd, 
+  cartRemove: actionCartRemove, 
+  cartChange: actionCartChange, 
+  cartClear: actionCartClear, 
+  cartMin: actionCartMin, 
+  order: actionOrder,
+}
+
+
+
+const PageBasket = connect(mapStateToProps, mapDispatchToProps)(GoodsInBasket);
+
+export default PageBasket;

+ 18 - 0
project/my-project/src/pages/pageGood.js

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

+ 29 - 0
project/my-project/src/reducer/authReducer.js

@@ -0,0 +1,29 @@
+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
+}
+
+export default authReducer;

+ 61 - 0
project/my-project/src/reducer/cartReducer.js

@@ -0,0 +1,61 @@
+function cartReducer(state={}, {type, good = {}, count=1}){
+  //{
+  //  _id1: {good, count}
+  //  _id2: {good, count}
+  //}
+  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 {
+          
+        };
+      },
+  }
+
+  if (type in types)
+      return types[type]()
+
+
+  return state
+}
+
+export default cartReducer;

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

@@ -0,0 +1,3 @@
+export { default as authReducer } from './authReducer';
+export { default as promiseReducer } from './promiseReducer';
+export {default as cartReducer} from './cartReducer';

+ 11 - 0
project/my-project/src/reducer/promiseReducer.js

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

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

@@ -0,0 +1 @@
+export { default as UseRoute } from './useRoute';

+ 24 - 0
project/my-project/src/route/useRoute.js

@@ -0,0 +1,24 @@
+import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
+import { SignIn, RegisterIn, ListOrders } from '../components';
+import { PageBasket, CPageCategory, CreatePageGood}  from '../pages';
+
+
+
+
+const UseRoute = () => {
+  return (
+    <Switch>
+      {/* <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}/> */}
+    </Switch>
+  )
+}
+
+export default UseRoute;

+ 5 - 0
project/my-project/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';

+ 14 - 0
project/my-project/src/store/index.js

@@ -0,0 +1,14 @@
+
+import thunk from 'redux-thunk';
+import { createStore, combineReducers, applyMiddleware } from 'redux';
+import { authReducer, promiseReducer, cartReducer } from '../reducer';
+import { actionRootCats } from "../action";
+
+export const store = createStore(combineReducers({
+  promise: promiseReducer, 
+  auth: authReducer, 
+  cart: cartReducer
+}), applyMiddleware(thunk));
+ 
+store.subscribe(() => console.log(store.getState()));
+store.dispatch(actionRootCats());

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

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

+ 11 - 0
project/my-project/src/utils/jwtDecode.js

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