Browse Source

Market done

Illia Kozyr 2 years ago
parent
commit
2853586a0f
3 changed files with 112 additions and 79 deletions
  1. 2 0
      HW 7/index.html
  2. 107 79
      Market GraphQL + Redux/script.js
  3. 3 0
      Market GraphQL + Redux/style.css

+ 2 - 0
HW 7/index.html

@@ -51,6 +51,8 @@
                     })
             );
 
+            
+
             tdarr.forEach(
                 (tdOut) =>
                     (tdOut.onmouseout = function () {

+ 107 - 79
Market GraphQL + Redux/script.js

@@ -102,7 +102,7 @@ const actionPromise = (name, promise) => async (dispatch) => {
 };
 
 function cartReducer(state = {}, { type, count = 1, good }) {
-    // type CART_ADD CART_REMOVE CART_CLEAR CART_DEC
+    // type CART_ADD CART_REMOVE CART_CLEAR CART_DEL
     // {
     //  id1: {count: 1, good: {name, price, images, id}}
     // }
@@ -114,18 +114,29 @@ function cartReducer(state = {}, { type, count = 1, good }) {
     }
 
     if (type === "CART_DELETE") {
-        return {
-            ...state,
-            [good._id]: { count: -count + (state[good._id]?.count || 0), good },
-        };
+        if (state[good._id].count > 1) {
+            return {
+                ...state,
+                [good._id]: {
+                    count: -count + (state[good._id]?.count || 0),
+                    good,
+                },
+            };
+        }
+
+        if (state[good._id].count === 1) {
+            let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
+            //delete newState[good._id]
+            return newState;
+        }
     }
 
     if (type === "CART_CLEAR") {
         return {};
     }
     if (type === "CART_REMOVE") {
-        //let newState = {...state}
-        let { [good._id]: poh, ...newState } = state; //o4en strashnoe koldunstvo
+        // let newState = {...state}
+        let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
         //delete newState[good._id]
         return newState;
     }
@@ -134,13 +145,9 @@ function cartReducer(state = {}, { type, count = 1, good }) {
 }
 
 const actionCartAdd = (good, count = 1) => ({ type: "CART_ADD", good, count });
-const actionCartChange = (good, count = 1) => ({
-    type: "CART_CHANGE",
-    good,
-    count,
-}); ///oninput меняяем полностью
 const actionCartDelete = (good) => ({ type: "CART_DELETE", good });
 const actionCartClear = () => ({ type: "CART_CLEAR" });
+const actionCartRemove = (good) => ({ type: "CART_REMOVE", good });
 
 function localStoreReducer(reducer, localStorageKey) {
     function localStoredReducer(state, action) {
@@ -330,56 +337,52 @@ const actionFullRegister = (login, password) => async (dispatch) => {
     }
 };
 
-const actionNewOrder = () => async (dispatch, getState) => {
-    const { cart } = getState();
-    let order = { orderGoods: [] };
-    for (let [key, value] of Object.entries(cart)) {
-        let newValue = { ...value };
-
-        let { name, price, images, ...id } = newValue.good;
-        newValue.good = id;
-        order.orderGoods.push({ ...newValue });
-    }
+const actionOrder = () => async (dispatch, getState) => {
+    let { cart } = getState();
+    const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({
+        good: { _id },
+        count,
+    }));
 
-    let newOrder = await dispatch(
+    let result = await dispatch(
         actionPromise(
-            "newOrder",
+            "order",
             gql(
-                `mutation newOrder($order: OrderInput) {
-                OrderUpsert(order: $order) {
-                _id
-                total
-                }
-            }`,
-                { order: order }
+                `
+                    mutation newOrder($order:OrderInput){
+                    OrderUpsert(order:$order)
+                        { _id total 	}
+                    }
+            `,
+                { order: { orderGoods } }
             )
         )
     );
-    if (newOrder) {
+    if (result?._id) {
         dispatch(actionCartClear());
+        document.location.hash = "#/cart/";
+        alert("Поздравляем, вы оформили заказ!");
     }
 };
 
-const actionOrders = () =>
+const orderHistory = () =>
     actionPromise(
-        "orders",
-        gql(
-            `query findOrder($q: String) {
-    OrderFind(query: $q) {
-      _id
-      total
-      createdAt
-      orderGoods {
-        count
-        good {
-          name
-          price
+        "history",
+        gql(` query OrderFind{
+        OrderFind(query:"[{}]"){
+            _id total createdAt orderGoods{
+                count good{
+                    _id name price images{
+                        url
+                    }
+                }
+                owner{
+                    _id login 
+                }
+            }
         }
-      }
     }
-  }`,
-            { q: JSON.stringify([{}]) }
-        )
+    `)
     );
 
 store.subscribe(() => {
@@ -580,12 +583,16 @@ store.subscribe(() => {
         goodByIdCount.innerText = count;
 
         buttonBuy.onclick = () => {
-            store.dispatch(actionNewOrder());
+            store.dispatch(actionOrder());
+            store.dispatch(orderHistory());
         };
-        
+
         buttonPlus.onclick = () => store.dispatch(actionCartAdd(value.good));
-        buttonMinus.onclick = () =>
+        buttonMinus.onclick = () => {
             store.dispatch(actionCartDelete(value.good));
+            console.log(value.good, "this");
+            // if(value.good.count === 0)
+        };
     }
 
     shoppingCart.innerHTML = "Cart: " + countSum;
@@ -691,30 +698,6 @@ function bPopupCreate(text) {
     };
 }
 
-// store.subscribe(() => {
-//     dashboardUl.innerHTML = ''
-//     const {orders} = store.getState().promise;
-//     const [,route, _id] = location.hash.split('/');
-//     if(orders?.payload && route === 'dashboard'){
-//         for(let {createdAt, total, orderGoods} of orders.payload){
-//             let date = new Date(+createdAt);
-//             let li = document.createElement("li");
-//             for(let {count, good} of orderGoods){
-//                 let div = document.createElement("div");
-//                 div.innerHTML = `<strong>${good.name}</strong>
-//                                 <span>${count} &#10006; ${good.price}</span>
-//                                 `
-//                 li.append(div);
-//             }
-//             li.innerHTML += `<div>${total}</div>
-//             <div>${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()}</div>
-//             <hr>`
-//             dashboardUl.append(li)
-//         }
-//     }
-
-// })
-
 window.onhashchange = () => {
     const [, route, _id] = location.hash.split("/");
 
@@ -726,8 +709,7 @@ window.onhashchange = () => {
             store.dispatch(actionGoodById(_id));
         },
         dashboard() {
-            store.dispatch(actionOrders());
-            console.log("заказостраница");
+            store.dispatch(orderHistory());
         },
     };
 
@@ -738,6 +720,51 @@ window.onhashchange = () => {
 
 window.onhashchange();
 
+store.dispatch(orderHistory());
+const h2 = document.createElement("h2");
+store.subscribe(() => {
+    const { history } = store.getState().promise;
+    const [, route] = location.hash.split("/");
+    purchaseHistory.onclick = () => {
+        const bPopup = document.createElement("div");
+        const bPopupContent = document.createElement("div");
+        bPopup.id = "b-popup";
+        bPopup.className = "b-popup";
+        bPopupContent.className = "b-popup-content b-poput-container-flex";
+        header.append(bPopup);
+        bPopup.append(bPopupContent);
+        const buttonCloseCart = document.createElement("button");
+        buttonCloseCart.innerText = `×`;
+        buttonCloseCart.id = "buttonCloseCartId";
+        bPopupContent.append(buttonCloseCart);
+
+        for (let [key, value] of Object.entries(history.payload)) {
+            const { _id, createdAt, total, orderGoods } = value;
+            console.log(total, "this");
+            const h2 = document.createElement("h2");
+            h2.className = "h2History"
+            const dateOfOrder = new Date(+createdAt);
+            h2.innerHTML = `${dateOfOrder.toLocaleDateString()} ${dateOfOrder.toLocaleTimeString()}
+                            Order ID: ${_id} от , c ${orderGoods.length} goods worth: ${total}`;
+                            bPopupContent.append(h2);
+        
+            
+        }
+
+        if (Object.keys(history.payload).length == 0) {
+            const p = document.createElement("p");
+            p.innerHTML = "<p>No purchases made yet</p>";
+            card.append(p);
+        }
+
+        buttonCloseCart.onclick = () => {
+            var parent = document.getElementById("header");
+            var child = document.getElementById("b-popup");
+            parent.removeChild(child);
+        };
+    };
+});
+
 login.onclick = () => {
     bPopupCreate(buttonLogin);
     buttonLogin.onclick = () => {
@@ -755,7 +782,8 @@ reg.onclick = () => {
     bPopupCreate(buttonReg);
     buttonReg.onclick = () => {
         store.dispatch(
-            actionFullRegister(loginInput.value, passwordInput.value)
+            actionFullRegister(loginInput.value, passwordInput.value),
+            store.dispatch(actionCartClear())
         );
         var parent = document.getElementById("header");
         var child = document.getElementById("b-popup");

+ 3 - 0
Market GraphQL + Redux/style.css

@@ -279,6 +279,9 @@ flexBlock img {
     height: 50px;
     margin: 0 30px 0 30px;
 }
+.h2History {
+    font-size: 14px;
+}
 
 .footer {
     padding-top: 20px;