Browse Source

searchUsers done

maryluis 3 years ago
parent
commit
06c883f54f

+ 31 - 0
shop/src/App.css

@@ -300,6 +300,34 @@ button {
   width: 250px;
 }
 
+.usersList {
+  display: flex;
+  width: 20%;
+  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%;
+}
+.oneUser {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  width: 100%;
+  margin: 10px;
+  border-bottom: 2px dotted rgb(229, 229, 243);
+}
+.oneUser a {
+  display: flex;
+  justify-content: space-around;
+  width: 100%;
+}
+.usersList img {
+  width: 30px;
+}
+
 .updateWrapper {
   display: flex;
   flex-direction: column;
@@ -447,6 +475,9 @@ button {
   .updateImg input{
     width: 250px;
   }
+  .usersList {
+    width: 100%;
+  }
   .order {
     padding-left: 10px;
     padding-right: 10px;

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

@@ -8,7 +8,7 @@ import store from "../reducers";
 import Catalog from "./catalog";
 import {actionCatalogCard, CBasketPage, searchInput, CGoodsCategory, 
     SearchInput, CGoodsSearch, LoginForm, CGoodCard, CYourProfile,
-    COrderPage} from "./index";
+    COrderPage, CUsersList} from "./index";
 
 
   
@@ -40,6 +40,7 @@ const Main = ({className = "MainImg" }) => {
                         <Route path = "/good/:id" component = {({match}) => <CGoodCard id = {match.params.id}/>}/>
                         <Route path = "/order" component = {COrderPage}/>
                         <Route path = "/login" component = {LoginForm}/>
+                        <Route path = "/searchUser/:users" component = {CUsersList}/>
                         <Route path = "/profile/:login" component = {CYourProfile}/>
                         <Route path = "/basket" component = {CBasketPage}/>
                         <Route path="/about" component = {About} exact/>

File diff suppressed because it is too large
+ 11 - 9
shop/src/components/footer.js


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

@@ -10,7 +10,7 @@ import Links from "./links"
 import CGoodsCategory from "./goodsCategory";
 import OneGood from './oneGood';
 import CGoodsList from "./goodsList";
-import SearchInput from "./searchInput";
+import {SearchInput, SearchUserInput} from "./searchInput";
 import CGoodsSearch from "./goodsSearch";
 import CGoodsListSearch from "./goodsListSearch";
 import GoodsNotFound from "./goodsNotFound";
@@ -20,11 +20,12 @@ import CUpdateForm from "./updateForm";
 import CYourProfile from "./profilePage";
 import CBasketPage from "./basket";
 import COrderPage from "./orderDonePage";
+import CUsersList from "./usersList";
 
 
 
 export {Header,Footer, actionCatalogCard, Main, Links, CGoodsCategory, OneGood, CGoodsList, SearchInput, CGoodsSearch, CGoodsListSearch, GoodsNotFound, 
-LoginForm, CGoodCard, CUpdateForm, CYourProfile, CBasketPage, COrderPage};
+LoginForm, CGoodCard, CUpdateForm, CYourProfile, CBasketPage, COrderPage, CUsersList, SearchUserInput};
 
 
 

+ 13 - 12
shop/src/components/profilePage.js

@@ -1,23 +1,33 @@
-import {CUpdateForm} from "./index";
+import {CUpdateForm, CUsersList, SearchUserInput} from "./index";
 import {gql, urlUpload, actionPromise, actionGoodCard, getGoods,
     actionUserFindOne, updateImgAction} 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';
+
 
 const YourProfile = ({state, data, getData, match:{params:{login}}}) => {
      useEffect(() =>  getData(`${login}`),[login])
      const date = new Date(data ? +data.createdAt : 0);
      const [showUpdate, onShow] = useState(false);
-     const [isUpdate, onUpdate] = useState(false);
+     const [searchInput, changeValue] = useState("Пошук");
+     const history = useHistory();
      //console.log(data)
      if(data){
         return (
             <>
+            <div className = "userSearch">
+                <input type = "text" placeholder = "Пошук юзера" onChange = {e => changeValue(e.target.value)} onKeyDown = {(e) => e.keyCode == 13 && history.push(`/searchUser/${searchInput}`)}/>
+                <Link to = {"/searchUser/" + searchInput}>
+                    <button>Пошук</button>
+                </Link>
+            </div>
+
                 <div className = "profilePage">
                     <h2>Привіт, {data.nick || "людино"}!</h2>
-                    <img src={data.avatar ? data.avatar : 'https://pngicon.ru/file/uploads/picca-1.png'} />
+                    <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>
@@ -48,21 +58,12 @@ const mapStateToProps = 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
   });
 
 
   
   const mapDispatchToProps = dispatch => bindActionCreators({
     getData: actionUserFindOne,
-    // onDel: actionCartDelete,
-    // onClear: actionCartClear,
-    // onOrder: actionOrder
   }, dispatch);
 
 const CYourProfile = connect(mapStateToProps, mapDispatchToProps)

+ 15 - 1
shop/src/components/searchInput.js

@@ -22,5 +22,19 @@ const SearchInput = ({ classname = "search", input = "Пошук"}) => {
     )
   }
 
+  const SearchUserInput = ({}) => {
+    const history = useHistory();
+    const [searchInput, changeValue] = useState("Пошук");
+    return (
+    <div className = "userSearch">
+      <input type = "text" placeholder = "Пошук юзера" onChange = {e => changeValue(e.target.value)} onKeyDown = {(e) => e.keyCode == 13 && history.push(`/searchUser/${searchInput}`)}/>
+      <Link to = {"/searchUser/" + searchInput}>
+          <button>Пошук</button>
+      </Link>
+    </div>
+    )
+
+
+  }
 
-  export default SearchInput;
+  export {SearchInput, SearchUserInput};

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

@@ -13,6 +13,7 @@ const UpdateForm = ({updateImg, updateUser, id}) => {
     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);
@@ -28,7 +29,7 @@ const UpdateForm = ({updateImg, updateUser, id}) => {
       <form className = "updateImg" action="/upload" method="post" enctype="multipart/form-data" id='form' ref={formRef} 
       onChange = {
         () => {
-          updateImg(formRef);
+          updateImg(formRef, getImage);
           changeImg(true);
       }}>
         <input type="file"  name="photo" id='photo'/>

+ 64 - 0
shop/src/components/usersList.js

@@ -0,0 +1,64 @@
+import { connect } from "react-redux";
+import { actionSearchUser, urlUpload } from "../reducers";
+import { useEffect, useState, useRef } from "react";
+import {SearchUserInput} from "./index";
+import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
+import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
+
+
+const OneUserIcon = ({nick, img, login, id}) => {
+
+    return(
+        <>
+            <div className = "oneUser">
+                <Link to = {"/profile/" + login }>
+                    <img src={img ? img : 'https://pngicon.ru/file/uploads/picca-1.png'} />
+                    <h5>{nick || login}</h5>
+                </Link>
+            </div>
+        </>
+    )
+}
+
+const UsersList = ({match:{params:{users}}, state, getData, usersList}) => {
+    useEffect(() =>  getData(`${users}`),[users]);
+    console.log(state)
+    if(usersList) {
+    return(
+        <>
+            <SearchUserInput/>
+           
+
+            <div className = "usersList">
+                {usersList.map((user) => 
+                    
+                    <OneUserIcon nick = {user.nick} login = {user.login} img = {user.avatar ? (`${urlUpload}/${user.avatar.url}`) : ('https://pngicon.ru/file/uploads/picca-1.png')}/>
+                )}
+            </div>
+        
+        </>
+    )} else {
+        return  (
+        <>
+         <SearchUserInput/>
+        </>
+        )
+    }
+}
+
+const mapStateToProps = state => ({
+    state: state,
+    usersList: state.promiseRed && state.promiseRed.FoundUser &&
+    state.promiseRed.FoundUser.payload && state.promiseRed.FoundUser.payload.data &&
+    state.promiseRed.FoundUser.payload.data.UserFind
+ });
+
+
+ 
+ const mapDispatchToProps = dispatch => bindActionCreators({
+   getData: actionSearchUser,
+ }, dispatch);
+
+ const CUsersList = connect(mapStateToProps, mapDispatchToProps)(UsersList);
+
+ export default CUsersList;

+ 36 - 0
shop/src/reducers/actionSearchUser.js

@@ -0,0 +1,36 @@
+import {actionPromise, gql} from "./index";
+
+
+let toRegexp = (str) => {
+    str = str.replace(/ +/g, " ").trim();
+    str = "/" + str.split(" ").join("|") + "/";
+    return str;
+  };
+  
+  let toQuery = (str, fields = ["login", "nick", "_id"]) => {
+    str = toRegexp(str);
+    let arr = fields.map((s) => {
+        console.log(s, typeof s);
+        return { [s]: str };
+    });
+    return { $or: arr };
+  };
+
+  function  actionSearchUser(queryString) {
+
+    return actionPromise("FoundUser", gql(
+        `query userOne($query: String) {
+            UserFind(query: $query){
+              login
+              _id
+              createdAt
+                  avatar {_id url}
+              acl
+              nick
+            }
+          }`, {query: JSON.stringify([toQuery(queryString)])}
+    ))
+      
+  }
+
+  export default actionSearchUser;

+ 24 - 5
shop/src/reducers/actionUpdateImg.js

@@ -1,16 +1,35 @@
 
 import {gql, urlUpload, actionPromise} from "./index";
 
+const actionImgOne = (_id) => {
+  const queryJson = JSON.stringify([{
+    "_id": `${_id}`
+  }]);
+  return (actionPromise('image', gql(
+    `query findImg($query: String)  {
+      ImageFindOne(query: $query) {
+        _id
+        createdAt
+        url
+      }
+    }`, {query: queryJson}
+  )))
+}
 
+ async function updateImgAction(ref, getData) {
+   debugger
+    let file = new FormData(ref.current);
 
- function updateImgAction(ref) {
- 
-    fetch(`${urlUpload}/upload`, {
+    await fetch(`${urlUpload}/upload`, {
       method: "POST",
       headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
-      body: new FormData(ref.current)
+      body: file
+    }).then(res => res.json()).then((res) => {
+        getData(res) 
     })
-    .then((res) => res.json())
+    // .then((res) => res.json()).then((res) => {
+    //   actionImgOne(res._id)
+    // })
   
   
   }    

+ 2 - 1
shop/src/reducers/actionsearch.js

@@ -20,7 +20,8 @@ let toRegexp = (str) => {
   
 
 function actionSearch(queryString) {
-    return actionPromise('search', gql(`query goods($query: String) {
+    return actionPromise('search', gql(
+      `query goods($query: String) {
         GoodFind(query: $query)  {
           name, price,
           images{url}, _id

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

@@ -15,7 +15,7 @@ import actionOrder from "./actionOrder";
 import actionReg from "./actionReg";
 import actionUserFindOne from "./actionFindOneUser";
 import actionUserUpdate from "./actionUserUpdate";
-
+import actionSearchUser from "./actionSearchUser";
 
 
 function promiseReducer(state={}, action){
@@ -41,7 +41,7 @@ function promiseReducer(state={}, action){
 export {actionPromise, gql, actionGoods, getGoods, promiseReducer, store, actionSearch,
    actionLogin, authReducer, actionAuthLogin, actionAuthLogout, urlUpload, actionGoodCard, 
    updateImgAction, actionCartAdd, actionCartDelete, actionCartClear, actionOrder,
-    actionReg, actionUserFindOne, actionUserUpdate};
+    actionReg, actionUserFindOne, actionUserUpdate, actionSearchUser};