瀏覽代碼

nachePratsue

maryluis 3 年之前
父節點
當前提交
822b062683

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

@@ -5,6 +5,7 @@ import {createStore, combineReducers, applyMiddleware, bindActionCreators} from
 import {gql, urlUpload, actionPromise, actionGoodCard, getGoods, actionGoods, 
     actionCartAdd, actionCartDelete, actionCartClear, actionOrder} from "../reducers";
 import { useHistory } from "react-router-dom";
+import COrderPage from "./orderDonePage";
 
 
 
@@ -67,7 +68,7 @@ const BasketPage = ({state, orderDeal, orderDone, basket, GoodsArr, onAdd, onDel
 
     if(!basket.price && !orderDone){
         return(
-            <div className = "basketNoGoods"><h2>Ой, у кошику порожно =( </h2><button>В каталог</button></div>
+            <div className = "basketNoGoods"><h2>Ой, у кошику порожно =( </h2><button onClick = {() => history.push("/catalog/")}>В каталог</button></div>
         )
     } else if(basket.price) {
     return (
@@ -109,7 +110,11 @@ const BasketPage = ({state, orderDeal, orderDone, basket, GoodsArr, onAdd, onDel
         </>
     )} else if(orderDone) {
         return(
-            <>{ history.push("./order")}</>
+            <>
+                <COrderPage/>
+                <div className = "basketNoGoods"><h2>Ой, у кошику порожно =( </h2><button  onClick = {() => history.push("/catalog/")}>В каталог</button></div>
+
+            </>
         )
     }
 }

+ 9 - 2
shop/src/components/catalog.js

@@ -16,12 +16,13 @@ const CatalogSubLink = ({name, arr}) => {
 }
 
 
-const Catalog = ({ state, categories = [], getData = () => console.log("no") }) => {
+const Catalog = ({ state, status, categories = [], getData = () => console.log("no") }) => {
     useEffect(() => categories.length == 0 && getData(), []);
 
 
     return (
-        
+            <>
+
             <ul className="catalog">
                 {categories.map(category =>
                 
@@ -35,6 +36,7 @@ const Catalog = ({ state, categories = [], getData = () => console.log("no") })
 
                 )}
             </ul>
+            </>
         
     )
 }
@@ -50,6 +52,11 @@ const getCategories = state => {
 
 const mapStateToProps = state => ({
     state: state,
+
+    status: state.promiseRed && state.promiseRed.categories &&
+    state.promiseRed.categories.payload && state.promiseRed.categories &&
+    state.promiseRed.categories.status,
+
     categories: getCategories(state)
 });
 

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

@@ -11,6 +11,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
   const mapStateToProps = state => ({
     state: state,
     basket: state.basket,
+    isAdmin: state.auth && state.auth.payload && state.auth.payload.sub && state.auth.payload.sub.acl && state.auth.payload.sub.acl.indexOf("admin") > -1,
     goodCard: getData(state, "goodCard", "GoodFindOne")
   });
   
@@ -26,10 +27,10 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
 
 
 
-  const GoodCard = ({id, goodCard = null, getGood, state, onAdd, getData, className = "goodCard"}) => {
+  const GoodCard = ({id, goodCard = null, getGood, state, onAdd, getData, className = "goodCard", isAdmin}) => {
     const history = useHistory();
     useEffect(() =>  getGood(id), [id]);
-    //console.log(state)
+    console.log(state)
 
 
     const [width, setWidth] = useState(window.innerWidth);
@@ -48,7 +49,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
       width > 900 ? setFinallyWidth(true) : setFinallyWidth(false);
 
       }
-      console.log(goodCard)
+      // console.log(goodCard)
 
      return(
         <> 
@@ -59,6 +60,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
             <span>{`${goodCard.price}грн`}</span>
             <p>{goodCard.description}</p>
             <button onClick = {() => onAdd(goodCard.name, goodCard.price, goodCard._id,  goodCard.description, goodCard.images)}>В кошик</button>
+            {isAdmin && <button>Редагувати</button>}
           </div>
         }
         </>

+ 6 - 3
shop/src/components/goodsListSearch.js

@@ -6,7 +6,10 @@ import {GoodsNotFound } from "./index";
 
 const mapStateToProps = state => ({
     state: state,
-    search: getData(state, "search")
+    search: getData(state, "search"),
+    status: state.promiseRed && state.promiseRed.search &&
+    state.promiseRed.search.payload && state.promiseRed.search &&
+    state.promiseRed.search.status,
   });
   
   const mapDispatchToProps = dispatch => bindActionCreators({
@@ -15,8 +18,8 @@ const mapStateToProps = state => ({
   
 
 
-const GoodsListSearch = ({search = [], className = "goods"}) => {
-    console.log(search)
+const GoodsListSearch = ({status, search = [], className = "goods"}) => {
+    console.log(status)
     if(search.length == 0) {
         return(
             <>

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

@@ -1,9 +1,9 @@
 
-const GoodsNotFound = ({className = "goodsNotFound"}) => {
+const GoodsNotFound = ({className = "order"}) => {
     return(
         <>
         <div className = {className}>
-            <h5>Нажаль за вашими критеріями нічого не знайдено</h5>
+            <p>Нажаль за вашими критеріями нічого не знайдено</p>
         </div>
         </>
     )

+ 16 - 5
shop/src/components/header.js

@@ -3,7 +3,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
 import {Provider, connect} from 'react-redux';
 import React, {Component, useState, useEffect} from 'react';
 // import createHistory from "history/createBrowserHistory";
-import {actionAuthLogout} from "../reducers"
+import {actionAuthLogout, actionUserFindOne} from "../reducers"
 import {createStore, combineReducers, applyMiddleware} from 'redux';
 import thunk from 'redux-thunk';
 
@@ -50,10 +50,12 @@ const TabletMenu = ({}) => {
     )
 }
 
-const ToLoginPage = ({login, onLogout}) => {
+const ToLoginPage = ({login, onLogout, getData, NickName = "User", loginId}) => {
+    // useEffect(() => login && getData(loginId),[login])
     const history = useHistory();
 
-    useEffect(() => history.location.pathname.includes(`/profile/`) && (login ?  history.push(`/profile/`) : 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">
@@ -61,13 +63,22 @@ const ToLoginPage = ({login, onLogout}) => {
         </svg>
         <Link to = {login ? "/profile/": "/login"} >
             <span className = "link">{login ? login : "Вхід"}</span>
-            {login && <button onClick = {onLogout}>Вихід</button>}
+            {login && <button onClick = {() => onLogout()}>Вихід</button>}
         </Link>
         </>
     )
 }
 
-const CToLoginPage = connect(s => ({login: s.auth.payload && s.auth.payload.sub.login}), {onLogout: actionAuthLogout}) (ToLoginPage);
+const CToLoginPage = connect(s => ({
+    login: s.auth.payload && s.auth.payload.sub.login,
+    loginId: s.auth.payload && s.auth.payload.sub._id,
+    NickName: s.promiseRed && s.promiseRed.user &&
+    s.promiseRed.user.payload && s.promiseRed.user.payload.data &&
+    s.promiseRed.user.payload.data.UserFindOne &&
+    s.promiseRed.user.payload.data.UserFindOne.login,
+}), {onLogout: actionAuthLogout,
+     getData: actionUserFindOne,
+}) (ToLoginPage);
 
 
 const Basket = ({basketCount, data, className = "basket"}) => {

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

@@ -19,7 +19,7 @@ const OrderPage = ({order = false,state}) => {
     
     //debugger
     const date =  order ? new Date(+order.createdAt) : 0;
-    console.log(date)
+
     if(order) {
     return(
         <>

+ 48 - 19
shop/src/components/profilePage.js

@@ -1,23 +1,25 @@
 import {CUpdateForm, CUsersList, SearchUserInput, CUpdateAdminForm} from "./index";
 import {gql, urlUpload, actionPromise, actionGoodCard, getGoods,
     actionUserFindOne, updateImgAction, actionAuthLogin, actionAuthLogout,
-    actionUserUpdate,getData } from "../reducers";
+    actionUserUpdate,getData, actionLogin } from "../reducers";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import { connect } from "react-redux";
 import { useEffect, useState, useRef } from "react";
 
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
+import { NewAuth } from "../reducers/actionAuthLog";
 
 
-const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg, 
-                        updateUser, isUserAdmin, status, data = {}, getData, 
-                        match:{params:{_id}}, isAdmin = [], isOwner, newPicture = "clear"}) => {
+const YourProfile = ({state, updatedUser = {}, isImg, token, onLogin, onLogout, updateImg, 
+                        updateUser, isUserAdmin = {}, status, data = {}, getData, 
+                        match:{params:{_id}}, isAdmin = [], isOwner = {}, newPicture = "clear"}) => {
 
     const history = useHistory();
 
     const formRef = useRef(null);
     const [nick, changeNick] = useState(null);
     const [newLogin, changeLogin] = useState(null);
+    const [nowPassword, superPassword] = useState(null);
     const [password, changePassword] = useState(null);
     const [password2, changePassword2] = useState(null);
     const [isUpdateImg, changeImg] = useState(false);
@@ -25,6 +27,8 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
     const [newImage, getImage] = useState({});
 
      useEffect(() =>  history.location.pathname.includes(`/profile/`) ? getData(`${isOwner.id}`) : getData(`${_id}`),[history.location.pathname])
+
+     useEffect(() => updatedUser && updatedUser.data && updatedUser.data.UserUpsert && window.location.reload(), [updatedUser])
      
      const date = new Date(data ? +data.createdAt : 0);
      const [showUpdate, onShow] = useState(false);
@@ -32,8 +36,8 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
      const [searchInput, changeValue] = useState("Пошук");
      
 
-     console.log(isOwner);
-     console.log(data);
+    //  console.log(state);
+    //  console.log(data);
      
 
         return (
@@ -59,13 +63,13 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
                     </div>
                     }
                     
-                    { (isOwner.login == data.login) ? <h2>Привіт, {data.nick || "людино"}!</h2> : <h2>{data.nick}</h2>}
+                    { (isOwner.id == data._id) ? <h2>Привіт, {data.nick || "людино"}!</h2> : <h2>{data.nick || data.login}</h2>}
 
                     <img src={data.avatar ? `${urlUpload}/${data.avatar.url}`: 'https://pngicon.ru/file/uploads/picca-1.png'} />
                     <span>
                         Сторінку створено {`${date.getDate()}. ${date.getMonth() + 1}. ${date.getFullYear()} о ${date.getHours()}: ${date.getMinutes()}: ${date.getSeconds()}  `}
                     </span>
-                    {( (isOwner.login == data.login) || (isAdmin && !isUserAdmin))  &&
+                    {( (isOwner.id == data._id) || (isAdmin && !isUserAdmin))  &&
                     <span>
                         <button  onClick = {() => onShow(!showUpdate)}>Редагувати</button>
                     </span>
@@ -73,6 +77,13 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
                     {showUpdate && 
                     <div className = "updateWrapper">
                     <h4>Редагування</h4>
+                    
+                    {updatedUser && updatedUser.errors && updatedUser.errors.length > 0 && <p>Введено невірні дані, або цей логін вже зайнято</p>}
+                    
+
+                    {(!isAdmin  || (isAdmin && isOwner.id == data._id))&&
+                    <input onChange = {(e) => superPassword(e.target.value)} placeholder = "Пароль для зміни даних"/>}
+                    
                     <input onChange = {(e) => changeNick(e.target.value)} placeholder = "Новий нікнейм"/>
                     <input onChange = {(e) => changeLogin(e.target.value)} placeholder = "Новий логін"/>
                     <input onChange = {(e) => changePassword(e.target.value)} placeholder = "Новий пароль"/>
@@ -84,7 +95,14 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
                         changeImg(true);
                       }
                         }/>
-                    <button disabled = {newPicture == "PENDING"}  onClick = {() => {
+
+
+
+                    <button disabled = {(newPicture == "PENDING") ||
+                       ( !isAdmin && !nowPassword) || 
+                        ((isAdmin && isOwner.id == data._id) && !nowPassword )}  
+                         onClick = {
+                        () => {
               
                       let newUser = {}
                       newUser._id = data._id;
@@ -106,15 +124,27 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
                         newUser.avatar._id = isImg._id;
                         newUser.avatar.url = isImg._url;
                       }
-                      updateUser(newUser);
+                        updateUser(newUser);
+
+
+
+                    
+                          if(!isAdmin || (isAdmin && isOwner.id == data._id)){
+
+                            onLogin(newLogin|| data.login, password || nowPassword);
+
+                           } else {
+                            window.location.reload();
+                           }
+
+
+                        
                       
 
-                      !isAdmin ? onLogout() : window.location.reload();
 
                        
                        
                     }}>Зберегти</button>
-                    {(isAdmin && (isOwner.login != data.login)) && <button className = "redAlert">Видалити юзера</button>}
                   </div>
 
                         
@@ -125,8 +155,7 @@ const YourProfile = ({state, isImg, token, onLogin, onLogout, updateImg,
                 </div>
             </>
           }
-          {status === ("PENDING") && <>Loading</>}
-          {/* {(status == "RESOLVED" && !data) && history.push("/error/")} */}
+
           </>
         )
        
@@ -148,6 +177,10 @@ const mapStateToProps = state => ({
      
      token: state.auth && state.auth.token,
 
+     updatedUser: state.promiseRed && state.promiseRed.newUser &&
+     state.promiseRed.newUser.payload && state.promiseRed.newUser.payload.data &&
+     state.promiseRed.newUser.payload,
+
      isUserAdmin: state.promiseRed && state.promiseRed.user &&
      state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
      state.promiseRed.user.payload.data.UserFindOne && 
@@ -171,14 +204,10 @@ const mapStateToProps = state => ({
     updateImg: updateImgAction,
     updateUser: actionUserUpdate,
     onLogout: actionAuthLogout,
-    onLogin: actionAuthLogin
+    onLogin: actionLogin
   }, dispatch);
 
 const CYourProfile = connect(mapStateToProps, mapDispatchToProps)
 (YourProfile)
 export default CYourProfile;
 
-
-  {/* <div class="spinner-border text-secondary" role="status">
-  <span class="sr-only"></span>
-</div> */}

+ 11 - 2
shop/src/reducers/actionAuthLog.js

@@ -1,7 +1,16 @@
 import jwt_decode from "jwt-decode";
+import { useHistory } from "react-router";
 
 
 const actionAuthLogin = jwt => ({type: 'LOGIN', jwt})
-const actionAuthLogout = () => ({type: 'LOGOUT'})
+const actionAuthLogout = () =>  ({type: 'LOGOUT'})
 
-export {actionAuthLogin, actionAuthLogout};
+
+const NewAuth = (jwt) => {
+    return async dispatch => {
+        dispatch(actionAuthLogin(jwt));
+    }
+}
+
+
+export {actionAuthLogin, actionAuthLogout, NewAuth};

+ 10 - 3
shop/src/reducers/actionLogin.js

@@ -1,25 +1,32 @@
 import {Provider, connect} from 'react-redux';
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import thunk from 'redux-thunk';
-import {actionPromise, actionAuthLogout, actionAuthLogin, gql} from "./index"
+import {actionPromise, actionAuthLogout, actionAuthLogin, gql, actionUserFindOne} from "./index"
 import { useEffect } from 'react';
 
 
 
 const actionLogin = (login, password) => 
 
-async dispatch => {
+ async dispatch => {
 
     const res = gql(
         `query login($login:String, $password:String){
           login(login:$login,password:$password)
         }`, { login, password } );
 
+    // let loginData = await dispatch(actionPromise('login', res))
+
+
     let loginData = await dispatch(actionPromise('login', res))
 
 
+
     if (loginData && loginData.data && loginData.data.login){
-        dispatch(actionAuthLogin(loginData.data.login))
+
+         dispatch(actionAuthLogin(loginData.data.login));
+         //dispatch(actionUserFindOne(loginData.data.login.sub._id))
+
     }
 }
 

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

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

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

@@ -21,10 +21,10 @@ function authReducer(state, action){
         return {token: action.jwt, payload: jwt_decode(action.jwt)}
     }
     if (action.type === 'LOGOUT'){
-        console.log('ЛОГАУТ')
+
         localStorage.removeItem("authToken");
         
-        // localStorage.removeItem("basket");
+        localStorage.removeItem("basket");
         return {}
     }
     return state