Przeglądaj źródła

edit good and category

viktoriia.kapran 1 rok temu
rodzic
commit
b0b3667635

+ 17 - 12
js21 react/my-react-app/src/components/EditCategory.js

@@ -1,8 +1,7 @@
 import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
 import React, { useState } from 'react';
-import { useDispatch } from 'react-redux';
 import { useNavigate } from 'react-router-dom';
-import { useCreateCategoryMutation, useGetCategoriesQuery } from '../store/api';
+import { useCreateCategoryMutation, useGetCategoriesQuery, useGetCategoriesWithSubCategoriesQuery } from '../store/api';
 
 const ITEM_HEIGHT = 48;
 const ITEM_PADDING_TOP = 8;
@@ -16,30 +15,37 @@ const MenuProps = {
 };
 
 function EditCategory({ buttonText, nameCategory, subCategories, categoryId }) {
-  const { data } = useGetCategoriesQuery();
+  const { data } = useGetCategoriesWithSubCategoriesQuery();
   const [name, setName] = useState(nameCategory || '');
   const [selectedCategories, setSelectedCategories] = useState(subCategories || []);
   const [createCategory, result] = useCreateCategoryMutation();
 
   const navigate = useNavigate();
 
-  const dispatch = useDispatch();
-
-  const handleChange = (event) => {
-    setSelectedCategories([...event.target.value]);
+  const onSubcategoryClick = (category) => {
+    if (selectedCategories.find(selectedCategory => selectedCategory._id == category._id)) {
+      setSelectedCategories(selectedCategories.filter(selectedCategory => selectedCategory._id != category._id));
+    } else {
+      setSelectedCategories([...selectedCategories, category]);
+    }
   };
-
+//
 
 
   const handleSubmit = () => {
     const category = {
       name,
       parent: null,
-      subCategories: selectedCategories,
+      subCategories: selectedCategories.map(subCategory => ({
+                                                              _id: subCategory._id,
+                                                              name: subCategory.name,
+                                                              
+                                                            })),
     }
     if (categoryId) {
       category._id = categoryId;
     }
+    console.log(category);
     createCategory(category).then(response => {
       navigate('/admin/categories');
     });
@@ -61,14 +67,13 @@ function EditCategory({ buttonText, nameCategory, subCategories, categoryId }) {
           <Select
             multiple
             value={selectedCategories}
-            onChange={handleChange}
             input={<OutlinedInput label="Category name" />}
             renderValue={(selected) => selected.map(item => item.name).join(', ')}
             MenuProps={MenuProps}
           >
             {data?.CategoryFind?.map((category) => (
-              <MenuItem key={category._id} value={category}>
-                <Checkbox checked={selectedCategories?.indexOf(category) > -1} />
+              <MenuItem key={category._id} value={category} onClick={() => onSubcategoryClick(category)}>
+                <Checkbox checked={!!selectedCategories?.find(selectedCategory => selectedCategory._id === category._id)} />
                 <ListItemText primary={category.name} />
               </MenuItem>
             ))}

+ 22 - 16
js21 react/my-react-app/src/components/EditGood.js

@@ -1,9 +1,8 @@
-import { Box, Button, FormControl, InputLabel, MenuItem, Select, Stack, TextField } from '@mui/material';
+import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
 import React, { useState } from 'react';
-import { useDispatch } from 'react-redux';
 import { useNavigate } from 'react-router-dom';
 import ImageUploader from '../components/ImageUploader';
-import { useCreateGoodMutation, useGetCategoriesQuery } from '../store/api';
+import { useCreateGoodMutation, useGetCategoriesWithSubCategoriesQuery } from '../store/api';
 
 
 const ITEM_HEIGHT = 48;
@@ -17,21 +16,23 @@ const MenuProps = {
   },
 };
 
-function EditGood({ name, category, price, description, goodImages, goodId, buttonText }) {
-  const { data } = useGetCategoriesQuery();
+function EditGood({ name, categories, price, description, goodImages, goodId, buttonText }) {
+  const { data } = useGetCategoriesWithSubCategoriesQuery();
   const [goodName, setGoodName] = useState(name || '');
-  const [selectedCategory, setSelectedCategory] = useState(category || '');
-  console.log(category)
+  const [selectedCategories, setSelectedCategories] = useState(categories || []);
   const [goodPrice, setGoodPrice] = useState(price || 0);
   const [goodDescription, setGoodDescription] = useState(description || '');
   const [images, setImages] = useState(goodImages || []);
-  console.log(images);
   const navigate = useNavigate();
   const [createGood, result] = useCreateGoodMutation();
 
 
-  const handleCategoryChange = (event) => {
-    setSelectedCategory(event.target.value);
+  const onCategoryClick = (category) => {
+    if (selectedCategories.find(selectedCategory => selectedCategory._id == category._id)) {
+      setSelectedCategories(selectedCategories.filter(selectedCategory => selectedCategory._id != category._id));
+    } else {
+      setSelectedCategories([...selectedCategories, category]);
+    }
   };
   const handlePriceChange = (event) => {
     setGoodPrice(event.target.value);
@@ -45,7 +46,10 @@ function EditGood({ name, category, price, description, goodImages, goodId, butt
 
     const good = {
       name: goodName,
-      categories: [selectedCategory],
+      categories: selectedCategories.map(category => ({
+        _id: category._id,
+        name: category.name
+      })),
       price: +goodPrice,
       description: goodDescription,
       images: images.map(image => ({ _id: image._id }))
@@ -72,14 +76,16 @@ function EditGood({ name, category, price, description, goodImages, goodId, butt
           sx={{ m: '0 auto 20px', width: '100%' }}>
           <InputLabel>Category</InputLabel>
           <Select
-            value={selectedCategory}
-            onChange={handleCategoryChange}
+            multiple
+            value={selectedCategories}
+            input={<OutlinedInput label="Category name" />}
+            renderValue={(selected) => selected.map(item => item.name).join(', ')}
             MenuProps={MenuProps}
-            renderValue={(selected => selectedCategory?.name)}
           >
             {data?.CategoryFind?.map((category) => (
-              <MenuItem key={category._id} value={category}>
-                {category?.name}
+              <MenuItem key={category._id} value={category} onClick={() => onCategoryClick(category)}>
+                <Checkbox checked={!!selectedCategories?.find(selectedCategory => selectedCategory._id === category._id)} />
+                <ListItemText primary={category.name} />
               </MenuItem>
             ))}
           </Select>

+ 0 - 1
js21 react/my-react-app/src/components/LoginForm.js

@@ -9,7 +9,6 @@ import { useLocation } from 'react-router-dom';
 
 const LoginForm = ({ submit, onSubmit }) => {
   const location = useLocation();
-  console.log(location);
   const [login, setLogin] = useState('');
   const [password, setPassword] = useState('');
   const [confirmPassword, setConfirmPassword] = useState('');

+ 11 - 7
js21 react/my-react-app/src/pages/RegisterPage.js

@@ -9,24 +9,27 @@ import { useLoginMutation, useRegisterMutation } from '../store/api';
 
 export default function RegisterPage() {
   const token = useSelector(state => state.auth.token);
-  const [fullRegister, resultMut] = useRegisterMutation();
+  const [fullRegister, {isError}] = useRegisterMutation();
   const [fullLogin, result] = useLoginMutation();
   const dispatch = useDispatch();
   const navigate = useNavigate();
 
-  //СДЕЛАТЬ ПРОВЕРКУ ОШИБКИ ЕСЛИ ПОЛЬЗОВАТЕЛЬ СУЩЕСТВУЕТ И ВЫВОДИТЬ СООБЩЕНИЕ, ЕСЛИ КЛИКАЕШЬ НА КНОПКУ ДО ТОГО КАК ЗАПОЛНИЛ ДАННЫЕ
   useEffect(() => {
     if (token) {
       navigate('/');
     }
   }, [token]);
-
+console.log(isError)
   const onRegister = (login, password) => {
+
     fullRegister({ login, password }).then(res => {
-      fullLogin({ login, password }).then(response => {
-        dispatch(loginAction(response.data.login));
-      })
-    });
+      if (res.data.UserUpsert) {
+        fullLogin({ login, password }).then(response => {
+          dispatch(loginAction(response.data.login));
+        });
+      }
+      });
+
   }
 
   return (
@@ -34,6 +37,7 @@ export default function RegisterPage() {
       <Title>Registration</Title>
       <Box sx={{ maxWidth: '300px', width: '100%', m: '150px auto' }}>
         <LoginForm submit='Registration' onSubmit={onRegister} />
+        {isError && <Box sx={{color: 'red', mt: '20px', textAlign: 'center'}}>This user is already exist</Box>}
       </Box>
     </>
   )

+ 9 - 6
js21 react/my-react-app/src/pages/admin/CategoriesPage.js

@@ -1,5 +1,5 @@
 import React, { useState } from 'react';
-import { useDeleteCategoryMutation, useGetCategoriesQuery, useGetCategoryCountQuery } from '../../store/api';
+import { useDeleteCategoryMutation, useGetCategoriesWithSubCategoriesQuery, useGetCategoryCountQuery } from '../../store/api';
 import Loader from '../../components/Loader';
 import {
   Button, IconButton, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tooltip, Dialog,
@@ -13,7 +13,7 @@ import { Image } from '../../components/Image/Image';
 
 function CategoriesPage() {
   const { data: categoryCount } = useGetCategoryCountQuery();
-  const { data, error, isFetching } = useGetCategoriesQuery();
+  const { data, error, isFetching } = useGetCategoriesWithSubCategoriesQuery();
   const [page, setPage] = useState(0);
   const [rowsPerPage, setRowsPerPage] = useState(5);
   const [open, setOpen] = useState(false);
@@ -40,13 +40,13 @@ function CategoriesPage() {
   };
 
   const onDeletionSubmit = () => {
-    const category = data?.CategoryFind?.find(category => category._id === selectedId);
-    deleteCategory(category).then(response => {
+  const category = data?.CategoryFind?.find(category => category._id === selectedId);
+    deleteCategory({_id: category._id, name: category.name}).then(response => {
       setOpen(false);
     });
   }
 
-  const Row = ({ _id, name, goods, category }) => {
+  const Row = ({ _id, name, goods, category, parent }) => {
     const [open, setOpen] = useState(false);
     return (
       <>
@@ -62,6 +62,7 @@ function CategoriesPage() {
           <TableCell>{_id}</TableCell>
           <TableCell>{name}</TableCell>
           <TableCell>{goods?.length}</TableCell>
+          <TableCell>{parent?.name ? 'Yes' : 'No'}</TableCell>
           <TableCell align='right'>
             <IconButton component={Link} to={`/admin/category/${category._id}`}><Edit /></IconButton>
           </TableCell>
@@ -121,6 +122,7 @@ function CategoriesPage() {
                     <TableCell>ID</TableCell>
                     <TableCell>Category</TableCell>
                     <TableCell>Goods count</TableCell>
+                    <TableCell>Subcategory</TableCell>
                     <TableCell align='right'></TableCell>
                     <TableCell align='right'></TableCell>
                   </TableRow>
@@ -131,7 +133,8 @@ function CategoriesPage() {
                       key={category?._id}
                       name={category?.name}
                       goods={category?.goods}
-                      category={category} />
+                      category={category}
+                      parent={category?.parent} />
                     // <TableRow key={category._id}>
                     //   <TableCell>{category._id}</TableCell>
                     //   <TableCell>{category.name}</TableCell>

+ 1 - 1
js21 react/my-react-app/src/pages/admin/EditGoodPage.js

@@ -18,7 +18,7 @@ function EditGoodPage() {
             buttonText='Edit'
             goodId={goodId}
             name={data?.GoodFindOne?.name}
-            category={data?.GoodFindOne?.categories[0]}
+            categories={data?.GoodFindOne?.categories}
             price={data?.GoodFindOne?.price}
             description={data?.GoodFindOne?.description}
             goodImages={data?.GoodFindOne?.images}

+ 23 - 4
js21 react/my-react-app/src/store/api.js

@@ -58,6 +58,27 @@ export const api = createApi({
                   `}),
       providesTags: ['Category'],
     }),
+    getCategoriesWithSubCategories: builder.query({
+      query: () => ({
+        document: gql`
+                  query GetCategories($q: String){
+                      CategoryFind(query: $q) {
+                        _id name goods {
+                          _id name price images {
+                            url
+                          }
+                        }, subCategories {
+                          name
+                        }, parent {
+                          name
+                        }
+                      }
+                    }
+                  `,
+        variables: { q: JSON.stringify([{}]) }
+      }),
+      providesTags: ['Category'],
+    }),
     getCategoryCount: builder.query({
       query: () => ({
         document: gql`
@@ -345,9 +366,7 @@ export const api = createApi({
         document: gql`
                     mutation deleteCategory($category: CategoryInput) {
                       CategoryDelete(category: $category) {
-                        _id, name, goods {
-                          name, _id
-                        }
+                        _id, name
                       }
                     }`,
         variables: { category }
@@ -386,6 +405,6 @@ export const api = createApi({
 export const { useGetCategoriesQuery, useGetCategoryByIdQuery, useGetGoodByIdQuery, useLoginMutation, useGetOrdersByOwnerIdQuery,
   useRegisterMutation, useGetUserByIdQuery, useCreateCategoryMutation, useDeleteCategoryMutation, useGetGoodsQuery, useGetUsersQuery,
   useGetOrderGoodQuery, useGetUserCountQuery, useGetOrderCountQuery, useGetGoodCountQuery, useGetCategoryCountQuery, useGetOrdersQuery,
-  useCreateGoodMutation, useDeleteGoodMutation, useCreateOrderMutation } = api;
+  useCreateGoodMutation, useDeleteGoodMutation, useCreateOrderMutation, useGetCategoriesWithSubCategoriesQuery } = api;
 
 export const { useUploadImageMutation } = imageApi;