{"version":3,"file":"cart.module-CnUTp4ZX.js","sources":["../../../../../Flow.Showcase.Static.Bundler/Root/modules/cart.module.ts"],"sourcesContent":["// @ts-nocheck\n\nimport eventBus from \"./event-bus.module.ts\";\nimport { commonState, updateCommonState } from \"./common-state.module.ts\";\n\n/**\n * Получить data аттрибуты количества товара у элемента\n * и функции для их обработки\n * @param {HTMLElement} element\n * @returns\n */\nexport function getQuantityAttributes(element) {\n /**\n * @type {NodeListOf}\n */\n const elements = document.querySelectorAll(\"[data-handle-add-to-cart]\");\n\n const productId = parseInt(element.dataset.productId || \"\");\n const variantId = parseInt(element.dataset.variantId || \"\");\n\n // Список всех элементов, обрабатывающих изменение количества того же варианта продукта\n const relatedElements = [...elements].filter((e) => {\n const pId = parseInt(e.dataset.productId || \"\");\n const vId = parseInt(e.dataset.variantId || \"\");\n return pId === productId && vId === variantId;\n });\n const relatedInputs = /** @type {HTMLInputElement[]} */ (\n relatedElements.filter((e) => e instanceof HTMLInputElement)\n );\n\n let quantityMin = parseInt(element.dataset.quantityMin || \"\");\n if (Number.isNaN(quantityMin)) {\n quantityMin = 0;\n }\n quantityMin = Math.max(quantityMin, 0);\n\n let quantityMax = parseInt(element.dataset.quantityInStock || \"\");\n if (Number.isNaN(quantityMax)) {\n quantityMax = Infinity;\n }\n\n let quantityPrev = parseInt(element.dataset.quantity || \"\");\n if (Number.isNaN(quantityPrev)) {\n quantityPrev = quantityMin;\n }\n\n let amountChange = 0;\n if (\"increase\" in element.dataset) {\n amountChange = 1;\n } else if (\"decrease\" in element.dataset) {\n amountChange = -1;\n }\n\n /**\n * Установить новое значение количества и отправить запрос\n * @param {number} quantity\n * @param {boolean} [updateInputValue=true]\n */\n function setQuantity(quantity, updateInputValue = true) {\n if (quantity < quantityMin) {\n return;\n }\n if (quantity > quantityMax) {\n if (quantityPrev < quantityMax) {\n quantity = quantityMax;\n eventBus.publish(\"not-enough-products\", {\n message: commonState.translations[\n \"Only {quantity} pieces available\"\n ].replace(\"{quantity}\", quantityMax),\n });\n } else {\n eventBus.publish(\"not-enough-products\", {\n message:\n commonState.translations[\n \"You have added the maximum quantity of this product\"\n ],\n });\n return;\n }\n }\n if (quantity !== quantityPrev) {\n relatedElements.forEach((e) => {\n e.dataset.quantity = quantity.toString();\n if (e instanceof HTMLButtonElement) {\n if (\"increase\" in e.dataset) {\n e.disabled = quantity >= quantityMax;\n } else if (\"decrease\" in e.dataset) {\n e.disabled = quantity <= quantityMin;\n }\n }\n });\n updateVariantInCart({\n productId,\n variantId,\n quantity,\n quantityPrev,\n });\n }\n if (updateInputValue) {\n relatedInputs.forEach((i) => {\n i.value = quantity.toString();\n });\n }\n }\n\n /**\n * Восстановить последнее корректно значение количества для элемента input\n */\n function resetInputValue() {\n relatedInputs.forEach((i) => {\n i.value = quantityPrev.toString();\n });\n }\n\n /**\n * Ограничить количество товара минимальным и максимальным значением\n * @param {number} quantity\n */\n function clamp(quantity) {\n return Math.min(Math.max(quantity, quantityMin), quantityMax);\n }\n\n return {\n quantity: quantityPrev,\n quantityMin,\n quantityMax,\n amountChange,\n setQuantity,\n resetInputValue,\n clamp,\n };\n}\n\n/**\n * Запрос изменения количества товаров в корзине\n * @typedef {Object} CartRequest\n * @property {number} productId ID продукта\n * @property {number} variantId ID варианта\n * @property {number} quantity Новое количество\n * @property {number} quantityPrev Предыдущее количество\n */\n\n/**\n * Очередь запросов изменения количества товаров в корзине\n * @type {CartRequest[]}\n */\nconst cartRequestsQueue = [];\n// Происходит ли запрос изменения корзины\nlet isLoading = false;\n// Промис для ожидания остановки запросов корзины\nlet stopPromise = null;\nlet stopPromiseResolve = null;\n\n/**\n * Изменение количества варианта продукта в корзине.\n * Запросы на изменение добавляются в очередь и выполняются последовательно.\n * Если в очереди уже есть запрос на изменение количества данного варианта,\n * то заменить его на новый, иначе добавить запрос в очередь.\n * @param {CartRequest} request\n */\nfunction updateVariantInCart(request) {\n if (stopPromise) {\n return;\n }\n if (isLoading) {\n const oldRequest = cartRequestsQueue.find(\n (r) =>\n r.productId === request.productId &&\n r.variantId === request.variantId\n );\n if (oldRequest) {\n oldRequest.quantity = request.quantity;\n } else {\n cartRequestsQueue.push(request);\n }\n } else {\n isLoading = true;\n cartRequestsQueue.push(request);\n setTimeout(async () => {\n while (cartRequestsQueue.length > 0) {\n const r = /** @type {CartRequest} */ (\n cartRequestsQueue.shift()\n );\n await updateVariantInCartRecursively(r, 5);\n }\n isLoading = false;\n if (stopPromiseResolve) {\n stopPromiseResolve();\n }\n }, 50);\n }\n}\n\n/**\n * Повторять запросы несколько раз, если версия корзины не актуальна\n * @param {CartRequest} request\n * @param {number} depth\n */\nfunction updateVariantInCartRecursively(request, depth) {\n return fetch(\"/cart/update\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n Version: commonState.cart.version,\n Id: request.productId,\n VariantId: request.variantId,\n Quantity: request.quantity,\n }),\n })\n .then((response) => {\n return handleCartResponse(response);\n })\n .then((data) => {\n updateCommonState({\n cart: {\n version: data.cart.version,\n code: data.cart.code,\n },\n });\n eventBus.publish(\"cart-changed\", {\n ...request,\n total: data.totalQuantityItems,\n totalPrice: data.cart.total,\n discountedTotal: data.cart.discountedTotal\n });\n })\n .catch((error) => {\n if (\n error instanceof HTTPError &&\n error.data.statusCode === 409 &&\n depth > 1\n ) {\n return getCart().then(() => {\n return updateVariantInCartRecursively(request, depth - 1);\n });\n }\n eventBus.publish(\"update-cart-error\", { error });\n throw error;\n });\n}\n\n// Получить новую версию корзины\nfunction getCart() {\n return fetch(\"/cart/get\", { method: \"GET\" })\n .then((response) => {\n return handleCartResponse(response);\n })\n .then((data) => {\n updateCommonState({\n cart: {\n version: data.cart.version,\n code: data.cart.code,\n },\n });\n });\n}\n\nfunction handleCartResponse(response) {\n if (response.ok) {\n return response.json();\n }\n return response.json().then((data) => {\n throw new HTTPError(data);\n });\n}\n\nclass HTTPError extends Error {\n constructor(data) {\n super(data.errorMessage || \"Failed to connect\");\n this.data = data;\n }\n}\n\n/**\n * Остановить возможность добавления новых запросов в очередь\n * Дождаться завершения всех текущих запросов\n */\nexport async function stopCartRequests() {\n if (!stopPromise) {\n stopPromise = new Promise((resolve) => {\n stopPromiseResolve = resolve;\n });\n }\n if (!isLoading) {\n stopPromiseResolve();\n }\n return stopPromise;\n}\n\n/**\n * Возобновить возможность добавления новых запросов в очередь\n * Если идет процесс остановки, то дождаться его завершения\n */\nexport async function resetCartRequests() {\n if (stopPromise) {\n await stopPromise;\n }\n stopPromise = null;\n stopPromiseResolve = null;\n}\n"],"names":["getQuantityAttributes","element","elements","productId","variantId","relatedElements","e","pId","vId","relatedInputs","quantityMin","quantityMax","quantityPrev","amountChange","setQuantity","quantity","updateInputValue","eventBus","commonState","updateVariantInCart","i","resetInputValue","clamp","cartRequestsQueue","isLoading","stopPromise","stopPromiseResolve","request","oldRequest","r","updateVariantInCartRecursively","depth","response","handleCartResponse","data","updateCommonState","error","HTTPError","getCart","stopCartRequests","resolve","resetCartRequests"],"mappings":"gHAWO,SAASA,EAAsBC,EAAS,CAIrC,MAAAC,EAAW,SAAS,iBAAiB,2BAA2B,EAEhEC,EAAY,SAASF,EAAQ,QAAQ,WAAa,EAAE,EACpDG,EAAY,SAASH,EAAQ,QAAQ,WAAa,EAAE,EAGpDI,EAAkB,CAAC,GAAGH,CAAQ,EAAE,OAAQI,GAAM,CAChD,MAAMC,EAAM,SAASD,EAAE,QAAQ,WAAa,EAAE,EACxCE,EAAM,SAASF,EAAE,QAAQ,WAAa,EAAE,EACvC,OAAAC,IAAQJ,GAAaK,IAAQJ,CAAA,CACvC,EACKK,EACFJ,EAAgB,OAAQC,GAAMA,aAAa,gBAAgB,EAG/D,IAAII,EAAc,SAAST,EAAQ,QAAQ,aAAe,EAAE,EACxD,OAAO,MAAMS,CAAW,IACVA,EAAA,GAEJA,EAAA,KAAK,IAAIA,EAAa,CAAC,EAErC,IAAIC,EAAc,SAASV,EAAQ,QAAQ,iBAAmB,EAAE,EAC5D,OAAO,MAAMU,CAA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