浏览代码

adminUpdateUser

maryluis 3 年之前
父节点
当前提交
3c33f28ad2

+ 31 - 29
shop/src/App.css

@@ -30,9 +30,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 +44,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 +55,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 +96,6 @@ button:disabled {
 .rightSide {
   height: 100%;
   align-items: center;
-  /* width: 30%; */
   display: flex;
   justify-content: space-around;
 
@@ -152,7 +149,6 @@ content {
   width: 80%;
 }
 .goodsNotFound {
-  /* height: 30em; */
   padding-top: 20%;
 }
 .goodsNotFound h5 {
@@ -219,7 +215,6 @@ content {
   flex-direction: column;
   margin: 5px;
   padding: 25px;
-  /* width: 70%; */
   padding: 35px;
   align-items: center;
   background-color: rgb(10, 10, 10);
@@ -276,6 +271,7 @@ button {
 }
 .profilePage {
   display: flex;
+  position: relative;
   flex-direction: column;
   align-items: center;
   width: 80%;
@@ -302,26 +298,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 +339,7 @@ button {
   flex-direction: column;
   flex-wrap: wrap;
   width: 80%;
-  /* background-color: rosybrown; */
+
 }
 .basketgoodsInner {
   display: flex;
@@ -363,17 +359,23 @@ button {
   width: 400px;
   height: 250px;
 }
-/* .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: 250px;
 }
-.oneGoodInner span{
-  position: relative;
-} */
+
+
 .basketButoons {
   display: flex;
 }
@@ -425,9 +427,7 @@ button {
   display: flex;
   justify-content: space-around;
 }
-/* .contacts svg {
-  margin: 0px 5px;
-} */
+
 
 
 @media screen and (max-width: 900px) {
@@ -575,7 +575,9 @@ button {
     font-size: 8px;
   }
 
-
+.basketNoGoods {
+  width: 100%;
+}
 
 
   .footer {

+ 4 - 3
shop/src/components/Main.js

@@ -39,9 +39,10 @@ const Main = ({className = "MainImg" }) => {
                         <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/>
@@ -73,7 +74,7 @@ const LoginError = () => {
     )}
 const MainMag = () => <div>Я тут кароче самый главный страниц</div>
 const About = () => <div>Мы крутой магазин, бла-бла</div>
-const NotFound = () => <div>Да пошел ты!</div>
+const NotFound = () => <div> <h5 className = "profilePage">Ой, щось пішло не так. Мабудь цієї сторінки немає, або сталася помилка. Спробуйте ще.</h5></div>
 const MainCatalog = () => <div>Chose</div>
 const Post = () => <div className = "post">Точно не знаю зачем это, возможно потом уберу. Но в некоторых магазинах есть такое</div>
 const Contacts = () => <div className = "contacts">Тут будет адрес, номер телефона и соцсети</div>

+ 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 (

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

@@ -38,7 +38,7 @@ const Catalog = ({ state, categories = [], getData = () => console.log("no") })
 }
 
 const getCategories = state => {
-
+    // console.log("state", state)
     if (state.promiseRed.categories && state.promiseRed.categories.payload) {
         return state.promiseRed.categories.payload.data.CategoryFind
     }

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

@@ -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>

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

@@ -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;
+

+ 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 - 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)

文件差异内容过多而无法显示
+ 141 - 18
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};

文件差异内容过多而无法显示
+ 16 - 4
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()))
+};
+
+
   
-  }    
 
   
 

+ 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