Browse Source

in progress 1

Graf15 2 years ago
parent
commit
5eb69d1f7e
37 changed files with 32758 additions and 0 deletions
  1. 23 0
      my-diplom/.gitignore
  2. 70 0
      my-diplom/README.md
  3. 30852 0
      my-diplom/package-lock.json
  4. 49 0
      my-diplom/package.json
  5. BIN
      my-diplom/public/favicon.ico
  6. 44 0
      my-diplom/public/index.html
  7. BIN
      my-diplom/public/logo192.png
  8. BIN
      my-diplom/public/logo512.png
  9. 25 0
      my-diplom/public/manifest.json
  10. 3 0
      my-diplom/public/robots.txt
  11. 67 0
      my-diplom/src/App.css
  12. 56 0
      my-diplom/src/App.js
  13. 119 0
      my-diplom/src/components/Basket.jsx
  14. 60 0
      my-diplom/src/components/CardProduct.jsx
  15. 52 0
      my-diplom/src/components/CarouselProductOnePage.js
  16. 73 0
      my-diplom/src/components/CategoryMenu.jsx
  17. 33 0
      my-diplom/src/components/CategoryOneBreadcrumbs.jsx
  18. 28 0
      my-diplom/src/components/CategoryOneMenu copy.jsx
  19. 190 0
      my-diplom/src/components/CategoryOneMenu.jsx
  20. 24 0
      my-diplom/src/components/LayoutPublic.jsx
  21. 14 0
      my-diplom/src/components/PublicFooter.jsx
  22. 48 0
      my-diplom/src/components/PublicHeader.jsx
  23. 21 0
      my-diplom/src/components/PublicHeaderSearch.jsx
  24. 237 0
      my-diplom/src/components/actions/actions.jsx
  25. 39 0
      my-diplom/src/components/public-pages/CategoryOnePage.jsx
  26. 28 0
      my-diplom/src/components/public-pages/HomePage.jsx
  27. 161 0
      my-diplom/src/components/public-pages/LoginPage.jsx
  28. 33 0
      my-diplom/src/components/public-pages/ProductOnePage.jsx
  29. 26 0
      my-diplom/src/components/public-pages/ProfilePage.jsx
  30. 13 0
      my-diplom/src/index.css
  31. 40 0
      my-diplom/src/index.js
  32. 13 0
      my-diplom/src/reportWebVitals.js
  33. 16 0
      my-diplom/src/store/authSlice.js
  34. 51 0
      my-diplom/src/store/cartSlice.js
  35. 96 0
      my-diplom/src/store/categoriesApi copy.js
  36. 140 0
      my-diplom/src/store/categoriesApi.js
  37. 14 0
      my-diplom/src/store/index.js

+ 23 - 0
my-diplom/.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
my-diplom/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
+ 30852 - 0
my-diplom/package-lock.json


+ 49 - 0
my-diplom/package.json

@@ -0,0 +1,49 @@
+{
+  "name": "my-diplom",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@emotion/react": "^11.10.6",
+    "@emotion/styled": "^11.10.6",
+    "@fontsource/roboto": "^4.5.8",
+    "@mui/icons-material": "^5.11.11",
+    "@mui/material": "^5.11.11",
+    "@reduxjs/toolkit": "^1.9.3",
+    "@rtk-query/graphql-request-base-query": "^2.2.0",
+    "@testing-library/jest-dom": "^5.16.5",
+    "@testing-library/react": "^13.4.0",
+    "@testing-library/user-event": "^13.5.0",
+    "graphql-request": "^5.2.0",
+    "react": "^18.2.0",
+    "react-dom": "^18.2.0",
+    "react-material-ui-carousel": "^3.4.2",
+    "react-redux": "^8.0.5",
+    "react-router-dom": "^6.8.1",
+    "react-scripts": "5.0.1",
+    "web-vitals": "^2.1.4"
+  },
+  "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"
+    ]
+  }
+}

BIN
my-diplom/public/favicon.ico


+ 44 - 0
my-diplom/public/index.html

@@ -0,0 +1,44 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
+    <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>

BIN
my-diplom/public/logo192.png


BIN
my-diplom/public/logo512.png


+ 25 - 0
my-diplom/public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

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

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

+ 67 - 0
my-diplom/src/App.css

@@ -0,0 +1,67 @@
+*,
+*:before,
+*:after {
+  box-sizing: border-box;
+}
+
+body {
+    margin: 0;
+    padding: 10px;
+
+}
+
+ul {
+  padding: 5px;
+  margin: 0px;
+}
+
+.HomePage {
+display: flex;
+flex-wrap: wrap;
+}
+
+.blockGrey {
+  padding: 30px;
+  background-color: darkgrey;
+  margin: 5px 0;
+}
+
+.categoryMenu {
+  padding: 10px;
+  background-color: orange;
+  height: 100%;
+}
+
+.categoryMenu a {
+  display: block;
+  padding: 5px;
+}
+
+.HomePageMain{
+  padding: 5px;
+  width: 75%;
+}
+
+.Slider {
+  padding: 50px;
+  background-color: aquamarine;
+}
+
+.HomePageMainProducts{
+  display: flex;
+  flex-wrap: wrap;
+  justify-content: center;
+}
+
+.HomePageMainProducts > * {
+  width: calc(25% - 10px);
+ background-color: brown;
+ margin: 5px;
+ padding: 100px 5px;
+ text-align: center;
+}
+
+.CategoryOneBreadcrumbs li {
+  display: inline-block;
+  padding: 3px;
+}

+ 56 - 0
my-diplom/src/App.js

@@ -0,0 +1,56 @@
+import { Route, Routes, Link } from "react-router-dom";
+import LayoutPublic from "./components/LayoutPublic";
+import './App.css';
+import HomePage from "./components/public-pages/HomePage";
+import CategoryOnePage from "./components/public-pages/CategoryOnePage";
+import { CssBaseline } from "@mui/material";
+import ProductOnePage from "./components/public-pages/ProductOnePage";
+import LoginPage from "./components/public-pages/LoginPage"
+import ProfilePage from "./components/public-pages/ProfilePage";
+
+
+
+
+function App() {
+  return (
+    <>
+    <CssBaseline />
+      <Routes>
+        <Route path='*' element={<LayoutPublic />}>
+          <Route index element={<HomePage/>}/>
+          <Route path='*' element={<p>Страница не найдена</p>}/>
+          <Route path="about" element={<p>о магазине</p>}/>
+          <Route path="category/:catId/*" element={<CategoryOnePage/>}/>
+          <Route path="product/:prodId/*" element={<ProductOnePage/>}/>
+          <Route path="login" element={<LoginPage/>}/>
+          <Route path="profile" element={<ProfilePage/>}/>
+        </Route>
+        <Route path='admin/*' element={<p>дашборд</p>}>
+
+        </Route>
+      </Routes>
+    </>
+  );
+}
+
+
+export default App;
+
+
+{/* <>
+<Link to={"/"}>Home</Link>
+<Link to={"admin"}>Admin</Link>
+<Link to={"about"}>About</Link>
+
+<Routes>
+  <Route path='/'>
+    <Route index element={<p>домашняя станица</p>} />
+    <Route path="*" element={<LayoutPublic />}>
+      <Route path="about" element={<p>о магазине</p>}/>
+    </Route>
+    <Route path='admin'>
+      <Route index element={<p>дашборд</p>} />
+    </Route>
+  </Route>
+</Routes>
+</> */}

+ 119 - 0
my-diplom/src/components/Basket.jsx

@@ -0,0 +1,119 @@
+import { ShoppingBasket } from "@mui/icons-material"
+import { Box, Button, Divider, Drawer, InputAdornment, List, ListItem, ListItemIcon, ListItemText, TextField } from "@mui/material"
+import { useDispatch, useSelector } from "react-redux"
+import { CartAdd, CartClear, CartDel, CartIncOne, CartSet } from "../store/cartSlice"
+
+const Basket = (props) => {
+    const {
+        cartOpen,
+        closeCart = Function.prototype,
+    } = props
+
+    const cartState = Object.values(useSelector(state => state.cart))
+
+    const dispatch = useDispatch()
+
+    const productsRender = ({product, count}) => {
+        
+        return (
+        <ListItem key={product._id} sx={{display:"block"}}>
+            <Box sx={{ margin: '10px 5px' }}>
+                <div style={{ 
+                    height: '50px',
+                    width: '50px',
+                    backgroundSize: 'contain',
+                            backgroundRepeat: 'no-repeat',
+                            backgroundPosition: 'center',
+      backgroundImage: `url(${product?.images ? `http://shop-roles.node.ed.asmer.org.ua/${product.images[0].url}` : "https://archive.org/download/no-photo-available/no-photo-available.png" })` 
+    }}></div>
+                <div>{product.name}</div>
+            </Box>
+            <Box>
+                <Button variant="outlined" size="small" onClick={()=> dispatch(CartAdd({product}))} sx={{height:"40px", margin: "3px"}}>+</Button>
+                <TextField
+                    sx={{height:"40px", margin: "3px"}}
+                    size="small"
+                    type="number"
+                    value={count}
+                    InputProps={{
+                        endAdornment: <InputAdornment position="start">шт</InputAdornment>,
+                        inputProps: { min: "1", step: "1" },
+                    }}
+                    onChange={(e) => dispatch(CartSet({product, count: e.target.value}))}
+                >
+
+                </TextField>
+                <Button
+                variant="outlined"
+                size="small"
+                onClick={() => dispatch(CartIncOne({product}))}
+                disabled = {count <=1 ? true: false}
+                sx={{height:"40px", margin: "3px"}}
+                >-</Button>
+                <Button variant="outlined" size="small" onClick={() => dispatch(CartDel({product}))} sx={{height:"40px", margin: "3px"}}>удалить</Button>
+            </Box>
+            <Divider />
+        </ListItem>
+    )
+                    }
+
+    {/* cartState.map((product) => (
+                        <div key={Math.random()}>
+                            <Box sx={{ margin: '10px 5px' }}>
+                                <div>_id: {product._id}</div>
+                                <div>name: {product.name}</div>
+                                <div>количество: {product.count}</div>
+                            </Box>
+                            <Box>
+                                <Button variant="outlined" size="small" onClick={() => dispatch(CartAdd(product))}>+</Button>
+                                <TextField
+                                    size="small"
+                                    type="number"
+                                    value={product.count}
+                                    InputProps={{
+                                        endAdornment: <InputAdornment position="start">шт</InputAdornment>,
+                                    }}
+                                    onChange={(e) => dispatch(CartSet(
+                                        (() => {
+                                            let result = { ...product, count: e.target.value }
+                                            return result
+                                        })
+                                            ()))}
+                                >
+
+                                </TextField>
+                                <Button variant="outlined" size="small" onClick={() => dispatch(CartIncOne(product))}>-</Button>
+                                <Button variant="outlined" size="small" onClick={() => dispatch(CartDel(product))}>удалить</Button>
+                            </Box>
+                            <Divider />
+                        </div>
+                    )
+                    ) */}
+
+    return (
+        <Drawer
+            anchor="right"
+            open={cartOpen}
+            onClose={closeCart}
+        >
+            <List sx={{ width: "400px" }}>
+                <ListItem>
+                    <ListItemIcon>
+                        <ShoppingBasket />
+                    </ListItemIcon>
+                    <ListItemText primary="Корзина" />
+                    <Button variant="outlined" onClick={() => dispatch(CartClear())}>Очитить корзину</Button>
+                </ListItem>
+            </List>
+            <Divider />
+
+            <List>
+            { cartState.length ? 
+                cartState.map(productsRender) : <ListItem>Ваша корзина пока пуста! </ListItem>
+            }
+            </List>
+        </Drawer>
+    )
+}
+
+export default Basket

+ 60 - 0
my-diplom/src/components/CardProduct.jsx

@@ -0,0 +1,60 @@
+import { ShoppingBasketSharp } from "@mui/icons-material"
+import { Button, Card, CardActionArea, CardActions, CardContent, CardMedia, Grid, Icon, IconButton, Typography } from "@mui/material"
+import { useDispatch } from "react-redux"
+import { Link } from "react-router-dom"
+import { CartAdd } from "../store/cartSlice"
+
+const CardProduct = ({product}) => {
+    const dispatch = useDispatch()
+    
+    return(
+        <Grid item xs={12} md={4}>
+            <Card sx={{ height: "100%", display: "flex", flexDirection: "column", justifyContent: 'space-between' }}>
+                <CardActionArea
+                 sx={{flex: "1", display: 'flex', flexDirection: "column"}}
+                 component={Link} to={`/product/${product._id}/${product.name}`}
+                 >
+                    <CardMedia
+                        sx={{ 
+                            height: '200px',
+                            width: '100%',
+                            backgroundSize: 'contain',
+                            backgroundRepeat: 'no-repeat',
+                            backgroundPosition: 'center',
+                            padding: "10px",
+                            backgroundOrigin: 'content-box'
+                            }}
+                        image={product?.images ? `http://shop-roles.node.ed.asmer.org.ua/${product.images[0].url}` : "https://archive.org/download/no-photo-available/no-photo-available.png" }
+                        alt={product?.name}
+                    />
+
+                    <CardContent sx={{flex: '1', display: "flex", flexDirection: "column", justifyContent: 'space-between' }}>
+                        <Typography
+                            variant="h6"
+                            component="h3"
+                            align="center"
+                            mb={2}
+                            >
+                            {product?.name} 
+                        </Typography>
+                        <Typography variant="body1" align="center">
+                            {product?.price + ' грн'}
+                        </Typography>
+                    </CardContent>
+                </CardActionArea>
+                <CardActions>
+                    <Button
+                        size="small"
+                        variant="contained"
+                        fullWidth
+                        onClick={ ()=> dispatch(CartAdd({product, count: 1}))}
+                    >
+                        <ShoppingBasketSharp sx={{ mr: 1 }} />В корзину
+                    </Button>
+                </CardActions>
+
+            </Card>
+        </Grid>
+    )}
+
+export default CardProduct

+ 52 - 0
my-diplom/src/components/CarouselProductOnePage.js

@@ -0,0 +1,52 @@
+import Carousel from 'react-material-ui-carousel'
+import { Paper, Button, CardMedia } from '@mui/material'
+import { Image } from '@mui/icons-material'
+
+export function CarouselProductOnePage({product})
+{
+    const items = product?.images
+
+    // [
+    //     {
+    //         name: "Random Name #1",
+    //         description: "Probably the most random thing you have ever seen!"
+    //     },
+    //     {
+    //         name: "Random Name #2",
+    //         description: "Hello World!"
+    //     }
+    // ]
+
+    return (
+        <Carousel
+         height='400px'
+        navButtonsAlwaysVisible={true}
+         >
+            {
+                items && items.map( (item, i) => <Item key={i} item={item} /> )
+            }
+        </Carousel>
+    )
+}
+
+function Item(props)
+{
+
+    return (
+        <Paper>
+        <CardMedia
+                        sx={{ 
+                            height: '400px',
+                            width: '100%',
+                            backgroundSize: 'contain',
+                            backgroundRepeat: 'no-repeat',
+                            backgroundPosition: 'center',
+                            padding: "10px",
+                            backgroundOrigin: 'content-box'
+                            }}
+                        image={props.item ? `http://shop-roles.node.ed.asmer.org.ua/${props.item.url}` : "https://archive.org/download/no-photo-available/no-photo-available.png" }
+                        // alt={product?.name}
+                    />
+         </Paper>
+    )
+}

+ 73 - 0
my-diplom/src/components/CategoryMenu.jsx

@@ -0,0 +1,73 @@
+import { List, ListItemButton, ListItemText} from "@mui/material"
+import { useEffect, useState } from "react"
+import { Link } from "react-router-dom"
+import { gqlRootCats } from "./actions/actions"
+import ListItem from '@mui/material/ListItem';
+import { useGetCategoriesQuery } from '../store/categoriesApi'
+
+// const CategoryMenu = () => {
+//     const [categories, setCategories] = useState(null)
+//     const {data: payload = null/*{data: {CategoryFind: payload = []}}*/} = useGetCategoriesQuery()
+//     console.log(payload)
+//     if(payload) setCategories(Object.values(payload.data)[0])
+
+//     // useEffect(
+//     //     () => {
+//     //         gqlRootCats().then(setCategories)
+//     //     }
+//     //     , []
+//     // )
+//     let categoryRender = (category) => {
+//         if (category) {
+//             return (
+//                 <ListItem key={category._id} disablePadding>
+//                     <ListItemButton component={Link} to={`/category/${category._id}/${category.name}`}>
+//                         <ListItemText primary={category.name} />
+//                     </ListItemButton>
+//                 </ListItem>
+//             )
+//         }
+//         else return ""
+//     }
+
+//     return(
+//         <>
+//         <nav className="categoryMenu">
+//         <List>
+//             {categories ? categories.map(categoryRender) : ""}
+//         </List>
+//         </nav>
+//         </>
+//     )
+// }
+
+const CategoryMenu = () => {
+    const {data: payload = null} = useGetCategoriesQuery()
+    const categories = payload ? Object.values(payload)[0] : null
+
+
+    let categoryRender = (category) => {
+        if (category) {
+            return (
+                <ListItem key={category._id} disablePadding>
+                    <ListItemButton component={Link} to={`/category/${category._id}/${category.name}`}>
+                        <ListItemText primary={category.name} />
+                    </ListItemButton>
+                </ListItem>
+            )
+        }
+        else return ""
+    }
+
+    return(
+        <>
+        <nav className="categoryMenu">
+        <List>
+            {categories ? categories.map(categoryRender) : ""}
+        </List>
+        </nav>
+        </>
+    )
+}
+
+export default CategoryMenu

+ 33 - 0
my-diplom/src/components/CategoryOneBreadcrumbs.jsx

@@ -0,0 +1,33 @@
+import { Breadcrumbs, Grid, Typography } from "@mui/material"
+import { useEffect } from "react"
+import { Link } from "react-router-dom"
+
+
+const CategoryOneBreadcrumbs = ({parentCategory, thisCategory}) => {
+    let parentCategoryLink = null
+   
+    if (parentCategory) { 
+        parentCategoryLink = `/category/${parentCategory._id}/${parentCategory.name}`
+    }
+ 
+    return (
+      <Grid item xs={12}>
+        <Breadcrumbs aria-label="breadcrumb">
+  <Link underline="hover" color="inherit" to="/">
+    Home
+  </Link>
+  {parentCategory && <Link
+    underline="hover"
+    color="inherit"
+    to={parentCategoryLink}
+  >
+    {parentCategory.name}
+  </Link>}
+  <Typography color="text.primary">{thisCategory?.name}</Typography>
+</Breadcrumbs>
+</Grid>
+    )
+
+}
+
+export default CategoryOneBreadcrumbs

+ 28 - 0
my-diplom/src/components/CategoryOneMenu copy.jsx

@@ -0,0 +1,28 @@
+import { Button } from "@mui/material"
+import { useEffect, useState } from "react"
+import { Link, useParams } from "react-router-dom"
+import { gqlCategoryGoodsAndSubCategoryGoods } from "./actions/actions"
+
+const CategoryOneMenu = ({category}) => {
+
+
+    let categoryRender = (category) => {
+        if (category) {
+            return <Link key={category._id} to={`/category/${category._id}/${category.name}`}>{category?.name}</Link>
+        }
+        else return ""
+    }
+    
+    return(
+        <>
+        <div className="categoryMenu">
+        <ul>
+            { category ? category.map(categoryRender) : "" }
+        </ul>
+        <Button variant="contained">Hello!</Button>
+        </div>
+        </>
+    )
+}
+
+export default CategoryOneMenu

+ 190 - 0
my-diplom/src/components/CategoryOneMenu.jsx

@@ -0,0 +1,190 @@
+import { Button } from "@mui/material"
+import { useEffect, useState } from "react"
+import { Link, useParams } from "react-router-dom"
+import { gqlCategoryGoodsAndSubCategoryGoods } from "./actions/actions"
+
+import AppBar from '@mui/material/AppBar';
+import Box from '@mui/material/Box';
+import CssBaseline from '@mui/material/CssBaseline';
+import Divider from '@mui/material/Divider';
+import Drawer from '@mui/material/Drawer';
+import IconButton from '@mui/material/IconButton';
+import InboxIcon from '@mui/icons-material/MoveToInbox';
+import List from '@mui/material/List';
+import ListItem from '@mui/material/ListItem';
+import ListItemButton from '@mui/material/ListItemButton';
+import ListItemIcon from '@mui/material/ListItemIcon';
+import ListItemText from '@mui/material/ListItemText';
+import MailIcon from '@mui/icons-material/Mail';
+import MenuIcon from '@mui/icons-material/Menu';
+import Toolbar from '@mui/material/Toolbar';
+import Typography from '@mui/material/Typography';
+
+const CategoryOneMenu = ({category}) => {
+
+    const drawerWidth = 240;
+
+// function ResponsiveDrawer(props) {
+//   const { window } = props;
+//   const [mobileOpen, setMobileOpen] = useState(false);
+
+//   const handleDrawerToggle = () => {
+//     setMobileOpen(!mobileOpen);
+//   };
+
+//   const drawer = (
+//     <div>
+//       <Toolbar />
+//       <Divider />
+//       <List>
+//         {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
+//           <ListItem key={text} disablePadding>
+//             <ListItemButton>
+//               <ListItemIcon>
+//                 {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
+//               </ListItemIcon>
+//               <ListItemText primary={text} />
+//             </ListItemButton>
+//           </ListItem>
+//         ))}
+//       </List>
+//       <Divider />
+//       <List>
+//         {['All mail', 'Trash', 'Spam'].map((text, index) => (
+//           <ListItem key={text} disablePadding>
+//             <ListItemButton>
+//               <ListItemIcon>
+//                 {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
+//               </ListItemIcon>
+//               <ListItemText primary={text} />
+//             </ListItemButton>
+//           </ListItem>
+//         ))}
+//       </List>
+//     </div>
+//   );
+
+//   const container = window !== undefined ? () => window().document.body : undefined;
+
+//   return (
+//     <Box sx={{ display: 'flex' }}>
+//       <CssBaseline />
+//       <AppBar
+//         position="fixed"
+//         sx={{
+//           width: { sm: `calc(100% - ${drawerWidth}px)` },
+//           ml: { sm: `${drawerWidth}px` },
+//         }}
+//       >
+//         <Toolbar>
+//           <IconButton
+//             color="inherit"
+//             aria-label="open drawer"
+//             edge="start"
+//             onClick={handleDrawerToggle}
+//             sx={{ mr: 2, display: { sm: 'none' } }}
+//           >
+//             <MenuIcon />
+//           </IconButton>
+//           <Typography variant="h6" noWrap component="div">
+//             Responsive drawer
+//           </Typography>
+//         </Toolbar>
+//       </AppBar>
+//       <Box
+//         component="nav"
+//         sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}
+//         aria-label="mailbox folders"
+//       >
+//         {/* The implementation can be swapped with js to avoid SEO duplication of links. */}
+//         <Drawer
+//           container={container}
+//           variant="temporary"
+//           open={mobileOpen}
+//           onClose={handleDrawerToggle}
+//           ModalProps={{
+//             keepMounted: true, // Better open performance on mobile.
+//           }}
+//           sx={{
+//             display: { xs: 'block', sm: 'none' },
+//             '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
+//           }}
+//         >
+//           {drawer}
+//         </Drawer>
+//         <Drawer
+//           variant="permanent"
+//           sx={{
+//             display: { xs: 'none', sm: 'block' },
+//             '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
+//           }}
+//           open
+//         >
+//           {drawer}
+//         </Drawer>
+//       </Box>
+//       {/* <Box
+//         component="main"
+//         sx={{ flexGrow: 1, p: 3, width: { sm: `calc(100% - ${drawerWidth}px)` } }}
+//       >
+//         <Toolbar />
+//         <Typography paragraph>
+//           Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
+//           tempor incididunt ut labore et dolore magna aliqua. Rhoncus dolor purus non
+//           enim praesent elementum facilisis leo vel. Risus at ultrices mi tempus
+//           imperdiet. Semper risus in hendrerit gravida rutrum quisque non tellus.
+//           Convallis convallis tellus id interdum velit laoreet id donec ultrices.
+//           Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit
+//           adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra
+//           nibh cras. Metus vulputate eu scelerisque felis imperdiet proin fermentum
+//           leo. Mauris commodo quis imperdiet massa tincidunt. Cras tincidunt lobortis
+//           feugiat vivamus at augue. At augue eget arcu dictum varius duis at
+//           consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem donec massa
+//           sapien faucibus et molestie ac.
+//         </Typography>
+//         <Typography paragraph>
+//           Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper
+//           eget nulla facilisi etiam dignissim diam. Pulvinar elementum integer enim
+//           neque volutpat ac tincidunt. Ornare suspendisse sed nisi lacus sed viverra
+//           tellus. Purus sit amet volutpat consequat mauris. Elementum eu facilisis
+//           sed odio morbi. Euismod lacinia at quis risus sed vulputate odio. Morbi
+//           tincidunt ornare massa eget egestas purus viverra accumsan in. In hendrerit
+//           gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem
+//           et tortor. Habitant morbi tristique senectus et. Adipiscing elit duis
+//           tristique sollicitudin nibh sit. Ornare aenean euismod elementum nisi quis
+//           eleifend. Commodo viverra maecenas accumsan lacus vel facilisis. Nulla
+//           posuere sollicitudin aliquam ultrices sagittis orci a.
+//         </Typography>
+//       </Box> */}
+//     </Box>
+//   );
+// }
+
+    let categoryRender = (category) => {
+
+            return (
+                <ListItem key={category._id} disablePadding>
+                    <ListItemButton component={Link} to={`/category/${category._id}/${category.name}`}>
+                        <ListItemText primary={category.name} />
+                    </ListItemButton>
+                </ListItem>
+            )
+    }
+
+    
+    return(
+        <nav aria-label="меню категорий товаров" className="categoryMenu">
+            <List >
+                {category ? category.map(categoryRender) : ""}
+            </List>
+        </nav>
+    )
+}
+
+export default CategoryOneMenu
+
+
+
+
+
+

+ 24 - 0
my-diplom/src/components/LayoutPublic.jsx

@@ -0,0 +1,24 @@
+import { Outlet } from "react-router-dom"
+import PublicHeader from "./PublicHeader"
+import PublicFooter from "./PublicFooter"
+import Basket from "./Basket"
+import { useState } from "react"
+
+const LayoutPublic = () => {
+    const [isCartOpen, setCartOpen] = useState(false)
+    return(
+        <>
+        <PublicHeader 
+            handleCart={()=> setCartOpen(true)}
+        />
+        <Outlet/>
+        <PublicFooter/>
+        <Basket 
+        cartOpen={isCartOpen}
+        closeCart={()=> setCartOpen(false)}
+        />
+        </>
+    )
+}
+
+export default LayoutPublic

+ 14 - 0
my-diplom/src/components/PublicFooter.jsx

@@ -0,0 +1,14 @@
+import { Link } from "react-router-dom"
+
+const PublicFooter = () => {
+    return(
+        <>
+        <div className="blockGrey">
+        
+
+        </div>
+        </>
+    )
+}
+
+export default PublicFooter

+ 48 - 0
my-diplom/src/components/PublicHeader.jsx

@@ -0,0 +1,48 @@
+import { ShoppingBasket, Person } from "@mui/icons-material"
+import { AppBar, IconButton, Toolbar, Link, Box, Badge, Button } from "@mui/material"
+import PublicHeaderSearch from "./PublicHeaderSearch"
+import { Link as RouterLink} from "react-router-dom"
+import { useSelector, useDispatch } from "react-redux"
+import {CartAdd} from "../store/cartSlice"
+
+
+
+const PublicHeader = ({handleCart, orderLenght}) => {
+    
+    const cartLenght = Object.keys(useSelector(state => state.cart)).length
+    const dispatch = useDispatch()
+    const myState = useSelector(state => state)
+
+    return (
+
+        <AppBar position="static" sx={{mb:2}}>
+            <Toolbar>
+                <Box sx={{ flexGrow: 1}}>
+                    <Link to="/" underline="none" variant="h5" sx={{ color: "white" }} component={RouterLink} >
+                        My Shop
+                    </Link>
+                </Box>
+
+                <PublicHeaderSearch />
+                <RouterLink to="/login" color="white">
+                <IconButton sx={{color: "white"}}>
+                    <Person />
+                </IconButton>
+                </RouterLink>
+                <IconButton
+                    color="inherit"
+                    onClick={handleCart}>
+                    <Badge
+                    color="secondary"
+                    badgeContent={cartLenght}>
+                    <ShoppingBasket />
+                    </Badge>
+                </IconButton>
+                
+            </Toolbar>
+        </AppBar>
+
+    )
+}
+
+export default PublicHeader

+ 21 - 0
my-diplom/src/components/PublicHeaderSearch.jsx

@@ -0,0 +1,21 @@
+import { Search } from "@mui/icons-material"
+import { TextField } from "@mui/material"
+
+const PublicHeaderSearch = ({value, onChange}) => {
+
+    return (
+        <TextField
+            label="search"
+            variant="standard"
+            type="search"
+            value={value}
+            onChange={onChange}
+            sx={{flexGrow: 1, color:"white"}}
+            InputLabelProps={{
+            style: { color: 'rgba(255, 255, 255, 0.3)'},
+  }}
+        />
+    )
+}
+
+export default PublicHeaderSearch

File diff suppressed because it is too large
+ 237 - 0
my-diplom/src/components/actions/actions.jsx


+ 39 - 0
my-diplom/src/components/public-pages/CategoryOnePage.jsx

@@ -0,0 +1,39 @@
+import { Link, useParams } from "react-router-dom"
+import CategoryOneMenu from "../CategoryOneMenu"
+import { useState, useEffect } from "react"
+import CategoryOneBreadcrumbs from "../CategoryOneBreadcrumbs"
+import { useGetCategoriesQuery, useGetCategoryQuery } from "../../store/categoriesApi"
+import CardProduct from "../CardProduct"
+import { Grid } from "@mui/material"
+
+
+const CategoryOnePage = () => {
+
+    let {catId} = useParams()
+
+    const {data: payload = null, isLoading} = useGetCategoryQuery(catId)
+    console.log(isLoading)
+    const category = payload ? Object.values(payload)[0] : null
+
+    const CardProductRender = (product) => (
+        <CardProduct
+            key={product._id}
+            product={product}
+        />
+    )
+
+    return (
+        isLoading ? <div> прелоадер </div> :
+        <Grid container spacing={2} alignItems="stretch" >
+            <Grid item xs={12} sm={4} md={3} align-self="stretch">
+                <CategoryOneMenu category={category?.subCategories} />
+            </Grid>
+            <Grid item xs={12} sm={8} md={9} container spacing={2} >
+                <CategoryOneBreadcrumbs parentCategory={category?.parent} thisCategory={category} />
+                {category?.goods && category.goods.map(CardProductRender)}
+            </Grid>
+        </Grid>
+    )
+}
+
+export default CategoryOnePage

+ 28 - 0
my-diplom/src/components/public-pages/HomePage.jsx

@@ -0,0 +1,28 @@
+import { Grid } from "@mui/material"
+import CardProduct from "../CardProduct"
+import CategoryMenu from "../CategoryMenu"
+
+const HomePage = () => {
+    return (
+        // <div className="HomePage">
+        
+        
+        <Grid container spacing={2} alignItems="stretch" >
+            <Grid item xs={12} sm={4} md={3} align-self= "stretch">
+                <CategoryMenu />
+            </Grid>
+            <Grid item xs={12} sm={8} md={9} container spacing={2} >
+            {/* <CardProduct />
+            <CardProduct />
+            <CardProduct />
+            <CardProduct />
+            <CardProduct /> */}
+           
+
+            </Grid>
+        </Grid>
+  
+    )
+}
+
+export default HomePage

+ 161 - 0
my-diplom/src/components/public-pages/LoginPage.jsx

@@ -0,0 +1,161 @@
+
+import Avatar from '@mui/material/Avatar';
+import Button from '@mui/material/Button';
+import CssBaseline from '@mui/material/CssBaseline';
+import TextField from '@mui/material/TextField';
+import FormControlLabel from '@mui/material/FormControlLabel';
+import Checkbox from '@mui/material/Checkbox';
+import Link from '@mui/material/Link';
+import Grid from '@mui/material/Grid';
+import Box from '@mui/material/Box';
+import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
+import Typography from '@mui/material/Typography';
+import Container from '@mui/material/Container';
+import { createTheme, ThemeProvider } from '@mui/material/styles';
+import { lightGreen } from '@mui/material/colors';
+import { categoriesApi, useGetLoginMutation } from '../../store/categoriesApi';
+import { useDispatch, useSelector } from 'react-redux';
+import { setCredentials } from '../../store/authSlice';
+import { Navigate } from 'react-router-dom';
+import { Alert, Snackbar } from '@mui/material';
+import { useState } from 'react';
+
+
+
+function jwtDecode(token) {
+    let result;
+    try {
+        let secondPartToken = token.split('.')[1];
+        result = JSON.parse(atob(secondPartToken));
+    } catch (e) {
+    }
+
+    return result;
+}
+
+const theme = createTheme();
+
+export default function SignIn() {
+
+    const [open, setOpen] = useState(false);
+
+    const handleClose = (event, reason) => {
+        if (reason === 'clickaway') {
+            return;
+        }
+        setOpen(false);
+    };
+
+    const userAuth = useSelector((state) => state.auth.user)
+    const dispatch = useDispatch()
+
+    const [loginQuery, { isLoading }] = useGetLoginMutation()
+
+    const handleSubmit = async (event) => {
+        event.preventDefault();
+        const dataForm = new FormData(event.currentTarget);
+
+        const { data } = await loginQuery({
+            login: dataForm.get('email'),
+            password: dataForm.get('password')
+        })
+        if (data) {
+            const token = data.login
+            const user = jwtDecode(token)
+
+            if (user) {
+                dispatch(setCredentials({ user, token }))
+                console.log(user.sub.id)
+                dispatch( categoriesApi.endpoints.getUserById.initiate(user.sub.id))
+            }
+            else {
+                setOpen(true)
+            }
+        }
+    };
+
+    return (
+        <>
+            {userAuth ? <Navigate replace to="/profile" /> :
+                <>
+                    <Snackbar
+                        open={open}
+                        autoHideDuration={2000}
+                        onClose={handleClose}
+                        message="Note archived"
+                    >
+                        <Alert severity="error">Вы ввели неправильный логин или пароль!</Alert>
+                    </Snackbar>
+
+                    <ThemeProvider theme={theme}>
+                        <Container component="main" maxWidth="xs">
+                            <CssBaseline />
+                            <Box
+                                sx={{
+                                    marginTop: 3,
+                                    display: 'flex',
+                                    flexDirection: 'column',
+                                    alignItems: 'center',
+                                    marginBottom: 3,
+                                }}
+                            >
+                                <Avatar sx={{ m: 1, bgcolor: lightGreen[800] }}>
+                                    <LockOutlinedIcon />
+                                </Avatar>
+                                <Typography component="h1" variant="h5">
+                                    Войти
+                                </Typography>
+                                <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
+                                    <TextField
+                                        margin="normal"
+                                        required
+                                        fullWidth
+                                        id="email"
+                                        label="Email или имя профиля"
+                                        name="email"
+                                        autoComplete="email"
+                                        autoFocus
+                                    />
+                                    <TextField
+                                        margin="normal"
+                                        required
+                                        fullWidth
+                                        name="password"
+                                        label="Пароль"
+                                        type="password"
+                                        id="password"
+                                        autoComplete="current-password"
+                                    />
+                                    <FormControlLabel
+                                        control={<Checkbox value="remember" color="primary" />}
+                                        label="Запомнить меня"
+                                    />
+                                    <Button
+                                        type="submit"
+                                        fullWidth
+                                        variant="contained"
+                                        sx={{ mt: 3, mb: 2 }}
+                                    >
+                                        Войти
+                                    </Button>
+                                    <Grid container>
+                                        <Grid item xs>
+                                            <Link href="#" variant="body2">
+                                                Забыли пароль?
+                                            </Link>
+                                        </Grid>
+                                        <Grid item>
+                                            <Link href="#" variant="body2">
+                                                {"У Вас нет аккаунта? Зарегистрироваться"}
+                                            </Link>
+                                        </Grid>
+                                    </Grid>
+                                </Box>
+                            </Box>
+                        </Container>
+                    </ThemeProvider>
+                </>
+            }
+        </>
+    );
+}

+ 33 - 0
my-diplom/src/components/public-pages/ProductOnePage.jsx

@@ -0,0 +1,33 @@
+import { Grid, Typography } from "@mui/material"
+import { useParams } from "react-router-dom"
+import { useGetProductQuery } from "../../store/categoriesApi"
+import { CarouselProductOnePage } from "../CarouselProductOnePage"
+
+
+const ProductOnePage = () => {
+    
+    const {prodId} = useParams()
+
+    const {data: payload = null} = useGetProductQuery(prodId)
+    const product = payload ? Object.values(payload)[0] : null
+    
+    return (
+        <Grid container spacing={2} alignItems="start" marginTop={3} marginBottom={3}>
+            <Grid item xs={12} sm={6} align-self="stretch" padding={2}>
+                <CarouselProductOnePage product={product} />
+            </Grid>
+            <Grid item xs={12} sm={6} align-self="stretch">
+                <Typography
+                    variant="h4"
+                    component="h1">
+                    {product?.name}
+                </Typography>
+                <Typography variant="body1">
+                    {product?.description}
+                </Typography>
+            </Grid>
+        </Grid>
+    )
+}
+
+export default ProductOnePage

+ 26 - 0
my-diplom/src/components/public-pages/ProfilePage.jsx

@@ -0,0 +1,26 @@
+import { Button, Snackbar } from "@mui/material"
+import { useState } from "react";
+import { useSelector } from "react-redux";
+import { useGetUserByIdQuery, useGetUserQuery } from "../../store/categoriesApi";
+
+const ProfilePage = () => {
+  const userAuth = useSelector((state)=> state.auth.user)
+  const _id = userAuth ?  userAuth.sub.id : null
+  const {data: payload = null} = useGetUserByIdQuery(_id)
+  const user = payload ? Object.values(payload)[0] : null
+  console.log(user)
+
+    return (
+    <div>
+    {!user ? <></> :
+    <>
+     <h2>{user.nick}</h2>
+     <div>{'login: ' + user.login}</div> 
+     </>
+     }
+    </div>
+    
+    )
+}
+
+export default ProfilePage

+ 13 - 0
my-diplom/src/index.css

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

+ 40 - 0
my-diplom/src/index.js

@@ -0,0 +1,40 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+//import reportWebVitals from './reportWebVitals';
+import {BrowserRouter} from "react-router-dom";
+import { ThemeProvider, createTheme } from '@mui/material';
+import { Provider } from 'react-redux';
+import store from './store'
+import { lightGreen } from '@mui/material/colors';
+
+const theme = createTheme({
+  palette: {
+    primary: {
+      main: lightGreen[800] 
+    },
+    secondary: {
+      main: "#FF9933"
+    }
+  }
+})
+
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <BrowserRouter>
+      <ThemeProvider theme={theme}>
+        <Provider store={store}>
+          <App />
+        </Provider>
+      </ThemeProvider>
+    </BrowserRouter>
+  </React.StrictMode>
+);
+
+// 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
+//reportWebVitals();

+ 13 - 0
my-diplom/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 16 - 0
my-diplom/src/store/authSlice.js

@@ -0,0 +1,16 @@
+import { createSlice } from "@reduxjs/toolkit";
+
+const authSlice = createSlice({
+    name: 'auth',
+    initialState: { user: null, token: null },
+    reducers: {
+      setCredentials: (state, { payload: { user, token } }) => {
+        state.user = user
+        state.token = token
+      },
+    },
+  })
+
+export const { setCredentials } = authSlice.actions
+
+export default authSlice.reducer

+ 51 - 0
my-diplom/src/store/cartSlice.js

@@ -0,0 +1,51 @@
+import { createSlice } from "@reduxjs/toolkit";
+
+const initialState = {}
+
+const cartSlice = createSlice({
+    name: 'cart',
+    initialState,
+    reducers: {
+        CartAdd(state, action) {
+            const {product, count=1} = action.payload
+            if (product._id in state) {
+                state[product._id].count += count
+            } else {
+            state[product._id] = {product, count}
+            }
+        },
+        CartIncOne(state, action) {
+            const { product, count = 1 } = action.payload
+            if (product._id in state) {
+                if ((state[product._id].count - count) <= 0) {
+                    delete state[product._id]
+                } else {
+                    state[product._id].count -= count
+                }
+            }
+        },
+        CartDel(state, action) {
+            const { product, count = 1 } = action.payload
+            if (product._id in state) {
+                delete state[product._id]
+            }
+          },
+        
+         CartSet(state, action) {
+            const { product, count = 1 } = action.payload
+            if (product._id in state && count <= 0) {
+                delete state[product._id]
+            } else {
+                state[product._id].count = count
+            }
+        },
+        CartClear() { 
+            return initialState
+        }
+    }
+
+})
+
+export const {CartAdd, CartIncOne, CartDel, CartSet, CartClear} = cartSlice.actions
+
+export default cartSlice.reducer

+ 96 - 0
my-diplom/src/store/categoriesApi copy.js

@@ -0,0 +1,96 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { gqlRootCats1, CategoryFindOne, GoodFindOne } from '../components/actions/actions'
+
+// export const categoriesApi = createApi({
+//     reducerPath: 'categoriesApi',
+//     // tagTypes: ['Categories'],
+//     baseQuery: fetchBaseQuery({ baseUrl: 'http://shop-roles.node.ed.asmer.org.ua/graphql' }),
+//     endpoints: (build) => ({
+//         getCategories: build.query({
+//             query: ()=> ({
+//                 method: 'POST',
+//                 headers: {
+//                     'Content-Type': 'application/json;charset=utf-8',
+//                     'Accept': 'application/json'
+//                 },
+//                 body: JSON.stringify({
+//                     query: `query categories{
+//                         CategoryFind(query:"[{}]"){
+//                             _id name 
+//                         }
+//                     }`
+//                 })
+//             }),
+//         //     providesTags: (result) =>
+//         // result
+//         //   ? [
+//         //       ...Object.values(result.data)[0].map(({ _id }) => ({ type: 'Categories', _id })),
+//         //       { type: 'Categories', id: 'LIST' },
+//         //     ]
+//         //   : [{ type: 'Categories', id: 'LIST' }],
+//         })
+//     })
+// })
+
+export const categoriesApi = createApi({
+    reducerPath: 'categoriesApi',
+    // tagTypes: ['Categories'],
+    baseQuery: fetchBaseQuery({ baseUrl: 'http://shop-roles.node.ed.asmer.org.ua/graphql' }),
+    endpoints: (build) => ({
+        getCategories: build.query({
+            query: ()=> ({
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json;charset=utf-8',
+                    'Accept': 'application/json'
+                },
+                body: JSON.stringify(gqlRootCats1)
+            }),
+        //     providesTags: (result) =>
+        // result
+        //   ? [
+        //       ...Object.values(result.data)[0].map(({ _id }) => ({ type: 'Categories', _id })),
+        //       { type: 'Categories', id: 'LIST' },
+        //     ]
+        //   : [{ type: 'Categories', id: 'LIST' }],
+        }),
+        getCategory: build.query({
+            query: (_id)=> ({
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json;charset=utf-8',
+                    'Accept': 'application/json'
+                },
+                body: JSON.stringify(CategoryFindOne(_id))
+            }),
+        //     providesTags: (result) =>
+        // result
+        //   ? [
+        //       ...Object.values(result.data)[0].map(({ _id }) => ({ type: 'Categories', _id })),
+        //       { type: 'Categories', id: 'LIST' },
+        //     ]
+        //   : [{ type: 'Categories', id: 'LIST' }],
+        }),
+        getProduct: build.query({
+            query: (_id)=> ({
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json;charset=utf-8',
+                    'Accept': 'application/json'
+                },
+                body: JSON.stringify(GoodFindOne(_id))
+            }),
+        //     providesTags: (result) =>
+        // result
+        //   ? [
+        //       ...Object.values(result.data)[0].map(({ _id }) => ({ type: 'Categories', _id })),
+        //       { type: 'Categories', id: 'LIST' },
+        //     ]
+        //   : [{ type: 'Categories', id: 'LIST' }],
+        })
+
+    })
+})
+
+export const {useGetCategoriesQuery, useGetCategoryQuery, useGetProductQuery} = categoriesApi
+

+ 140 - 0
my-diplom/src/store/categoriesApi.js

@@ -0,0 +1,140 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { gql } from 'graphql-request'
+import {graphqlRequestBaseQuery} from '@rtk-query/graphql-request-base-query'
+
+export const categoriesApi = createApi({
+    reducerPath: 'categoriesApi',
+    baseQuery: graphqlRequestBaseQuery({ 
+      url: 'http://shop-roles.node.ed.asmer.org.ua/graphql',
+      prepareHeaders:(headers, { getState }) => {
+        // By default, if we have a token in the store, let's use that for authenticated requests
+        const token = getState().auth.token;
+        if (token) {
+            headers.set("Authorization", `Bearer ${token}`);
+        }
+        return headers;
+    }
+    }),
+    endpoints: (builder) => ({
+        getCategories: builder.query({
+            query: () => ({
+                document: gql`query baseCategory($searchNullparent: String){
+                    CategoryFind(query: $searchNullparent){
+                      _id name parent {
+                        _id
+                        name
+                      }
+                    }
+                  }`,
+                variables: {
+                    searchNullparent: JSON.stringify([{parent: null}]),
+                 },
+            })
+        }),
+        getCategory: builder.query({
+            query: (_id) => ({
+                document: gql`query CategoryFindOne($qCategoryId: String) {
+                        CategoryFindOne(query: $qCategoryId){
+                          _id
+                          name
+                          parent{
+                            _id
+                            name
+                          }
+                          subCategories{
+                            _id
+                            name
+                            goods{
+                              _id
+                              name
+                            }
+                          }
+                          goods{
+                            _id name price 
+                            images {
+                              url
+                            }
+                          }
+                        }
+                      }`,
+                variables: {
+                    qCategoryId: JSON.stringify([{ _id }])
+                }
+            })
+        }),
+        getProduct: builder.query({
+            query: (_id) => ({
+                document: gql`query oneProduct($GoodId: String){
+                    GoodFindOne(query: $GoodId){
+                      _id
+                      description
+                      name
+                      price
+                      categories{
+                        name
+                      }
+                      images{
+                        url
+                      }
+                    }  
+                  }`,
+                variables: {
+                    GoodId: JSON.stringify( [{ _id }] )
+                }
+            })
+        }),
+        getLogin: builder.mutation({
+            query: ({login, password}) => ({
+                document: gql`query login($login:String, $password:String){
+                    login(login:$login, password:$password)
+                  }`,
+                variables: {
+                    login,
+                    password
+                }
+            })
+        }),
+        getUser: builder.query({
+          query: (_id) => ({
+              document: gql`query oneUser($UserId: String){
+                UserFindOne(query: $UserId){
+                    _id
+                    login
+                    nick
+                    avatar
+                    
+                  }
+                }`,
+              variables: {
+                UserId: JSON.stringify( [{ _id }] )
+              }
+          })
+      }),
+      getUserById: builder.query({
+        query: (_id) => ({
+            document: gql`
+                query GetUser($q: String) {
+                    UserFindOne(query: $q) {
+                        _id
+                        login
+                        nick
+                        avatar { url }
+                    }
+                }
+            `,
+            variables: {q: JSON.stringify([{_id}])}
+        }),
+        providesTags: (result, error, id) =>  ( [{ type: 'User', id}])
+    }),
+    })
+})
+
+export const {
+  useGetCategoriesQuery,
+  useGetCategoryQuery,
+  useGetProductQuery,
+  useGetLoginMutation,
+  useGetUserQuery,
+  useGetUserByIdQuery
+} = categoriesApi
+

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

@@ -0,0 +1,14 @@
+import { configureStore } from "@reduxjs/toolkit";
+import cartReducer from './cartSlice'
+import authReducer from './authSlice'
+import { categoriesApi } from './categoriesApi'
+
+ 
+export default configureStore({
+    reducer:{
+        cart: cartReducer,
+        auth: authReducer,
+        [categoriesApi.reducerPath]: categoriesApi.reducer,
+    },
+        middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(categoriesApi.middleware)
+})