2 次代碼提交 06c883f54f ... f79897aa8b

作者 SHA1 備註 提交日期
  maryluis f79897aa8b updateNew 3 年之前
  maryluis 3c33f28ad2 adminUpdateUser 3 年之前

二進制
shop/public/favicon.ico


+ 1 - 1
shop/public/index.html

@@ -2,7 +2,7 @@
 <html lang="en">
   <head>
     <meta charset="utf-8" />
-    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <link rel="icon" src="/public/favicon.ico" />
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
     <meta name="viewport" content="width=device-width, initial-scale=1" />
     <meta name="theme-color" content="#000000" />

+ 36 - 30
shop/src/App.css

@@ -8,6 +8,9 @@ a {
   text-decoration: none;
   color: rgb(229, 229, 243);
 }
+a:hover {
+  color: rgb(229, 229, 243);
+}
 input {
   background-color: rgb(229, 229, 243);
   border-radius: 10%;
@@ -30,9 +33,9 @@ button:disabled {
  .catalog li {
    padding-left: 5px;
  }
- /* .catalog li:hover {
-   transform: scale(1.05);
- } */
+.adminSmile {
+  margin: 5px;
+}
 
  .subCatalog .subLink li {
   background-color: rgb(10, 10, 10);
@@ -44,10 +47,9 @@ button:disabled {
   list-style: none;
 }
 
- /* .loginForm
- .links li:hover {
-  color: rgb(65, 65, 150);
- } */
+.redAlert {
+  background-color: rgb(41, 9, 9);
+}
 .header {
   position: fixed;
   width: 100%;
@@ -56,7 +58,6 @@ button:disabled {
   background-color: rgb(58, 58, 65);
   display: flex;
   justify-content: space-between;
-  /* padding-top: 10px; */
   height: 50px;
   z-index: 2;
 }
@@ -98,7 +99,6 @@ button:disabled {
 .rightSide {
   height: 100%;
   align-items: center;
-  /* width: 30%; */
   display: flex;
   justify-content: space-around;
 
@@ -152,7 +152,6 @@ content {
   width: 80%;
 }
 .goodsNotFound {
-  /* height: 30em; */
   padding-top: 20%;
 }
 .goodsNotFound h5 {
@@ -219,7 +218,6 @@ content {
   flex-direction: column;
   margin: 5px;
   padding: 25px;
-  /* width: 70%; */
   padding: 35px;
   align-items: center;
   background-color: rgb(10, 10, 10);
@@ -276,6 +274,7 @@ button {
 }
 .profilePage {
   display: flex;
+  position: relative;
   flex-direction: column;
   align-items: center;
   width: 80%;
@@ -302,26 +301,26 @@ button {
 
 .usersList {
   display: flex;
-  width: 20%;
+  width: 40%;
   flex-direction: column;
   align-items: center;
   background-color: rgb(10, 10, 10);
   padding: 5px 10px;
   border: 2px solid;
   border-color:rgb(229, 229, 243);
-  border-radius: 10%;
+  /* border-radius: 10%; */
 }
 .oneUser {
   display: flex;
   align-items: center;
-  justify-content: center;
+  /* justify-content: space-between; */
   width: 100%;
   margin: 10px;
   border-bottom: 2px dotted rgb(229, 229, 243);
 }
 .oneUser a {
   display: flex;
-  justify-content: space-around;
+  justify-content: space-between;
   width: 100%;
 }
 .usersList img {
@@ -343,7 +342,7 @@ button {
   flex-direction: column;
   flex-wrap: wrap;
   width: 80%;
-  /* background-color: rosybrown; */
+
 }
 .basketgoodsInner {
   display: flex;
@@ -361,19 +360,25 @@ button {
   border-color:rgb(229, 229, 243);
   border-radius: 5%;
   width: 400px;
-  height: 250px;
+  height: 280px;
 }
-/* .basketInner .oneGood {
-  height: 320px;
-} */
-
 
-/* .oneGoodInner {
-  position: relative;
+.basketNoGoods {
+  padding-left: 10px;
+  padding-right: 10px;
+  display: flex;
+  flex-direction: column;
+  justify-content: space-around;
+  background-color: rgb(10, 10, 10);
+  border: 2px solid;
+  align-items: center;
+  border-color:rgb(229, 229, 243);
+  border-radius: 5%;
+  width: 400px;
+  height: 280px;
 }
-.oneGoodInner span{
-  position: relative;
-} */
+
+
 .basketButoons {
   display: flex;
 }
@@ -425,9 +430,7 @@ button {
   display: flex;
   justify-content: space-around;
 }
-/* .contacts svg {
-  margin: 0px 5px;
-} */
+
 
 
 @media screen and (max-width: 900px) {
@@ -575,7 +578,10 @@ button {
     font-size: 8px;
   }
 
-
+.basketNoGoods {
+  width: 100%;
+  height: auto;
+}
 
 
   .footer {

+ 3 - 2
shop/src/App.js

@@ -1,9 +1,10 @@
 
 import './App.css';
+import history from "./reducers/history"
 import {Provider, connect} from 'react-redux';
 import {Header, Footer, actionCatalogCard, Main, SearchInput} from "./components/index"
 import {BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom';
-import createHistory from "history/createBrowserHistory";
+// import createHistory from "history/createBrowserHistory";
 import {Catalog, UpdateForm} from "./components/"
 import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
 import thunk from 'redux-thunk';
@@ -22,7 +23,7 @@ function App() {
   return (
     <>
       <Provider store={store}>
-        <Router history = {createHistory}>
+        <Router history = {history}>
           <Header/>
           <Main/>
           <Footer/>

+ 40 - 9
shop/src/components/Main.js

@@ -1,5 +1,5 @@
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
-import createHistory from "history/createBrowserHistory";
+// import createHistory from "history/createBrowserHistory";
 import { useState } from 'react';
 import {Provider, connect} from 'react-redux';
 import {createStore, combineReducers, applyMiddleware} from 'redux';
@@ -33,18 +33,19 @@ const Main = ({className = "MainImg" }) => {
 
                 <content>
                     <Switch>
-                        <Route path = "/" component = {MainMag} exact/>
+                        <Route path = "/" component = {About} exact/>
                         <Route path = "/catalog/" component={MainCatalog} exact/>
                         <Route path = "/catalog/:id" component= {({match}) => <CGoodsCategory id = {match.params.id} /> }/>
                         <Route path = "/search/:name" component = {({match}) => <CGoodsSearch name = {match.params.name}/>}/>
                         <Route path = "/good/:id" component = {({match}) => <CGoodCard id = {match.params.id}/>}/>
                         <Route path = "/order" component = {COrderPage}/>
-                        <Route path = "/login" component = {LoginForm}/>
+                        <Route path = "/login/" component = {LoginForm}/>
                         <Route path = "/searchUser/:users" component = {CUsersList}/>
-                        <Route path = "/profile/:login" component = {CYourProfile}/>
+                        <Route path = "/profile/" component = {CYourProfile}/>
+                        <Route path = "/user/:_id" component = {CYourProfile}/>
                         <Route path = "/basket" component = {CBasketPage}/>
                         <Route path="/about" component = {About} exact/>
-                        <Route path = "/post" component = {Post} exact/>
+                        {/* <Route path = "/post" component = {Post} exact/> */}
                         <Route path = "/contacts" component = {Contacts} />
                         <Route path = "/loginError" component={LoginError} />
                         <Route component = { NotFound } exact/>
@@ -72,11 +73,41 @@ const LoginError = () => {
         </>
     )}
 const MainMag = () => <div>Я тут кароче самый главный страниц</div>
-const About = () => <div>Мы крутой магазин, бла-бла</div>
-const NotFound = () => <div>Да пошел ты!</div>
-const MainCatalog = () => <div>Chose</div>
+const About = () => 
+    <div className = "basketNoGoods">
+
+            <h4>Ласкаво просимо до нашого магазину!</h4>
+            <p>
+                Серед наших товарів ви знайдете що пожувати, де сховати залишки продуктів, та на чому подивитись кіно.
+            </p>
+            <p>
+                Так, саме так, у нас є техніка та смаколики, бо ми хазяйновиті та любимо смачно поїсти.
+            </p>
+            <p>
+                Щоб зробити замовлення перейдіть до каталогу, або скористуйтеся пошуком.
+            </p>
+
+    </div>
+const NotFound = () => {
+    return(
+        <>
+            <div className = "basketNoGoods">
+                <h4>Упс, сторінку не знайдено, або сталася помилка</h4>
+            </div>
+        </>
+    )
+}
+{/* <div> <h5 className = "profilePage">Ой, щось пішло не так. Мабудь цієї сторінки немає, або сталася помилка. Спробуйте ще.</h5></div> */}
+const MainCatalog = () => <div></div>
 const Post = () => <div className = "post">Точно не знаю зачем это, возможно потом уберу. Но в некоторых магазинах есть такое</div>
-const Contacts = () => <div className = "contacts">Тут будет адрес, номер телефона и соцсети</div>
+const Contacts = () => 
+    <div className = "order">
+        <h4>Як ви нас зможете знайти:</h4>
+        <p>Номер телефону: + 38 068 811 3262</p>
+        <p>Ми в instagram: <a href = "https://www.instagram.com/alevelua/?hl=ru" target="_blank">alevelua </a> </p>
+        <p>Ми у Facebook: <a href = "https://www.facebook.com/alevelukraine" target="_blank"> https://www.facebook.com/alevelukraine </a></p>
+        <p>Адреса: пл. Павловская 6, 2й этаж Харьков, Харьковская область, Украина 61022</p>
+    </div>
   
 
 export default Main;

+ 2 - 2
shop/src/components/basket.js

@@ -63,11 +63,11 @@ const mapStateToProps = state => ({
 const BasketPage = ({state, orderDeal, orderDone, basket, GoodsArr, onAdd, onDel, onClear, onOrder, order}) => {
     const history = useHistory();
     console.log(state)
-    console.log(order)
+
 
     if(!basket.price && !orderDone){
         return(
-            <div>Зайдіть у каталог щоб замовити, та повертайтесь</div>
+            <div className = "basketNoGoods"><h2>Ой, у кошику порожно =( </h2><button>В каталог</button></div>
         )
     } else if(basket.price) {
     return (

+ 8 - 6
shop/src/components/catalog.js

@@ -10,7 +10,7 @@ const CatalogSubLink = ({name, arr}) => {
     const [show, changeValue] = useState(false);
     return(
         <li><span  onClick = {() =>changeValue(!show)}>{name} </span>{<ul className="subCatalog">{ show && arr.map(key =>
-            <Links className = {"subLink"} key={key._id} url={`/catalog/` + key._id} text={key.name}> </Links>)}</ul>}</li>
+            <Links className = {"subLink"} key={`${key._id}${Math.random()}`} url={`/catalog/` + key._id} text={key.name}> </Links>)}</ul>}</li>
 
     )
 }
@@ -21,24 +21,26 @@ const Catalog = ({ state, categories = [], getData = () => console.log("no") })
 
 
     return (
-        <>
+        
             <ul className="catalog">
                 {categories.map(category =>
+                
                     category.subCategories == null ?
-                        <Links key={category._id} url={`/catalog/` + category._id} text={category.name}> </Links> :
+                    
+                        <Links key={`${category._id}${Math.random()}`} url={`/catalog/` + category._id} text={category.name}> </Links> :
 
-                         <CatalogSubLink name = {category.name} arr = {category.subCategories}/>
+                         <CatalogSubLink name = {category.name} key = {`${category.subCategories._id}${Math.random()}`}arr = {category.subCategories}/>
 
 
 
                 )}
             </ul>
-        </>
+        
     )
 }
 
 const getCategories = state => {
-
+    // console.log("state", state)
     if (state.promiseRed.categories && state.promiseRed.categories.payload) {
         return state.promiseRed.categories.payload.data.CategoryFind
     }

+ 5 - 5
shop/src/components/goodCard.js

@@ -1,5 +1,5 @@
 import { connect } from "react-redux";
-import {gql, urlUpload, actionPromise, actionGoodCard, getGoods, actionCartAdd} from "../reducers";
+import {gql, urlUpload, actionPromise, actionGoodCard, getData, actionCartAdd} from "../reducers";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import { useEffect, useState } from 'react';
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
@@ -11,11 +11,11 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
   const mapStateToProps = state => ({
     state: state,
     basket: state.basket,
-    goodCard: getGoods(state, "goodCard", "GoodFindOne")
+    goodCard: getData(state, "goodCard", "GoodFindOne")
   });
   
   const mapDispatchToProps = dispatch => bindActionCreators({
-    getData: actionGoodCard,
+    getGood: actionGoodCard,
     onAdd: actionCartAdd
 
   }, dispatch);
@@ -26,9 +26,9 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
 
 
 
-  const GoodCard = ({id, goodCard = null, state, onAdd, getData, className = "goodCard"}) => {
+  const GoodCard = ({id, goodCard = null, getGood, state, onAdd, getData, className = "goodCard"}) => {
     const history = useHistory();
-    useEffect(() =>  getData(id), [id]);
+    useEffect(() =>  getGood(id), [id]);
     //console.log(state)
 
 

+ 2 - 2
shop/src/components/goodsCategory.js

@@ -2,7 +2,7 @@ import {Provider, connect} from 'react-redux';
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import thunk from 'redux-thunk';
 import {actionPromise} from "./index"
-import {gql, actionGoods, getGoods, actionCartAdd} from "../reducers/index";
+import {gql, actionGoods, getData, actionCartAdd} from "../reducers/";
 import { useEffect } from 'react';
 import {OneGood, CGoodsList} from "./index";
 
@@ -10,7 +10,7 @@ import {OneGood, CGoodsList} from "./index";
   
   const mapStateToProps = state => ({
     state: state,
-    goods: getGoods(state, "goods", "GoodFind"),
+    goods: getData(state, "goods", "GoodFind"),
 
   });
   

+ 9 - 9
shop/src/components/goodsList.js

@@ -1,12 +1,12 @@
 import {OneGood, GoodsNotFound} from "./index";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
-import {getData, getGoods, actionGoods, urlUpload} from "../reducers";
+import {getData, actionGoods, urlUpload} from "../reducers/index";
 import {Provider, connect} from 'react-redux';
 
 
   const mapStateToProps = state => ({
     state: state,
-    arr: getGoods(state),
+    arr: getData(state),
     // search: getGoods(state)
   });
   
@@ -29,14 +29,14 @@ const GoodsList = ({arr = [], className = "goods", onAdd}) => {
   return (
     <div className = {className}>          
       {arr.map((good) => 
-      <>
-      <div className = "oneGood">
-      <OneGood key = {good._id} id = {good._id} name = {good.name} price = {good.price} image = {good.images ? `${urlUpload}/${good.images[0].url}` : `https://images.ua.prom.st/2259265311_korobka-syurpriz-dlya.jpg`}/>
-      <div>
+      
+      <div key = {`${Math.random}${good._id}`}className = "oneGood">
+        <OneGood  id = {good._id} name = {good.name} price = {good.price} image = {good.images ? `${urlUpload}/${good.images[0].url}` : `https://images.ua.prom.st/2259265311_korobka-syurpriz-dlya.jpg`}/>
+        <div>
             <button onClick = {() => onAdd(good.name, good.price, good._id,  good.description, good.images)}>В кошик</button>
-          </div>
-          </div>
-      </>
+        </div>
+      </div>
+      
       )}
 
     </div>

+ 2 - 2
shop/src/components/goodsListSearch.js

@@ -1,12 +1,12 @@
 import {OneGood} from "./index";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
-import {getData, getGoods, actionGoods, getSearchedGoods, actionSearch} from "../reducers";
+import {getData, actionGoods, getSearchedGoods, actionSearch} from "../reducers";
 import {Provider, connect} from 'react-redux';
 import {GoodsNotFound } from "./index";
 
 const mapStateToProps = state => ({
     state: state,
-    search: getGoods(state, "search")
+    search: getData(state, "search")
   });
   
   const mapDispatchToProps = dispatch => bindActionCreators({

+ 2 - 2
shop/src/components/goodsSearch.js

@@ -2,14 +2,14 @@ import {Provider, connect} from 'react-redux';
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import thunk from 'redux-thunk';
 import {actionPromise} from "./index"
-import {gql, actionGoods, getGoods, actionSearch, actionCartAdd} from "../reducers/index";
+import {gql, actionGoods, getData, actionSearch, actionCartAdd} from "../reducers/index";
 import { useEffect } from 'react';
 import {OneGood, CGoodsList} from "./index";
 
 
 const mapStateToProps = state => ({
     state: state,
-    search: getGoods(state, "search", "GoodFind")
+    search: getData(state, "search", "GoodFind")
   });
   
   const mapDispatchToProps = dispatch => bindActionCreators({

+ 4 - 4
shop/src/components/header.js

@@ -2,7 +2,7 @@ import {Footer, Links} from "./index"
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
 import {Provider, connect} from 'react-redux';
 import React, {Component, useState, useEffect} from 'react';
-import createHistory from "history/createBrowserHistory";
+// import createHistory from "history/createBrowserHistory";
 import {actionAuthLogout} from "../reducers"
 import {createStore, combineReducers, applyMiddleware} from 'redux';
 import thunk from 'redux-thunk';
@@ -21,7 +21,7 @@ const StandartMenu = ({className = "standartMenu", getCat = null}) => {
 
                 <Links url = {"/catalog"} text = {"Каталог"}/>
                 <Links url = {"/about"} text = {"Про нас"}/>
-                <Links url = {"/post"} text = {"Оплата і доставка"}/>
+                {/* <Links url = {"/post"} text = {"Оплата і доставка"}/> */}
                 <Links url = {"/contacts"} text = {"Контакти"}></Links>
 
             </ul>
@@ -53,13 +53,13 @@ const TabletMenu = ({}) => {
 const ToLoginPage = ({login, onLogout}) => {
     const history = useHistory();
 
-    useEffect(() => history.location.pathname.includes(`/profile/`) && (login ?  history.push(`/profile/` + login) : history.push(`/login`)),[login])
+    useEffect(() => history.location.pathname.includes(`/profile/`) && (login ?  history.push(`/profile/`) : history.push(`/login`)),[login])
     return(
         <>
         <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-person" viewBox="0 0 16 16">
         <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10z"/>
         </svg>
-        <Link to = {login ? "/profile/" + login: "/login"} >
+        <Link to = {login ? "/profile/": "/login"} >
             <span className = "link">{login ? login : "Вхід"}</span>
             {login && <button onClick = {onLogout}>Вихід</button>}
         </Link>

+ 2 - 2
shop/src/components/index.js

@@ -1,6 +1,6 @@
 import React, { useState } from 'react';
 import {BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom';
-import createHistory from "history/createBrowserHistory";
+// import createHistory from "history/createBrowserHistory";
 import {createStore, combineReducers, applyMiddleware} from 'redux';
 import Header from "./header";
 import Footer from "./footer";
@@ -16,7 +16,7 @@ import CGoodsListSearch from "./goodsListSearch";
 import GoodsNotFound from "./goodsNotFound";
 import LoginForm from "./loginOnPage";
 import CGoodCard from "./goodCard";
-import CUpdateForm from "./updateForm";
+import {CUpdateForm} from "./updateForm";
 import CYourProfile from "./profilePage";
 import CBasketPage from "./basket";
 import COrderPage from "./orderDonePage";

+ 29 - 0
shop/src/components/layout.js

@@ -0,0 +1,29 @@
+import React, { useState } from 'react';
+import {BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom';
+import createHistory from "history/createBrowserHistory";
+import {Header, Footer} from "./index"
+import MainImg from "./MainImg"
+
+
+
+
+
+const Layout =({}) =>{
+    return(
+        <>
+
+
+        </>
+    )
+}
+
+
+
+
+
+
+
+
+
+export default Layout;
+

+ 1 - 1
shop/src/components/links.js

@@ -4,7 +4,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-rout
 const Links = ({url, text, className = "links"}) => {
     return (
 
-            <Link className = {className} to={url}><li>{text}</li></Link>
+            <Link className = {className} to={url}><li key = {`${url}${Math.random() || Math.random()}`}>{text}</li></Link>
 
     )
 }

+ 10 - 6
shop/src/components/loginOnPage.js

@@ -36,12 +36,16 @@ const PasswordConfirm = ({status, loginStatus, state, login, isLoggedIn, onLogin
     const [pass2, setPass2] = useState("");
     const history = useHistory();
     useEffect(() => {
-        //debugger
-            login ?  history.push(`/profile/` + login) : history.push(`/login`);
-            clearLogin()
+
+        if(login) {
+            history.push(`/profile/` + login) 
+            return
+        }
+        history.push(`/login`);
+        clearLogin()
         },[login]
 )
-    console.log(state)
+
 
     function Login() {
         
@@ -96,8 +100,8 @@ const FormReg = ({onReg, onLogin, login, state, isReg}) => {
     const [pass1, setPass1] = useState("");
     const [pass2, setPass2] = useState("");
     const history = useHistory();
-    useEffect(() => login ?  history.push(`/profile/` + login) : history.push(`/login`),[login])
-    console.log(isReg)
+    useEffect(() => login ?  history.push(`/profile/`) : history.push(`/login`),[login])
+
 
     return (
         <>

+ 1 - 1
shop/src/components/oneGood.js

@@ -1,6 +1,6 @@
 import {BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom';
 
-const OneGood = ({className = "oneGoodInner", image, name, price, id}) => {
+const OneGood = ({className = "oneGoodInner", image,  name, price, id}) => {
 
     return (
       <>

+ 1 - 2
shop/src/components/orderDonePage.js

@@ -16,8 +16,7 @@ const mapStateToProps = state => ({
 
 const OrderPage = ({order = false,state}) => {
     const history = useHistory();
-    console.log(state)
-    console.log(order)
+    
     //debugger
     const date =  order ? new Date(+order.createdAt) : 0;
     console.log(date)

File diff suppressed because it is too large
+ 137 - 24
shop/src/components/profilePage.js


+ 111 - 26
shop/src/components/updateForm.js

@@ -1,22 +1,21 @@
 import { useState, useRef, useEffect } from 'react';
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
-import {gql, urlUpload, actionPromise, actionGoodCard, getGoods, updateImgAction, actionUserUpdate} from "../reducers";
+import {gql, urlUpload, actionPromise, actionGoodCard, actionUserFindOne, getGoods, updateImgAction, actionUserUpdate, actionAuthLogout, actionAuthLogin} from "../reducers";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import { connect } from 'react-redux';
 
-const UpdateForm = ({updateImg, updateUser, id}) => {
-    const history = useHistory();
-    const formRef = useRef(null);
-    const [nick, changeNick] = useState(null);
-    const [login, changeLogin] = useState(null);
-    const [password, changePassword] = useState(null);
-    const [password2, changePassword2] = useState(null);
-    const [isUpdateImg, changeImg] = useState(false);
-    const [isUpdatePage, changePage] = useState(false);
-    const [newImage, getImage] = useState({});
-    
-    useEffect(() => isUpdatePage && window.location.reload()[isUpdatePage])
-    console.log(formRef);
+
+
+const UpdateAdminForm = ({onLogin, onLogout, data, getData, updateImg, updateUser, id, token}) => {
+  const history = useHistory();
+  const formRef = useRef(null);
+  const [nick, changeNick] = useState(null);
+  const [login, changeLogin] = useState(null);
+  const [password, changePassword] = useState(null);
+  const [password2, changePassword2] = useState(null);
+  const [isUpdateImg, changeImg] = useState(false);
+  const [isUpdatePage, changePage] = useState(false);
+  const [newImage, getImage] = useState({});
 
   return(
     <>
@@ -26,11 +25,14 @@ const UpdateForm = ({updateImg, updateUser, id}) => {
       <input onChange = {(e) => changeLogin(e.target.value)} placeholder = "Новий логін"/>
       <input onChange = {(e) => changePassword(e.target.value)} placeholder = "Новий пароль"/>
       <input onChange = {(e) => changePassword2(e.target.value)} placeholder = "Повторіть пароль"/>
+      <button>Назначити адміном</button>
+      <button>Зняти з адміна</button>
+      <button>Зтерти юзера</button>
       <form className = "updateImg" action="/upload" method="post" enctype="multipart/form-data" id='form' ref={formRef} 
       onChange = {
         () => {
-          updateImg(formRef, getImage);
-          changeImg(true);
+          updateImg(formRef);
+          // changeImg(true);
       }}>
         <input type="file"  name="photo" id='photo'/>
       </form>
@@ -59,6 +61,82 @@ const UpdateForm = ({updateImg, updateUser, id}) => {
          changePage(true);
          
          
+      }}>Зберегти</button>
+    </div>
+    </>
+  )
+}
+
+
+
+
+
+
+const UpdateForm = ({state, onLogin, onLogout, isImg, data, getData, updateImg, updateUser, id, token}) => {
+    const history = useHistory();
+    const formRef = useRef(null);
+    const [nick, changeNick] = useState(null);
+    const [login, changeLogin] = useState(null);
+    const [password, changePassword] = useState(null);
+    const [password2, changePassword2] = useState(null);
+    const [isUpdateImg, changeImg] = useState(false);
+    const [isUpdatePage, changePage] = useState(false);
+    const [newImage, getImage] = useState({});
+    
+    useEffect(() => {
+      if(isUpdatePage) {
+        let jwt = token;
+        onLogout();
+        onLogin(jwt);
+        history.push("/login")
+
+      }
+    },
+      [isUpdatePage])
+
+  return(
+    <>
+    <div className = "updateWrapper">
+      <h4>Редагування</h4>
+      <input onChange = {(e) => changeNick(e.target.value)} placeholder = "Новий нікнейм"/>
+      <input onChange = {(e) => changeLogin(e.target.value)} placeholder = "Новий логін"/>
+      <input onChange = {(e) => changePassword(e.target.value)} placeholder = "Новий пароль"/>
+      <input onChange = {(e) => changePassword2(e.target.value)} placeholder = "Повторіть пароль"/>
+      <input type="file"  name="photo" id='photo' 
+        onChange={(ev) => {
+          updateImg(ev.target.files[0])
+
+          changeImg(true);
+        }
+          }/>
+      <button onClick = {() => {
+
+        let newUser = {}
+        newUser._id = id;
+        if(nick){
+          newUser.nick = nick;
+        }
+        if(login) {
+          newUser.login = login;
+        } 
+        if (password && password == password2) {
+          newUser.password = password
+        } else if (password !== password2) {
+          history.push("/loginError");
+          return
+        }
+        if(isUpdateImg) {
+          
+        }
+        updateUser(newUser);
+        changePage(true)
+        // let jwt = token;
+
+        //  onLogout();
+        //  onLogin(jwt)
+        //  history.push("/login/")
+         
+         
       }}>Зберегти</button>
     </div>
 
@@ -69,15 +147,17 @@ const UpdateForm = ({updateImg, updateUser, id}) => {
 
 const mapStateToProps = state => ({
   state: state,
-  // data: state.promiseRed && state.promiseRed.user &&
-  // state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
-  // state.promiseRed.user.payload.data.UserFindOne
- // basket: state.basket,
- // GoodsArr: arrFromObj(ObjFilter(state.basket, "price")),
- // order: orderArr(arrFromObj(ObjFilter(state.basket, "price"))),
- // orderDone: state.promiseRed && state.promiseRed.order && 
- // state.promiseRed.order.payload && 
- // state.promiseRed.order.payload.data.OrderUpsert
+
+  data: state.promiseRed && state.promiseRed.user &&
+  state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
+  state.promiseRed.user.payload.data.UserFindOne,
+
+  token: state.auth && state.auth.token,
+  
+  isImg: state.promiseRed && state.promiseRed.photo &&
+  state.promiseRed.photo.payload && state.promiseRed.photo.payload.data &&
+  state.promiseRed.photo.payload
+
 });
 
 
@@ -85,12 +165,17 @@ const mapStateToProps = state => ({
 const mapDispatchToProps = dispatch => bindActionCreators({
  updateImg: updateImgAction,
  updateUser: actionUserUpdate,
+ getData: actionUserFindOne,
+ onLogout: actionAuthLogout,
+ onLogin: actionAuthLogin
  // onDel: actionCartDelete,
  // onClear: actionCartClear,
  // onOrder: actionOrder
 }, dispatch);
 
 
+const CUpdateAdminForm = connect(mapStateToProps, mapDispatchToProps)(UpdateAdminForm)
+
 const CUpdateForm = connect(mapStateToProps, mapDispatchToProps)(UpdateForm)
 
-export default CUpdateForm;
+export {CUpdateForm};

File diff suppressed because it is too large
+ 19 - 7
shop/src/components/usersList.js


+ 1 - 1
shop/src/reducers/actionFindOneUser.js

@@ -7,7 +7,7 @@ const actionUserFindOne = (user) => {
     //debugger
     return async dispatch => {
         const queryJson = JSON.stringify([{
-            "login": user}]);
+            "_id": user}]);
         await dispatch(actionPromise(`user`, gql(
             `query userOne ($query: String){
                 UserFindOne(query: $query){

+ 3 - 1
shop/src/reducers/actionGoodCard.js

@@ -2,10 +2,11 @@ import {actionPromise, gql} from "./index";
 
 
 const actionGoodCard = (_id) => {
+    return async dispatch => {
     const queryJson = JSON.stringify([{
         "_id": `${_id}`
       }]);
-    return (actionPromise(`goodCard`, gql (
+    await dispatch(actionPromise(`goodCard`, gql (
         `query oneGood($query: String) {
             GoodFindOne(query: $query) {
                 _id
@@ -18,5 +19,6 @@ const actionGoodCard = (_id) => {
           }
     ` ,{ query: queryJson})))
   }
+}
 
   export default actionGoodCard;

+ 13 - 16
shop/src/reducers/actionUpdateImg.js

@@ -16,23 +16,20 @@ const actionImgOne = (_id) => {
   )))
 }
 
- async function updateImgAction(ref, getData) {
-   debugger
-    let file = new FormData(ref.current);
-
-    await fetch(`${urlUpload}/upload`, {
-      method: "POST",
-      headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
-      body: file
-    }).then(res => res.json()).then((res) => {
-        getData(res) 
-    })
-    // .then((res) => res.json()).then((res) => {
-    //   actionImgOne(res._id)
-    // })
-  
+const updateImgAction = selectedFile => {
+  const formData = new FormData();
+
+  formData.append('photo', selectedFile);
+
+  return actionPromise("photo", fetch(`${urlUpload}/upload`, {
+    method: 'POST',
+    headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
+    body: formData,
+  }).then((response) => response.json()))
+};
+
+
   
-  }    
 
   
 

+ 1 - 1
shop/src/reducers/actionUserUpdate.js

@@ -9,7 +9,7 @@ const actionUserUpdate = (data) => {
                 user: data
             }
         )
-        await dispatch(actionPromise('user', gql(
+        await dispatch(actionPromise('NewUser', gql(
             `mutation updateMe($user:UserInput){
                 UserUpsert(user: $user){
                   _id

+ 2 - 0
shop/src/reducers/authReducer.js

@@ -23,6 +23,8 @@ function authReducer(state, action){
     if (action.type === 'LOGOUT'){
         console.log('ЛОГАУТ')
         localStorage.removeItem("authToken");
+        
+        // localStorage.removeItem("basket");
         return {}
     }
     return state

+ 2 - 2
shop/src/reducers/getGoods.js

@@ -1,7 +1,7 @@
 
 
 
-  const getGoods = (state, key, funk) => {
+  const getData = (state, key, funk) => {
   //debugger
     if(state.promiseRed[key] && state.promiseRed[key].payload) {
         return state.promiseRed[key].payload.data[funk]
@@ -10,4 +10,4 @@
     return [];
   };
 
-  export default getGoods;
+  export default getData;

+ 3 - 0
shop/src/reducers/history.js

@@ -0,0 +1,3 @@
+import {createBrowserHistory} from "history";
+
+export default createBrowserHistory();

+ 2 - 2
shop/src/reducers/index.js

@@ -3,7 +3,7 @@ import thunk from 'redux-thunk';
 import actionPromise from "./actionPromise";
 import {gql, urlUpload} from "./gql";
 import actionGoods from "./actionGoods"
-import getGoods from "./getGoods";
+import getData from "./getData";
 import {actionSearch} from "./actionsearch";
 import actionLogin from "./actionLogin";
 import authReducer from "./authReducer";
@@ -38,7 +38,7 @@ function promiseReducer(state={}, action){
       basket: cartReducer
   }), compose(applyMiddleware(thunk)))
 
-export {actionPromise, gql, actionGoods, getGoods, promiseReducer, store, actionSearch,
+export {actionPromise, gql, actionGoods, getData, promiseReducer, store, actionSearch,
    actionLogin, authReducer, actionAuthLogin, actionAuthLogout, urlUpload, actionGoodCard, 
    updateImgAction, actionCartAdd, actionCartDelete, actionCartClear, actionOrder,
     actionReg, actionUserFindOne, actionUserUpdate, actionSearchUser};