-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
820 lines (722 loc) · 20.6 KB
/
Copy pathscript.js
File metadata and controls
820 lines (722 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// CONSTS
const aside = document.querySelector(".aside");
const categoriesList = document.querySelector(".good-categories");
const main = document.querySelector(".main-content");
const reducers = {
promise: promiseReducer,
auth: localStoredReducer(authReducer, "authToken"),
cart: localStoredReducer(cartReducer, "cart"),
};
// PROMISE AND ACTIONS
const actionPromise = (name, promise) => {
return async (dispatch) => {
dispatch(actionPending(name));
try {
const payload = await promise;
dispatch(actionFulfilled(name, payload));
return payload;
} catch (error) {
dispatch(actionRejected(name, error));
}
};
};
const actionPending = (name) => {
return {
type: "PROMISE",
status: "PENDING",
name,
};
};
const actionFulfilled = (name, payload) => {
return {
type: "PROMISE",
status: "FULFILLED",
payload,
name,
};
};
const actionRejected = (name, error) => {
return {
type: "PROMISE",
status: "REJECTED",
error,
name,
};
};
// REDUCERS
const totalReducer = combineReducers(reducers);
function combineReducers(reducers) {
function totalReducer(state = {}, action) {
const newTotalState = {};
for (const [reducerName, reducer] of Object.entries(reducers)) {
const newSubState = reducer(state[reducerName], action);
if (newSubState !== state[reducerName]) {
newTotalState[reducerName] = newSubState;
}
}
if (Object.keys(newTotalState).length) {
return {
...state,
...newTotalState,
};
}
return state;
}
return totalReducer;
}
function promiseReducer(state = {}, { type, status, payload, error, name }) {
if (type === "PROMISE") {
return {
...state,
[name]: { status, payload, error },
};
}
return {
...state,
};
}
function localStoredReducer(originalReducer, localStorageKey) {
function wrapper(state, action) {
if (state === undefined) {
try {
return JSON.parse(localStorage[localStorageKey]);
} catch (error) {}
}
const stateNew = originalReducer(state, action);
localStorage[localStorageKey] = JSON.stringify(stateNew);
return stateNew;
}
return wrapper;
}
function cartReducer(state = {}, { type, count, good }) {
newState = { ...state };
if (type === "CART_ADD" && count > 0) {
if (newState[good._id]) {
newState[good._id].count += count;
} else {
newState = {
...newState,
...{ [good._id]: { count: count, good } },
};
}
return newState;
}
if (type === "CART_SUB" && count > 0) {
if (newState[good._id]) {
newState[good._id].count -= count;
if (newState[good._id].count < 1) {
delete newState[good._id];
}
}
return newState;
}
if (type === "CART_DEL") {
if (newState[good._id]) {
delete newState[good._id];
}
return newState;
}
if (type === "CART_SET") {
if (newState[good._id] && count > 0) {
newState[good._id].count = count;
} else if (newState[good._id] && count < 1) {
delete newState[good._id];
} else if (count > 0) {
newState = {
...newState,
...{ [good._id]: { count: count, good } },
};
}
return newState;
}
if (type === "CART_CLEAR") {
localStorage.removeItem("cart");
return {};
}
return state;
}
// додавання товару
const actionCartAdd = (good, count = 1) => {
return {
type: "CART_ADD",
count,
good,
};
};
//Зменшення кількості товару
const actionCartSub = (good, count = 1) => {
return {
type: "CART_SUB",
count,
good,
};
};
//Видалення товару
const actionCartDel = (good) => {
return {
type: "CART_DEL",
good,
};
};
//Задання кількості товару
const actionCartSet = (good, count = 1) => {
return {
type: "CART_SET",
count,
good,
};
};
//Очищення кошика
const actionCartClear = () => {
return {
type: "CART_CLEAR",
};
};
function authReducer(state = {}, { type, token }) {
if (type === "AUTH_LOGIN") {
const payload = jwtDecode(token);
if (payload) {
return {
token,
payload,
};
}
}
if (type === "AUTH_LOGOUT") {
return {};
}
return state;
}
// Actions Login/Logout
const actionAuthLogin = (token) => {
return {
type: "AUTH_LOGIN",
token,
};
};
const actionAuthLogout = () => {
return {
type: "AUTH_LOGOUT",
};
};
const actionFullLogin = (login, password) => {
return async (dispatch) => {
const token = await dispatch(actionLogin(login, password));
if (token) {
dispatch(actionAuthLogin(token));
}
};
};
const actionFullRegister = (login, password) => {
return async (dispatch) => {
await dispatch(actionRegister(login, password));
dispatch(actionFullLogin(login, password));
};
};
//Запит на логін
const actionLogin = (login, password) =>
actionPromise(
"login",
gql(
`query login($login:String, $password:String){
login(login:$login, password:$password)
}`,
{ login: login, password: password }
)
);
//Запит на реєстрацію
const actionRegister = (login, password) =>
actionPromise(
"registration",
gql(
`mutation Reg($login:String, $password:String){
UserUpsert(user:{login:$login, password:$password}){_id, login}
}`,
{ login: login, password: password }
)
);
// CREATE STORE
function createStore(reducer) {
let state = reducer(undefined, {});
let cbs = [];
const getState = () => state;
const subscribe = (cb) => (
cbs.push(cb), () => (cbs = cbs.filter((c) => c !== cb))
);
const dispatch = (action) => {
if (typeof action === "function") {
return action(dispatch, getState);
}
const newState = reducer(state, action);
if (newState !== state) {
state = newState;
for (let cb of cbs) cb(state);
}
};
return {
getState,
dispatch,
subscribe,
};
}
const store = createStore(totalReducer);
// GQL
const gql = getGql("http://shop-roles.node.ed.asmer.org.ua/graphql");
function getGql(endpoint) {
return async function gql(query, variables = {}) {
return fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...(store.getState().auth.token
? { authorization: "Bearer " + store.getState().auth.token }
: {}),
},
body: JSON.stringify({ query, variables }),
})
.then((res) => res.json())
.then((res1) => {
if (!res1.data && res1.errors) {
throw new Error(JSON.stringify(res1.errors));
} else {
return Object.values(res1.data)[0];
}
});
};
}
// REGISTRATION
const createUserForm = () => {
const { payload } = store.getState().auth;
const user = document.getElementById("user");
const btnOrders = document.getElementById("btnOrders");
const btnRegister = document.getElementById("btnRegister");
const btnLogin = document.getElementById("btnLogin");
if (payload) {
user.innerText = payload.sub.login;
btnLogin.style = "display:none";
btnRegister.style = "display:none";
btnLogout.style = "display:block";
btnOrders.style = "display:block";
} else {
user.innerText = "is not authorized";
btnLogin.style = "display:block";
btnRegister.style = "display:block";
btnLogout.style = "display:none";
btnOrders.style = "display:none";
}
};
store.subscribe(createUserForm);
const btnLogout = document.getElementById("btnLogout");
btnLogout.onclick = () => {
store.dispatch(actionCartClear());
store.dispatch(actionAuthLogout());
};
const userLogin = () => {
const [_, route] = location.hash.split("/");
if (route !== "login") return;
if (store.getState().promise.login) {
const { status, payload } = store.getState().promise.login;
console.log("promise login", store.getState().promise.login);
if (status === "FULFILLED" && !payload) {
alert(`User with this username and password does not exist! Try again!`);
}
}
};
store.subscribe(userLogin);
const stateRegistration = () => {
const [_, route] = location.hash.split("/");
if (route !== "register") return;
if (store.getState().promise.registration) {
const { status, payload } = store.getState().promise.registration;
if (status === "FULFILLED" && payload) {
alert(`User successfully registered!`);
store.dispatch(actionAuthLogin(token));
} else if (status === "FULFILLED" && !payload) {
alert(`This username already exists!`);
}
}
};
store.subscribe(stateRegistration);
const stateOrder = () => {
const [_, route] = location.hash.split("/");
if (route !== "cart") return;
if (store.getState().promise.newOrder) {
const { status, payload } = store.getState().promise.newOrder;
if (
status === "FULFILLED" &&
payload &&
Object.keys(store.getState().cart).length
) {
alert(`Твой заказ создан успешно!`);
store.dispatch(actionCartClear());
} else if (status === "FULFILLED" && !payload) {
alert(`Твой заказ создать не удалось!`);
}
}
};
store.subscribe(stateOrder);
//Запит на перелiк кореневих категорій
const actionRootCategories = () =>
actionPromise(
"RootCategories",
gql(
`query categories($q: String) {
CategoryFind(query: $q){
_id
name
}
}`,
{ q: JSON.stringify([{ parent: null }]) }
)
);
store.dispatch(actionRootCategories());
store.subscribe(() => {
const { status, payload } = store.getState().promise.RootCategories;
if (status === "FULFILLED" && payload) {
let categories = "";
for (const { _id, name } of payload) {
categories += `<li class=rootCat><a href="#/cat/${_id}">${name}</a></li>`;
}
categoriesList.innerHTML = categories;
}
});
//Запит для отримання однієї категорії з товарами та картинками
const actionOneCategoryWithGoods = (_id) =>
actionPromise(
"oneCategoryWithGoods",
gql(
`query categories($q: String) {
CategoryFindOne(query: $q){
_id
name
goods {
_id,
name,
price,
images {
url
}
}
}
}`,
{ q: JSON.stringify([{ _id }]) }
)
);
const CreateCategories = () => {
const [_, route] = location.hash.split("/");
if (route !== "cat") return;
const { status, payload } = store.getState().promise.oneCategoryWithGoods;
if (status === "FULFILLED") {
const { name, goods } = payload;
const container = document.createElement("div");
container.className = "wrapper";
container.innerHTML = `<h1>${name}</h1>`;
let good = "";
for (const { _id, name, images, price } of goods) {
good += `
<div class="goods-card">
<h3 class="font">${name}</h3>
<img src="http://shop-roles.node.ed.asmer.org.ua/${images[0].url}" alt="card"/>
<span class="font">Цена: ${price} грн.</span>
<a href="#/good/${_id}">Подробнее</a>
<button class="goods-card-button">Добавить в корзину</button>
</div>`;
}
container.innerHTML += good;
main.innerHTML = "";
main.appendChild(container);
const buttonCard = document.querySelectorAll(".goods-card-button");
buttonCard.forEach((button, index) => {
button.addEventListener("click", () => {
const selectedGood = goods[index];
store.dispatch(actionCartAdd(selectedGood));
});
});
}
};
store.subscribe(CreateCategories);
//Запит на отримання товару з описом та картинками
const ActionGoodsWithDescription = (_id) =>
actionPromise(
"GoodsWithDescription",
gql(
`query categories($q: String){
GoodFindOne(query:$q){
_id
name
price
description
images {
url
}
}
}`,
{ q: JSON.stringify([{ _id }]) }
)
);
const CreateGoodsWithDescription = () => {
const [_, route] = location.hash.split("/");
if (route !== "good") return;
const { status, payload } = store.getState().promise.GoodsWithDescription;
if (status === "FULFILLED") {
const { name, description, price, images } = payload;
let details = "";
details += `
<div class="details-of-good">
<div class="wrapper-of-good">
<h3 class="font">${name}</h3>
<img src="http://shop-roles.node.ed.asmer.org.ua/${images[0].url}" alt="card-description"/>
<p class="font">Описание: ${description}</p>
<span class="font">Цена: ${price} грн.</span>
<button class="add-from-details font">Добавить в корзину</button>
<button class="remove-from-details font">Удалить с корзины</button>
</div>
</div>`;
main.innerHTML = details;
const addToCard = document.querySelector(".add-from-details");
addToCard.addEventListener("click", () => {
store.dispatch(actionCartAdd(payload));
});
const removeFromCard = document.querySelector(".remove-from-details");
removeFromCard.addEventListener("click", () => {
store.dispatch(actionCartSub(payload));
updateCartAmount();
});
}
};
store.subscribe(CreateGoodsWithDescription);
//Запит історії замовлень
const actionHistoryOrders = () =>
actionPromise(
"orders",
gql(`query orderFind {
OrderFind(query: "[{}]") {
_id
total
orderGoods {
good {
_id
name
}
total
price
count
}
}
}`)
);
const actionCreateOrder = () => (dispatch, getState) => {
const goodsInCart = getState().cart;
const arrGoods = [];
for (key in goodsInCart) {
arrGoods.push({
good: { _id: goodsInCart[key].good._id },
count: goodsInCart[key].count,
});
}
if (arrGoods.length !== 0) {
dispatch(actionOrderUpsert(arrGoods));
} else return;
};
//Запит на оформлення замовлення
const actionOrderUpsert = (goods) =>
actionPromise(
"newOrder",
gql(
`mutation newOrder($goods: [OrderGoodInput]) {
OrderUpsert(order: {orderGoods: $goods}) {
_id
createdAt
total
}
}`,
{ goods: goods }
)
);
const createOrders = () => {
const [_, route] = location.hash.split("/");
if (route !== "orders") return;
const { status, payload } = store.getState().promise.orders;
if (status === "FULFILLED") {
let totalPrice = 0;
let userOrders = "";
const container = document.createElement("div");
container.className = "wrapper";
container.innerHTML = `<h1>Заказы пользователя</h1>`;
payload.forEach((order) => {
order.orderGoods.forEach((item) => {
const { price, good, count } = item;
const itemTotalPrice = price * count;
userOrders += `
<div class="order-details">
<h3>${good.name}</h3>
<span class="order-count">Количество: ${count}</span>
<span>Цена/шт: ${price} грн.</span>
<span>Общая стоимость: ${itemTotalPrice} грн.</span>
</div>`;
totalPrice += itemTotalPrice;
});
});
container.innerHTML += userOrders;
main.innerHTML = "";
main.appendChild(container);
}
};
store.subscribe(createOrders);
const createCart = () => {
const [_, route] = location.hash.split("/");
if (route !== "cart") return;
const goodsInCart = store.getState().cart;
main.innerHTML = `<h1 class="cart-text">Корзина</h1>`;
let cart = "";
for (let key in goodsInCart) {
if (goodsInCart.hasOwnProperty(key) > 0) {
let value = goodsInCart[key];
const totalPrice = value.count * value.good.price;
cart += `
<div class="cart-details">
<h3>${value.good.name}</h3>
<span class="order-count">Количество:
<button class="btnDecrease" data-good-id="${key}">-</button>
<span class="count">${value.count}</span>
<button class="btnIncrease" data-good-id="${key}">+</button>
</span>
<span>Цена/шт: ${value.good.price} грн.</span>
<span>Общая цена: ${totalPrice} грн.</span>
<button class="btnRemove" data-good-id="${key}">Удалить</button>
</div>`;
}
}
main.innerHTML += cart;
if (Object.keys(goodsInCart).length === 0) {
main.innerHTML += '<p class="cart-text">Корзина пустая</p>';
} else {
const btnContainer = document.createElement("div");
btnContainer.className = "btn-container";
const btnOrder = document.createElement("button");
btnOrder.innerText = "Заказать";
btnOrder.className = "btnForOrder";
btnOrder.addEventListener("click", () => {
store.dispatch(actionCreateOrder());
main.remove(btnOrder);
main.remove(btnClearCart);
});
const btnClearCart = document.createElement("button");
btnClearCart.innerText = "Очистить корзину";
btnClearCart.className = "btnForClearCart";
btnClearCart.addEventListener("click", () => {
store.dispatch(actionCartClear());
main.remove(btnOrder);
main.remove(btnClearCart);
});
btnContainer.appendChild(btnOrder);
btnContainer.appendChild(btnClearCart);
main.append(btnContainer);
}
const btnIncrease = document.querySelectorAll(".btnIncrease");
btnIncrease.forEach((btn) => {
btn.addEventListener("click", () => {
const goodId = btn.dataset.goodId;
store.dispatch(actionCartAdd(goodsInCart[goodId].good));
});
});
const btnDecrease = document.querySelectorAll(".btnDecrease");
btnDecrease.forEach((btn) => {
btn.addEventListener("click", () => {
const goodId = btn.dataset.goodId;
store.dispatch(actionCartSub(goodsInCart[goodId].good));
});
});
const btnRemove = document.querySelectorAll(".btnRemove");
btnRemove.forEach((btn) => {
btn.addEventListener("click", () => {
const goodId = btn.dataset.goodId;
store.dispatch(actionCartDel(goodsInCart[goodId].good));
});
});
};
store.subscribe(createCart);
//оновляє цифру товару в іконці
const updateCartAmount = () => {
const stateCart = Object.keys(store.getState().cart).length;
const goodsInCart = document.getElementById("goodsInCart");
if (stateCart) {
goodsInCart.innerText = stateCart;
} else goodsInCart.innerText = "";
};
store.subscribe(updateCartAmount);
// onhashchange
window.onhashchange = () => {
const [_, route, _id] = location.hash.split("/");
const routes = {
cat() {
store.dispatch(actionOneCategoryWithGoods(_id));
},
good() {
store.dispatch(ActionGoodsWithDescription(_id));
},
login() {
main.innerHTML = `<h1 class='form-title font'>Авторизация</h1>`;
createForm(main, "login");
},
register() {
main.innerHTML = `<h1 class='form-title font'>Регистрация</h1>`;
createForm(main, "register");
},
orders() {
store.dispatch(actionHistoryOrders());
},
cart() {
createCart();
},
};
if (route in routes) {
routes[route]();
}
};
// Reg/Auth form
function createForm(parent, action) {
const container = document.createElement("div");
container.setAttribute("class", "form-container");
const loginInput = document.createElement("input");
loginInput.placeholder = "Enter login";
loginInput.type = "text";
loginInput.setAttribute("class", "loginInput");
const passwordInput = document.createElement("input");
passwordInput.placeholder = "Enter password";
passwordInput.type = "text";
passwordInput.setAttribute("class", "passwordInput");
const button = document.createElement("button");
button.type = "submit";
button.innerText = "Submit";
button.onclick = function () {
if (action === "login") {
store.dispatch(actionFullLogin(loginInput.value, passwordInput.value));
loginInput.value = "";
passwordInput.value = "";
} else {
store.dispatch(actionFullRegister(loginInput.value, passwordInput.value));
loginInput.value = "";
passwordInput.value = "";
}
};
container.append(loginInput, passwordInput, button);
parent.appendChild(container);
}
function jwtDecode(token) {
let arr = [];
if (typeof token !== "string") {
return undefined;
}
arr = token.split(".");
if (arr.length !== 3) {
return undefined;
}
try {
return JSON.parse(atob(arr[1]));
} catch {
return undefined;
}
}
window.onhashchange();