ソースを参照

login works properly.Now loged in user can see orders list which is unavailable for unauthorized users

miskson 3 年 前
コミット
f5196b00ba
2 ファイル変更125 行追加29 行削除
  1. 11 7
      hw15-gql-cathegory-pg/GQL.html
  2. 114 22
      hw15-gql-cathegory-pg/GQL_files/index.js

+ 11 - 7
hw15-gql-cathegory-pg/GQL.html

@@ -42,6 +42,14 @@
       margin: 10px;
       padding : 10px;
     }
+
+    .linkDeco {
+      color: white;
+      background-color: purple;
+      padding: 0px 5px;
+      text-decoration: none;
+      margin: 0 10px;
+    }
   </style>
   <style type="text/css"></style>
 </head>
@@ -58,13 +66,9 @@
       </div>
       <a 
         href="#/cart" 
-        id="cartBtn" 
-        style="
-          color: white;
-          background-color: purple;
-          padding: 0px 5px;
-          text-decoration: none;
-        ">
+        id="cartBtn"
+        class="linkDeco"
+      >
       в корзину <span id="itemCount" style="color: gold;"></span>
       </a>
     </nav>

+ 114 - 22
hw15-gql-cathegory-pg/GQL_files/index.js

@@ -163,6 +163,26 @@ const actionFullLogin = (login, password) =>
         }
     }
 
+const actionGetOrders = () =>
+    actionPromise('orders', gql(`
+    query ord {
+        OrderFind(query:"[{}]"){
+          _id
+          orderGoods {
+            price 
+            count 
+            total 
+            good{
+              name
+              _id
+              images {
+                  url
+              }
+            }
+          }
+        }
+      }
+    `))
 //const actionRegister //actionPromise
 //const actionFullRegister = (login, password) => //actionRegister + actionFullLogin
 //+ интерфейс к этому - форму логина, регистрации, может повесить это на #/login #/register 
@@ -174,7 +194,7 @@ let logBtn = document.getElementById('logBtn')
 /********************************MY STUFFF END****************************************************** */
 
 /********************************MY STUFFF CART START****************************************************** */
-function cartReducer(state = {}, { type, good={}, count = 1 }) {
+function cartReducer(state = {}, { type, good = {}, count = 1 }) {
     //{
     //  _id1: {good, count}
     //  _id2: {good, count}
@@ -213,7 +233,7 @@ function cartReducer(state = {}, { type, good={}, count = 1 }) {
 //понаписывать action
 //прикрутить к товару кнопку которая делает store.dispatch(actionCartAdd(good))
 const actionCartAdd = (good, count = 1) => ({ type: 'CART_ADD', good, count })
-const actionCartDel = (good, count = 1) => ({ type: 'CART_REMOVE', good, count})
+const actionCartDel = (good, count = 1) => ({ type: 'CART_REMOVE', good, count })
 
 /********************************MY STUFFF CART END****************************************************** */
 const actionRootCats = () =>
@@ -287,20 +307,22 @@ window.onhashchange = () => {
             navBar.style.visibility = 'hidden'
 
             let pass, log
+            console.log('login')
             aside.innerHTML = ''
             main.innerHTML = `
                 <div style="border: 5px solid purple; padding: 10px; background-color: black;">
                     <button id="returnBtnLogin" style="font-size: small;">&#8656 назад</button>
-                    <input  id="logInp" style="font-size: small; display:block; margin:10px" type="text" placeholder="login"/>
-                    <input  id="passInp" style="font-size: small; display:block; margin:10px" type="text" placeholder="password"/>
+                    <input  id="logInp" style="font-size: small; display:block; margin:10px" type="text" placeholder="Логин"/>
+                    <input  id="passInp" style="font-size: small; display:block; margin:10px" type="password" placeholder="Пароль"/>
                     <small id="errBox" style="display: block; width:fit-content; color: red; margin: 0 auto;"></small>
-                    <button id="submitBtn" style="font-size: small; display:block; margin:0 auto">LOGIN</button>
+                    <button id="submitBtn" style="font-size: small; display:block; margin:0 auto">ВОЙТИ</button>
                 </div>
             `
             let returnBtn = document.getElementById('returnBtnLogin')
             let logInp = document.getElementById('logInp')
             let passInp = document.getElementById('passInp')
             let submitBtn = document.getElementById('submitBtn')
+            let errBox = document.getElementById('errBox')
 
             passInp.oninput = (e) => { pass = e.target.value }
 
@@ -312,11 +334,23 @@ window.onhashchange = () => {
             }
 
             submitBtn.onclick = () => {
-                store.dispatch(actionFullLogin(log, pass))
+                if (log && pass) {
+                    (async () => {
+                        await store.dispatch(actionFullLogin(log, pass))
+                        aside.innerHTML = ``
+
+                        if (store.getState().auth.payload) {
+                            errBox.innerText = ''
+                            store.dispatch(actionGetOrders())
+                        } else {
+                            errBox.innerText = 'Неправильный логин или пароль'
+                        }
+                    })();
+                }
             }
         },
         cart() {
-            const {cart} = store.getState()
+            const { cart } = store.getState()
             aside.innerHTML = ''
             main.innerHTML = `
                 <button onclick="history.back()" style="font-size: smaller;">&#8656 назад</button>
@@ -331,7 +365,7 @@ window.onhashchange = () => {
             }
 
             let fullPrice = 0
-            for(let item in cart) {
+            for (let item in cart) {
                 let orderPrice = cart[item].good.price * cart[item].count
                 let card = document.createElement('div')
                 fullPrice += orderPrice
@@ -364,7 +398,7 @@ window.onhashchange = () => {
                     <a href="#/good/${cart[item].good._id}">На страницу товара</a>
                     <br>
                 `)
-                
+
                 card.style.backgroundColor = "whitesmoke"
                 card.style.border = "1px solid black"
                 card.style.margin = "10px"
@@ -374,6 +408,50 @@ window.onhashchange = () => {
             console.log('full prise', fullPrice)
             let fullPriceSpan = document.getElementById('fullPrice')
             fullPriceSpan.innerText = `${fullPrice}`
+        },
+        orders() {
+            aside.innerHTML = ''
+            main.innerHTML = `
+                <button onclick="history.back()" style="font-size: smaller;">&#8656 назад</button>
+                <h2>Список заказов ${store.getState().auth.payload.sub.login}</h2>
+                <br>
+            `
+
+            if (store.getState().promise.orders) {
+                const payload = store.getState().promise.orders.payload
+                if (payload.length > 0) {
+                    for (let { orderGoods } of payload) {
+                        for (let item of orderGoods) {
+                            try {
+                                let card = document.createElement('div')
+                                card.insertAdjacentHTML('beforeend', `
+                                    <br>
+                                    <h2>${item.good.name}</h2>
+                                    <div style="border:5px solid mediumvioletred; background-color: black; color: white; padding: 0px 5px;">
+                                        <h4>Кол-во: ${item.count}</h4>
+                                        <h4>Стоимость заказа: ${item.total}</h4>
+                                    </div>
+                                    <br>
+                                    <img style="border: 1px dashed grey;" src="${backURL}/${item.good.images[0].url}" />
+                                    <br>
+                                    <strong>Цена за ед. товара: ${item.price}</strong>
+                                    <br>
+                                    <a href="#/good/${item.good._id}">На страницу товара</a>
+                                    <br>
+                                `)
+
+                                card.style.backgroundColor = "whitesmoke"
+                                card.style.border = "1px solid black"
+                                card.style.margin = "10px"
+                                card.style.padding = "10px"
+                                main.append(card)
+                            } catch (e) {
+                                console.log('nulls are ignored')
+                            }
+                        }
+                    }
+                }
+            }
         }
     }
     if (route in routes)
@@ -433,7 +511,6 @@ store.subscribe(() => {
                 card.append(cartButton)
 
                 cartButton.onclick = () => {
-                    console.log('nuaaaaaa', good)
                     store.dispatch(actionCartAdd(good))
                 }
             }
@@ -465,27 +542,32 @@ store.subscribe(() => {
 })
 
 store.subscribe(() => {
-    const {payload} = store.getState().auth
+    const { payload } = store.getState().auth
     const [, route, _id] = location.hash.split('/')
-    
+
     let logBtn = document.getElementById('logBtn')
     let logLink = document.getElementById('logLink')
     let nameField = document.getElementById('nameField')
-    if(!payload) {
+    let navBar = document.getElementById('navBar')
+
+    if (!payload) {
         nameField.innerText = ''
         logBtn.style.backgroundColor = 'mediumaquamarine'
         logLink.innerText = 'Войти'
+        logBtn.onclick = () => {/*killing onclick login action*/ }
+        try {
+            let orderBtn = document.getElementById('orderBtn')
+            navBar.removeChild(orderBtn)
+        } catch (e) { }
 
-    } else if(payload && route === 'login') {
-        console.log('loginPayload', payload)
+    } else if (payload && route === 'login') {
+        aside.innerHTML = ``
         main.innerHTML = `
             <h2>Вы успешно вошли под логином пользователя '${payload.sub.login}'<h2>
             <button id="returnBtn">&#8656 Венуться к просмотру</button>
         `
-
         let retBtn = document.getElementById('returnBtn')
         retBtn.onclick = () => {
-            let navBar = document.getElementById('navBar')
             navBar.style.visibility = 'visible'
             history.back()
         }
@@ -494,20 +576,28 @@ store.subscribe(() => {
         nameField.innerText = payload.sub.login
         logBtn.style.backgroundColor = 'firebrick'
         logBtn.innerHTML = 'Выйти'
+        if (!document.getElementById('orderBtn')) {
+            let orderBtn = document.createElement('a')
+            orderBtn.href = '#/orders'
+            orderBtn.id = 'orderBtn'
+            orderBtn.innerText = 'список заказов'
+            orderBtn.className = 'linkDeco'
+            navBar.append(orderBtn)
+        }
         logBtn.onclick = () => {
             nameField.innerText = ''
             logBtn.style.backgroundColor = 'mediumaquamarine'
             logBtn.innerHTML = `<a href="#/login" style="color: white; text-decoration: none;" id="logLink">Войти</a>`
-            actionAuthLogout()
+            store.dispatch(actionAuthLogout())
+            store.dispatch(actionGetOrders())
         }
-        
     }
 })
 
-store.subscribe(()=> {
-    const {cart} = store.getState()
+store.subscribe(() => {
+    const { cart } = store.getState()
     let items = 0
-    for(let item in cart) {
+    for (let item in cart) {
         items += cart[item].count
     }
     let itemCount = document.getElementById('itemCount')
@@ -515,5 +605,7 @@ store.subscribe(()=> {
 })
 
 window.onload = () => {
+    console.log('RELOADED')
     location.href = "#/category/5dc49f4d5df9d670df48cc64"
+    store.dispatch(actionGetOrders())
 }