Emmanuil преди 4 години
родител
ревизия
499fd72242

+ 50 - 16
myproject/src/myProfile/chatGroups/actionChatGroup/actionChatGroup.js

@@ -31,7 +31,7 @@ import { actionPromise, store } from "../../../store/store";
 
 // const handleClick = () => history.push("/my_profile")
 
-const getGQL = (url, headers = {}) => (query = "") =>
+const getGQL = (url, headers = {}) => (query = "", variables = {}) =>
   fetch(url, {
     method: "POST",
     headers: {
@@ -39,30 +39,43 @@ const getGQL = (url, headers = {}) => (query = "") =>
       "Content-Type": "application/json",
       ...headers,
     },
-    body: JSON.stringify({ query }),
-  })
-  // .then((res) => console.log(res))
-    .then((res) => res.json())
-    // .then((a) => console.log(a));
+    body: JSON.stringify({ query, variables }),
+  }).then((res) => res.json());
 
-const actionChatGroupPromise = () => {
+// const actionChatGroupPromise = () => {
+//   var promise = getGQL("http://localhost:3330/graphql")(
+//     `query allChatGroup{
+//       getAllChatGroups {
+//         id, inId {
+//           id, login
+//         }, outId {
+//           id, login
+//         }
+//       }
+//     }`
+//   );
+//   return actionPromise("chatGroup", promise);
+// };
+
+const actionChatGroupPromise = (id) => {
   var promise = getGQL("http://localhost:3330/graphql")(
-    `query allChatGroup{
-      getAllChatGroups {
-        id, inId {
+    `query allMessOneUser($id: ID!){
+      getAllChatGroupsOneUser(id: $id){
+        id, autorId{
           id, login
-        }, outId {
+        }, partnerId {
           id, login
         }
       }
-    }`
+    }`,
+    { id }
   );
   return actionPromise("chatGroup", promise);
 };
 
-const actionChatGroup = () => {
+const actionChatGroup = (id) => {
   return async (dispatch) => {
-    var token = await dispatch(actionChatGroupPromise());
+    var token = await dispatch(actionChatGroupPromise(id));
     // console.log(token);
     // if (token === undefined) await dispatch(actionLoginPromise1(login, password))
     // if(token) history.push("/my_profile")
@@ -73,7 +86,9 @@ const actionMessagePromise = () => {
   var promise = getGQL("http://localhost:3330/graphql")(
     `query allMessage{
       getAllMessages {
-        id, message, inId {
+        id, message, autorId {
+          id, login
+        }, partnerId {
           id, login
         }
       }
@@ -89,4 +104,23 @@ const actionMessage = () => {
   };
 };
 
-export { actionChatGroup, actionMessage };
+const actionUsersPromise = (email) => {
+  var promise = getGQL("http://localhost:3330/graphql")(
+    `query find($email: String) {
+      getUser(email: $email) {
+        id, email, login
+      }
+    }`,
+    { email }
+  );
+  return actionPromise("users", promise);
+};
+
+const actionUsers = (email) => {
+  return async (dispatch) => {
+    var token = await dispatch(actionUsersPromise(email));
+    // console.log(token);
+  };
+};
+
+export { actionChatGroup, actionMessage, actionUsers };

+ 1 - 1
myproject/src/myProfile/chatGroups/chatGroups.js

@@ -31,7 +31,7 @@ const ChatGroups = ({ id, login, state }) => {
 
   return (
     <>
-      <div className="groups" onClick={() => console.log(id)}>
+      <div className="groups" >
         <div className="avatar">
           {/* <img src={props.src} /> */}
           <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" />

+ 36 - 0
myproject/src/myProfile/chatMessages/actionMessages/actionMessages.js

@@ -0,0 +1,36 @@
+import { actionPromise, store } from "../../../store/store";
+
+const getGQL = (url, headers = {}) => (query = "", variables = {}) =>
+  fetch(url, {
+    method: "POST",
+    headers: {
+      Accept: "application/json",
+      "Content-Type": "application/json",
+      ...headers,
+    },
+    body: JSON.stringify({ query, variables }),
+  }).then((res) => res.json());
+
+const actionMessagePromise = () => {
+  var promise = getGQL("http://localhost:3330/graphql")(
+    `query allMessage{
+      getAllMessages {
+        id, message, autorId {
+          id, login
+        }, partnerId {
+          id, login
+        }
+      }
+    }`
+  );
+  return actionPromise("message", promise);
+};
+
+const actionMessage = () => {
+  return async (dispatch) => {
+    var token = await dispatch(actionMessagePromise());
+    // console.log(token);
+  };
+};
+
+export { actionMessage };

+ 10 - 2
myproject/src/myProfile/chatMessages/chatMessages.css

@@ -5,15 +5,23 @@
   padding-bottom: 15px;
 }
 
-.messagePartner {
+.chatMessages {
   padding: 15px 100px;
   height: 85%;
 }
 
-.message {
+.messagesBlock {
   height: 100%;
 }
 
+.messageAutor {
+  color: red;
+}
+
+.messagePartner {
+  color: green;
+}
+
 .sendMessage {
   text-align: center;
 }

+ 75 - 14
myproject/src/myProfile/chatMessages/chatMessages.js

@@ -1,22 +1,83 @@
-import React, { useState } from "react";
+import React, { useState, Component } from "react";
+import { connect } from "react-redux";
+
+import { actionMessage } from "./actionMessages/actionMessages";
 import "./chatMessages.css";
 
-const ChatMessage = (props) => {
-  // debugger
+const Messages = ({ id, login, message, autor, partner }) => {
+  localStorage.setItem("login", login);
   return (
-    <>
-      <div className="loginPartner">
-        {/* {props.message[0].idSendUser} */}
-        </div>
+    <div className="messages">
+      <div className="messageAutor">
+        {+localStorage.getItem("id") === autor.id ? message : console.log("hi")}
+      </div>
+
       <div className="messagePartner">
-        <div className="message">jkdflgdfl/gkdf;</div>
-        <div className="sendMessage">
-          <input />
-          <button>Send</button>
-        </div>
+        {+localStorage.getItem("id") === partner.id
+          ? message
+          : console.log("hi")}
       </div>
-    </>
+    </div>
   );
 };
 
-export default ChatMessage
+class ChatMessageInfo extends Component {
+  way(obj, resolverName, a) {
+    const stateObj = this.props.state[obj];
+    for (var keys in stateObj) {
+      for (var keyData in stateObj[keys]) {
+        if (keyData === "data") {
+          const allObj = stateObj[keys][keyData][resolverName];
+          console.log(allObj);
+          if (allObj) return allObj.map(a);
+        }
+      }
+    }
+  }
+
+  render() {
+    return (
+      <>
+        <div className="loginPartner">{localStorage.getItem("login")}</div>
+        <div className="chatMessages">
+          <div className="messagesBlock">
+            {this.way("message", "getAllMessages", (el) => (
+              <Messages
+                key={el.id}
+                id={
+                  +localStorage.getItem("id") !== el.autorId.id
+                    ? el.autorId.id
+                    : el.partnerId.id
+                }
+                message={el.message}
+                autor={el.autorId}
+                partner={el.partnerId}
+                login={
+                  +localStorage.getItem("id") !== el.autorId.id
+                    ? el.autorId.login
+                    : el.partnerId.login
+                }
+              />
+            ))}
+          </div>
+
+          <div className="sendMessage">
+            <input />
+            <button>Send</button>
+          </div>
+        </div>
+      </>
+    );
+  }
+}
+
+const ChatMessage = () => <ConnectedChatMessage />;
+
+const ConnectedChatMessage = connect(
+  (state) => {
+    return { state };
+  },
+  { message: actionMessage }
+)(ChatMessageInfo);
+
+export default ChatMessage;

+ 20 - 0
myproject/src/myProfile/myProfile.css

@@ -101,3 +101,23 @@
   width: 100%;
   padding-top: 15px;
 }
+
+.createChat {
+  transition: all 0.3s;
+}
+
+.createChat:hover {
+  color: #339cfd;
+}
+
+.create {
+  background: green;
+  padding: 50px;
+  position: absolute;
+  top: 30%;
+  left: 40%;
+}
+
+.search {
+  outline: none;
+}

+ 69 - 50
myproject/src/myProfile/myProfile.js

@@ -4,11 +4,21 @@ import { connect } from "react-redux";
 import "./myProfile.css";
 
 import ChatGroupsBar from "./chatGroups/chatGroups";
-import ChatMessages from "./chatMessages/chatMessages";
+import ChatMessage from "./chatMessages/chatMessages";
 import {
   actionChatGroup,
   actionMessage,
+  actionUsers,
 } from "./chatGroups/actionChatGroup/actionChatGroup";
+import history from "../history";
+
+const Create = () => {
+  return (
+    <div className="create">
+      <input type="text" />
+    </div>
+  );
+};
 
 class MyProfile1 extends Component {
   constructor(props) {
@@ -16,54 +26,34 @@ class MyProfile1 extends Component {
     this.state = { text: "" };
   }
 
-  // chatGroups() {
-  //   const stateChatGroup = this.props.state.chatGroup;
-  //   for (var keys in stateChatGroup) {
-  //     for (var keyData in stateChatGroup[keys]) {
-  //       if (keyData === "data") {
-  //         const allChatGroups = stateChatGroup[keys][keyData].getAllChatGroups;
-  //         return allChatGroups.map((el) => (
-  //           <ChatGroupsBar key={el.id} id={el.id} login={el.inId.login} />
-  //         ));
-  //       }
-  //     }
-  //   }
-  // }
-
-  // chatGroupsMessage() {
-  //   const stateMessages = this.props.state.message;
-  //   for (var keys in stateMessages) {
-  //     for (var keyData in stateMessages[keys]) {
-  //       if (keyData === "data") {
-  //         const allMessages = stateMessages[keys][keyData].getAllMessages;
-  //         return allMessages.map((el) => (
-  //           <ChatMessages
-  //             key={el.id}
-  //             id={el.id}
-  //             login={el.inId.login}
-  //             message={el.message}
-  //           />
-  //         ));
-  //       }
-  //     }
-  //   }
-  // }
-
   way(obj, resolverName, a) {
     const stateObj = this.props.state[obj];
     for (var keys in stateObj) {
       for (var keyData in stateObj[keys]) {
         if (keyData === "data") {
           const allObj = stateObj[keys][keyData][resolverName];
-          console.log(allObj);
-          return allObj.map(a);
+          if (allObj) return allObj.map(a);
+        }
+      }
+    }
+  }
+
+  way1(obj, resolverName) {
+    const stateObj = this.props.state[obj];
+    for (var keys in stateObj) {
+      for (var keyData in stateObj[keys]) {
+        if (keyData === "data") {
+          const allObj = stateObj[keys][keyData][resolverName];
+          if (allObj)
+            return <ChatGroupsBar id={allObj.id} login={allObj.login} />;
         }
       }
     }
   }
 
   componentDidMount() {
-    this.props.chatGroup();
+    const a = localStorage.getItem("id");
+    this.props.chatGroup(a);
     this.props.message();
   }
 
@@ -78,35 +68,60 @@ class MyProfile1 extends Component {
                   <TeamOutlined />
                   <span className="span">Список чатов</span>
                 </div>
-                <FormOutlined />
+                <FormOutlined className="createChat" onClick={() => {}} />
               </div>
 
               <div className="search-input">
                 <input
                   value={this.state.text}
                   onChange={(e) => this.setState({ text: e.target.value })}
-                  placeholder="Поиск..."
+                  placeholder="Введите E-mail"
+                />
+                <SearchOutlined
+                  className="search"
+                  onClick={() => this.props.users(this.state.text)}
                 />
-                <SearchOutlined />
               </div>
             </div>
 
             <div className="chat-groups">
-              {this.way("chatGroup", "getAllChatGroups", (el) => (
-                <ChatGroupsBar key={el.id} id={el.id} login={el.outId.login} />
-              ))}
+              {this.way1("users", "getUser") ||
+                this.way("chatGroup", "getAllChatGroupsOneUser", (el) => (
+                  // <div onClick={() => history.push(`/my_profile/${el.id}`)}>
+                  <ChatGroupsBar
+                    key={el.id}
+                    id={el.id}
+                    login={
+                      +localStorage.getItem("id") !== el.autorId.id
+                        ? el.autorId.login
+                        : el.partnerId.login
+                    }
+                  />
+                  // </div>
+                ))}
             </div>
           </div>
-
+          {/* <Create /> */}
           <div className="chat-messages">
-            {this.way("message", "getAllMessages", (el) => (
+            <ChatMessage />
+            {/* {this.way("message", "getAllMessages", (el) => (
               <ChatMessages
                 key={el.id}
-                id={el.id}
-                login={el.inId.login}
+                id={
+                  +localStorage.getItem("id") !== el.autorId.id
+                    ? el.autorId.id
+                    : el.partnerId.id
+                }
                 message={el.message}
+                autor={el.autorId}
+                partner={el.partnerId}
+                login={
+                  +localStorage.getItem("id") !== el.autorId.id
+                    ? el.autorId.login
+                    : el.partnerId.login
+                }
               />
-            ))}
+            ))} */}
           </div>
         </div>
       </div>
@@ -114,13 +129,17 @@ class MyProfile1 extends Component {
   }
 }
 
-const MyProfile = (props) => <ConnectedChatGroups />;
+const MyProfile = () => <ConnectedChatGroups />;
 
 const ConnectedChatGroups = connect(
   (state) => {
     return { state };
   },
-  { chatGroup: actionChatGroup, message: actionMessage }
+  {
+    chatGroup: actionChatGroup,
+    message: actionMessage,
+    users: actionUsers,
+  }
 )(MyProfile1);
 
 export default MyProfile;

+ 1 - 1
myproject/src/signIn/actionLogin/actionLogin.js

@@ -75,7 +75,7 @@ const actionLogin = (login, password) => {
     var token = await dispatch(actionLoginPromise(login, password));
     console.log(token);
     // if (token === undefined) await dispatch(actionLoginPromise1(login, password))
-    // if(token) history.push("/my_profile")
+    if(token) history.push("/my_profile")
   };
 };
 

+ 123 - 7
myproject/src/signIn/signIn.js

@@ -1,4 +1,4 @@
-import React, { useState } from "react";
+import React, { useState, Component } from "react";
 import { Link } from "react-router-dom";
 import { connect } from "react-redux";
 import {
@@ -12,6 +12,7 @@ import jwtDecode from "jwt-decode";
 import { actionLogin } from "./actionLogin/actionLogin";
 import history from "../history";
 import { actionChatGroup } from "../myProfile/chatGroups/actionChatGroup/actionChatGroup";
+import MyProfile from "../myProfile/myProfile";
 import "./signIn.css";
 
 const loginEye = () => {
@@ -33,7 +34,7 @@ const loginEye = () => {
 const LoginForm = ({ onLogin, backError, state }) => {
   const [login, setLogin] = useState("");
   const [password, setPassword] = useState("");
-
+  
   const way = (obj, resolverName, a) => {
     const stateObj = state[obj];
     for (var keys in stateObj) {
@@ -41,8 +42,10 @@ const LoginForm = ({ onLogin, backError, state }) => {
         if (keyData === "data") {
           const allObj = stateObj[keys][keyData][resolverName];
           if (allObj) {
-            const x = jwtDecode(allObj);
-            // return x.sub.email;
+            var x = jwtDecode(allObj);
+            localStorage.setItem("id", x.sub.id);
+            localStorage.setItem("email", x.sub.email);
+            localStorage.setItem("login", x.sub.login);
           } else {
             return (
               <div className="error">
@@ -54,7 +57,7 @@ const LoginForm = ({ onLogin, backError, state }) => {
       }
     }
   };
-
+// console.log(localStorage.getItem("id"));
   const buttonEnter = (e) => {
     if (e.key === "Enter") onLogin(login, password);
   };
@@ -96,7 +99,7 @@ const LoginForm = ({ onLogin, backError, state }) => {
             <EyeOutlined />
           </div>
         </div>
-        
+
         {way("login", "getLogin")}
 
         <button
@@ -116,13 +119,126 @@ const LoginForm = ({ onLogin, backError, state }) => {
   );
 };
 
+// class LoginForm extends Component  {
+//   constructor(props) {
+//     super(props);
+//     this.state = { login: "", password: "" };
+//     // console.log(this.props);
+//   }
+
+//    way (obj, resolverName, a)  {
+//     const stateObj = this.props.state[obj];
+//     for (var keys in stateObj) {
+//       for (var keyData in stateObj[keys]) {
+//         if (keyData === "data") {
+//           const allObj = stateObj[keys][keyData][resolverName];
+//           if (allObj) {
+//             var x = jwtDecode(allObj);
+//             // return x.sub.email;
+//             // console.log(x);
+//           } else {
+//             return (
+//               <div className="error">
+//                 <p>Неверный логин или пароль, попробуйте заново.</p>
+//               </div>
+//             );
+//           }
+//         }
+//       }
+//     }
+//   };
+
+//   way1 (obj, resolverName, a)  {
+//     const stateObj = this.props.state[obj];
+//     for (var keys in stateObj) {
+//       for (var keyData in stateObj[keys]) {
+//         if (keyData === "data") {
+//           const allObj = stateObj[keys][keyData][resolverName];
+//           if (allObj) {
+//             var x = jwtDecode(allObj);
+//             return x.sub.email;
+//           }
+//         }
+//       }
+//     }
+//   };
+
+//   componentDidMount() {
+//     this.props.chatGroup("2");
+//     // this.props.message();
+//   }
+
+//   // buttonEnter (e) {
+//   //   if (e.key === "Enter") this.props.onLogin(login, password);
+//   // };
+
+//   // const handleClick = () => history.push("/my_profile");
+
+//   render(){
+//   return (
+//     <div className="login">
+//       <div className="login-form"
+//       // onKeyPress={buttonEnter}
+//       >
+//         <div className="login-title">
+//           <h2>Войти в аккаунт</h2>
+//           <p>Пожалуйста, войдите в свой аккаунт</p>
+//         </div>
+
+//         <div className="login-icon icon">
+//           <UserOutlined />
+//           <input
+//             id="login"
+//             value={this.state.login}
+//             placeholder="Логин"
+//             type="text"
+//             onChange={(e) => this.setState({ login: e.target.value })}
+//           />
+//         </div>
+
+//         <div className="password-icon icon">
+//           <LockOutlined />
+//           <input
+//             id="password"
+//             value={this.state.password}
+//             placeholder="Пароль"
+//             type="password"
+//             onChange={(e) => this.setState({ password: e.target.value })}
+//           />
+//           <div className="not-see" onClick={loginEye}>
+//             <EyeInvisibleOutlined />
+//           </div>
+//           <div className="see" onClick={loginEye}>
+//             <EyeOutlined />
+//           </div>
+//         </div>
+
+//         {this.way("login", "getLogin")}
+
+//         <button
+//           className="login-button"
+//           onClick={() => this.props.onLogin(this.state.login, this.state.password)}
+//           disabled={!this.state.login || !this.state.password}
+//         >
+//           Войти
+//         </button>
+
+//         <div className="register-put-password">
+//           <Link to="/sign_up">Зарегестрироваться</Link>
+//           <Link to="/put_password">Забыли пароль?</Link>
+//         </div>
+//       </div>
+//     </div>
+//   )}
+// };
+
 const Login = (props) => <ConnectedLoginForm />;
 
 const ConnectedLoginForm = connect(
   (state) => {
     return { state };
   },
-  { onLogin: actionLogin }
+  { onLogin: actionLogin, chatGroup: actionChatGroup }
 )(LoginForm);
 
 export default Login;

+ 24 - 9
server/index.js

@@ -92,7 +92,7 @@ const authenticate = async ({ login, password }) => {
 var schema = buildSchema(`
   type Query {
     getLogin(login: String, password: String): String
-    getUser(id: ID!): User
+    getUser(email: String): User
     getAllUsers: [User]
     getMessage(id: ID!): Message
     getAllMessages: [Message]
@@ -129,7 +129,7 @@ var schema = buildSchema(`
   }
 `);
 
-const getUser = async ({ id }) => await User.findByPk(id);
+const getUser = async ({ email }) => await User.findOne({ where: { email } });
 
 const getLogin = async ({ login, password }) => {
   const userFind = await User.findOne({ where: { login, password } });
@@ -223,23 +223,38 @@ const getAllChatGroupsOneUser = async ({ id }) => {
   for (var allUsers of foundAllChatGroups) {
     const autor = await User.findAll({ where: { id: allUsers.autorId } });
     const partner = await User.findAll({ where: { id: allUsers.partnerId } });
-    const m =
-      allUsers.autorId === autor[0].id || allUsers.autorId === partner[0].id;
     const ma = autor[0].id === +id || partner[0].id === +id;
 
-    if ((m === ma) === true) {
+    if (ma === true) {
       const y = await ChatGroup.findAll({ where: { autorId: id } });
       const u = await ChatGroup.findAll({ where: { partnerId: id } });
 
-      if (y && u) {
+      if ((y.length && u.length) !== 0) {
         const p = [...y, ...u];
         for (var key of p) {
+          const r = await User.findAll({ where: { id: key.autorId } });
+          const r1 = await User.findAll({ where: { id: key.partnerId } });
+          key.autorId = r[0];
+          key.partnerId = r1[0];
+        }
+        return p;
+      } else if (y.length !== 0) {
+        const pt = [...y];
+        for (var key of pt) {
+          const r = await User.findAll({ where: { id: key.partnerId } });
           key.autorId = autor[0];
+          key.partnerId = r[0];
+        }
+        return pt;
+      } else {
+        const ptu = [...u];
+        for (var key of ptu) {
+          const r = await User.findAll({ where: { id: key.autorId } });
+          key.autorId = r[0];
           key.partnerId = partner[0];
         }
-        return p;
-      } else if (y) return y;
-      else return u;
+        return ptu;
+      }
     } else console.log("bye");
   }
 };