Gennadysht преди 2 години
родител
ревизия
d1f6048134

+ 8 - 5
src/App.js

@@ -8,11 +8,10 @@ import { CGood, CGoodsList, CLoginForm, CMainAppBar, COrder, COrdersList } from
 import { CLogout } from './Components';
 import { CSidebar } from './Components/Sidebar';
 import { CRootCats } from './Components';
-
 import './App.css';
 import { CCategory } from './Components/Category';
 import { categoryApi } from './reducers/categoryReducer';
-import { ordersReducer } from './reducers/ordersReducer';
+import { ordersApi, ordersReducer } from './reducers/ordersReducer';
 import { CCart } from './Components/Cart';
 import { authApiReducer, authReducer, authApiReducerPath, loginApi, authReducerPath } from './reducers';
 import storage from "redux-persist/lib/storage";
@@ -34,11 +33,14 @@ export const history = createBrowserHistory();
 const rootReducer = combineReducers({
   [authReducerPath]: persistReducer({ key: authReducerPath, storage }, authReducer),
   [authApiReducerPath]: authApiReducer,
-  [categoryApi.reducerPath]: persistReducer({ key: categoryApi.reducerPath, storage }, categoryApi.reducer),
-  [goodsApi.reducerPath]: persistReducer({ key: goodsApi.reducerPath, storage }, goodsApi.reducer),
+  //[categoryApi.reducerPath]: persistReducer({ key: categoryApi.reducerPath, storage }, categoryApi.reducer),
+  //[goodsApi.reducerPath]: persistReducer({ key: goodsApi.reducerPath, storage }, goodsApi.reducer),
+  //[ordersApi.reducerPath]: persistReducer({ key: ordersApi.reducerPath, storage }, ordersApi.reducer),
+  [categoryApi.reducerPath]: categoryApi.reducer,
+  [goodsApi.reducerPath]: goodsApi.reducer,
+  [ordersApi.reducerPath]: ordersApi.reducer,
   promise: promiseReducer,
   frontend: frontEndReducer,
-  orders: ordersReducer,
   cart: cartReducer,
   cartData: cartGoodsReducer
 });
@@ -48,6 +50,7 @@ export const store = configureStore({
     ...getDefaultMiddleware({ serializableCheck: { ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER] } }),
     categoryApi.middleware,
     goodsApi.middleware,
+    ordersApi.middleware,
     loginApi.middleware],
   reducer: rootReducer
 });

+ 4 - 4
src/Components/Cart.js

@@ -2,7 +2,7 @@ import React, { useEffect } from 'react';
 import { Button, Typography } from "@mui/material"
 import { Box, Container } from "@mui/system"
 import { connect } from "react-redux"
-import { actionLoadCart, getCart, actionPlaceOrder } from "../reducers"
+import { actionLoadCart, getCart, actionPlaceOrder, actionAddOrder } from "../reducers"
 import { CartGoodsList } from "./CartGoodsList"
 import { findObjectIndexById } from '../utills';
 
@@ -14,7 +14,7 @@ const mapCountToGood = (goodData, goodsCounts) => {
     return count;
 }
 
-const Cart = ({ goods, goodsData, uniqueId, loadData, placeOrder }) => {
+const Cart = ({ goods, goodsData, uniqueId, loadData }) => {
     goodsData = goodsData?.map(gd => ({ ...gd, count: mapCountToGood(gd, goods) })) ?? [];
 
     useEffect(() => {
@@ -29,7 +29,7 @@ const Cart = ({ goods, goodsData, uniqueId, loadData, placeOrder }) => {
                     </Typography>
                     <CartGoodsList goods={goodsData ?? []} />
                     <Button size='small' color='primary'
-                        onClick={() => placeOrder()}
+                        onClick={() => actionAddOrder()}
                     >
                         Place Order
                     </Button>
@@ -45,6 +45,6 @@ const CCart = connect(state => ({
     ...getCart(state) 
     //cart: getCart(state) 
 }),
-    { loadData: actionLoadCart, placeOrder: actionPlaceOrder })(Cart);
+    { loadData: actionLoadCart })(Cart);
 
 export { CCart };

+ 2 - 3
src/Components/LoginForm.js

@@ -3,8 +3,7 @@ import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
 import Button from '@mui/material/Button';
 import { Container, CssBaseline, TextField, Avatar, Typography, FormControlLabel, Checkbox, Grid, Link } from '@mui/material';
 import { Box } from '@mui/system';
-import { connect, useSelector } from 'react-redux';
-import { actionFullLogin } from '../gql';
+import { connect } from 'react-redux';
 import { MyLink } from './MyLink';
 import { useLoginMutation } from '../reducers/authReducer';
 
@@ -84,6 +83,6 @@ const LoginForm = () => {
         </Container>
     )
 }
-const CLoginForm = connect(null, { onLogin: actionFullLogin })(LoginForm)
+const CLoginForm = connect(null, { })(LoginForm)
 
 export { CLoginForm };

+ 12 - 9
src/Components/Order.js

@@ -1,10 +1,11 @@
 import React, { useEffect } from 'react';
 import { Typography } from "@mui/material"
 import { Box, Container } from "@mui/system"
-import { connect } from "react-redux"
-import { actionOrderFindOne, getCurrentOrder } from "../reducers/ordersReducer"
+import { connect, useDispatch } from "react-redux"
+import { actionOrderFindOne, getCurrentOrder, useGetOrderByIdQuery } from "../reducers/ordersReducer"
 import { OrderGoodsList } from "./OrderGoodsList"
 import { useParams } from 'react-router-dom/cjs/react-router-dom';
+import { actionSetCurrentOrder } from '../reducers/frontEndReducer';
 
 let exampleOrder = {
     "_id": "62cdc9b3b74e1f5f2ec1a0e9",
@@ -60,11 +61,7 @@ let exampleOrder = {
         }
     ]
 }
-const Order = ({ order = {}, loadData }) => {
-    const { _id: currentOrderId } = useParams();
-    useEffect(() => {
-        loadData(currentOrderId);
-    }, [currentOrderId, loadData]);
+const Order = ({ order = {} }) => {
     return (
         <>
             <Container>
@@ -81,7 +78,13 @@ const Order = ({ order = {}, loadData }) => {
         </>
     )
 }
-const COrder = connect(state => ({ order: getCurrentOrder(state) }),
-    { loadData: actionOrderFindOne })(Order);
+const COrder = () => {
+    const { _id } = useParams();
+    const { isLoading, data } = useGetOrderByIdQuery(_id);
+    let order = isLoading ? { name: 'loading', order: {} } : data?.OrderFindOne;
+    const dispatch = useDispatch();
+    dispatch(actionSetCurrentOrder(_id));
+    return !isLoading && <Order order={order} />;
+}
 
 export { COrder };

Файловите разлики са ограничени, защото са твърде много
+ 3 - 143
src/Components/OrderGoodsList.js


+ 17 - 66
src/Components/OrderList.js

@@ -1,53 +1,14 @@
-import React, { useEffect } from 'react';
+import React from 'react';
 import { Container, Typography, Paper, Link } from '@mui/material';
 import { Table, TableBody, TableContainer, TableHead, TableRow } from "@mui/material";
 import { StyledTableCell, StyledTableRow } from './StyledTableElements';
 import { COrdersPagination } from './Pagination';
-import { actionFindOrders, actionOrdersCount } from '../reducers';
-import { connect } from 'react-redux';
 import { COrdersSearchInput } from './SearchInput';
 import { MyLink } from '.';
+import { useSelector } from 'react-redux';
+import { useGetOrdersCountQuery, useGetOrdersQuery } from '../reducers';
 
-/*function stableSort(array, comparator) {
-    const stabilizedThis = array.map((el, index) => [el, index]);
-    stabilizedThis.sort((a, b) => {
-        const order = comparator(a[0], b[0]);
-        if (order !== 0) {
-            return order;
-        }
-        return a[1] - b[1];
-    });
-    return stabilizedThis.map((el) => el[0]);
-}
-function getComparator(order, orderBy) {
-    return order === 'desc'
-        ? (a, b) => descendingComparator(a, b, orderBy)
-        : (a, b) => -descendingComparator(a, b, orderBy);
-}
-function descendingComparator(a, b, orderBy) {
-    if (b[orderBy] < a[orderBy]) {
-        return -1;
-    }
-    if (b[orderBy] > a[orderBy]) {
-        return 1;
-    }
-    return 0;
-}*/
-const OrderList = ({ orders, searchStr, fromPage = 0, pageSize = 5, loadData, loadOrdersCount }) => {
-    /*const [order, setOrder] = React.useState('asc');
-    const [orderBy, setOrderBy] = React.useState('calories');
-    const [page, setPage] = React.useState(0);
-    const [rowsPerPage, setRowsPerPage] = React.useState(5);*/
-
-    useEffect(() => {
-        loadData(fromPage, pageSize, searchStr);
-        loadOrdersCount(searchStr);
-    }, [fromPage, pageSize, searchStr]);
-
-    /*<StyledTableCell align={headCell.align}>{headCell.label}</StyledTableCell>*/
-    /*    const createSortHandler = (property) => (event) => {
-            onRequestSort(event, property);
-          };*/
+const OrderList = ({ orders, fromPage, pageSize }) => {
 
     let headCells = [
         {
@@ -101,7 +62,7 @@ const OrderList = ({ orders, searchStr, fromPage = 0, pageSize = 5, loadData, lo
                             <TableRow>
                                 {
                                     headCells.map(headCell => {
-                                        return <StyledTableCell align={headCell.align}>{headCell.label}</StyledTableCell>
+                                        return <StyledTableCell key={headCell.id} align={headCell.align}>{headCell.label}</StyledTableCell>
                                         /*return (
                                             <StyledTableCell
                                                 key={headCell.id}
@@ -177,29 +138,19 @@ const OrderList = ({ orders, searchStr, fromPage = 0, pageSize = 5, loadData, lo
         </>
     )
 
-    /*
-                    <TablePagination
-                        rowsPerPageOptions={[5, 10, 25]}
-                        component="div"
-                        count={exampleOrderList.length}
-                        rowsPerPage={rowsPerPage}
-                        page={page}
-                        onPageChange={handleChangePage}
-                        onRowsPerPageChange={handleChangeRowsPerPage}
-                    />
-    */
 }
+const COrdersList = () => {
+    let state = useSelector(state => state);
+    const searchStr = state.frontend.ordersSearchStr;
+    const fromPage = state.frontend.ordersPaging.fromPage;
+    const pageSize = state.frontend.ordersPaging.pageSize;
+
+    const ordersResult = useGetOrdersQuery({ fromPage, pageSize, searchStr });
+    const ordersCountResult = useGetOrdersCountQuery({ searchStr });
+    let isLoading = ordersResult.isLoading || ordersCountResult.isLoading;
 
-const COrdersList = connect(
-    state => {
-        return (
-            {
-                orders: state.orders?.orders?.payload,
-                searchStr: state.frontend.ordersSearchStr,
-                fromPage: state.frontend.ordersPaging.fromPage,
-                pageSize: state.frontend.ordersPaging.pageSize,
-            })
-    },
-    { loadData: actionFindOrders, loadOrdersCount: actionOrdersCount })(OrderList);
+    let orders = ordersResult.data?.OrderFind;
+    return !isLoading && orders && <OrderList orders={orders} fromPage={fromPage} pageSize={pageSize} />
+}
 
 export { COrdersList };

+ 13 - 35
src/Components/Pagination.js

@@ -1,22 +1,15 @@
 import { TablePagination } from '@mui/material';
-import { useState } from 'react';
-import { connect, useDispatch, useSelector } from 'react-redux';
-import { actionFindOrders } from '../reducers';
+import { useDispatch, useSelector } from 'react-redux';
+import { getOrdersCount } from '../reducers';
 import { actionSetGoodsPaging, actionSetOrdersPaging, getGoodsCount } from '../reducers';
 
-const Pagination = ({ allEntitiesCount, fromPage, pageSize, changePage, changePageFE, changeRowsPerPage, changeRowsPerPageFE }) => {
+const Pagination = ({ allEntitiesCount, fromPage, pageSize, changePageFE, changeRowsPerPageFE }) => {
     allEntitiesCount = allEntitiesCount ?? 0;
-    //const [rowsPerPage, setRowsPerPage] = useState(5);
     const handleChangePage = (event, newPage) => {
-        if (changePage)
-            changePage(newPage);
         changePageFE(newPage);
     };
     const handleChangeRowsPerPage = (event) => {
         let newPageSize = parseInt(event.target.value, 10);
-        //setRowsPerPage(newPageSize);
-        if (changeRowsPerPage)
-            changeRowsPerPage(newPageSize);
         changeRowsPerPageFE(newPageSize);
     };
     return (
@@ -32,20 +25,17 @@ const Pagination = ({ allEntitiesCount, fromPage, pageSize, changePage, changePa
     )
 }
 
-export const COrdersPagination = connect(
-    state => (
-        {
-            allEntitiesCount: state.orders.ordersCount?.payload,
-        }),
-    {
-        changePageFE: (fromPage, pageSize) => actionSetOrdersPaging({ fromPage, pageSize }),
-        changePage: (fromPage, pageSize) => actionFindOrders(fromPage, pageSize),
-        changeRowsPerPageFE: pageSize => actionSetOrdersPaging({ fromPage: 0, pageSize }),
-        changeRowsPerPage: pageSize => actionFindOrders(0, pageSize),
-    })(Pagination);
-
-
 
+export const COrdersPagination = () => {
+    let state = useSelector(state => state);
+    let allEntitiesCount = getOrdersCount(state);
+    let dispatch = useDispatch();
+    let changePageFE = (fromPage) => dispatch(actionSetOrdersPaging({ fromPage }));
+    let changeRowsPerPageFE = pageSize => dispatch(actionSetOrdersPaging({ fromPage: 0, pageSize }));
+    let fromPage = state.frontend.ordersPaging.fromPage;
+    const pageSize = state.frontend.ordersPaging.pageSize;
+    return <Pagination allEntitiesCount={allEntitiesCount} fromPage={fromPage} pageSize={pageSize} changePageFE={changePageFE} changeRowsPerPageFE={changeRowsPerPageFE} />
+}
 export const CGoodsPagination = () => {
     let state = useSelector(state => state);
     let allEntitiesCount = getGoodsCount(state);
@@ -57,15 +47,3 @@ export const CGoodsPagination = () => {
     return <Pagination allEntitiesCount={allEntitiesCount} fromPage={fromPage} pageSize={pageSize} changePageFE={changePageFE} changeRowsPerPageFE={changeRowsPerPageFE} />
 }
 
-/*export const CGoodsPagination = connect(
-    state => (
-        {
-            allEntitiesCount: state.goods.goodsCount?.payload ?? 0,
-        }),
-    {
-        changePageFE: (fromPage, pageSize) => actionSetGoodsPaging({ fromPage, pageSize }),
-        changePage: (fromPage, pageSize) => actionGoodFind(fromPage, pageSize),
-        changeRowsPerPageFE: pageSize => actionSetGoodsPaging({ fromPage: 0, pageSize }),
-        changeRowsPerPage: pageSize => actionGoodFind(0, pageSize),
-    })(Pagination);
-*/

+ 1 - 1
src/Components/index.js

@@ -3,7 +3,7 @@ export { CGoodItem } from './GoodItem';
 export { CGood } from './Good';
 export { CGoodsList } from './GoodsList';
 export { OrderGood } from './OrderGood';
-export { OrderGoodsList, exampleOrderGoodsList } from './OrderGoodsList'
+export { OrderGoodsList} from './OrderGoodsList'
 export { COrder } from './Order';
 export { COrdersList } from './OrderList';
 export { MyLink } from './MyLink';

+ 0 - 53
src/gql/BAK/gqlAuth.js

@@ -1,53 +0,0 @@
-/*import {gql} from "../utills";
-import {actionAuthLogin} from '../reducers';
-
-
-export const actionLogin = (login, password) => {
-    const upsertQuery = `query login($login:String, $password:String){
-                        login(login:$login, password:$password)
-                }`;
-
-    return gql(upsertQuery, { login: login, password: password });
-}
-
-export const actionFullLogin = (login, password) => {
-    return async (dispatch) => {
-        try {
-            delete localStorage.authToken;
-            //dispatch возвращает то, что вернул thunk, возвращаемый actionLogin, а там промис, 
-            //так как actionPromise возвращает асинхронную функцию
-            let promiseResult = actionLogin(login, password);
-            let res = await promiseResult;
-            if (res && res.data) {
-                let token = Object.values(res.data)[0];
-                if (token && typeof token == 'string')
-                    return dispatch(actionAuthLogin(token));
-            }
-        }
-        catch (error) {
-            throw error;
-        }
-    }
-}
-////////////////////////////////////////
-export const actionAuthUpsert = (login, password) => {
-    const loginQuery = `mutation UserRegistration($login: String, $password: String) {
-                            UserUpsert(user: {login: $login, password: $password}) {
-                                _id createdAt
-                            }
-                        }`;
-
-    return gql(loginQuery, { login: login, password: password });////////  
-}*/
-/*export const actionFullAuthUpsert = (login, password) => {
-    return gqlFullAuthUpsert = async (dispatch) => {
-        //dispatch возвращает то, что вернул thunk, возвращаемый actionLogin, а там промис, 
-        //так как actionPromise возвращает асинхронную функцию
-        delete localStorage.authToken;
-        let promiseResult = actionAuthUpsert(login, password);
-        let res = await promiseResult;
-        dispatch(actionFullLogin(login, password));
-        console.log(res)
-        //проверьте что token - строка и отдайте его в actionAuthLogin
-    }
-}*/

+ 0 - 54
src/gql/gqlOrders.js

@@ -1,54 +0,0 @@
-import { gql } from "../utills/gql";
-import { createFullQuery } from "./gqlUtils";
-
-const getOrderSearchParams = query => ({ searchStr: query, searchFieldNames: ["_id"] });
-
-export const gqlOrderFindOne = (_id) => {
-    let params = createFullQuery({ queryExt: { _id } });
-    const gqlQuery = `query OrderFindOne($q: String) {
-        OrderFindOne(query: $q) {
-            _id total createdAt
-            orderGoods {
-                _id price count total createdAt
-                good {
-                    _id
-                    name 
-                    images { url }
-                }
-            }
-        }
-        }`;
-    return gql(gqlQuery, params);
-}
-
-export const gqlFindOrders = (fromPage, pageSize, query = '') => {
-    let params = createFullQuery(getOrderSearchParams(query), { fromPage, pageSize });
-    const gqlQuery = `query OrderFind($q: String) {
-                            OrderFind(query: $q) {
-                                _id total
-                                orderGoods {
-                                    _id price count total createdAt
-                                    good {
-                                        name 
-                                        images { url }
-                                    }
-                                }
-                            }
-                            }`;
-    return gql(gqlQuery, params);
-}
-
-export const gqlOrdersCount = (query = '') => {
-    let params = createFullQuery(getOrderSearchParams(query));
-    const catQuery = `query OrdersCount($q: String) { OrderCount(query: $q) }`;
-    return gql(catQuery, params);
-}
-
-export const gqlAddOrder = (order, id = null) => {
-    const orderUpsertQuery = `mutation OrderUpsert($order: OrderInput) {
-                            OrderUpsert(order: $order) {
-                                _id
-                            }
-                        }`;
-    return gql(orderUpsertQuery, { order: { "_id": id, "orderGoods": order } });
-}

+ 0 - 2
src/gql/index.js

@@ -1,4 +1,2 @@
-export { actionAuthUpsert, actionLogin, actionFullLogin } from './BAK/gqlAuth';
 export { gqlGoodFind, gqlGoodFindOne } from './gqlGoods';
-export { gqlOrderFindOne, gqlFindOrders, gqlOrdersCount, gqlAddOrder } from './gqlOrders';
 export {createFullQuery} from './gqlUtils';

+ 0 - 38
src/reducers/BAK/ordersReducer.js

@@ -1,38 +0,0 @@
-import { gqlFindOrders, gqlOrderFindOne, gqlOrdersCount, gqlAddOrder } from "../gql/gqlOrders";
-import { actionClearCart } from "./cartReducer";
-
-import { actionPromiseGeneric, createPromiseReducerSlice } from "./promiseReducer";
-
-const actionFindOrders = (fromPage = 0, pageSize = undefined, query = null) =>
-    actionPromiseOrders('orders', gqlFindOrders(fromPage, pageSize, query));
-
-const actionOrdersCount = (query = null) =>
-    actionPromiseOrders('ordersCount', gqlOrdersCount(query));
-
-const currentOrder = 'currentOrder';
-const actionOrderFindOne = (id) =>
-    actionPromiseOrders(currentOrder, gqlOrderFindOne(id));
-const getCurrentOrder = state => (
-    state.orders[currentOrder]?.payload
-)
-const actionPlaceOrder = () => {
-    return async (dispatch, getState) => {
-        let state = getState();
-        if (state.cart.goods.length > 0) {
-            let order = [];
-            for (let good of Object.values(state.cart.goods)) {
-                order.push({ good: { _id: good._id }, count: good.count });
-            }
-            dispatch(actionPromiseOrders('placedOrderInfo', gqlAddOrder(order)));
-            dispatch(actionClearCart());
-        }
-    }
-}
-
-
-const ordersReducerSlice = createPromiseReducerSlice('orders');
-const actionPromiseOrders = (name, promise) =>
-    actionPromiseGeneric(ordersReducerSlice, name, promise);
-
-let ordersReducer = ordersReducerSlice.reducer;
-export { ordersReducer, actionOrdersCount, actionFindOrders, actionOrderFindOne, actionPlaceOrder, getCurrentOrder }

+ 42 - 7
src/reducers/frontEndReducer.js

@@ -1,6 +1,9 @@
 import { createSlice } from "@reduxjs/toolkit"
+import { useDispatch } from "react-redux";
+import { actionClearCart } from "./cartReducer";
 import { categoryApi } from "./categoryReducer";
 import { goodsApi } from "./goodsReducer";
+import { ordersApi } from "./ordersReducer";
 
 const frontEndReducerSlice = createSlice({ //promiseReducer
     name: 'frontend', //префикс типа наподобие AUTH_
@@ -15,7 +18,10 @@ const frontEndReducerSlice = createSlice({ //promiseReducer
             return state;
         },
         setOrdersPaging(state, action) {
-            state.ordersPaging = { fromPage: action.payload.page.fromPage, pageSize: action.payload.page.pageSize };
+            let { fromPage, pageSize } = action.payload.page;
+            fromPage = fromPage ?? state.goodsPaging?.fromPage;
+            pageSize = pageSize ?? state.goodsPaging?.pageSize;
+            state.ordersPaging = { fromPage, pageSize };
             return state;
         },
         setOrdersSearch(state, action) {
@@ -23,7 +29,7 @@ const frontEndReducerSlice = createSlice({ //promiseReducer
             return state;
         },
         setGoodsPaging(state, action) {
-            let {fromPage, pageSize} = action.payload.page;
+            let { fromPage, pageSize } = action.payload.page;
             fromPage = fromPage ?? state.goodsPaging?.fromPage;
             pageSize = pageSize ?? state.goodsPaging?.pageSize;
             state.goodsPaging = { fromPage, pageSize };
@@ -41,6 +47,10 @@ const frontEndReducerSlice = createSlice({ //promiseReducer
             setCurrentGood(state, action.payload._id);
             return state;
         },
+        setCurrentOrder(state, action) {
+            setCurrentOrder(state, action.payload._id);
+            return state;
+        },
     },
     extraReducers: builder => {
         builder.addMatcher(goodsApi.endpoints.getGoodsCount.matchFulfilled,
@@ -51,6 +61,15 @@ const frontEndReducerSlice = createSlice({ //promiseReducer
             (state, { payload }) => {
                 state.goodsPaging.fromPage = 0;
             });
+        builder.addMatcher(ordersApi.endpoints.getOrdersCount.matchFulfilled,
+            (state, { payload }) => {
+                state.orders = { ordersCount: { payload: payload.OrderCount } }
+            });
+        builder.addMatcher(ordersApi.endpoints.addOrder.matchFulfilled,
+            (state, { payload }) => {
+                const dispatch = useDispatch();
+                dispatch(actionClearCart());
+            });
     }
 
 })
@@ -76,6 +95,11 @@ let actionSetCurrentCategory = (_id) =>
         dispatch(frontEndReducerSlice.actions.setCurrentCategory({ _id }))
     }
 
+let actionSetCurrentOrder = (_id) =>
+    async dispatch => {
+        dispatch(frontEndReducerSlice.actions.setCurrentOrder({ _id }))
+    }
+
 let actionSetCurrentGood = (_id) =>
     async dispatch => {
         dispatch(frontEndReducerSlice.actions.setCurrentGood({ _id }))
@@ -92,31 +116,42 @@ let actionSetGoodsSearch = (searchStr) =>
     }
 
 const currentCategory = 'currentCategory';
-
 const getCurrentCategory = state => {
     let result = state.frontend[currentCategory]?.payload
     return result;
 }
-
 const setCurrentCategory = (state, id) => {
     return state[currentCategory] = { payload: id };
 }
-const currentGood = 'currentGood';
 
+const currentGood = 'currentGood';
 const getCurrentGood = state => {
     let result = state.frontend[currentGood]?.payload
     return result;
 }
-
 const setCurrentGood = (state, id) => {
     return state[currentGood] = { payload: id };
 }
 
+const currentOrder = 'currentOrder';
+const getCurrentOrder = state => {
+    let result = state.frontend[currentOrder]?.payload
+    return result;
+}
+const setCurrentOrder = (state, id) => {
+    return state[currentOrder] = { payload: id };
+}
+
 const getGoodsCount = state => {
     let result = state.frontend.goods.goodsCount?.payload ?? 0;
     return result;
 }
+const getOrdersCount = state => {
+    let result = state.frontend.orders.ordersCount?.payload ?? 0;
+    return result;
+}
 
 
 export { frontEndReducer, actionSetSidebar, actionSetOrdersPaging, actionSetOrderSearch, actionSetGoodsPaging, actionSetGoodsSearch };
-export { getCurrentCategory, getCurrentGood, actionSetCurrentCategory, actionSetCurrentGood, getGoodsCount }
+export { getCurrentCategory, getCurrentGood, actionSetCurrentCategory, actionSetCurrentGood, getGoodsCount, getCurrentOrder, actionSetCurrentOrder }
+export { getOrdersCount };

+ 2 - 2
src/reducers/index.js

@@ -3,9 +3,9 @@ export { authApiReducer, authReducer, authApiReducerPath, loginApi, authReducerP
 export { cartReducer, actionAddGoodToCart, actionDeleteGoodFromCart, actionRestoreCart, actionClearCart, getCart, } from "./cartReducer";
 export { cartGoodsReducer, actionLoadCart } from "./cartGoodsReducer";
 export { localStoredReducer, } from "./localStoredReducer";
-export { frontEndReducer, getCurrentCategory, actionSetGoodsPaging, actionSetOrdersPaging, getCurrentGood, getGoodsCount } from "./frontEndReducer";
+export { frontEndReducer, getCurrentCategory, actionSetGoodsPaging, actionSetOrdersPaging, getCurrentGood, getGoodsCount, getOrdersCount } from "./frontEndReducer";
 export { useGetRootCategoriesQuery, useGetCategoryByIdQuery } from './categoryReducer';
-export { actionFindOrders, actionOrdersCount, actionPlaceOrder } from './ordersReducer';
+export { ordersApi, useGetOrderByIdQuery, useGetOrdersCountQuery, useGetOrdersQuery, actionAddOrder } from './ordersReducer';
 export { goodsApi, useGetGoodByIdQuery, useGetGoodsCountQuery, useGetGoodsQuery } from './goodsReducer';
 
 

+ 97 - 25
src/reducers/ordersReducer.js

@@ -1,21 +1,96 @@
-import { gqlFindOrders, gqlOrderFindOne, gqlOrdersCount, gqlAddOrder } from "../gql/gqlOrders";
-import { actionClearCart } from "./cartReducer";
-
-import { actionPromiseGeneric, createPromiseReducerSlice } from "./promiseReducer";
-
-const actionFindOrders = (fromPage = 0, pageSize = undefined, query = null) =>
-    actionPromiseOrders('orders', gqlFindOrders(fromPage, pageSize, query));
-
-const actionOrdersCount = (query = null) =>
-    actionPromiseOrders('ordersCount', gqlOrdersCount(query));
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query"
+import { gql } from "graphql-request";
+import { createFullQuery } from '../gql';
+ 
+const getOrderSearchParams = query => ({ searchStr: query, searchFieldNames: ["_id"] });
+const prepareHeaders = (headers, { getState }) => {
+    const token = getState().auth.token;
+    if (token) {
+        headers.set("Authorization", `Bearer ${token}`);
+    }
+    return headers;
+}
+const getOrdersSearchParams = query => ({ searchStr: query, searchFieldNames: ["_id"] });
+const ordersApi = createApi({
+    reducerPath: 'orders',
+    baseQuery: graphqlRequestBaseQuery({
+        url: '/graphql',
+        prepareHeaders
+    }),
+    endpoints: (builder) => ({
+        getOrders: builder.query({
+            query: ({ fromPage, pageSize, searchStr = '' }) => {
+                let params = createFullQuery(getOrderSearchParams(searchStr), { fromPage, pageSize });
+                return {
+                    document: gql`
+                            query OrderFind($q: String) {
+                                OrderFind(query: $q) {
+                                    _id total
+                                    orderGoods {
+                                        _id price count total createdAt
+                                        good {
+                                            name 
+                                            images { url }
+                                        }
+                                    }
+                                }
+                            }
+                `,
+                    variables: params
+                }
+            },
+        }),
+        getOrdersCount: builder.query({
+            query: ({ searchStr = '' }) => {
+                let params = createFullQuery(getOrderSearchParams(searchStr));
+                return {
+                    document: gql`
+                            query OrdersCount($q: String) { OrderCount(query: $q) }
+                    `,
+                    variables: params
+                }
+            },
+        }),
+        getOrderById: builder.query({
+            query: (_id) => {
+                let params = createFullQuery({ queryExt: { _id } });
+                return {
+                    document: gql`
+                            query OrderFindOne($q: String) {
+                                OrderFindOne(query: $q) {
+                                    _id total createdAt
+                                    orderGoods {
+                                        _id price count total createdAt
+                                        good {
+                                            _id
+                                            name 
+                                            images { url }
+                                        }
+                                    }
+                                }
+                            }
+                    `,
+                    variables: params
+                }
+            },
+        }),
+        addOrder: builder.mutation({
+            query: ({ order, id = null }) => ({
+                document: gql`
+                        mutation OrderUpsert($order: OrderInput) {
+                            OrderUpsert(order: $order) {
+                                _id
+                            } 
+                        }
+                        `,
+                variables: JSON.stringify({ order: { "_id": id, "orderGoods": order } })
+            })
+        }),
+    }),
+});
 
-const currentOrder = 'currentOrder';
-const actionOrderFindOne = (id) =>
-    actionPromiseOrders(currentOrder, gqlOrderFindOne(id));
-const getCurrentOrder = state => (
-    state.orders[currentOrder]?.payload
-)
-const actionPlaceOrder = () => {
+const actionAddOrder = () => {
     return async (dispatch, getState) => {
         let state = getState();
         if (state.cart.goods.length > 0) {
@@ -23,16 +98,13 @@ const actionPlaceOrder = () => {
             for (let good of Object.values(state.cart.goods)) {
                 order.push({ good: { _id: good._id }, count: good.count });
             }
-            dispatch(actionPromiseOrders('placedOrderInfo', gqlAddOrder(order)));
-            dispatch(actionClearCart());
+            const addOrderMutation = ordersApi.useAddOrderMutation();
+            dispatch(addOrderMutation({ order }));
+            //dispatch(actionClearCart());
         }
     }
 }
 
+export const { useGetOrdersQuery, useGetOrdersCountQuery, useGetOrderByIdQuery } = ordersApi;
+export { ordersApi, actionAddOrder };
 
-const ordersReducerSlice = createPromiseReducerSlice('orders');
-const actionPromiseOrders = (name, promise) =>
-    actionPromiseGeneric(ordersReducerSlice, name, promise);
-
-let ordersReducer = ordersReducerSlice.reducer;
-export { ordersReducer, actionOrdersCount, actionFindOrders, actionOrderFindOne, actionPlaceOrder, getCurrentOrder }