script.js 24 KB

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