|
@@ -25,10 +25,6 @@ function createStore(reducer) {
|
|
|
}
|
|
|
|
|
|
function promiseReducer(state = {}, {type, name, status, payload, error}) {
|
|
|
- //{
|
|
|
- // login: {status, payload, error}
|
|
|
- // catById: {status, payload, error}
|
|
|
- //}
|
|
|
if (type === 'PROMISE') {
|
|
|
return {
|
|
|
...state,
|
|
@@ -41,10 +37,9 @@ function promiseReducer(state = {}, {type, name, status, payload, error}) {
|
|
|
function jwtDecode(token) {
|
|
|
try {
|
|
|
let newToken = token.split('.')[1];
|
|
|
- let myToken = JSON.parse(atob(newToken));
|
|
|
- return myToken;
|
|
|
+ return JSON.parse(atob(newToken));
|
|
|
} catch (e) {
|
|
|
- console.log(e);
|
|
|
+ console.error(e);
|
|
|
}
|
|
|
//раскодировать токен:
|
|
|
//выкусить середочку
|
|
@@ -53,12 +48,18 @@ function jwtDecode(token) {
|
|
|
//на любом этапе могут быть исключения
|
|
|
}
|
|
|
|
|
|
+function getTokenFromLS() {
|
|
|
+ const token = localStorage.getItem('auth');
|
|
|
|
|
|
-function authReducer(state = {}, {type, token}) {
|
|
|
+ return !!token && token !== 'undefined' ? {token} : {};
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+function authReducer(state = getTokenFromLS(), {type, token}) {
|
|
|
if (!state) {
|
|
|
- if (localStorage.getItem('authToken')) {
|
|
|
+ if (localStorage.getItem('auth')) {
|
|
|
type = 'AUTH_LOGIN';
|
|
|
- token = localStorage.getItem('authToken');
|
|
|
+ token = localStorage.getItem('auth');
|
|
|
} else {
|
|
|
return {};
|
|
|
}
|
|
@@ -80,18 +81,15 @@ function authReducer(state = {}, {type, token}) {
|
|
|
};
|
|
|
}
|
|
|
if (type === 'AUTH_LOGOUT') {
|
|
|
- localStorage.removeItem('authToken');
|
|
|
+ localStorage.removeItem('auth');
|
|
|
return {};
|
|
|
//почистить localStorage
|
|
|
//вернуть пустой объект
|
|
|
}
|
|
|
+ console.log(state);
|
|
|
return state;
|
|
|
}
|
|
|
|
|
|
-const actionAuthLogin = token => ({type: 'AUTH_LOGIN', token});
|
|
|
-
|
|
|
-const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'});
|
|
|
-
|
|
|
function combineReducers(reducers) {
|
|
|
|
|
|
return (state = {}, action) => {
|
|
@@ -123,9 +121,19 @@ function combineReducers(reducers) {
|
|
|
const combinedReducer = combineReducers({promise: promiseReducer, auth: authReducer, cart: cartReducer});
|
|
|
const store = createStore(combinedReducer);
|
|
|
|
|
|
-// console.log(store.getState())
|
|
|
+const actionAuthLogin = (token) => ({type: 'AUTH_LOGIN', token});
|
|
|
+
|
|
|
+const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'});
|
|
|
+
|
|
|
+
|
|
|
+function getCartFromLS() {
|
|
|
+ const cart = JSON.parse(localStorage.getItem('cart'));
|
|
|
|
|
|
-function cartReducer(state = {}, {type, good = {}, count = 1}) {
|
|
|
+ return !!cart ? cart : {};
|
|
|
+}//??
|
|
|
+
|
|
|
+
|
|
|
+function cartReducer(state = getCartFromLS(), {type, good = {}, count = 1}) {
|
|
|
const {_id} = good;
|
|
|
// const {count} = good;
|
|
|
// {
|
|
@@ -144,22 +152,16 @@ function cartReducer(state = {}, {type, good = {}, count = 1}) {
|
|
|
},
|
|
|
CART_REMOVE() { //смочь скопировать объект и выкинуть ключ. как вариант через
|
|
|
//деструктуризацию
|
|
|
- const newState = {...state};
|
|
|
- // const {_id} = good;
|
|
|
|
|
|
- // delete newState[_id];
|
|
|
- // console.log({newState});
|
|
|
- return {
|
|
|
- [_id]: {good, count},
|
|
|
- ...newState
|
|
|
- };
|
|
|
+ return Object.fromEntries(Object.entries(state).filter(([key, value]) => {
|
|
|
+ return key !== _id;
|
|
|
+
|
|
|
+ }));
|
|
|
},
|
|
|
CART_CHANGE() {
|
|
|
- // const {_id} = good;
|
|
|
return {
|
|
|
...state, //по аналогии с promiseReducer дописать
|
|
|
- [_id]: {good, count: state[_id]?.count - count}
|
|
|
-
|
|
|
+ [_id]: {good, count}
|
|
|
};
|
|
|
},
|
|
|
CART_CLEAR() {
|
|
@@ -168,7 +170,6 @@ function cartReducer(state = {}, {type, good = {}, count = 1}) {
|
|
|
};
|
|
|
|
|
|
if (type in types) {
|
|
|
- console.log(types[type]());
|
|
|
return types[type]();
|
|
|
}
|
|
|
return state;
|
|
@@ -195,11 +196,10 @@ const actionLogin = (login, password) =>
|
|
|
|
|
|
const actionFullLogin = (login, password) =>
|
|
|
async dispatch => {
|
|
|
- console.log(login, password);
|
|
|
- let token = await dispatch(actionLogin(login, password));
|
|
|
- console.log(token);
|
|
|
+ const token = await dispatch(actionLogin(login, password));
|
|
|
if (token) {
|
|
|
- dispatch(actionAuthLogin(token));
|
|
|
+ await dispatch(actionAuthLogin(token));
|
|
|
+ await dispatch(actionMyOrders());
|
|
|
}
|
|
|
};
|
|
|
|
|
@@ -234,27 +234,7 @@ const actionCartChange = (good, count = 1) => ({type: 'CART_CHANGE', good, count
|
|
|
const actionCartDelete = (good, count = 0) => ({type: 'CART_REMOVE', good, count});
|
|
|
const actionCartClear = () => ({type: 'CART_CLEAR'});
|
|
|
|
|
|
-const actionOrder = () =>
|
|
|
- async (dispatch, getState) => {
|
|
|
- let {cart} = getState();
|
|
|
|
|
|
- const orderGoods = Object.entries(cart)
|
|
|
- .map(([_id, {...key}]) => ({good: {_id}, count: key.count}));
|
|
|
-
|
|
|
- let result = await dispatch(actionPromise('order', gql(`
|
|
|
- mutation newOrder($order:OrderInput){
|
|
|
- OrderUpsert(order:$order)
|
|
|
- { _id total }
|
|
|
- }
|
|
|
- `, {order: {orderGoods}})));
|
|
|
-
|
|
|
- if (result?._id) {
|
|
|
- dispatch(actionCartClear());
|
|
|
- }
|
|
|
- };
|
|
|
-
|
|
|
-
|
|
|
-console.log(store.getState()); //стартовое состояние может быть с токеном
|
|
|
store.subscribe(() => console.log(store.getState()));
|
|
|
|
|
|
//проверить:
|
|
@@ -265,7 +245,6 @@ const actionPending = name => ({type: 'PROMISE', status: 'PENDING', name});
|
|
|
const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload});
|
|
|
const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error});
|
|
|
const actionPromise = (name, promise) =>
|
|
|
-
|
|
|
async dispatch => {
|
|
|
dispatch(actionPending(name)); // 1. {delay1000: {status: 'PENDING'}}
|
|
|
try {
|
|
@@ -285,8 +264,7 @@ const getGQL = url =>
|
|
|
headers: {
|
|
|
//заголовок content-type
|
|
|
'Content-Type': 'application/json',
|
|
|
- ...(localStorage.authToken ? {'Authorization': 'Bearer ' + localStorage.authToken} :
|
|
|
- {})
|
|
|
+ ...(localStorage.getItem('auth') ? {'Authorization': 'Bearer ' + localStorage.getItem('auth')} : {})
|
|
|
},
|
|
|
//body с ключами query и variables
|
|
|
body: JSON.stringify({query, variables})
|
|
@@ -302,8 +280,6 @@ const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
|
|
|
|
|
|
const gql = getGQL(`${backURL}/graphql`);
|
|
|
|
|
|
-const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
|
|
|
-
|
|
|
const actionRootCats = () =>
|
|
|
actionPromise('rootCats', gql(`query {
|
|
|
CategoryFind(query: "[{\\"parent\\":null}]"){
|
|
@@ -349,6 +325,47 @@ const actionGoodById = (_id) =>
|
|
|
|
|
|
store.dispatch(actionRootCats());
|
|
|
|
|
|
+const actionOrder = () =>
|
|
|
+ async (dispatch, getState) => {
|
|
|
+ let {cart} = getState();
|
|
|
+
|
|
|
+ const orderGoods = Object.entries(cart)
|
|
|
+ .map(([_id, {...key}]) => ({good: {_id}, count: key.count}));
|
|
|
+
|
|
|
+ let result = await dispatch(actionPromise('order', gql(`
|
|
|
+ mutation newOrder($order:OrderInput){
|
|
|
+ OrderUpsert(order:$order)
|
|
|
+ { _id total orderGoods{
|
|
|
+ price count good{
|
|
|
+ name createdAt price images{
|
|
|
+ url
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ `, {order: {orderGoods}})));
|
|
|
+
|
|
|
+ if (result?._id) {
|
|
|
+ dispatch(actionCartClear());
|
|
|
+ }
|
|
|
+ };
|
|
|
+
|
|
|
+actionMyOrders = () =>
|
|
|
+ actionPromise('myOrders', gql(
|
|
|
+ `query o{
|
|
|
+ OrderFind(query:"[{}]"){
|
|
|
+ _id total orderGoods{
|
|
|
+ price count total
|
|
|
+ good{
|
|
|
+ createdAt name price images{
|
|
|
+ url text
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}`));
|
|
|
+
|
|
|
|
|
|
store.subscribe(() => {
|
|
|
const {rootCats} = store.getState().promise;
|
|
@@ -356,7 +373,6 @@ store.subscribe(() => {
|
|
|
if (rootCats?.payload) {
|
|
|
aside.innerHTML = '';
|
|
|
|
|
|
-
|
|
|
for (const {_id, name} of rootCats?.payload) {
|
|
|
const link = document.createElement('a');
|
|
|
link.href = `#/category/${_id}`;
|
|
@@ -369,9 +385,7 @@ store.subscribe(() => {
|
|
|
|
|
|
window.onhashchange = () => {
|
|
|
const [, route, _id] = location.hash.split('/');
|
|
|
- console.log(_id, route);
|
|
|
const routes = {
|
|
|
-
|
|
|
category() {
|
|
|
store.dispatch(actionCatById(_id));
|
|
|
console.log('КАТЕГОРИИСТРАНИЦА');
|
|
@@ -381,47 +395,65 @@ window.onhashchange = () => {
|
|
|
console.log('ТОВАРОСТРАНИЦА');
|
|
|
},
|
|
|
login() {
|
|
|
+ console.log('LOGIN');
|
|
|
main.innerHTML = '';
|
|
|
+ const token = localStorage.getItem('auth');
|
|
|
|
|
|
- const h2Greeting = document.createElement('h2');
|
|
|
- h2Greeting.textContent = 'Вход в личный кабинет';
|
|
|
+ if (!token || token === 'undefined') {
|
|
|
+ const h2Greeting = document.createElement('h2');
|
|
|
+ h2Greeting.textContent = 'Вход в личный кабинет';
|
|
|
|
|
|
- const loginInput = document.createElement('input');
|
|
|
- loginInput.type = 'text';
|
|
|
- loginInput.className = 'loginInput';
|
|
|
- loginInput.placeholder = 'Логин';
|
|
|
+ const loginInput = document.createElement('input');
|
|
|
+ loginInput.type = 'login';
|
|
|
+ loginInput.className = 'loginInput';
|
|
|
+ loginInput.placeholder = 'Логин';
|
|
|
|
|
|
- const pswInput = document.createElement('input');
|
|
|
- pswInput.type = 'password';
|
|
|
- pswInput.className = 'pswInput';
|
|
|
- pswInput.placeholder = 'Пароль';
|
|
|
+ const pswInput = document.createElement('input');
|
|
|
+ pswInput.type = 'password';
|
|
|
+ pswInput.className = 'pswInput';
|
|
|
+ pswInput.placeholder = 'Пароль';
|
|
|
|
|
|
- const buttonSend = document.createElement('button');
|
|
|
- buttonSend.className = 'buttonSend';
|
|
|
- buttonSend.textContent = 'Войти';
|
|
|
- buttonSend.onclick = (e) => {
|
|
|
- store.dispatch(actionFullLogin(loginInput.value, pswInput.value));
|
|
|
+ const buttonSend = document.createElement('button');
|
|
|
+ buttonSend.className = 'buttonSend';
|
|
|
+ buttonSend.textContent = 'Войти';
|
|
|
|
|
|
- };
|
|
|
+ buttonSend.onclick = () => {
|
|
|
+ if (loginInput.value !== '' && pswInput.value !== '') {
|
|
|
+ loginInput.style.borderColor = '#ccc';
|
|
|
+ pswInput.style.borderColor = '#ccc';
|
|
|
+ store.dispatch(actionFullLogin(loginInput.value, pswInput.value));
|
|
|
+ console.log('нажала на логин');
|
|
|
+ location.href = `#/dashboard/${_id}`;
|
|
|
+ } else {
|
|
|
+ loginInput.style.borderColor = 'red';
|
|
|
+ pswInput.style.borderColor = 'red';
|
|
|
|
|
|
- main.appendChild(h2Greeting);
|
|
|
- main.appendChild(loginInput);
|
|
|
- main.appendChild(pswInput);
|
|
|
- main.appendChild(buttonSend);
|
|
|
+ loginInput.placeholder = 'Введите логин!';
|
|
|
+ pswInput.placeholder = 'Введите пароль!';
|
|
|
+ }
|
|
|
+ };
|
|
|
|
|
|
- const divQuestion = document.createElement('div');
|
|
|
- divQuestion.textContent = 'Вы еще не зарегистрированы?';
|
|
|
- divQuestion.className = 'divQuestion';
|
|
|
+ main.appendChild(h2Greeting);
|
|
|
+ main.appendChild(loginInput);
|
|
|
+ main.appendChild(pswInput);
|
|
|
+ main.appendChild(buttonSend);
|
|
|
|
|
|
- const a = document.createElement('a');
|
|
|
- a.className = 'link';
|
|
|
- a.href = `#/register/${_id}`;
|
|
|
- a.textContent = 'Регистрация';
|
|
|
- main.appendChild(divQuestion);
|
|
|
- main.appendChild(a);
|
|
|
+ const divQuestion = document.createElement('div');
|
|
|
+ divQuestion.textContent = 'Вы еще не зарегистрированы?';
|
|
|
+ divQuestion.className = 'divQuestion';
|
|
|
|
|
|
+ const a = document.createElement('a');
|
|
|
+ a.className = 'link';
|
|
|
+ a.href = `#/register/${_id}`;
|
|
|
+ a.textContent = 'Регистрация';
|
|
|
+ main.appendChild(divQuestion);
|
|
|
+ main.appendChild(a);
|
|
|
+ console.log('Задиспатчила логин и пароль по клику');
|
|
|
|
|
|
- console.log('Задиспатчила логин и пароль по клику');
|
|
|
+ } else {
|
|
|
+ location.href = `#/dashboard/${_id}`; //??
|
|
|
+ console.log('перехожу в доску заказов, птмш уже авторизована');
|
|
|
+ }
|
|
|
|
|
|
},
|
|
|
register() {
|
|
@@ -468,13 +500,12 @@ window.onhashchange = () => {
|
|
|
a.href = `#/login/${_id}`;
|
|
|
a.textContent = 'Войти в личный кабинет';
|
|
|
main.appendChild(a);
|
|
|
-
|
|
|
};
|
|
|
console.log('передаю данные на регистрацию');
|
|
|
},
|
|
|
cart() {
|
|
|
|
|
|
- if (Object.entries(store.getState().cart).length !== 0) {
|
|
|
+ if (Object.keys(store.getState().cart).length !== 0) {
|
|
|
main.innerHTML = '';
|
|
|
|
|
|
for (const key in store.getState().cart) {
|
|
@@ -482,7 +513,6 @@ window.onhashchange = () => {
|
|
|
let {count} = store.getState().cart[key];
|
|
|
|
|
|
let {name, price, images} = good;
|
|
|
- console.log(good);
|
|
|
|
|
|
const headerName = document.createElement('h2');
|
|
|
headerName.innerHTML = name;
|
|
@@ -498,56 +528,29 @@ window.onhashchange = () => {
|
|
|
divPrice.innerHTML = `${currentPrice}грн`;
|
|
|
main.appendChild(divPrice);
|
|
|
|
|
|
-
|
|
|
- console.log(currentPrice, price);
|
|
|
-
|
|
|
const wrapperForCounter = document.createElement('div');
|
|
|
wrapperForCounter.className = 'wrapperForCounter';
|
|
|
|
|
|
- const buttonDelete = document.createElement('input');
|
|
|
- buttonDelete.type = 'button';
|
|
|
- buttonDelete.className = 'buttonDelete';
|
|
|
- buttonDelete.value = '-';
|
|
|
-
|
|
|
- buttonDelete.onclick = () => {
|
|
|
- divCount.innerHTML = `${--count}`;
|
|
|
-
|
|
|
- currentPrice = currentPrice - price;
|
|
|
- divPrice.innerHTML = `${currentPrice}грн`;
|
|
|
- console.log(currentPrice, price);
|
|
|
- store.dispatch(actionCartChange(good, 1));
|
|
|
- };
|
|
|
- wrapperForCounter.appendChild(buttonDelete);
|
|
|
-
|
|
|
- const divCount = document.createElement('div');
|
|
|
- divCount.innerHTML = count;
|
|
|
- wrapperForCounter.appendChild(divCount);
|
|
|
-
|
|
|
-
|
|
|
- const buttonAdd = document.createElement('input');
|
|
|
- buttonAdd.type = 'button';
|
|
|
- buttonAdd.className = 'buttonAdd';
|
|
|
- buttonAdd.value = '+';
|
|
|
-
|
|
|
- buttonAdd.onclick = () => {
|
|
|
- divCount.innerHTML = `${++count}`;
|
|
|
- currentPrice += price;
|
|
|
- divPrice.innerHTML = `${currentPrice}грн`;
|
|
|
-
|
|
|
- console.log(currentPrice, price);
|
|
|
- store.dispatch(actionCartAdd(good, 1));
|
|
|
+ const inputChangeNumber = document.createElement('input');
|
|
|
+ inputChangeNumber.className = 'inputChangeNumber';
|
|
|
+ inputChangeNumber.type = 'number';
|
|
|
+ inputChangeNumber.value = count;
|
|
|
|
|
|
+ inputChangeNumber.onclick = () => {
|
|
|
+ const inputValue = inputChangeNumber.value;
|
|
|
+ divPrice.innerHTML = `${price * +inputValue}грн`;
|
|
|
+ store.dispatch(actionCartChange(good, +inputValue));
|
|
|
};
|
|
|
|
|
|
- wrapperForCounter.appendChild(buttonAdd);
|
|
|
+ wrapperForCounter.appendChild(inputChangeNumber);
|
|
|
|
|
|
const buttonDeleteGood = document.createElement('input');
|
|
|
buttonDeleteGood.type = 'button';
|
|
|
buttonDeleteGood.className = 'buttonDeleteGood';
|
|
|
buttonDeleteGood.value = 'х';
|
|
|
buttonDeleteGood.onclick = () => {
|
|
|
- store.dispatch(actionCartDelete());
|
|
|
- main.innerHTML = '';
|
|
|
+ store.dispatch(actionCartDelete(good, inputChangeNumber.value));
|
|
|
+ window.location.reload()
|
|
|
};
|
|
|
wrapperForCounter.appendChild(buttonDeleteGood);
|
|
|
|
|
@@ -561,12 +564,8 @@ window.onhashchange = () => {
|
|
|
main.appendChild(buttonSend);
|
|
|
|
|
|
buttonSend.onclick = () => {
|
|
|
- if (Object.entries(store.getState().auth).length !== 0) {
|
|
|
- store.dispatch(actionOrder(_id));
|
|
|
- store.dispatch(actionCartClear());
|
|
|
- } else {
|
|
|
- main.innerHTML = 'Вы не можете оформить заказ, войдите в личный кабинет или зарегестрируйтесь!';
|
|
|
- }
|
|
|
+ store.dispatch(actionOrder(_id));
|
|
|
+ location.href = `#/dashboard/${_id}`;
|
|
|
};
|
|
|
|
|
|
console.log('СТРАНИЦА КОРЗИНЫ');
|
|
@@ -576,12 +575,41 @@ window.onhashchange = () => {
|
|
|
|
|
|
},
|
|
|
dashboard() {
|
|
|
+ store.dispatch(actionMyOrders());
|
|
|
+
|
|
|
+ main.innerHTML = '';
|
|
|
+
|
|
|
+ const wrapperForPrivate = document.createElement('div');
|
|
|
+ wrapperForPrivate.className = 'wrapperForPrivate';
|
|
|
+
|
|
|
+ const divNameofPage = document.createElement('h2');
|
|
|
+ divNameofPage.className = 'divNameofPage';
|
|
|
+ divNameofPage.textContent = 'Личный кабинет';
|
|
|
+ wrapperForPrivate.appendChild(divNameofPage);
|
|
|
+
|
|
|
+ const buttonLogOff = document.createElement('button');
|
|
|
+ buttonLogOff.className = 'buttonLogOff';
|
|
|
+ buttonLogOff.textContent = 'Выход';
|
|
|
+ wrapperForPrivate.appendChild(buttonLogOff);
|
|
|
+
|
|
|
+ buttonLogOff.onclick = () => {
|
|
|
+ store.dispatch(actionAuthLogout());
|
|
|
+ main.innerHTML = 'Вы вышли с личного кабинета! До новых встреч :)'; //??
|
|
|
+ };
|
|
|
+
|
|
|
+ main.appendChild(wrapperForPrivate);
|
|
|
+
|
|
|
+ const headerOrders = document.createElement('div');
|
|
|
+ headerOrders.style.fontSize = '20px';
|
|
|
+ headerOrders.textContent = 'История заказов';
|
|
|
+ main.appendChild(headerOrders);
|
|
|
+
|
|
|
+ console.log('СТОРЕ ДИСПАТЧ ПРОЧИТАТЬ БЫВШИЕ ЗАКАЗЫ');
|
|
|
|
|
|
}
|
|
|
};
|
|
|
|
|
|
if (route in routes) {
|
|
|
- console.log(route);
|
|
|
routes[route]();
|
|
|
}
|
|
|
};
|
|
@@ -589,39 +617,88 @@ window.onhashchange = () => {
|
|
|
window.onhashchange();
|
|
|
|
|
|
store.subscribe(() => {
|
|
|
- const {login} = store.getState().promise;//??
|
|
|
- const [, route, _id] = location.hash.split('/');
|
|
|
+ const [, route, _id] = location.hash.split('/');
|
|
|
+ console.log(route);
|
|
|
|
|
|
- header.innerHTML = `<a class="nameGategory">Категории</a>
|
|
|
- <a href="#/login/${_id}" class="enterToPrivate">Вход в кабинет</a>`;
|
|
|
-
|
|
|
- //доработать логику
|
|
|
- // const {auth} = store.getState().auth;
|
|
|
- // if (store.getState().auth !== '') {
|
|
|
- console.log(store.getState().auth !== '');
|
|
|
- if (login?.payload && route === 'login') {
|
|
|
- console.log(login?.payload && route === 'login');
|
|
|
- // main.innerHTML = '';
|
|
|
- main.innerHTML = 'Личный кабинет, в процессе разработки...';
|
|
|
-
|
|
|
- const buttonBuy = document.createElement('button');
|
|
|
- buttonBuy.className = 'buttonBuy';
|
|
|
- buttonBuy.textContent = 'Выйти';
|
|
|
- buttonBuy.onclick = () => {
|
|
|
- store.dispatch(actionAuthLogout());
|
|
|
- main.innerHTML = 'Вы вышли с личного кабинета! До новых встреч :)'; //??
|
|
|
- };
|
|
|
+ if (route === 'dashboard') {
|
|
|
+ console.log('ДОСКА ЗАКАЗОВ');
|
|
|
|
|
|
- main.appendChild(buttonBuy);
|
|
|
+ const auth = store.getState().auth;
|
|
|
|
|
|
+ if (Object.keys(auth).length !== 0) {
|
|
|
+
|
|
|
+ localStorage.setItem('auth', auth.token);
|
|
|
+
|
|
|
+ const myOrders = store.getState().promise?.myOrders;
|
|
|
+ if (myOrders?.payload) {
|
|
|
+
|
|
|
+ myOrders?.payload.filter(order => {
|
|
|
+
|
|
|
+ const {total, orderGoods} = order;
|
|
|
+
|
|
|
+ if (total !== null) {
|
|
|
+
|
|
|
+ const divDashboardOrders = document.createElement('h2');
|
|
|
+ divDashboardOrders.className = 'divDashboardOrders';
|
|
|
+ main.appendChild(divDashboardOrders);
|
|
|
+
|
|
|
+ const divDescriptionOrder = document.createElement('div');
|
|
|
+ divDescriptionOrder.className = 'divDescriptionOrder';
|
|
|
+
|
|
|
+ const img = document.createElement('img');
|
|
|
+ img.src = `${backURL}/${orderGoods[0].good.images[0].url}`;
|
|
|
+ img.className = 'imgGood';
|
|
|
+ divDashboardOrders.appendChild(img);
|
|
|
+
|
|
|
+ const divName = document.createElement('div');
|
|
|
+ divName.className = 'divName';
|
|
|
+ divName.textContent = `${orderGoods[0].good.name}`;
|
|
|
+ divDescriptionOrder.appendChild(divName);
|
|
|
+
|
|
|
+ const wrapperForCharacteristicGood = document.createElement('div');
|
|
|
+ wrapperForCharacteristicGood.className = 'wrapperForCharacteristicGood';
|
|
|
+
|
|
|
+ const quantityDiv = document.createElement('div');
|
|
|
+ quantityDiv.textContent = `${orderGoods[0]['count']}шт`;
|
|
|
+ wrapperForCharacteristicGood.appendChild(quantityDiv);
|
|
|
+
|
|
|
+ const totalDiv = document.createElement('div');
|
|
|
+ totalDiv.textContent = `${order.total} грн`;
|
|
|
+ totalDiv.className = 'totalDiv';
|
|
|
+ wrapperForCharacteristicGood.appendChild(totalDiv);
|
|
|
+
|
|
|
+
|
|
|
+ divDashboardOrders.appendChild(divDescriptionOrder);
|
|
|
+ divDescriptionOrder.appendChild(wrapperForCharacteristicGood);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
}
|
|
|
- // }
|
|
|
+
|
|
|
}
|
|
|
-);
|
|
|
+
|
|
|
+});
|
|
|
|
|
|
store.subscribe(() => {
|
|
|
+ const [, , _id] = location.hash.split('/');
|
|
|
|
|
|
- const [, route, _id] = location.hash.split('/');
|
|
|
+ header.innerHTML = '';
|
|
|
+
|
|
|
+ const namCat = document.createElement('div');
|
|
|
+ namCat.className = 'nameGategory';
|
|
|
+ namCat.textContent = 'Категории';
|
|
|
+ const enter = document.createElement('a');
|
|
|
+ enter.className = 'enterToPrivate';
|
|
|
+ enter.textContent = 'Вход в кабинет';
|
|
|
+ enter.href = `#/login/${_id}`;
|
|
|
+
|
|
|
+ header.appendChild(namCat);
|
|
|
+ header.appendChild(enter);
|
|
|
+ }
|
|
|
+);
|
|
|
+
|
|
|
+store.subscribe(() => {
|
|
|
+ const [, , _id] = location.hash.split('/');
|
|
|
|
|
|
let wrapperForCart = document.createElement('div');
|
|
|
wrapperForCart.className = 'wrapperForCart';
|
|
@@ -635,15 +712,9 @@ store.subscribe(() => {
|
|
|
<a href="#/cart/${_id}">Корзина</a>
|
|
|
<img src="cart.png" class="cartImg">`;
|
|
|
|
|
|
- // for (const key in store.getState().cart) {
|
|
|
- // console.log(route, _id);
|
|
|
- const orderGoods = Object.entries(store.getState().cart)
|
|
|
- .map(([_id, {...key}]) => ({good: {_id}, count: key.count}));
|
|
|
-
|
|
|
const cartArr = Object.values(store.getState().cart);
|
|
|
const counter = cartArr.length === 0 ? 0 : cartArr.reduce((accum, {count}) => accum + count, 0);
|
|
|
|
|
|
- console.log(counter);
|
|
|
wrapperForCart.innerHTML = `<a href="#/cart/${_id}">Корзина ${counter}</a>
|
|
|
<img src="cart.png" class="cartImg">`;
|
|
|
}
|
|
@@ -685,7 +756,6 @@ store.subscribe(() => {
|
|
|
buttonBuy.onclick = () => {
|
|
|
store.dispatch(actionCartAdd(good, 1));
|
|
|
};
|
|
|
-
|
|
|
card.appendChild(buttonBuy);
|
|
|
aside.append(link);
|
|
|
main.append(card);
|
|
@@ -695,37 +765,29 @@ store.subscribe(() => {
|
|
|
}
|
|
|
);
|
|
|
|
|
|
+
|
|
|
store.subscribe(() => {
|
|
|
const {goodById} = store.getState().promise;
|
|
|
-
|
|
|
-
|
|
|
const [, route, _id] = location.hash.split('/');
|
|
|
+
|
|
|
if (goodById?.payload && route === 'good') {
|
|
|
console.log('я на странице описания товара');
|
|
|
if (location.hash.indexOf(`#/good/${_id}`) !== -1) {
|
|
|
main.innerHTML = '';
|
|
|
|
|
|
- const {_id, name, price, images, description} = goodById.payload;
|
|
|
+ const {name, price, images, description} = goodById.payload;
|
|
|
const card = document.createElement('div');
|
|
|
card.innerHTML = `<h2>${name}</h2>
|
|
|
<img src="${backURL}/${images[0].url}" />
|
|
|
<strong>${price}</strong>
|
|
|
<div>${description}</div>
|
|
|
-<!-- <button onclick="store.dispatch(actionCartAdd(good))">Купить</button> -->
|
|
|
`;
|
|
|
main.append(card);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
-)
|
|
|
-;
|
|
|
-
|
|
|
-//store.dispatch(actionPromise('delay1000', delay(1000)))
|
|
|
-//store.dispatch(actionPromise('delay2000', delay(2000)))
|
|
|
-//store.dispatch(actionPromise('failedfetch', fetch('https://swapi.dev/api/people/1/')
|
|
|
-//.then(res => res.json())))
|
|
|
-
|
|
|
-store.dispatch(actionPromise('delay1000', delay(1000)));//{promise: {delay1000: '''}, auth: {}}
|
|
|
-// store.dispatch(actionAuthLogin('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE3NDdmNWM3NTBjMTJiYTZiYTQwOTUiLCJsb2dpbiI6Imxlc2hhIiwiYWNsIjpbIjYxYTc0N2Y1Yzc1MGMxMmJhNmJhNDA5NSIsInVzZXIiXX0sImlhdCI6MTYzODQ0MjQyOH0.vPUZ-JmygQ1DyhJgbgYDZqZQpe_c2X5a2Dtn1cJcvFE'
|
|
|
-// ));//{promise: {delay1000: '''}, auth: {token .....}}
|
|
|
+);
|
|
|
|
|
|
+store.subscribe(() => {
|
|
|
+ localStorage.setItem('cart', JSON.stringify(store.getState().cart));
|
|
|
+});
|