소스 검색

orderUpsert done

maryluis 3 년 전
부모
커밋
93f3592670

+ 1 - 1
shop/package.json

@@ -1,4 +1,4 @@
-{
+{"proxy": "http://сервер.a-level.com.ua/",
 
   
   "name": "shop",

+ 48 - 0
shop/src/App.css

@@ -436,6 +436,33 @@ button {
   height: 280px;
 }
 
+.orderUpdateWrapper {
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  /* margin-bottom: 50px; */
+  align-items: center;
+}
+
+.orderUpdateWrapper h4 {
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  background-color: rgba(10, 10, 10, 0.5);
+  text-align: center;
+}
+
+
+.orderUpdateBottom {
+  display: flex;
+  justify-content: center;
+
+}
+
+.orderUpdateBottom button {
+  margin-bottom: 50px;
+}
+
 .basketNoGoods {
   padding-left: 10px;
   padding-right: 10px;
@@ -469,6 +496,9 @@ button {
 .basketInner .oneGood button {
   width: 40px;
 }
+.basketButoons button {
+  width: 40px;
+}
 
 
 .bottom {
@@ -605,6 +635,10 @@ button {
     font-size: 13px;
   }
 
+  .orderUpdateBottom button {
+    margin-bottom: 20px;
+  }
+
   .catalog li{
     font-size: 10px;
 
@@ -694,3 +728,17 @@ button {
     width: 70%;
   }
 }
+
+@media screen and (max-width: 300px){
+  .header {
+    /* position: relative; */
+  }
+
+  .header button {
+    transform: rotate(-90deg);
+    width: 30px;
+    /* position: absolute; */
+    /* width: 30px;
+    font-size: 6px; */
+  }
+}

+ 5 - 4
shop/src/components/goodsCategory.js

@@ -2,7 +2,7 @@ import {Provider, connect} from 'react-redux';
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 import thunk from 'redux-thunk';
 import {actionPromise} from "./index"
-import {gql, actionGoods, getData, actionCartAdd} from "../reducers/";
+import {gql, actionGoods, actionOrderAddNewGood, getData, actionCartAdd} from "../reducers/";
 import { useEffect } from 'react';
 import {OneGood, CGoodsList} from "./index";
 
@@ -19,19 +19,20 @@ import {OneGood, CGoodsList} from "./index";
   
   const mapDispatchToProps = dispatch => bindActionCreators({
     getData: actionGoods,
-    onAdd: actionCartAdd
+    onAdd: actionCartAdd,
+    onAddtoOrder: actionOrderAddNewGood
   }, dispatch);
   
 
 
-const GoodsCategory = ({goods, id, tittle = "Товари", getData, onAdd}) => {
+const GoodsCategory = ({goods, id, tittle = "Товари", onAddtoOrder, getData, onAdd}) => {
 
   useEffect(() =>  getData(id), [id])
   return(
       <>
         
         <div className = "goodsWrapper">
-            <CGoodsList arr = {goods} onAdd = {onAdd}/>
+            <CGoodsList arr = {goods} onAdd = {onAdd} onAddtoOrder = {onAddtoOrder}/>
         </div>
       </>
   )

+ 3 - 3
shop/src/components/goodsList.js

@@ -1,6 +1,6 @@
 import {OneGood, GoodsNotFound} from "./index";
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
-import {getData, actionGoods, urlUpload} from "../reducers/index";
+import {getData, actionGoods, actionOrderAddNewGood, urlUpload} from "../reducers/index";
 import {Provider, connect} from 'react-redux';
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
 
@@ -18,7 +18,7 @@ import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from
 
 
 
-const GoodsList = ({arr = [], className = "goods", onAdd}) => {
+const GoodsList = ({arr = [], className = "goods", onAdd, onAddtoOrder}) => {
   const history = useHistory();
   // console.log(arr)
   if(arr.length == 0) {
@@ -38,7 +38,7 @@ const GoodsList = ({arr = [], className = "goods", onAdd}) => {
         />
         <div>
            {(history.location.pathname.includes(`/catalog/`) || history.location.pathname.includes(`/search/`)) && <button onClick = {() => onAdd(good.name, good.price, good._id,  good.description, good.images)}>В кошик</button>}
-           {history.location.pathname.includes(`/orderPage/`) && <button onClick = {() => onAdd(good.name, good.price, good._id,  good.description, good.images)}>Додати до замовлення</button>}
+           {history.location.pathname.includes(`/orderPage/`) && <button onClick = {() => onAddtoOrder(good._id, good.name, good.images, good.price,   )}>Додати до замовлення</button>} 
         </div>
       </div>
       

+ 81 - 26
shop/src/components/orderUpdate.js

@@ -1,55 +1,110 @@
-import { actionOrdersFind, actionOrderFindOne, urlUpload} from "../reducers";
+import { actionOrdersFind, actionOrderUpdate, actionOrderClear, actionOrderAddOne, actionOrderFindOne, urlUpload, actionOrderDelete} from "../reducers";
 import { connect } from "react-redux";
+import {OneGood, GoodsNotFound} from "./index";
 import { useEffect, useState, useRef } from "react";
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
 import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
 
 
 
-const OrderUpdate = ({orderFind, state, match:{params:{_id}}}) => {
-    useEffect(() => orderFind(_id), [])
+const OrderUpdate = ({orderFind, orderUpdated, orderUpdate, onAddOne, orderClear, onDelete, orderObj, goodsArr, orderId, state, match:{params:{_id}}}) => {
+    //const [orderData, findOrder] = useState(_id);
+    //useEffect(() => orderFind(orderData), [])
+    const history = useHistory();
     console.log(state)
+    console.log(orderId)
+    // useEffect(() => )
+    
 
     return (
-        <>
-        </>
+        <div className = "orderUpdateWrapper">
+            <div className = "goods">
+                {goodsArr.length > 0 ? goodsArr.map((good) => 
+                    
+                    <div className = "oneGood">
+                        <OneGood id = {good._id}  name = {good.good.name} price = {good.price} 
+                        image = {good.good.images ? `${urlUpload}/${good.good.images[0].url}` : `https://images.ua.prom.st/2259265311_korobka-syurpriz-dlya.jpg`}
+                        
+                    />
+                            <div className = "basketButoons">
+                            <button 
+                            onClick = {() => onAddOne(good.good._id)}
+                                >+</button> 
+                            <h4>{good.count}</h4>    
+                            <button 
+                            onClick = {() =>  { 
+
+                                onDelete(good.good._id)}}
+                                >-</button>   
+                        </div> 
+                    </div>
+                ) : 
+                <h4>В замовленні немає товарів</h4>
+                } 
+            </div>
+            <h4>{orderObj.total}грн</h4>
+            <div className = "orderUpdateBottom">
+                <button onClick = {() => orderClear()}>Скасувати замовлення</button>
+                <button onClick = {async () =>  {
+                    // await orderFind(orderId)
+                    await orderUpdate(orderId, arrForUpdate(goodsArr));
+                    let ownerId = orderObj.owner;
+                    await orderClear();
+                    history.push("/user/"+ownerId)
+                }} >Зберегти змінення</button>
+            </div>
+        </div>
     )
 }
 
+function arrForUpdate(arr) {
+    var newArr = [];
+    for(let key of arr) {
+        let oneObj = {};
+        oneObj.count = key.count;
+        oneObj.good = {};
+        oneObj.good._id = key.good._id;
+        newArr.push(oneObj)
+    }
+    return newArr;
+}
 
-const mapStateToProps = state => ({
-    state: state,
-
-    orders: state.promiseRed && state.promiseRed.ordersFind &&
-    state.promiseRed.ordersFind.payload && state.promiseRed.ordersFind.payload.data &&
-    state.promiseRed.ordersFind.payload.data.OrderFind,
+function arrFromObj(obj) {
     
-    token: state.auth && state.auth.token,
+    var newArr = [];
+    for (let key in obj) {
+            newArr.push(obj[key])
+    }
+    return newArr;
+}
 
-    status: state.promiseRed && state.promiseRed.ordersFind &&
-    state.promiseRed.ordersFind.payload && state.promiseRed.ordersFind &&
-    state.promiseRed.ordersFind.status,
 
-    isUserAdmin: state.promiseRed && state.promiseRed.user &&
-    state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
-    state.promiseRed.user.payload.data.UserFindOne && 
-    state.promiseRed.user.payload.data.UserFindOne.acl &&
-    state.promiseRed.user.payload.data.UserFindOne.acl.indexOf("admin") > -1,
+const mapStateToProps = state => ({
+    state: state,
 
-    owner: state.auth && state.auth.payload && state.auth.payload.sub &&
-    state.auth.payload.sub,
+    order: state.promiseRed && state.promiseRed.oneOrder &&
+    state.promiseRed.oneOrder.payload && state.promiseRed.oneOrder.payload.data &&
+    state.promiseRed.oneOrder.payload.data.OrderFindOne,
 
-    isAdmin: state.auth && state.auth.payload && state.auth.payload.sub &&
-    state.auth.payload.sub.acl && state.auth.payload.sub.acl.indexOf("admin") > -1,
+    orderUpdated: state.promiseRed && state.promiseRed.orderUpdated &&
+    state.promiseRed.orderUpdated.payload && state.promiseRed.orderUpdated.payload.data &&
+    state.promiseRed.orderUpdated.payload.data.OrderUpsert,
+    
+    orderObj: state.orderUpdateReducer,
 
+    goodsArr: arrFromObj(state.orderUpdateReducer.goods),
     
+    orderId: state.orderUpdateReducer.id
  });
 
 
  
  const mapDispatchToProps = dispatch => bindActionCreators({
-
-   orderFind: actionOrderFindOne
+    onDelete: actionOrderDelete,
+    onAddOne: actionOrderAddOne,
+    orderFind: actionOrderFindOne,
+    orderClear: actionOrderClear,
+    orderUpdate: actionOrderUpdate
  }, dispatch);
 
 

+ 32 - 10
shop/src/components/ordersList.js

@@ -1,4 +1,4 @@
-import { actionOrdersFind, urlUpload} from "../reducers";
+import { actionOrdersFind, urlUpload, actionOrderAdd, actionOrderAddOrder} from "../reducers";
 import { connect } from "react-redux";
 import { useEffect, useState, useRef } from "react";
 import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
@@ -23,9 +23,26 @@ const OneOrderGood = ({img, name, count, keyprop, price}) => {
 
 
 
-const OneOrder = ({price, total, _id, img, isAdmin, keyprop, goodsArr = [],count,  createdAt}) => {
+const OneOrder = ({price, total, _id, owner, img, onClick, isAdmin, keyprop, goodsArr = [],count,  createdAt}) => {
     const date =  new Date(+createdAt);
     const history = useHistory();
+
+
+
+
+
+    function goodsObj(arr) {
+        let oneObj = {};
+        for(let i = 0; i < arr.length; i++) {
+            oneObj[arr[i].good._id] = arr[i];
+        }
+
+        return oneObj
+    }
+
+
+
+
     return(
 
         <div key = {keyprop} className = "oneOrder">
@@ -35,8 +52,8 @@ const OneOrder = ({price, total, _id, img, isAdmin, keyprop, goodsArr = [],count
                 </h5>
                 <div key = {Math.random()} className = "oneOrderInner">
                     <div className = "oneOrderGoods">
-                        {(!goodsArr || goodsArr.length == 0) && <div key = {`${_id}${Math.random}`}>Замовлення скасовано</div>}
-                        {goodsArr && goodsArr.map((good) =>  { 
+                        {(!goodsArr || goodsArr.length == 0 || !total) && <div key = {`${_id}${Math.random}`}>Замовлення скасовано</div>}
+                        {goodsArr && total > 0 && goodsArr.map((good) =>  { 
                              if(good.good == null || good.good.name == null) {
                                  return(
                                     <div key = {`${Math.random()}`}>Товар відмінено</div>
@@ -44,6 +61,7 @@ const OneOrder = ({price, total, _id, img, isAdmin, keyprop, goodsArr = [],count
                              } else {
                                  
                                  return(
+
                                      
                              <OneOrderGood key = {Math.random()} name = {good.good ? good.good.name : "товар"} count = {good.count} price = {good.good ? good.good.price : ""} img = {good.good && good.good.images && good.good.images[0].url ? `${good.good.images[0].url}` : `https://images.ua.prom.st/2259265311_korobka-syurpriz-dlya.jpg`}/>
 
@@ -53,7 +71,11 @@ const OneOrder = ({price, total, _id, img, isAdmin, keyprop, goodsArr = [],count
                         })}
                     </div>
                     <div> {<h5>{(total && total > 0 && total != 0) ? `Сума замовлення: ${total}грн` : ""}</h5>}
-                    {isAdmin && goodsArr &&  total > 0 && <button onClick = {() => history.push(`/orderPage/${_id}`)}>Редагувати</button>}
+                    {isAdmin && goodsArr &&  total > 0 && <button onClick = {() =>  {
+                        let newObj = goodsObj(goodsArr)
+                        {onClick(_id, newObj, total, owner)}
+                        history.push(`/orderPage/${_id}`) }}>
+                            Редагувати</button>}
                     
                     </div>
                 </div>
@@ -67,14 +89,14 @@ const OneOrder = ({price, total, _id, img, isAdmin, keyprop, goodsArr = [],count
 
 
 
-const OrdersList = ({orders = [], status, ordersFind, owner, isAdmin, match:{params:{_id}}}) => {
+const OrdersList = ({orders = [], onOrder, status, ordersFind, owner, isAdmin, match:{params:{_id}}}) => {
     const history = useHistory();
 
     function ordersOnPage(arr) {
         let newArr = arr.slice();
         newArr.reverse()
-        console.log(newArr)
-        return newArr.map((order) => <OneOrder isAdmin = {isAdmin} key = {order._id} _id = {order._id} createdAt = {order.createdAt} goodsArr = {order.orderGoods} total = {order.total}/>)}
+        //console.log(newArr)
+        return newArr.map((order) => <OneOrder  owner = {order.owner._id} onClick = {onOrder} isAdmin = {isAdmin} key = {order._id} _id = {order._id} createdAt = {order.createdAt} goodsArr = {order.orderGoods} total = {order.total}/>)}
     
 
     useEffect(() =>   {
@@ -140,8 +162,8 @@ const mapStateToProps = state => ({
 
  
  const mapDispatchToProps = dispatch => bindActionCreators({
-
-   ordersFind: actionOrdersFind
+    onOrder: actionOrderAddOrder,
+    ordersFind: actionOrdersFind
  }, dispatch);
 
  const COrdersList = connect(mapStateToProps, mapDispatchToProps)(OrdersList);

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

@@ -103,7 +103,7 @@ const YourProfile = ({state, orders, updateStatus, updatedUser = {}, newImg, tok
                     <div className = "updateWrapper">
                     <h4>Редагування</h4>
                     
-                    {updatedUser && updatedUser.errors && updatedUser.errors.length > 0 && <p>Введено невірні дані, або цей логін вже зайнято</p>}
+                    {updatedUser && updatedUser.errors && updatedUser.errors.length > 0 && <p>Цей логін вже зайнято</p>}
                     
 
                     {(!isAdmin  || (isAdmin && isOwner.id == data._id))&&

+ 1 - 0
shop/src/reducers/actionOrdersFind.js

@@ -19,6 +19,7 @@ const actionOrdersFind = (data) => {
                   createdAt
                   owner {
                     login
+                    _id
                   }
                   
                 }

+ 30 - 0
shop/src/reducers/actionUpdateOrder.js

@@ -0,0 +1,30 @@
+import {actionPromise, gql} from "./index";
+
+
+
+const actionOrderUpdate = (id, arrGoods) => {
+
+    return async dispatch => {
+
+        const queryJson = JSON.stringify(
+        {
+            newOrder: {
+                _id: id,
+                orderGoods: arrGoods
+            }
+        });
+
+        await dispatch(actionPromise("orderUpdated", gql (
+            `mutation orderChange($newOrder: OrderInput) {
+                OrderUpsert(order: $newOrder) {
+                  
+                  total
+                  orderGoods {good {name}}
+                  owner {_id, login}
+                }
+              }`, queryJson
+        )))
+    }
+}
+
+export default actionOrderUpdate;

+ 6 - 3
shop/src/reducers/index.js

@@ -17,7 +17,9 @@ import actionUserFindOne from "./actionFindOneUser";
 import actionUserUpdate from "./actionUserUpdate";
 import actionSearchUser from "./actionSearchUser";
 import actionGoodUpdate from "./actionGoodUpdate";
+import {orderUpdateReducer, actionOrderClear, actionOrderAddNewGood, actionOrderAddOne, actionOrderAddOrder, actionOrderDelete} from "./orderUpdateReduser"
 import {actionOrdersFind, actionOrderFindOne} from "./actionOrdersFind";
+import actionOrderUpdate from "./actionUpdateOrder";
 
 
 function promiseReducer(state={}, action){
@@ -37,13 +39,14 @@ function promiseReducer(state={}, action){
   const store = createStore(combineReducers({
       promiseRed: promiseReducer, 
       auth: authReducer,
-      basket: cartReducer
+      basket: cartReducer,
+      orderUpdateReducer
   }), compose(applyMiddleware(thunk)))
 
 export {actionPromise, actionOrdersFind,  gql, actionGoods, getData, promiseReducer, store, actionSearch,
    actionLogin, authReducer, actionAuthLogin, actionAuthLogout, urlUpload, actionGoodCard, 
-   updateImgAction, actionCartAdd, actionCartDelete, actionCartClear, actionOrder,
-    actionReg, actionUserFindOne, actionOrderFindOne, actionUserUpdate, actionSearchUser, actionGoodUpdate};
+   updateImgAction, actionCartAdd, actionOrderClear, actionCartDelete, actionCartClear, actionOrder,
+    actionReg, actionOrderUpdate, actionUserFindOne, actionOrderAddNewGood, actionOrderAddOne, orderUpdateReducer, actionOrderAddOrder, actionOrderDelete, actionOrderFindOne, actionUserUpdate, actionSearchUser, actionGoodUpdate};
 
 
 

+ 177 - 0
shop/src/reducers/orderUpdateReduser.js

@@ -0,0 +1,177 @@
+
+
+function orderUpdateReducer(state, { type, total, id, owner, goods, Id, images, name, description,  price, count }) {
+    if(state === undefined){
+
+            state = {}
+
+    }
+
+    if (type === "ORDER_ADD_ORDER") {
+        state = {
+            ...state,  
+            owner: owner,
+            total: total,        
+            id: id,
+            goods: goods
+                
+        }
+
+    }
+
+    if (type === "ORDER_DELETE_ONE") {
+        if((state.goods[Id].count - 1) == 0 ){
+            state = {
+                ...state,
+                goods: {
+                    ...state.goods,
+
+                },
+                total: +state.total - state.goods[Id].price  
+            }
+            delete state.goods[Id]
+        }
+        else {
+            state = {
+                ...state,
+                goods : {
+                    ...state.goods,
+                    [Id]: {
+                        ...state.goods[Id],
+                        count: +[state.goods[Id].count] - 1,
+
+                    }
+                },
+                total: +state.total - state.goods[Id].price                   
+            }
+        }
+    }
+    
+    if (type === "ORDER_ADD_ONE") {
+
+        state = {
+            ...state,
+            goods : {
+                ...state.goods,
+                [Id]: {
+                    ...state.goods[Id],
+                    count: +[state.goods[Id].count] + 1,
+
+                }
+            },
+            total: +state.total + state.goods[Id].price                   
+        }
+    }
+
+    if (type === "ORDER_ADD_NEW_GOOD") {
+
+        if(state.goods[Id]){
+            state = {
+                ...state,
+                goods : {
+                    ...state.goods,
+                    [Id]: {
+                        ...state.goods[Id],
+                        count: +[state.goods[Id].count] + 1,
+    
+                    }
+                },
+                total: +state.total + state.goods[Id].price                   
+            }
+        }
+        else {
+
+            state = {
+                ...state,
+                goods: {
+                    ...state.goods,
+                    [Id]: {
+                        count: (state.goods && state.goods[Id] ? state.goods[Id] : 0) + 1,
+                        good: {
+                            name: name,
+                            images: images,
+                            price: price,
+                            _id : Id,
+
+                        },
+                        
+                        _id : Id,
+                        price: price,
+                    }
+
+                }
+            }
+        }
+    }
+    if (type === "ORDER_CLEAR") {
+
+        state = {
+            id: state.id,
+            goods: {},
+            total: 0,
+            count: 0
+            
+        }
+    }
+
+
+
+
+
+    return state;
+}
+    
+
+
+
+const actionOrderAddOrder = ( id, goods, total, owner, name, price, images, count = 0) => ({
+    type: "ORDER_ADD_ORDER",
+    id,
+    goods,
+    count,
+    owner,
+    price,
+    name,
+    images,
+    total
+    
+});
+
+const actionOrderDelete = (Id, id, goods, images) => ({
+    type: "ORDER_DELETE_ONE",
+    id,
+    Id,
+    goods,
+    images
+
+});
+const actionOrderAddOne = (Id, id, goods, images) => ({
+    type: "ORDER_ADD_ONE",
+    id,
+    Id,
+    goods,
+    images
+
+});
+const actionOrderAddNewGood = (Id, name, images, price) => ({
+    type: "ORDER_ADD_NEW_GOOD",
+
+    Id,
+    name,
+
+    images,
+    price
+
+});
+
+const actionOrderClear = () => ({
+    type:"ORDER_CLEAR"
+})
+
+
+// const actionCartClear = (count, price) => ({
+//     type: "CART_CLEAR",
+//     count,
+//     price
+// });
+export {orderUpdateReducer, actionOrderClear, actionOrderAddNewGood, actionOrderAddOne, actionOrderAddOrder, actionOrderDelete};