script.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. function createStore(reducer) {
  2. let state = reducer(undefined, {}); //стартовая инициализация состояния, запуск редьюсера со state === undefined
  3. let cbs = []; //массив подписчиков
  4. const getState = () => state; //функция, возвращающая переменную из замыкания
  5. const subscribe = (cb) => (
  6. cbs.push(cb), //запоминаем подписчиков в массиве
  7. () => (cbs = cbs.filter((c) => c !== cb))
  8. ); //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
  9. const dispatch = (action) => {
  10. if (typeof action === "function") {
  11. //если action - не объект, а функция
  12. return action(dispatch, getState); //запускаем эту функцию и даем ей dispatch и getState для работы
  13. }
  14. const newState = reducer(state, action); //пробуем запустить редьюсер
  15. if (newState !== state) {
  16. //проверяем, смог ли редьюсер обработать action
  17. state = newState; //если смог, то обновляем state
  18. for (let cb of cbs) cb(); //и запускаем подписчиков
  19. }
  20. };
  21. return {
  22. getState, //добавление функции getState в результирующий объект
  23. dispatch,
  24. subscribe, //добавление subscribe в объект
  25. };
  26. }
  27. function jwtDecode(token) {
  28. try {
  29. return JSON.parse(atob(token.split(".")[1]));
  30. } catch (e) {}
  31. }
  32. function authReducer(state, { type, token }) {
  33. if (state === undefined) {
  34. if (localStorage.authToken) {
  35. type = "AUTH_LOGIN";
  36. token = localStorage.authToken;
  37. }
  38. }
  39. if (type === "AUTH_LOGIN") {
  40. let payload = jwtDecode(token);
  41. if (payload) {
  42. localStorage.authToken = token;
  43. return { token, payload };
  44. }
  45. }
  46. if (type === "AUTH_LOGOUT") {
  47. localStorage.removeItem("authToken");
  48. return {};
  49. }
  50. return state || {};
  51. }
  52. const actionAuthLogin = (token) => ({ type: "AUTH_LOGIN", token });
  53. const actionAuthLogout = () => (dispatch) => {
  54. dispatch({ type: "AUTH_LOGOUT" });
  55. localStorage.removeItem("authToken");
  56. };
  57. function promiseReducer(state = {}, { type, name, status, payload, error }) {
  58. if (type === "PROMISE") {
  59. return {
  60. ...state,
  61. [name]: { status, payload, error },
  62. };
  63. }
  64. return state;
  65. }
  66. const actionPending = (name) => ({
  67. type: "PROMISE",
  68. status: "PENDING",
  69. name,
  70. });
  71. const actionFulfilled = (name, payload) => ({
  72. type: "PROMISE",
  73. status: "FULFILLED",
  74. name,
  75. payload,
  76. });
  77. const actionRejected = (name, error) => ({
  78. type: "PROMISE",
  79. status: "REJECTED",
  80. name,
  81. error,
  82. });
  83. const actionPromise = (name, promise) => async (dispatch) => {
  84. try {
  85. dispatch(actionPending(name));
  86. let payload = await promise;
  87. dispatch(actionFulfilled(name, payload));
  88. return payload;
  89. } catch (e) {
  90. dispatch(actionRejected(name, e));
  91. }
  92. };
  93. function cartReducer(state = {}, { type, count = 1, good }) {
  94. // type CART_ADD CART_REMOVE CART_CLEAR CART_DEL
  95. // {
  96. // id1: {count: 1, good: {name, price, images, id}}
  97. // }
  98. if (type === "CART_ADD") {
  99. return {
  100. ...state,
  101. [good._id]: { count: count + (state[good._id]?.count || 0), good },
  102. };
  103. }
  104. if (type === "CART_DELETE") {
  105. if (state[good._id].count > 1) {
  106. return {
  107. ...state,
  108. [good._id]: {
  109. count: -count + (state[good._id]?.count || 0),
  110. good,
  111. },
  112. };
  113. }
  114. if (state[good._id].count === 1) {
  115. let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
  116. //delete newState[good._id]
  117. return newState;
  118. }
  119. }
  120. if (type === "CART_CLEAR") {
  121. return {};
  122. }
  123. if (type === "CART_REMOVE") {
  124. // let newState = {...state}
  125. let { [good._id]: id1, ...newState } = state; //o4en strashnoe koldunstvo
  126. //delete newState[good._id]
  127. return newState;
  128. }
  129. return state;
  130. }
  131. const actionCartAdd = (good, count = 1) => ({ type: "CART_ADD", good, count });
  132. const actionCartDelete = (good) => ({ type: "CART_DELETE", good });
  133. const actionCartClear = () => ({ type: "CART_CLEAR" });
  134. const actionCartRemove = (good) => ({ type: "CART_REMOVE", good });
  135. function localStoreReducer(reducer, localStorageKey) {
  136. function localStoredReducer(state, action) {
  137. // Если state === undefined, то достать старый state из local storage
  138. if (state === undefined) {
  139. try {
  140. return JSON.parse(localStorage[localStorageKey]);
  141. } catch (e) {}
  142. }
  143. const newState = reducer(state, action);
  144. // Сохранить newState в local storage
  145. localStorage[localStorageKey] = JSON.stringify(newState);
  146. return newState;
  147. }
  148. return localStoredReducer;
  149. }
  150. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  151. function combineReducers(reducers) {
  152. //пачку редьюсеров как объект {auth: authReducer, promise: promiseReducer}
  153. function combinedReducer(combinedState = {}, action) {
  154. //combinedState - типа {auth: {...}, promise: {....}}
  155. const newCombinedState = {};
  156. for (const [reducerName, reducer] of Object.entries(reducers)) {
  157. const newSubState = reducer(combinedState[reducerName], action);
  158. if (newSubState !== combinedState[reducerName]) {
  159. newCombinedState[reducerName] = newSubState;
  160. }
  161. }
  162. if (Object.keys(newCombinedState).length === 0) {
  163. return combinedState;
  164. }
  165. return { ...combinedState, ...newCombinedState };
  166. }
  167. return combinedReducer; //нам возвращают один редьюсер, который имеет стейт вида {auth: {...стейт authReducer-а}, promise: {...стейт promiseReducer-а}}
  168. }
  169. const getGQL = (url) => (query, variables) =>
  170. fetch(url, {
  171. method: "POST",
  172. headers: {
  173. "Content-Type": "application/json",
  174. // 'Accept' : 'application/json',
  175. ...(localStorage.authToken
  176. ? { Authorization: "Bearer " + localStorage.authToken }
  177. : {}),
  178. },
  179. body: JSON.stringify({ query, variables }),
  180. })
  181. .then((res) => res.json())
  182. .then((data) => {
  183. if (data.data) {
  184. return Object.values(data.data)[0];
  185. } else throw new Error(JSON.stringify(data.errors));
  186. });
  187. const backendURL = "http://shop-roles.node.ed.asmer.org.ua";
  188. const gql = getGQL(backendURL + "/graphql");
  189. const store = createStore(
  190. combineReducers({
  191. auth: authReducer,
  192. promise: promiseReducer,
  193. cart: localStoreReducer(cartReducer, "cart"),
  194. })
  195. ); //не забудьте combineReducers если он у вас уже есть
  196. if (localStorage.authToken) {
  197. store.dispatch(actionAuthLogin(localStorage.authToken));
  198. }
  199. store.subscribe(() => console.log(store.getState()));
  200. const actionRootCats = () =>
  201. actionPromise(
  202. "rootCats",
  203. gql(
  204. `query {
  205. CategoryFind(query: "[{\\"parent\\":null}]"){
  206. _id name
  207. }
  208. }`
  209. )
  210. );
  211. const actionCatById = (_id) =>
  212. actionPromise(
  213. "catById",
  214. gql(
  215. `query catById($q: String){
  216. CategoryFindOne(query: $q){
  217. _id name subCategories {
  218. name _id
  219. }
  220. goods {
  221. _id name price images {
  222. url
  223. }
  224. }
  225. }
  226. }`,
  227. { q: JSON.stringify([{ _id }]) }
  228. )
  229. );
  230. const actionLogin = (login, password) =>
  231. actionPromise(
  232. "actionLogin",
  233. gql(
  234. `query log($login:String, $password:String){
  235. login(login:$login, password:$password)
  236. }`,
  237. { login, password }
  238. )
  239. );
  240. const actionGoodById = (_id) =>
  241. actionPromise(
  242. "GoodFineOne",
  243. gql(
  244. `query goodByid($goodId: String) {
  245. GoodFindOne(query: $goodId) {
  246. _id
  247. name
  248. price
  249. description
  250. images {
  251. url
  252. }
  253. }
  254. }`,
  255. { goodId: JSON.stringify([{ _id }]) }
  256. )
  257. );
  258. store.dispatch(actionRootCats());
  259. const actionFullLogin = (log, pass) => async (dispatch) => {
  260. let token = await dispatch(
  261. actionPromise(
  262. "login",
  263. gql(
  264. `query login($login: String, $password: String) {
  265. login(login: $login, password: $password)
  266. }`,
  267. { login: log, password: pass }
  268. )
  269. )
  270. );
  271. if (token) {
  272. dispatch(actionAuthLogin(token));
  273. }
  274. };
  275. const actionFullRegister = (login, password) => async (dispatch) => {
  276. let user = await dispatch(
  277. actionPromise(
  278. "register",
  279. gql(
  280. `mutation register($login: String, $password: String) {
  281. UserUpsert(user: {login: $login, password: $password}) {
  282. _id
  283. login
  284. }
  285. }`,
  286. { login: login, password: password }
  287. )
  288. )
  289. );
  290. if (user) {
  291. dispatch(actionFullLogin(login, password));
  292. }
  293. };
  294. const actionOrder = () => async (dispatch, getState) => {
  295. let { cart } = getState();
  296. const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({
  297. good: { _id },
  298. count,
  299. }));
  300. let result = await dispatch(
  301. actionPromise(
  302. "order",
  303. gql(
  304. `
  305. mutation newOrder($order:OrderInput){
  306. OrderUpsert(order:$order)
  307. { _id total }
  308. }
  309. `,
  310. { order: { orderGoods } }
  311. )
  312. )
  313. );
  314. if (result?._id) {
  315. dispatch(actionCartClear());
  316. document.location.hash = "#/cart/";
  317. alert("Поздравляем, вы оформили заказ!");
  318. }
  319. };
  320. const orderHistory = () =>
  321. actionPromise(
  322. "history",
  323. gql(` query OrderFind{
  324. OrderFind(query:"[{}]"){
  325. _id total createdAt orderGoods{
  326. count good{
  327. _id name price images{
  328. url
  329. }
  330. }
  331. owner{
  332. _id login
  333. }
  334. }
  335. }
  336. }
  337. `)
  338. );
  339. store.subscribe(() => {
  340. const { rootCats } = store.getState().promise;
  341. if (rootCats?.payload) {
  342. aside.innerHTML = "";
  343. for (let { _id, name } of rootCats?.payload) {
  344. const a = document.createElement("a");
  345. a.href = `#/category/${_id}`;
  346. a.innerHTML = name;
  347. aside.append(a);
  348. }
  349. }
  350. });
  351. store.subscribe(() => {
  352. const { catById } = store.getState().promise;
  353. const [, route] = location.hash.split("/");
  354. if (catById?.payload && route === "category") {
  355. const { name, goods, subCategories } = catById?.payload;
  356. categoryName.innerHTML = `<h1>${name}</h1>`;
  357. var element = document.getElementById("productBlock");
  358. while (element.firstChild) {
  359. element.removeChild(element.firstChild);
  360. }
  361. if (subCategories) {
  362. for (let { name, _id } of subCategories) {
  363. const link = document.createElement("a");
  364. link.id = "subCategories";
  365. link.href = `#/category/${_id}`;
  366. link.innerText = name;
  367. productBlock.append(link);
  368. }
  369. }
  370. for (let { _id, name, price, images } of goods) {
  371. const description = document.createElement("div");
  372. const textBlock = document.createElement("div");
  373. const imgProduct = document.createElement("img");
  374. const a = document.createElement("p");
  375. const productPrice = document.createElement("p");
  376. const linkCard = document.createElement("a");
  377. productBlock.append(linkCard);
  378. linkCard.href = `#/good/${_id}`;
  379. linkCard.append(description);
  380. description.setAttribute("class", "card");
  381. description.id = "card";
  382. description.append(imgProduct);
  383. imgProduct.src = `${backendURL}/${images[0].url}`;
  384. description.append(textBlock);
  385. a.innerHTML = name;
  386. textBlock.append(a);
  387. productPrice.innerHTML = "price: " + price;
  388. textBlock.append(productPrice);
  389. const addToCartButton = document.createElement("p");
  390. addToCartButton.innerText = "click to buy";
  391. addToCartButton.className = "addToCartButton";
  392. textBlock.append(addToCartButton);
  393. }
  394. }
  395. });
  396. const flexBlockForGFO = document.createElement("div");
  397. flexBlockForGFO.id = "flexBlockForGFO";
  398. const goodFineOneImgBlock = document.createElement("div");
  399. const goodFineOneTextBlock = document.createElement("div");
  400. const goodFineOneName = document.createElement("h2");
  401. const goodFineOneImg = document.createElement("img");
  402. const goodFineOnePrice = document.createElement("p");
  403. const goodFineOneDescription = document.createElement("p");
  404. const goodFineOneAddToCartButton = document.createElement("button");
  405. const buttonPlus = document.createElement("button");
  406. const buttonMinus = document.createElement("button");
  407. buttonPlus.innerHTML = "+";
  408. buttonMinus.innerHTML = "-";
  409. store.subscribe(() => {
  410. const { GoodFineOne } = store.getState().promise;
  411. const [, route, _id] = location.hash.split("/");
  412. if (GoodFineOne?.payload && route === "good") {
  413. productBlock.innerHTML = "";
  414. const { name, images, price, description } = GoodFineOne?.payload;
  415. productBlock.append(flexBlockForGFO);
  416. flexBlockForGFO.append(goodFineOneImgBlock);
  417. goodFineOneImg.src = `${backendURL}/${images[0].url}`;
  418. goodFineOneImg.id = "goodOneImg";
  419. goodFineOneImgBlock.append(goodFineOneImg);
  420. flexBlockForGFO.append(goodFineOneTextBlock);
  421. goodFineOneName.innerHTML = name;
  422. goodFineOneTextBlock.append(goodFineOneName);
  423. goodFineOnePrice.innerHTML = "price: " + price;
  424. goodFineOneTextBlock.append(goodFineOnePrice);
  425. goodFineOneDescription.innerHTML = description;
  426. goodFineOneTextBlock.append(goodFineOneDescription);
  427. goodFineOneAddToCartButton.innerHTML = "add to cart";
  428. goodFineOneTextBlock.append(goodFineOneAddToCartButton);
  429. goodFineOneAddToCartButton.onclick = () => {
  430. store.dispatch(actionCartAdd(GoodFineOne.payload));
  431. };
  432. }
  433. });
  434. const bPoputDeleteBlock = document.createElement("div");
  435. const bPoput = document.createElement("div");
  436. bPoput.className = "b-popup";
  437. bPoput.id = "b-popup";
  438. const bPoputContainer = document.createElement("div");
  439. bPoputContainer.className = "b-popup-content";
  440. bPoputContainer.id = "b-popup-content";
  441. const buttonGoodDeleteBlock = document.createElement("div");
  442. buttonGoodDeleteBlock.id = "buttonGoodDeleteBlock";
  443. const buttonCloseCart = document.createElement("button");
  444. buttonCloseCart.innerText = `×`;
  445. buttonCloseCart.id = "buttonCloseCartId";
  446. const buttonGoodDelete = document.createElement("button");
  447. buttonGoodDelete.innerText = "delete";
  448. buttonGoodDelete.id = "buttonDelete";
  449. shoppingCart.onclick = () => {
  450. header.append(bPoput);
  451. bPoput.append(bPoputContainer);
  452. };
  453. bPoputContainer.append(buttonGoodDeleteBlock);
  454. buttonGoodDeleteBlock.append(buttonGoodDelete);
  455. bPoputContainer.append(buttonCloseCart);
  456. const divToCardBlock = document.createElement("div");
  457. const goodByIdPrice = document.createElement("h2");
  458. const buyBlock = document.createElement("div");
  459. buyBlock.className = "buyBlock";
  460. const buttonBuy = document.createElement("button");
  461. buttonBuy.className = "buttonBuy";
  462. buttonBuy.id = "buttonBuy";
  463. store.subscribe(() => {
  464. divToCardBlock.innerHTML = "";
  465. goodByIdPrice.innerHTML = "";
  466. const toCartById = store.getState().cart;
  467. let countSum = 0;
  468. let priceSum = 0;
  469. for (let value of Object.values(toCartById)) {
  470. const { count, good, price } = value;
  471. countSum += count;
  472. priceSum += good.price * count;
  473. divToCardBlock.id = "divToCartBlock";
  474. const divToCart = document.createElement("div");
  475. const goodByIdImage = document.createElement("img");
  476. const goodByIdName = document.createElement("h2");
  477. const goodByIdCount = document.createElement("h2");
  478. const buttonPlus = document.createElement("button");
  479. const buttonMinus = document.createElement("button");
  480. buttonBuy.style.display = "block";
  481. buttonBuy.innerHTML = "Buy";
  482. goodByIdPrice.innerHTML = "Total: " + priceSum;
  483. buttonPlus.innerHTML = "+";
  484. buttonMinus.innerHTML = "-";
  485. buttonPlus.id = "buttonPlus";
  486. buttonMinus.id = "buttonMinus";
  487. divToCart.id = "divToCart";
  488. bPoputContainer.append(divToCardBlock);
  489. divToCardBlock.append(divToCart);
  490. divToCart.append(goodByIdImage);
  491. divToCart.append(goodByIdName);
  492. divToCart.append(goodByIdCount);
  493. divToCart.append(buttonPlus);
  494. divToCart.append(buttonMinus);
  495. bPoputContainer.append(buyBlock);
  496. buyBlock.append(goodByIdPrice);
  497. buyBlock.append(buttonBuy);
  498. goodByIdImage.src = `${backendURL}/${value.good.images[0].url}`;
  499. goodByIdName.innerText = good.name;
  500. goodByIdCount.innerText = count;
  501. buttonBuy.onclick = () => {
  502. store.dispatch(actionOrder());
  503. store.dispatch(orderHistory());
  504. };
  505. buttonPlus.onclick = () => store.dispatch(actionCartAdd(value.good));
  506. buttonMinus.onclick = () => {
  507. store.dispatch(actionCartDelete(value.good));
  508. console.log(value.good, "this");
  509. // if(value.good.count === 0)
  510. };
  511. }
  512. shoppingCart.innerHTML = "Cart: " + countSum;
  513. buttonCloseCart.onclick = () => {
  514. var parent = document.getElementById("header");
  515. var child = document.getElementById("b-popup");
  516. parent.removeChild(child);
  517. };
  518. const payload = store.getState().auth.token;
  519. if (payload) {
  520. shoppingCart.style.display = "block";
  521. } else {
  522. shoppingCart.style.display = "none";
  523. }
  524. });
  525. buttonGoodDelete.onclick = () => {
  526. store.dispatch(actionCartClear());
  527. let a = document.getElementById("divToCartBlock");
  528. a.innerHTML = "";
  529. let b = document.getElementById("shoppingCart");
  530. b.innerHTML = "Cart";
  531. let c = document.getElementById("buttonBuy");
  532. c.style.display = "none";
  533. };
  534. const goodByIdName = document.createElement("div");
  535. const h2text = document.createElement("h2");
  536. h2text.id = "h2text";
  537. qwer.append(h2text);
  538. const logoutButton = document.createElement("button");
  539. logoutButton.id = "logoutButton";
  540. qwer.append(logoutButton);
  541. store.subscribe(() => {
  542. const payload = store.getState().auth.token;
  543. if (payload) {
  544. logoutButton.style.display = "block";
  545. logoutButton.innerHTML = "Logout";
  546. login.style.display = "none";
  547. reg.style.display = "none";
  548. h2text.style.display = "block";
  549. h2text.innerText = jwtDecode(payload).sub.login;
  550. } else {
  551. h2text.style.display = "none";
  552. logoutButton.style.display = "none";
  553. }
  554. });
  555. // store.subscribe(() => {
  556. // const orders = store.dispatch()
  557. // })
  558. const buttonLogin = document.createElement("button");
  559. buttonLogin.id = "loginInputt";
  560. buttonLogin.innerText = "Login";
  561. const buttonReg = document.createElement("button");
  562. buttonReg.id = "regInput";
  563. buttonReg.innerText = "Registration";
  564. function bPopupCreate(text) {
  565. const bPopup = document.createElement("div");
  566. const bPopupContent = document.createElement("div");
  567. bPopup.id = "b-popup";
  568. bPopup.className = "b-popup";
  569. bPopupContent.className = "b-popup-content b-poput-container-flex";
  570. header.append(bPopup);
  571. bPopup.append(bPopupContent);
  572. const buttonCloseCart = document.createElement("button");
  573. buttonCloseCart.innerText = `×`;
  574. buttonCloseCart.id = "buttonCloseCartId";
  575. bPopupContent.append(buttonCloseCart);
  576. const loginText = document.createElement("h2");
  577. const passwordText = document.createElement("h2");
  578. loginText.innerText = "Enter Login:";
  579. bPopupContent.append(loginText);
  580. const loginInput = document.createElement("input");
  581. loginInput.type = "text";
  582. bPopupContent.append(loginInput);
  583. loginInput.id = "loginInput";
  584. loginInput.value = "illiaKozyr";
  585. passwordText.innerText = "Enter Password:";
  586. bPopupContent.append(passwordText);
  587. const loginInputPassword = document.createElement("input");
  588. loginInputPassword.type = "password";
  589. bPopupContent.append(loginInputPassword);
  590. loginInputPassword.id = "passwordInput";
  591. loginInputPassword.value = "qwerty123456";
  592. bPopupContent.append(text);
  593. buttonCloseCart.onclick = () => {
  594. var parent = document.getElementById("header");
  595. var child = document.getElementById("b-popup");
  596. parent.removeChild(child);
  597. };
  598. }
  599. window.onhashchange = () => {
  600. const [, route, _id] = location.hash.split("/");
  601. const routes = {
  602. category() {
  603. store.dispatch(actionCatById(_id));
  604. },
  605. good() {
  606. store.dispatch(actionGoodById(_id));
  607. },
  608. dashboard() {
  609. store.dispatch(orderHistory());
  610. },
  611. };
  612. if (route in routes) {
  613. routes[route]();
  614. }
  615. };
  616. window.onhashchange();
  617. store.dispatch(orderHistory());
  618. const h2 = document.createElement("h2");
  619. store.subscribe(() => {
  620. const { history } = store.getState().promise;
  621. const [, route] = location.hash.split("/");
  622. purchaseHistory.onclick = () => {
  623. const bPopup = document.createElement("div");
  624. const bPopupContent = document.createElement("div");
  625. bPopup.id = "b-popup";
  626. bPopup.className = "b-popup";
  627. bPopupContent.className = "b-popup-content b-poput-container-flex";
  628. header.append(bPopup);
  629. bPopup.append(bPopupContent);
  630. const buttonCloseCart = document.createElement("button");
  631. buttonCloseCart.innerText = `×`;
  632. buttonCloseCart.id = "buttonCloseCartId";
  633. bPopupContent.append(buttonCloseCart);
  634. for (let [key, value] of Object.entries(history.payload)) {
  635. const { _id, createdAt, total, orderGoods } = value;
  636. console.log(total, "this");
  637. const h2 = document.createElement("h2");
  638. h2.className = "h2History"
  639. const dateOfOrder = new Date(+createdAt);
  640. h2.innerHTML = `${dateOfOrder.toLocaleDateString()} ${dateOfOrder.toLocaleTimeString()}
  641. Order ID: ${_id} от , c ${orderGoods.length} goods worth: ${total}`;
  642. bPopupContent.append(h2);
  643. }
  644. if (Object.keys(history.payload).length == 0) {
  645. const p = document.createElement("p");
  646. p.innerHTML = "<p>No purchases made yet</p>";
  647. card.append(p);
  648. }
  649. buttonCloseCart.onclick = () => {
  650. var parent = document.getElementById("header");
  651. var child = document.getElementById("b-popup");
  652. parent.removeChild(child);
  653. };
  654. };
  655. });
  656. login.onclick = () => {
  657. bPopupCreate(buttonLogin);
  658. buttonLogin.onclick = () => {
  659. store.dispatch(actionFullLogin(loginInput.value, passwordInput.value));
  660. logoutButton.style.display = "block";
  661. var parent = document.getElementById("header");
  662. var child = document.getElementById("b-popup");
  663. parent.removeChild(child);
  664. purchaseHistory.style.display = "block";
  665. };
  666. };
  667. reg.onclick = () => {
  668. bPopupCreate(buttonReg);
  669. buttonReg.onclick = () => {
  670. store.dispatch(
  671. actionFullRegister(loginInput.value, passwordInput.value),
  672. store.dispatch(actionCartClear())
  673. );
  674. var parent = document.getElementById("header");
  675. var child = document.getElementById("b-popup");
  676. parent.removeChild(child);
  677. };
  678. };
  679. logoutButton.onclick = () => {
  680. store.dispatch(actionAuthLogout());
  681. login.style.display = "block";
  682. reg.style.display = "block";
  683. purchaseHistory.style.display = "none";
  684. };
  685. // purchaseHistory.onclick = () => {
  686. // }