@dropins/storefront-quick-order 0.1.2-alpha2 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/api.js +1 -1
  2. package/chunks/QuickOrderDisabledOverlay.js +1 -1
  3. package/chunks/QuickOrderDisabledOverlay.js.map +1 -1
  4. package/chunks/debounce.js +4 -0
  5. package/chunks/debounce.js.map +1 -0
  6. package/chunks/getStoreConfig.js +10 -0
  7. package/chunks/getStoreConfig.js.map +1 -0
  8. package/components/QuickOrderVariantsActions/QuickOrderVariantsActions.d.ts +5 -0
  9. package/components/QuickOrderVariantsActions/index.d.ts +19 -0
  10. package/components/QuickOrderVariantsGrid/QuickOrderVariantsGrid.d.ts +5 -0
  11. package/components/QuickOrderVariantsGrid/index.d.ts +19 -0
  12. package/components/index.d.ts +2 -0
  13. package/containers/QuickOrderCsvUpload.js +2 -2
  14. package/containers/QuickOrderCsvUpload.js.map +1 -1
  15. package/containers/QuickOrderItems.js +1 -1
  16. package/containers/QuickOrderItems.js.map +1 -1
  17. package/containers/QuickOrderMultipleSku.js +1 -1
  18. package/containers/QuickOrderMultipleSku.js.map +1 -1
  19. package/containers/QuickOrderVariantsGrid/QuickOrderVariantsGrid.d.ts +5 -0
  20. package/containers/QuickOrderVariantsGrid/index.d.ts +19 -0
  21. package/containers/QuickOrderVariantsGrid.d.ts +3 -0
  22. package/containers/QuickOrderVariantsGrid.js +6 -0
  23. package/containers/QuickOrderVariantsGrid.js.map +1 -0
  24. package/containers/index.d.ts +1 -0
  25. package/hooks/index.d.ts +1 -0
  26. package/hooks/useQuickOrderVariantsData.d.ts +4 -0
  27. package/i18n/en_US.json.d.ts +90 -70
  28. package/package.json +1 -1
  29. package/render.js +3 -2
  30. package/render.js.map +1 -1
  31. package/types/index.d.ts +1 -0
  32. package/types/quickOrderVariantsGrid.types.d.ts +141 -0
  33. package/chunks/initialize.js +0 -10
  34. package/chunks/initialize.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"QuickOrderCsvUpload.js","sources":["/@dropins/storefront-quick-order/src/lib/cleanCsvValue.ts","/@dropins/storefront-quick-order/src/lib/validateCsvContent.ts","/@dropins/storefront-quick-order/src/hooks/useQuickOrderCsvUpload.tsx","/@dropins/storefront-quick-order/src/containers/QuickOrderCsvUpload/QuickOrderCsvUpload.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Cleans CSV value by removing surrounding quotes and trimming whitespace\n * Handles both double quotes (\") and single quotes (')\n * @param val - The raw CSV value to clean\n * @returns Cleaned string value\n */\nexport const cleanCsvValue = (val: string): string =>\n val.trim().replace(/^[\"']|[\"']$/g, '');\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CSVValidationResult, SubmitSkuValue } from '@/b2b-quick-order/types';\nimport { cleanCsvValue } from './cleanCsvValue';\n\n// Maximum number of rows allowed in CSV\nconst MAX_ROWS = 200;\n\nexport interface ValidationMessages {\n emptyFile: string;\n missingColumns: string;\n extraColumns: string;\n maxRowsExceeded: string;\n skuRequired: string;\n invalidQuantity: string;\n noValidData: string;\n}\n\n/**\n * Validates CSV content and extracts SKU/quantity data\n * Handles BOM, different line endings, quoted values, and empty lines\n * @param content - Raw CSV file content\n * @param messages - Localized error messages\n * @returns Validation result with data or error\n */\nexport const validateCsvContent = (\n content: string,\n messages: ValidationMessages\n): CSVValidationResult => {\n // Remove BOM if present\n const cleanContent = content.replace(/^\\uFEFF/, '');\n\n // Split by different line endings (handle \\r\\n, \\n, \\r)\n const lines = cleanContent.trim().split(/\\r?\\n|\\r/);\n\n // Check if file is effectively empty after removing empty lines\n const hasContent = lines.some((line) => line.trim());\n if (!hasContent) {\n return { isValid: false, error: messages.emptyFile };\n }\n\n const header = lines[0]\n .split(',')\n .map((col) => cleanCsvValue(col).toLowerCase());\n const skuIndex = header.indexOf('sku');\n const qtyIndex = header.indexOf('qty');\n\n if (skuIndex === -1 || qtyIndex === -1) {\n return {\n isValid: false,\n error: messages.missingColumns,\n };\n }\n\n if (header.length !== 2) {\n return {\n isValid: false,\n error: messages.extraColumns,\n };\n }\n\n if (lines.length - 1 > MAX_ROWS) {\n return {\n isValid: false,\n error: messages.maxRowsExceeded.replace('{maxRows}', MAX_ROWS.toString()),\n };\n }\n\n const data: SubmitSkuValue = [];\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n const values = line.split(',').map((val) => cleanCsvValue(val));\n const sku = values[skuIndex];\n const qty = values[qtyIndex];\n\n if (!sku) {\n return {\n isValid: false,\n error: messages.skuRequired.replace('{rowNumber}', i.toString()),\n };\n }\n\n const quantity = parseInt(qty, 10);\n if (isNaN(quantity) || quantity <= 0 || !Number.isInteger(quantity)) {\n return {\n isValid: false,\n error: messages.invalidQuantity.replace('{rowNumber}', i.toString()),\n };\n }\n\n data.push({ sku, quantity });\n }\n\n if (data.length === 0) {\n return { isValid: false, error: messages.noValidData };\n }\n\n return { isValid: true, data };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useCallback, useState } from 'preact/hooks';\nimport {\n UseQuickOrderCsvUploadProps,\n UseQuickOrderCsvUploadReturn,\n} from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { validateCsvContent } from '@/b2b-quick-order/lib';\n\nexport const useQuickOrderCsvUpload = ({\n routeSampleCSV,\n onFileUpload,\n}: UseQuickOrderCsvUploadProps): UseQuickOrderCsvUploadReturn => {\n const [error, setError] = useState<string | null>(null);\n const [fileName, setFileName] = useState<string | null>(null);\n\n const t = useText({\n invalidFile: 'QuickOrder.CsvFileInput.uploadCSVErrors.invalidFile',\n emptyFile: 'QuickOrder.CsvFileInput.uploadCSVErrors.emptyFile',\n missingColumns: 'QuickOrder.CsvFileInput.uploadCSVErrors.missingColumns',\n extraColumns: 'QuickOrder.CsvFileInput.uploadCSVErrors.extraColumns',\n maxRowsExceeded: 'QuickOrder.CsvFileInput.uploadCSVErrors.maxRowsExceeded',\n skuRequired: 'QuickOrder.CsvFileInput.uploadCSVErrors.skuRequired',\n invalidQuantity: 'QuickOrder.CsvFileInput.uploadCSVErrors.invalidQuantity',\n noValidData: 'QuickOrder.CsvFileInput.uploadCSVErrors.noValidData',\n onlyCSV: 'QuickOrder.CsvFileInput.uploadCSVErrors.onlyCSV',\n failedToRead: 'QuickOrder.CsvFileInput.uploadCSVErrors.failedToRead',\n failedToParse: 'QuickOrder.CsvFileInput.uploadCSVErrors.failedToParse',\n });\n\n const handleFileUpload = useCallback(\n (file: File) => {\n setError(null);\n setFileName(file.name);\n\n if (!file.name.toLowerCase().endsWith('.csv')) {\n setError(t.onlyCSV);\n return;\n }\n\n const reader = new FileReader();\n\n reader.onload = (e) => {\n try {\n const content = e.target?.result as string;\n const validation = validateCsvContent(content, {\n emptyFile: t.emptyFile,\n missingColumns: t.missingColumns,\n extraColumns: t.extraColumns,\n maxRowsExceeded: t.maxRowsExceeded,\n skuRequired: t.skuRequired,\n invalidQuantity: t.invalidQuantity,\n noValidData: t.noValidData,\n });\n\n if (!validation.isValid) {\n setError(validation.error!);\n return;\n }\n\n // Success - emit event or call custom callback\n if (onFileUpload) {\n onFileUpload(validation.data!);\n } else {\n events.emit('quick-order/add-items', validation.data!);\n }\n\n // Reset state after successful upload\n setFileName(null);\n setError(null);\n } catch (err) {\n setError(t.failedToParse);\n }\n };\n\n reader.onerror = () => {\n setError(t.failedToRead);\n };\n\n reader.readAsText(file);\n },\n [onFileUpload, t]\n );\n\n const handleDownloadSample = useCallback(() => {\n if (routeSampleCSV) {\n window.open(routeSampleCSV(), '_blank');\n } else {\n const csvContent = 'SKU,QTY\\nSKU123,1\\nSKU456,2\\nSKU789,3';\n const blob = new Blob([csvContent], { type: 'text/csv' });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = 'sample-quick-order.csv';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n }\n }, [routeSampleCSV]);\n\n return {\n handleFileUpload,\n error,\n fileName,\n handleDownloadSample,\n showSampleDownload: true,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CsvFileInput } from '@/b2b-quick-order/components/CsvFileInput';\nimport { QuickOrderDisabledOverlay } from '@/b2b-quick-order/components';\nimport { useQuickOrderCsvUpload } from '@/b2b-quick-order/hooks/useQuickOrderCsvUpload';\nimport { QuickOrderCsvUploadProps } from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport { config } from '@/b2b-quick-order/api/initialize';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, Container } from '@adobe-commerce/elsie/lib';\n\nexport const QuickOrderCsvUpload: Container<QuickOrderCsvUploadProps> = ({\n className,\n routeSampleCSV,\n onFileUpload,\n}) => {\n const isQuickOrderActive = config.getConfig().quickOrderActive;\n\n const t = useText({\n title: 'QuickOrder.CsvFileInput.title',\n helperText: 'QuickOrder.CsvFileInput.helperText',\n downloadSample: 'QuickOrder.CsvFileInput.downloadSample',\n inputLabel: 'QuickOrder.CsvFileInput.inputLabel',\n selectedFile: 'QuickOrder.CsvFileInput.selectedFile',\n disabledMessage: 'QuickOrder.QuickOrderItem.disabledMessage',\n });\n\n const {\n handleFileUpload,\n error,\n fileName,\n handleDownloadSample,\n showSampleDownload,\n } = useQuickOrderCsvUpload({\n routeSampleCSV,\n onFileUpload,\n });\n\n return (\n <div\n className={classes(['b2b-quick-order-quick-order-upload-csv', className])}\n data-testid=\"quick-order-upload-csv\"\n >\n <QuickOrderDisabledOverlay\n isDisabled={!isQuickOrderActive}\n message={t.disabledMessage}\n >\n <CsvFileInput\n t={t}\n onFileUpload={handleFileUpload}\n error={error}\n fileName={fileName}\n onDownloadSample={handleDownloadSample}\n showSampleDownload={showSampleDownload}\n />\n </QuickOrderDisabledOverlay>\n </div>\n );\n};\n"],"names":["cleanCsvValue","val","MAX_ROWS","validateCsvContent","content","messages","lines","line","header","col","skuIndex","qtyIndex","data","i","values","sku","qty","quantity","useQuickOrderCsvUpload","routeSampleCSV","onFileUpload","error","setError","useState","fileName","setFileName","t","useText","handleFileUpload","useCallback","file","reader","e","_a","validation","events","handleDownloadSample","csvContent","blob","url","link","QuickOrderCsvUpload","className","isQuickOrderActive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Y,CAACL,EACb,QAASjB,EAAE,gBAEX,SAAAoB,EAACG,EAAA,CACC,EAAAvB,EACA,aAAcE,EACd,MAAAP,EACA,SAAAG,EACA,iBAAkBY,EAClB,mBAAAS,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CAGN"}
1
+ {"version":3,"file":"QuickOrderCsvUpload.js","sources":["/@dropins/storefront-quick-order/src/lib/cleanCsvValue.ts","/@dropins/storefront-quick-order/src/lib/validateCsvContent.ts","/@dropins/storefront-quick-order/src/hooks/useQuickOrderCsvUpload.tsx","/@dropins/storefront-quick-order/src/containers/QuickOrderCsvUpload/QuickOrderCsvUpload.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Cleans CSV value by removing surrounding quotes and trimming whitespace\n * Handles both double quotes (\") and single quotes (')\n * @param val - The raw CSV value to clean\n * @returns Cleaned string value\n */\nexport const cleanCsvValue = (val: string): string =>\n val.trim().replace(/^[\"']|[\"']$/g, '');\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CSVValidationResult, SubmitSkuValue } from '@/b2b-quick-order/types';\nimport { cleanCsvValue } from './cleanCsvValue';\n\n// Maximum number of rows allowed in CSV\nconst MAX_ROWS = 200;\n\nexport interface ValidationMessages {\n emptyFile: string;\n missingColumns: string;\n extraColumns: string;\n maxRowsExceeded: string;\n skuRequired: string;\n invalidQuantity: string;\n noValidData: string;\n}\n\n/**\n * Validates CSV content and extracts SKU/quantity data\n * Handles BOM, different line endings, quoted values, and empty lines\n * @param content - Raw CSV file content\n * @param messages - Localized error messages\n * @returns Validation result with data or error\n */\nexport const validateCsvContent = (\n content: string,\n messages: ValidationMessages\n): CSVValidationResult => {\n // Remove BOM if present\n const cleanContent = content.replace(/^\\uFEFF/, '');\n\n // Split by different line endings (handle \\r\\n, \\n, \\r)\n const lines = cleanContent.trim().split(/\\r?\\n|\\r/);\n\n // Check if file is effectively empty after removing empty lines\n const hasContent = lines.some((line) => line.trim());\n if (!hasContent) {\n return { isValid: false, error: messages.emptyFile };\n }\n\n const header = lines[0]\n .split(',')\n .map((col) => cleanCsvValue(col).toLowerCase());\n const skuIndex = header.indexOf('sku');\n const qtyIndex = header.indexOf('qty');\n\n if (skuIndex === -1 || qtyIndex === -1) {\n return {\n isValid: false,\n error: messages.missingColumns,\n };\n }\n\n if (header.length !== 2) {\n return {\n isValid: false,\n error: messages.extraColumns,\n };\n }\n\n if (lines.length - 1 > MAX_ROWS) {\n return {\n isValid: false,\n error: messages.maxRowsExceeded.replace('{maxRows}', MAX_ROWS.toString()),\n };\n }\n\n const data: SubmitSkuValue = [];\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n const values = line.split(',').map((val) => cleanCsvValue(val));\n const sku = values[skuIndex];\n const qty = values[qtyIndex];\n\n if (!sku) {\n return {\n isValid: false,\n error: messages.skuRequired.replace('{rowNumber}', i.toString()),\n };\n }\n\n const quantity = parseInt(qty, 10);\n if (isNaN(quantity) || quantity <= 0 || !Number.isInteger(quantity)) {\n return {\n isValid: false,\n error: messages.invalidQuantity.replace('{rowNumber}', i.toString()),\n };\n }\n\n data.push({ sku, quantity });\n }\n\n if (data.length === 0) {\n return { isValid: false, error: messages.noValidData };\n }\n\n return { isValid: true, data };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useCallback, useState } from 'preact/hooks';\nimport {\n UseQuickOrderCsvUploadProps,\n UseQuickOrderCsvUploadReturn,\n} from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { validateCsvContent } from '@/b2b-quick-order/lib';\n\nexport const useQuickOrderCsvUpload = ({\n routeSampleCSV,\n onFileUpload,\n}: UseQuickOrderCsvUploadProps): UseQuickOrderCsvUploadReturn => {\n const [error, setError] = useState<string | null>(null);\n const [fileName, setFileName] = useState<string | null>(null);\n\n const t = useText({\n invalidFile: 'QuickOrder.CsvFileInput.uploadCSVErrors.invalidFile',\n emptyFile: 'QuickOrder.CsvFileInput.uploadCSVErrors.emptyFile',\n missingColumns: 'QuickOrder.CsvFileInput.uploadCSVErrors.missingColumns',\n extraColumns: 'QuickOrder.CsvFileInput.uploadCSVErrors.extraColumns',\n maxRowsExceeded: 'QuickOrder.CsvFileInput.uploadCSVErrors.maxRowsExceeded',\n skuRequired: 'QuickOrder.CsvFileInput.uploadCSVErrors.skuRequired',\n invalidQuantity: 'QuickOrder.CsvFileInput.uploadCSVErrors.invalidQuantity',\n noValidData: 'QuickOrder.CsvFileInput.uploadCSVErrors.noValidData',\n onlyCSV: 'QuickOrder.CsvFileInput.uploadCSVErrors.onlyCSV',\n failedToRead: 'QuickOrder.CsvFileInput.uploadCSVErrors.failedToRead',\n failedToParse: 'QuickOrder.CsvFileInput.uploadCSVErrors.failedToParse',\n });\n\n const handleFileUpload = useCallback(\n (file: File) => {\n setError(null);\n setFileName(file.name);\n\n if (!file.name.toLowerCase().endsWith('.csv')) {\n setError(t.onlyCSV);\n return;\n }\n\n const reader = new FileReader();\n\n reader.onload = (e) => {\n try {\n const content = e.target?.result as string;\n const validation = validateCsvContent(content, {\n emptyFile: t.emptyFile,\n missingColumns: t.missingColumns,\n extraColumns: t.extraColumns,\n maxRowsExceeded: t.maxRowsExceeded,\n skuRequired: t.skuRequired,\n invalidQuantity: t.invalidQuantity,\n noValidData: t.noValidData,\n });\n\n if (!validation.isValid) {\n setError(validation.error!);\n return;\n }\n\n // Success - emit event or call custom callback\n if (onFileUpload) {\n onFileUpload(validation.data!);\n } else {\n events.emit('quick-order/add-items', validation.data!);\n }\n\n // Reset state after successful upload\n setFileName(null);\n setError(null);\n } catch (err) {\n setError(t.failedToParse);\n }\n };\n\n reader.onerror = () => {\n setError(t.failedToRead);\n };\n\n reader.readAsText(file);\n },\n [onFileUpload, t]\n );\n\n const handleDownloadSample = useCallback(() => {\n if (routeSampleCSV) {\n window.open(routeSampleCSV(), '_blank');\n } else {\n const csvContent = 'SKU,QTY\\nSKU123,1\\nSKU456,2\\nSKU789,3';\n const blob = new Blob([csvContent], { type: 'text/csv' });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = 'sample-quick-order.csv';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n }\n }, [routeSampleCSV]);\n\n return {\n handleFileUpload,\n error,\n fileName,\n handleDownloadSample,\n showSampleDownload: true,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CsvFileInput } from '@/b2b-quick-order/components/CsvFileInput';\nimport { QuickOrderDisabledOverlay } from '@/b2b-quick-order/components';\nimport { useQuickOrderCsvUpload } from '@/b2b-quick-order/hooks/useQuickOrderCsvUpload';\nimport { QuickOrderCsvUploadProps } from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport { config } from '@/b2b-quick-order/api/initialize';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, Container } from '@adobe-commerce/elsie/lib';\n\nexport const QuickOrderCsvUpload: Container<QuickOrderCsvUploadProps> = ({\n className,\n routeSampleCSV,\n onFileUpload,\n}) => {\n const isQuickOrderActive = config.getConfig().quickOrderActive;\n\n const t = useText({\n title: 'QuickOrder.CsvFileInput.title',\n helperText: 'QuickOrder.CsvFileInput.helperText',\n downloadSample: 'QuickOrder.CsvFileInput.downloadSample',\n inputLabel: 'QuickOrder.CsvFileInput.inputLabel',\n selectedFile: 'QuickOrder.CsvFileInput.selectedFile',\n disabledMessage: 'QuickOrder.QuickOrderItem.disabledMessage',\n });\n\n const {\n handleFileUpload,\n error,\n fileName,\n handleDownloadSample,\n showSampleDownload,\n } = useQuickOrderCsvUpload({\n routeSampleCSV,\n onFileUpload,\n });\n\n return (\n <div\n className={classes(['b2b-quick-order-quick-order-upload-csv', className])}\n data-testid=\"quick-order-upload-csv\"\n >\n <QuickOrderDisabledOverlay\n isDisabled={!isQuickOrderActive}\n message={t.disabledMessage}\n >\n <CsvFileInput\n t={t}\n onFileUpload={handleFileUpload}\n error={error}\n fileName={fileName}\n onDownloadSample={handleDownloadSample}\n showSampleDownload={showSampleDownload}\n />\n </QuickOrderDisabledOverlay>\n </div>\n );\n};\n"],"names":["cleanCsvValue","val","MAX_ROWS","validateCsvContent","content","messages","lines","line","header","col","skuIndex","qtyIndex","data","i","values","sku","qty","quantity","useQuickOrderCsvUpload","routeSampleCSV","onFileUpload","error","setError","useState","fileName","setFileName","t","useText","handleFileUpload","useCallback","file","reader","e","_a","validation","events","handleDownloadSample","csvContent","blob","url","link","QuickOrderCsvUpload","className","isQuickOrderActive","config","showSampleDownload","jsx","classes","QuickOrderDisabledOverlay","CsvFileInput"],"mappings":"iiBAuBO,MAAMA,EAAiBC,GAC5BA,EAAI,OAAO,QAAQ,eAAgB,EAAE,ECHjCC,EAAW,IAmBJC,EAAqB,CAChCC,EACAC,IACwB,CAKxB,MAAMC,EAHeF,EAAQ,QAAQ,UAAW,EAAE,EAGvB,KAAA,EAAO,MAAM,UAAU,EAIlD,GAAI,CADeE,EAAM,KAAMC,GAASA,EAAK,MAAM,EAEjD,MAAO,CAAE,QAAS,GAAO,MAAOF,EAAS,SAAA,EAG3C,MAAMG,EAASF,EAAM,CAAC,EACnB,MAAM,GAAG,EACT,IAAKG,GAAQT,EAAcS,CAAG,EAAE,aAAa,EAC1CC,EAAWF,EAAO,QAAQ,KAAK,EAC/BG,EAAWH,EAAO,QAAQ,KAAK,EAErC,GAAIE,IAAa,IAAMC,IAAa,GAClC,MAAO,CACL,QAAS,GACT,MAAON,EAAS,cAAA,EAIpB,GAAIG,EAAO,SAAW,EACpB,MAAO,CACL,QAAS,GACT,MAAOH,EAAS,YAAA,EAIpB,GAAIC,EAAM,OAAS,EAAIJ,EACrB,MAAO,CACL,QAAS,GACT,MAAOG,EAAS,gBAAgB,QAAQ,YAAaH,EAAS,UAAU,CAAA,EAI5E,MAAMU,EAAuB,CAAA,EAC7B,QAASC,EAAI,EAAGA,EAAIP,EAAM,OAAQO,IAAK,CACrC,MAAMN,EAAOD,EAAMO,CAAC,EAAE,KAAA,EACtB,GAAI,CAACN,EAAM,SAEX,MAAMO,EAASP,EAAK,MAAM,GAAG,EAAE,IAAKN,GAAQD,EAAcC,CAAG,CAAC,EACxDc,EAAMD,EAAOJ,CAAQ,EACrBM,EAAMF,EAAOH,CAAQ,EAE3B,G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B,eAAAC,EACA,aAAAC,CAAA,CACD,EAED,OACE0B,EAAC,MAAA,CACC,UAAWC,EAAQ,CAAC,yCAA0CL,CAAS,CAAC,EACxE,cAAY,yBAEZ,SAAAI,EAACE,EAAA,CACC,WAAY,CAACL,EACb,QAASjB,EAAE,gBAEX,SAAAoB,EAACG,EAAA,CACC,EAAAvB,EACA,aAAcE,EACd,MAAAP,EACA,SAAAG,EACA,iBAAkBY,EAClB,mBAAAS,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CAGN"}
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2026 Adobe
2
2
  All Rights Reserved. */
3
- import{jsx as v,jsxs as D}from"@dropins/tools/preact-jsx-runtime.js";import{AlertBanner as rr}from"@dropins/tools/components.js";import{Q as tr,a as er}from"../chunks/QuickOrderDisabledOverlay.js";import{classes as P}from"@dropins/tools/lib.js";import{useState as R,useRef as J,useCallback as A,useEffect as y}from"@dropins/tools/preact-hooks.js";import{events as S}from"@dropins/tools/event-bus.js";import{useText as z}from"@dropins/tools/i18n.js";import"@dropins/tools/preact-compat.js";import{c as nr}from"../chunks/initialize.js";import"@dropins/tools/fetch-graphql.js";const sr=["sku","parentSku","quantity","optionsUIDs","valid","productType"],ir=e=>{const t=[],r=[];return e.forEach((n,u)=>{if(sr.includes(u))return;const i=n;i&&i.match(/^[A-Za-z0-9+/=]+$/)?t.push(i):r.push({uid:u,value:i})}),{optionUIDs:t,enteredOptions:r}},or=e=>{const t=Number(e.get("quantity")),r=!t||t<1?1:t,n={sku:e.get("sku"),quantity:r},u=e.get("parentSku");u&&(n.parentSku=u);const{optionUIDs:i,enteredOptions:a}=ir(e);return i.length>0&&(n.optionsUIDs=i),a.length>0&&(n.enteredOptions=a),n},_={sku:"",quantity:1,name:"",images:[],inStock:!1,addToCartAllowed:!1,isBundle:!1,prices:{},attributes:[],options:[],url:"",urlKey:"",externalId:"",productType:"simple",shortDescription:"",metaDescription:"",metaKeyword:"",metaTitle:"",description:""},L=(e,t)=>!t||!Array.isArray(t)?e.map(r=>({..._,sku:r.sku,quantity:r.quantity??1})):e.map(r=>{const n=t.find(u=>(u==null?void 0:u.sku)===(r==null?void 0:r.sku));return n?{...n,...r.variantSku&&{variantSku:r.variantSku},quantity:r.quantity??1}:{..._,sku:r.sku,...r.variantSku&&{variantSku:r.variantSku},quantity:r.quantity??1}}),K=e=>e.length===0?!1:e.every(t=>!((t.urlKey||t.url)&&t.name)||t.inStock===!1?!1:t.options&&t.options.length>0?t.options.some(i=>i.required)?t.options.every(i=>{var a;return i.required?(a=i.items)==null?void 0:a.some(l=>l.selected):!0}):t.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0)):!0),x=e=>{const t=[];return e.forEach(r=>{if(!((r.urlKey||r.url)&&r.name)){t.push({sku:r.sku,name:r.name||"Unknown",reason:"incomplete_data"});return}if(r.inStock===!1){t.push({sku:r.sku,name:r.name,reason:"out_of_stock"});return}if(r.options&&r.options.length>0){if(r.options.some(a=>a.required)){r.options.every(l=>{var h;return l.required?(h=l.items)==null?void 0:h.some(Q=>Q.selected):!0})||t.push({sku:r.sku,name:r.name,reason:"missing_required_options"});return}r.options.some(a=>a.items&&a.items.length>0&&a.items.some(l=>l.selected===!0))||t.push({sku:r.sku,name:r.name,reason:"missing_options"})}}),t},w=e=>`quick-order-item-${e.id||e.variantSku||e.sku}`,W=e=>`${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,j=(e,t)=>e.findIndex(r=>t.variantSku&&r.variantSku?r.variantSku===t.variantSku:r.variantSku&&!t.variantSku&&t.sku?r.variantSku===t.sku:t.variantSku&&!r.variantSku&&r.sku?r.sku===t.variantSku:!t.variantSku&&!r.variantSku?r.sku===t.sku:!1),ar=(e,t,r)=>e.findIndex(n=>n.id===r?!1:t.variantSku&&n.variantSku?n.variantSku===t.variantSku:t.variantSku&&!n.variantSku&&n.sku?n.sku===t.variantSku:!1),ur=(e,t,r,n=1)=>e.map((u,i)=>i===r?{...u,quantity:u.quantity+n}:i===t?null:u).filter(Boolean),cr=(e,t,r)=>{const n=[...e],u=[],i=[],a=[];return t.forEach((l,h)=>{const Q=r[h];if(Q!=null&&Q.replaceItemSku){const p=n.findIndex(g=>g.sku===Q.replaceItemSku||g.id===Q.replaceItemSku);if(p!==-1){const g=j(n,l);if(g!==-1&&g!==p){n.splice(p,1);const O=g>p?g-1:g;n[O]={...n[O],quantity:n[O].quantity+l.quantity},a.push(n[O])}else{const O={...l,id:W(l.sku)};n[p]=O,i.push(O)}return}}const q=j(n,l);if(q!==-1)n[q]={...n[q],quantity:n[q].quantity+l.quantity},a.push(n[q]);else{const p={...l,id:W(l.sku)};n.push(p),u.push(p)}}),{updatedItems:n,addedItems:u,replacedItems:i,mergedItems:a}},dr=(e,t,r,n=1)=>{const u=t?ar(e,r,t):-1;if(u!==-1){const a=e.findIndex(l=>l.id===t);return{updatedItems:ur(e,a,u,n),wasMerged:!0,mergedIntoIndex:u}}return{updatedItems:e.map(a=>t&&a.id===t?{...a,...r,id:t}:!t&&a.sku===r.sku?{...a,...r}:a),wasMerged:!1}},lr=e=>e.map(t=>{const r=t.id||t.sku,n=document.forms[`form-${r}`];if(!n)return null;const u=new FormData(n);return u.get("valid")==="true"?or(u):null}),kr=e=>{let t=[];return e&&typeof e=="object"?e.optionsUIDs&&Array.isArray(e.optionsUIDs)?t=e.optionsUIDs:Array.isArray(e)&&(t=e):typeof e=="string"&&(t=[e]),t},G=e=>{try{const t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch(t){console.error("Error reading from localStorage:",t)}return{}},fr=(e,t,r)=>{if(r.length!==0)try{const n=G(e);n[t]=r,localStorage.setItem(e,JSON.stringify(n))}catch(n){console.error("Error saving to localStorage:",n)}},pr=(e,t,r)=>e.map(n=>{const u=t.find(i=>n.sku===i.sku||n.sku===i.variantSku);if(u){const i=u.id||u.sku,a=r[i];if(a&&a.length>0)return{...n,optionsUIDs:a}}return n}),mr=e=>{const t=!e.inStock||!e.addToCartAllowed;if(e.options&&e.options.length>0){if(e.options.some(i=>!i.items||i.items.length===0))return!0;if(e.options.some(i=>i.required)){const i=e.options.every(a=>{var l;return a.required?(l=a.items)==null?void 0:l.some(h=>h.selected):!0});return t||!i}const u=e.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0));return t||!u}return t},hr=({getProductsData:e,handleAddToCart:t}={})=>{const[r,n]=R([]),[u,i]=R(!1),[a,l]=R(new Set),[h,Q]=R(!1),[q,p]=R(null),[g,O]=R([]),C=J([]),I=z({validationError:"QuickOrder.QuickOrderItem.notification.validationError",backendError:"QuickOrder.QuickOrderItem.notification.backendError",success:"QuickOrder.QuickOrderItem.notification.success",partialSuccess:"QuickOrder.QuickOrderItem.notification.partialSuccess",unexpectedError:"QuickOrder.QuickOrderItem.notification.unexpectedError"}),B="quick-order-selected-options",F=A(()=>{p(null)},[]),b=A(s=>{Q(s)},[]);y(()=>{const s=S.on("quick-order/loading",o=>{i(o)},{eager:!0});return()=>{s==null||s.off()}},[]),y(()=>{const s=S.on("quick-order/add-items",async o=>{if(o&&o.length>0){if(!e)return;i(!0),S.emit("quick-order/loading",!0);const k=o.map(d=>d.sku).filter(Boolean);l(d=>new Set([...Array.from(d),...k]));try{let d=[];try{const f=await e(o)??[];b(o.length!==f.length),d=L(o,f)}catch(f){console.error("Error fetching products data:",f),d=L(o,[])}const c=x(d);if(c.length>0){const f=c.map(m=>m.sku);p(m=>{if((m==null?void 0:m.type)==="validation"&&m.clickableSkus){const T=[...new Set([...m.clickableSkus,...f])];return{...m,clickableSkus:T}}return{type:"validation",variant:"warning",message:I.validationError,clickableSkus:f}})}n(f=>{const{updatedItems:m,addedItems:T,mergedItems:H,replacedItems:X}=cr(f,d,o);return X.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),H.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),T.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),m})}finally{i(!1),S.emit("quick-order/loading",!1),l(d=>new Set(Array.from(d).filter(c=>!k.includes(c))))}}},{eager:!0});return()=>{s==null||s.off()}},[e,b]),y(()=>{const s=r.map(o=>{const k=w(o),d=o.id;return S.on(`${k}/pdp/data`,c=>{n(f=>dr(f,d||"",c,o.quantity||1).updatedItems)})});return()=>{s==null||s.forEach(o=>{o==null||o.off()})}},[r]),y(()=>{const s=K(r);b(!s)},[r,b]),y(()=>{p(s=>{if(!s||!s.clickableSkus||s.clickableSkus.length===0)return s;const o=s.clickableSkus.filter(k=>{const d=r.filter(c=>c.sku===k||c.variantSku===k);return d.length===0?!1:d.some(c=>mr(c))});return o.length===0?null:o.length!==s.clickableSkus.length?{...s,clickableSkus:o}:s})},[r]),y(()=>{!h||r.length===0||p(s=>{if(s&&(s.type==="validation"||s.type==="partial-success"))return s;const o=x(r);if(o.length===0)return s;const k=[...new Set(o.map(f=>f.sku))],d=(s==null?void 0:s.clickableSkus)||[];return k.length!==d.length||!k.every(f=>d.includes(f))?{type:"validation",variant:"warning",message:I.validationError,clickableSkus:k}:s})},[h,r,I.validationError]),y(()=>{const s=r.map(o=>{const k=w(o),d=o.id||o.sku;return S.on(`${k}/pdp/values`,c=>{const f=kr(c);fr(B,d,f)})});return()=>{s.forEach(o=>{o==null||o.off()})}},[r,B]),y(()=>{C.current=g},[g]),y(()=>{const s=S.on("cart/product/added",k=>{const d=Array.isArray(k)?k.length:0,c=Array.isArray(k)?k.map(f=>f.sku).filter(Boolean):[];if(g.length>0){const f=g.filter(m=>!c.includes(m));f.length>0&&d>0&&(p({type:"partial-success",variant:"warning",message:I.partialSuccess,count:d,clickableSkus:f}),O([]))}else return}),o=S.on("quick-order/add-to-cart-error",k=>{p({type:"backend-error",variant:"warning",message:I.backendError,details:k.message}),O([])});return()=>{s==null||s.off(),o==null||o.off()}},[g]),y(()=>{const s=S.on("cart/data",o=>{if(C.current.length===0||!(o!=null&&o.items)||o.items.length===0)return;const k=o.items.flatMap(c=>{var m;const f=[];return c.sku&&f.push(c.sku),(m=c.product)!=null&&m.sku&&f.push(c.product.sku),f}),d=C.current.filter(c=>k.includes(c));d.length!==0&&(p({type:"success",variant:"success",message:I.success,count:d.length}),O([]),S.emit("quick-order/loading",!1))},{eager:!0});return()=>{s==null||s.off()}},[]);const M=A(s=>{n(o=>o.filter(k=>k.id!==s&&k.sku!==s))},[]),N=A(()=>{n([]),p(null)},[]),V=A((s,o)=>{n(k=>k.map(d=>d.sku===s?{...d,quantity:o}:d))},[]),$=A(s=>a.has(s),[a]),Z=A(()=>{const s=lr(r).filter(c=>c!==null);if(r.length>0&&!K(r)){const m=x(r).map(T=>T.sku);p({type:"validation",variant:"warning",message:I.validationError,clickableSkus:m});return}if(s.length===0){if(r.length>0){const f=x(r).map(m=>m.sku);p({type:"validation",variant:"warning",message:I.validationError,clickableSkus:f})}return}p(null);const o=s.map(c=>c.sku).filter(c=>!!c);O(o);const k=G(B),d=pr(s,r,k);t?(S.emit("quick-order/loading",!0),Promise.resolve(t(d,N)).then(c=>{c&&typeof c=="string"&&(p({type:"backend-error",variant:"warning",message:I.backendError,details:c}),O([]))}).catch(c=>{p({type:"backend-error",variant:"warning",message:I.backendError,details:c.message||I.unexpectedError}),O([])}).finally(()=>{S.emit("quick-order/loading",!1)})):S.emit("quick-order/add-to-cart",d)},[r,t,B]);return{items:r,loading:u,removeItem:M,clearItems:N,updateItemQuantity:V,addToCart:Z,isItemUpdating:$,isDisabledButton:h,setDisabledCartButton:b,notification:q,dismissNotification:F}},gr=({notification:e,onDismiss:t,onSkuClick:r,validationErrorText:n,backendErrorText:u,successText:i,partialSuccessText:a})=>{if(!e)return null;const l=()=>{switch(e.type){case"validation":return Or(n,e.clickableSkus,e.details,r);case"partial-success":return Sr(a,e.message,e.count,e.clickableSkus,r);case"backend-error":return Ir(u,e.details);case"success":return Qr(i,e.count);default:return v("span",{children:e.message})}};return v("div",{className:P(["b2b-quick-order-notification-banner",[`b2b-quick-order-notification-banner--${e.variant}`,e.variant]]),children:v(rr,{variant:e.variant,message:l(),onDismiss:t})})};function Y(e,t){return e.map((r,n)=>D("span",{children:[v("a",{href:"#",onClick:u=>{u.preventDefault(),t(r)},style:{cursor:"pointer",textDecoration:"underline",color:"white"},children:r}),n<e.length-1?", ":""]},r))}function Or(e,t,r,n){return t!=null&&t.length&&n?D("span",{children:[e," - ",Y(t,n)]}):D("span",{children:[e," - ",r]})}function Sr(e,t,r,n,u){if(!e)return v("span",{children:t});const i=e.replace("{count}",String(r||0)).replace("{total}",String((r||0)+((n==null?void 0:n.length)||0)));return n!=null&&n.length&&u?D("span",{children:[i,": ",Y(n,u)]}):D("span",{children:[i,": ",(n==null?void 0:n.join(", "))||"Unknown"]})}function Ir(e,t){return D("span",{children:[e,t?` - ${t}`:""]})}function Qr(e,t){return t!==void 0?v("span",{children:e.replace("{count}",String(t))}):v("span",{children:e})}const Tr=({className:e,slots:t,getProductsData:r,handleAddToCart:n,productsSearch:u,searchFilter:i})=>{const a=nr.getConfig().quickOrderActive,l=J(null),h=z({title:"QuickOrder.QuickOrderItem.title",quantity:"QuickOrder.QuickOrderItem.quantity",price:"QuickOrder.QuickOrderItem.price",remove:"QuickOrder.QuickOrderItem.remove",removeItem:"QuickOrder.QuickOrderItem.removeItem",showOptions:"QuickOrder.QuickOrderItem.showOptions",hideOptions:"QuickOrder.QuickOrderItem.hideOptions",additionalOptions:"QuickOrder.QuickOrderItem.additionalOptions",noAdditionalOptions:"QuickOrder.QuickOrderItem.noAdditionalOptions",emptyList:"QuickOrder.QuickOrderItem.emptyList",sku:"QuickOrder.QuickOrderItem.sku",loading:"QuickOrder.QuickOrderItem.loading",productNotFound:"QuickOrder.QuickOrderItem.productNotFound",productNotFoundDescription:"QuickOrder.QuickOrderItem.productNotFoundDescription",productOptions:"QuickOrder.QuickOrderItem.productOptions",configurableProductError:"QuickOrder.QuickOrderItem.configurableProductError",configurableProductErrorDescription:"QuickOrder.QuickOrderItem.configurableProductErrorDescription",addAllToCart:"QuickOrder.QuickOrderItem.addAllToCart",configurableOptionsWarning:"QuickOrder.QuickOrderItem.configurableOptionsWarning",configurableOptionsWarningDescription:"QuickOrder.QuickOrderItem.configurableOptionsWarningDescription",outOfStock:"QuickOrder.QuickOrderItem.outOfStock",searchPlaceholder:"QuickOrder.Search.placeholder",searchAriaLabel:"QuickOrder.Search.ariaLabel",searchEmptyState:"QuickOrder.Search.emptyState",resultsAvailable:"QuickOrder.Search.resultsAvailable",resultAvailable:"QuickOrder.Search.resultAvailable",srInstructions:"QuickOrder.Search.srInstructions",notificationValidationError:"QuickOrder.QuickOrderItem.notification.validationError",notificationBackendError:"QuickOrder.QuickOrderItem.notification.backendError",notificationSuccess:"QuickOrder.QuickOrderItem.notification.success",notificationPartialSuccess:"QuickOrder.QuickOrderItem.notification.partialSuccess",disabledMessage:"QuickOrder.QuickOrderItem.disabledMessage"}),{items:Q,loading:q,removeItem:p,clearItems:g,updateItemQuantity:O,addToCart:C,isItemUpdating:I,setDisabledCartButton:B,isDisabledButton:F,notification:b,dismissNotification:M}=hr({getProductsData:r,handleAddToCart:n});y(()=>{b&&b.variant==="warning"&&l.current&&l.current.scrollIntoView({behavior:"smooth",block:"start"})},[b]);const N=V=>{const $=document.querySelector(`form[data-sku="${V}"]`);$&&$.scrollIntoView({behavior:"smooth",block:"center"})};return D("div",{className:P(["b2b-quick-order-quick-order-items",!a&&"b2b-quick-order-disabled",e]),"data-testid":"quick-order-items",style:{position:"relative"},children:[v("div",{ref:l,children:v(gr,{notification:b,onDismiss:M,onSkuClick:N,validationErrorText:h.notificationValidationError,backendErrorText:h.notificationBackendError,successText:h.notificationSuccess,partialSuccessText:h.notificationPartialSuccess})}),v(tr,{isDisabled:!a,message:h.disabledMessage,children:v(er,{t:h,items:Q,onRemove:p,clearItems:g,onUpdateQuantity:O,handleAddToCart:C,isItemUpdating:I,slots:t,loading:q,setDisabledCartButton:B,isDisabledButton:F,productsSearch:u,searchFilter:i})})]})};export{Tr as QuickOrderItems,Tr as default};
3
+ import{jsx as v,jsxs as D}from"@dropins/tools/preact-jsx-runtime.js";import{AlertBanner as rr}from"@dropins/tools/components.js";import{Q as tr,a as er}from"../chunks/QuickOrderDisabledOverlay.js";import{classes as P}from"@dropins/tools/lib.js";import"../chunks/debounce.js";import{useState as R,useRef as J,useCallback as A,useEffect as y}from"@dropins/tools/preact-hooks.js";import{events as S}from"@dropins/tools/event-bus.js";import{useText as z}from"@dropins/tools/i18n.js";import"@dropins/tools/preact-compat.js";import{c as nr}from"../chunks/getStoreConfig.js";import"@dropins/tools/fetch-graphql.js";const sr=["sku","parentSku","quantity","optionsUIDs","valid","productType"],ir=e=>{const t=[],r=[];return e.forEach((n,u)=>{if(sr.includes(u))return;const i=n;i&&i.match(/^[A-Za-z0-9+/=]+$/)?t.push(i):r.push({uid:u,value:i})}),{optionUIDs:t,enteredOptions:r}},or=e=>{const t=Number(e.get("quantity")),r=!t||t<1?1:t,n={sku:e.get("sku"),quantity:r},u=e.get("parentSku");u&&(n.parentSku=u);const{optionUIDs:i,enteredOptions:a}=ir(e);return i.length>0&&(n.optionsUIDs=i),a.length>0&&(n.enteredOptions=a),n},_={sku:"",quantity:1,name:"",images:[],inStock:!1,addToCartAllowed:!1,isBundle:!1,prices:{},attributes:[],options:[],url:"",urlKey:"",externalId:"",productType:"simple",shortDescription:"",metaDescription:"",metaKeyword:"",metaTitle:"",description:""},L=(e,t)=>!t||!Array.isArray(t)?e.map(r=>({..._,sku:r.sku,quantity:r.quantity??1})):e.map(r=>{const n=t.find(u=>(u==null?void 0:u.sku)===(r==null?void 0:r.sku));return n?{...n,...r.variantSku&&{variantSku:r.variantSku},quantity:r.quantity??1}:{..._,sku:r.sku,...r.variantSku&&{variantSku:r.variantSku},quantity:r.quantity??1}}),K=e=>e.length===0?!1:e.every(t=>!((t.urlKey||t.url)&&t.name)||t.inStock===!1?!1:t.options&&t.options.length>0?t.options.some(i=>i.required)?t.options.every(i=>{var a;return i.required?(a=i.items)==null?void 0:a.some(l=>l.selected):!0}):t.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0)):!0),x=e=>{const t=[];return e.forEach(r=>{if(!((r.urlKey||r.url)&&r.name)){t.push({sku:r.sku,name:r.name||"Unknown",reason:"incomplete_data"});return}if(r.inStock===!1){t.push({sku:r.sku,name:r.name,reason:"out_of_stock"});return}if(r.options&&r.options.length>0){if(r.options.some(a=>a.required)){r.options.every(l=>{var h;return l.required?(h=l.items)==null?void 0:h.some(Q=>Q.selected):!0})||t.push({sku:r.sku,name:r.name,reason:"missing_required_options"});return}r.options.some(a=>a.items&&a.items.length>0&&a.items.some(l=>l.selected===!0))||t.push({sku:r.sku,name:r.name,reason:"missing_options"})}}),t},w=e=>`quick-order-item-${e.id||e.variantSku||e.sku}`,W=e=>`${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,j=(e,t)=>e.findIndex(r=>t.variantSku&&r.variantSku?r.variantSku===t.variantSku:r.variantSku&&!t.variantSku&&t.sku?r.variantSku===t.sku:t.variantSku&&!r.variantSku&&r.sku?r.sku===t.variantSku:!t.variantSku&&!r.variantSku?r.sku===t.sku:!1),ar=(e,t,r)=>e.findIndex(n=>n.id===r?!1:t.variantSku&&n.variantSku?n.variantSku===t.variantSku:t.variantSku&&!n.variantSku&&n.sku?n.sku===t.variantSku:!1),ur=(e,t,r,n=1)=>e.map((u,i)=>i===r?{...u,quantity:u.quantity+n}:i===t?null:u).filter(Boolean),cr=(e,t,r)=>{const n=[...e],u=[],i=[],a=[];return t.forEach((l,h)=>{const Q=r[h];if(Q!=null&&Q.replaceItemSku){const p=n.findIndex(g=>g.sku===Q.replaceItemSku||g.id===Q.replaceItemSku);if(p!==-1){const g=j(n,l);if(g!==-1&&g!==p){n.splice(p,1);const O=g>p?g-1:g;n[O]={...n[O],quantity:n[O].quantity+l.quantity},a.push(n[O])}else{const O={...l,id:W(l.sku)};n[p]=O,i.push(O)}return}}const q=j(n,l);if(q!==-1)n[q]={...n[q],quantity:n[q].quantity+l.quantity},a.push(n[q]);else{const p={...l,id:W(l.sku)};n.push(p),u.push(p)}}),{updatedItems:n,addedItems:u,replacedItems:i,mergedItems:a}},dr=(e,t,r,n=1)=>{const u=t?ar(e,r,t):-1;if(u!==-1){const a=e.findIndex(l=>l.id===t);return{updatedItems:ur(e,a,u,n),wasMerged:!0,mergedIntoIndex:u}}return{updatedItems:e.map(a=>t&&a.id===t?{...a,...r,id:t}:!t&&a.sku===r.sku?{...a,...r}:a),wasMerged:!1}},lr=e=>e.map(t=>{const r=t.id||t.sku,n=document.forms[`form-${r}`];if(!n)return null;const u=new FormData(n);return u.get("valid")==="true"?or(u):null}),kr=e=>{let t=[];return e&&typeof e=="object"?e.optionsUIDs&&Array.isArray(e.optionsUIDs)?t=e.optionsUIDs:Array.isArray(e)&&(t=e):typeof e=="string"&&(t=[e]),t},G=e=>{try{const t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch(t){console.error("Error reading from localStorage:",t)}return{}},fr=(e,t,r)=>{if(r.length!==0)try{const n=G(e);n[t]=r,localStorage.setItem(e,JSON.stringify(n))}catch(n){console.error("Error saving to localStorage:",n)}},pr=(e,t,r)=>e.map(n=>{const u=t.find(i=>n.sku===i.sku||n.sku===i.variantSku);if(u){const i=u.id||u.sku,a=r[i];if(a&&a.length>0)return{...n,optionsUIDs:a}}return n}),mr=e=>{const t=!e.inStock||!e.addToCartAllowed;if(e.options&&e.options.length>0){if(e.options.some(i=>!i.items||i.items.length===0))return!0;if(e.options.some(i=>i.required)){const i=e.options.every(a=>{var l;return a.required?(l=a.items)==null?void 0:l.some(h=>h.selected):!0});return t||!i}const u=e.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0));return t||!u}return t},hr=({getProductsData:e,handleAddToCart:t}={})=>{const[r,n]=R([]),[u,i]=R(!1),[a,l]=R(new Set),[h,Q]=R(!1),[q,p]=R(null),[g,O]=R([]),C=J([]),I=z({validationError:"QuickOrder.QuickOrderItem.notification.validationError",backendError:"QuickOrder.QuickOrderItem.notification.backendError",success:"QuickOrder.QuickOrderItem.notification.success",partialSuccess:"QuickOrder.QuickOrderItem.notification.partialSuccess",unexpectedError:"QuickOrder.QuickOrderItem.notification.unexpectedError"}),B="quick-order-selected-options",F=A(()=>{p(null)},[]),b=A(s=>{Q(s)},[]);y(()=>{const s=S.on("quick-order/loading",o=>{i(o)},{eager:!0});return()=>{s==null||s.off()}},[]),y(()=>{const s=S.on("quick-order/add-items",async o=>{if(o&&o.length>0){if(!e)return;i(!0),S.emit("quick-order/loading",!0);const k=o.map(d=>d.sku).filter(Boolean);l(d=>new Set([...Array.from(d),...k]));try{let d=[];try{const f=await e(o)??[];b(o.length!==f.length),d=L(o,f)}catch(f){console.error("Error fetching products data:",f),d=L(o,[])}const c=x(d);if(c.length>0){const f=c.map(m=>m.sku);p(m=>{if((m==null?void 0:m.type)==="validation"&&m.clickableSkus){const T=[...new Set([...m.clickableSkus,...f])];return{...m,clickableSkus:T}}return{type:"validation",variant:"warning",message:I.validationError,clickableSkus:f}})}n(f=>{const{updatedItems:m,addedItems:T,mergedItems:H,replacedItems:X}=cr(f,d,o);return X.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),H.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),T.forEach(E=>{const U=w(E);S.emit(`${U}/pdp/data`,E)}),m})}finally{i(!1),S.emit("quick-order/loading",!1),l(d=>new Set(Array.from(d).filter(c=>!k.includes(c))))}}},{eager:!0});return()=>{s==null||s.off()}},[e,b]),y(()=>{const s=r.map(o=>{const k=w(o),d=o.id;return S.on(`${k}/pdp/data`,c=>{n(f=>dr(f,d||"",c,o.quantity||1).updatedItems)})});return()=>{s==null||s.forEach(o=>{o==null||o.off()})}},[r]),y(()=>{const s=K(r);b(!s)},[r,b]),y(()=>{p(s=>{if(!s||!s.clickableSkus||s.clickableSkus.length===0)return s;const o=s.clickableSkus.filter(k=>{const d=r.filter(c=>c.sku===k||c.variantSku===k);return d.length===0?!1:d.some(c=>mr(c))});return o.length===0?null:o.length!==s.clickableSkus.length?{...s,clickableSkus:o}:s})},[r]),y(()=>{!h||r.length===0||p(s=>{if(s&&(s.type==="validation"||s.type==="partial-success"))return s;const o=x(r);if(o.length===0)return s;const k=[...new Set(o.map(f=>f.sku))],d=(s==null?void 0:s.clickableSkus)||[];return k.length!==d.length||!k.every(f=>d.includes(f))?{type:"validation",variant:"warning",message:I.validationError,clickableSkus:k}:s})},[h,r,I.validationError]),y(()=>{const s=r.map(o=>{const k=w(o),d=o.id||o.sku;return S.on(`${k}/pdp/values`,c=>{const f=kr(c);fr(B,d,f)})});return()=>{s.forEach(o=>{o==null||o.off()})}},[r,B]),y(()=>{C.current=g},[g]),y(()=>{const s=S.on("cart/product/added",k=>{const d=Array.isArray(k)?k.length:0,c=Array.isArray(k)?k.map(f=>f.sku).filter(Boolean):[];if(g.length>0){const f=g.filter(m=>!c.includes(m));f.length>0&&d>0&&(p({type:"partial-success",variant:"warning",message:I.partialSuccess,count:d,clickableSkus:f}),O([]))}else return}),o=S.on("quick-order/add-to-cart-error",k=>{p({type:"backend-error",variant:"warning",message:I.backendError,details:k.message}),O([])});return()=>{s==null||s.off(),o==null||o.off()}},[g]),y(()=>{const s=S.on("cart/data",o=>{if(C.current.length===0||!(o!=null&&o.items)||o.items.length===0)return;const k=o.items.flatMap(c=>{var m;const f=[];return c.sku&&f.push(c.sku),(m=c.product)!=null&&m.sku&&f.push(c.product.sku),f}),d=C.current.filter(c=>k.includes(c));d.length!==0&&(p({type:"success",variant:"success",message:I.success,count:d.length}),O([]),S.emit("quick-order/loading",!1))},{eager:!0});return()=>{s==null||s.off()}},[]);const M=A(s=>{n(o=>o.filter(k=>k.id!==s&&k.sku!==s))},[]),N=A(()=>{n([]),p(null)},[]),V=A((s,o)=>{n(k=>k.map(d=>d.sku===s?{...d,quantity:o}:d))},[]),$=A(s=>a.has(s),[a]),Z=A(()=>{const s=lr(r).filter(c=>c!==null);if(r.length>0&&!K(r)){const m=x(r).map(T=>T.sku);p({type:"validation",variant:"warning",message:I.validationError,clickableSkus:m});return}if(s.length===0){if(r.length>0){const f=x(r).map(m=>m.sku);p({type:"validation",variant:"warning",message:I.validationError,clickableSkus:f})}return}p(null);const o=s.map(c=>c.sku).filter(c=>!!c);O(o);const k=G(B),d=pr(s,r,k);t?(S.emit("quick-order/loading",!0),Promise.resolve(t(d,N)).then(c=>{c&&typeof c=="string"&&(p({type:"backend-error",variant:"warning",message:I.backendError,details:c}),O([]))}).catch(c=>{p({type:"backend-error",variant:"warning",message:I.backendError,details:c.message||I.unexpectedError}),O([])}).finally(()=>{S.emit("quick-order/loading",!1)})):S.emit("quick-order/add-to-cart",d)},[r,t,B]);return{items:r,loading:u,removeItem:M,clearItems:N,updateItemQuantity:V,addToCart:Z,isItemUpdating:$,isDisabledButton:h,setDisabledCartButton:b,notification:q,dismissNotification:F}},gr=({notification:e,onDismiss:t,onSkuClick:r,validationErrorText:n,backendErrorText:u,successText:i,partialSuccessText:a})=>{if(!e)return null;const l=()=>{switch(e.type){case"validation":return Or(n,e.clickableSkus,e.details,r);case"partial-success":return Sr(a,e.message,e.count,e.clickableSkus,r);case"backend-error":return Ir(u,e.details);case"success":return Qr(i,e.count);default:return v("span",{children:e.message})}};return v("div",{className:P(["b2b-quick-order-notification-banner",[`b2b-quick-order-notification-banner--${e.variant}`,e.variant]]),children:v(rr,{variant:e.variant,message:l(),onDismiss:t})})};function Y(e,t){return e.map((r,n)=>D("span",{children:[v("a",{href:"#",onClick:u=>{u.preventDefault(),t(r)},style:{cursor:"pointer",textDecoration:"underline",color:"white"},children:r}),n<e.length-1?", ":""]},r))}function Or(e,t,r,n){return t!=null&&t.length&&n?D("span",{children:[e," - ",Y(t,n)]}):D("span",{children:[e," - ",r]})}function Sr(e,t,r,n,u){if(!e)return v("span",{children:t});const i=e.replace("{count}",String(r||0)).replace("{total}",String((r||0)+((n==null?void 0:n.length)||0)));return n!=null&&n.length&&u?D("span",{children:[i,": ",Y(n,u)]}):D("span",{children:[i,": ",(n==null?void 0:n.join(", "))||"Unknown"]})}function Ir(e,t){return D("span",{children:[e,t?` - ${t}`:""]})}function Qr(e,t){return t!==void 0?v("span",{children:e.replace("{count}",String(t))}):v("span",{children:e})}const Ur=({className:e,slots:t,getProductsData:r,handleAddToCart:n,productsSearch:u,searchFilter:i})=>{const a=nr.getConfig().quickOrderActive,l=J(null),h=z({title:"QuickOrder.QuickOrderItem.title",quantity:"QuickOrder.QuickOrderItem.quantity",price:"QuickOrder.QuickOrderItem.price",remove:"QuickOrder.QuickOrderItem.remove",removeItem:"QuickOrder.QuickOrderItem.removeItem",showOptions:"QuickOrder.QuickOrderItem.showOptions",hideOptions:"QuickOrder.QuickOrderItem.hideOptions",additionalOptions:"QuickOrder.QuickOrderItem.additionalOptions",noAdditionalOptions:"QuickOrder.QuickOrderItem.noAdditionalOptions",emptyList:"QuickOrder.QuickOrderItem.emptyList",sku:"QuickOrder.QuickOrderItem.sku",loading:"QuickOrder.QuickOrderItem.loading",productNotFound:"QuickOrder.QuickOrderItem.productNotFound",productNotFoundDescription:"QuickOrder.QuickOrderItem.productNotFoundDescription",productOptions:"QuickOrder.QuickOrderItem.productOptions",configurableProductError:"QuickOrder.QuickOrderItem.configurableProductError",configurableProductErrorDescription:"QuickOrder.QuickOrderItem.configurableProductErrorDescription",addAllToCart:"QuickOrder.QuickOrderItem.addAllToCart",configurableOptionsWarning:"QuickOrder.QuickOrderItem.configurableOptionsWarning",configurableOptionsWarningDescription:"QuickOrder.QuickOrderItem.configurableOptionsWarningDescription",outOfStock:"QuickOrder.QuickOrderItem.outOfStock",searchPlaceholder:"QuickOrder.Search.placeholder",searchAriaLabel:"QuickOrder.Search.ariaLabel",searchEmptyState:"QuickOrder.Search.emptyState",resultsAvailable:"QuickOrder.Search.resultsAvailable",resultAvailable:"QuickOrder.Search.resultAvailable",srInstructions:"QuickOrder.Search.srInstructions",notificationValidationError:"QuickOrder.QuickOrderItem.notification.validationError",notificationBackendError:"QuickOrder.QuickOrderItem.notification.backendError",notificationSuccess:"QuickOrder.QuickOrderItem.notification.success",notificationPartialSuccess:"QuickOrder.QuickOrderItem.notification.partialSuccess",disabledMessage:"QuickOrder.QuickOrderItem.disabledMessage"}),{items:Q,loading:q,removeItem:p,clearItems:g,updateItemQuantity:O,addToCart:C,isItemUpdating:I,setDisabledCartButton:B,isDisabledButton:F,notification:b,dismissNotification:M}=hr({getProductsData:r,handleAddToCart:n});y(()=>{b&&b.variant==="warning"&&l.current&&l.current.scrollIntoView({behavior:"smooth",block:"start"})},[b]);const N=V=>{const $=document.querySelector(`form[data-sku="${V}"]`);$&&$.scrollIntoView({behavior:"smooth",block:"center"})};return D("div",{className:P(["b2b-quick-order-quick-order-items",!a&&"b2b-quick-order-disabled",e]),"data-testid":"quick-order-items",style:{position:"relative"},children:[v("div",{ref:l,children:v(gr,{notification:b,onDismiss:M,onSkuClick:N,validationErrorText:h.notificationValidationError,backendErrorText:h.notificationBackendError,successText:h.notificationSuccess,partialSuccessText:h.notificationPartialSuccess})}),v(tr,{isDisabled:!a,message:h.disabledMessage,children:v(er,{t:h,items:Q,onRemove:p,clearItems:g,onUpdateQuantity:O,handleAddToCart:C,isItemUpdating:I,slots:t,loading:q,setDisabledCartButton:B,isDisabledButton:F,productsSearch:u,searchFilter:i})})]})};export{Ur as QuickOrderItems,Ur as default};
4
4
  //# sourceMappingURL=QuickOrderItems.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"QuickOrderItems.js","sources":["/@dropins/storefront-quick-order/src/lib/processFormOptions.ts","/@dropins/storefront-quick-order/src/lib/buildCartItem.ts","/@dropins/storefront-quick-order/src/configs/order-item.config.ts","/@dropins/storefront-quick-order/src/lib/mapProductsToOrderItems.ts","/@dropins/storefront-quick-order/src/lib/validateOrderItems.ts","/@dropins/storefront-quick-order/src/lib/getItemScope.ts","/@dropins/storefront-quick-order/src/lib/generateItemId.ts","/@dropins/storefront-quick-order/src/lib/findDuplicateItem.ts","/@dropins/storefront-quick-order/src/lib/mergeDuplicateItems.ts","/@dropins/storefront-quick-order/src/lib/replaceOrAddItems.ts","/@dropins/storefront-quick-order/src/lib/updateItemInList.ts","/@dropins/storefront-quick-order/src/lib/buildCartItemsFromForms.ts","/@dropins/storefront-quick-order/src/lib/productOptionsStorage.ts","/@dropins/storefront-quick-order/src/lib/isItemValid.ts","/@dropins/storefront-quick-order/src/hooks/useQuickOrderItems.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderNotificationBanner/QuickOrderNotificationBanner.tsx","/@dropins/storefront-quick-order/src/containers/QuickOrderItems/QuickOrderItems.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nconst STANDARD_FIELDS = [\n 'sku',\n 'parentSku',\n 'quantity',\n 'optionsUIDs',\n 'valid',\n 'productType',\n];\n\nexport interface ProcessedFormOptions {\n optionUIDs: string[];\n enteredOptions: { uid: string; value: string }[];\n}\n\n/**\n * Processes form data to extract product options\n * Separates base64-encoded configurable options (optionUIDs) from custom entered options\n */\nexport const processFormOptions = (\n formData: FormData\n): ProcessedFormOptions => {\n const optionUIDs: string[] = [];\n const enteredOptions: { uid: string; value: string }[] = [];\n\n formData.forEach((value, key) => {\n if (STANDARD_FIELDS.includes(key)) return;\n\n const valueStr = value as string;\n // Check if this is an option UID (base64 encoded configurable option)\n if (valueStr && valueStr.match(/^[A-Za-z0-9+/=]+$/)) {\n optionUIDs.push(valueStr);\n } else {\n enteredOptions.push({ uid: key, value: valueStr });\n }\n });\n\n return { optionUIDs, enteredOptions };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { processFormOptions } from './processFormOptions';\n\nexport interface CartItem {\n sku: string;\n quantity: number;\n parentSku?: string;\n optionsUIDs?: string[];\n enteredOptions?: { uid: string; value: string }[];\n}\n\n/**\n * Builds a cart item object from form data\n * Extracts SKU, quantity, parent SKU, and product options\n */\nexport const buildCartItem = (formData: FormData): CartItem => {\n const quantityValue = Number(formData.get('quantity'));\n const quantity = !quantityValue || quantityValue < 1 ? 1 : quantityValue;\n\n const cartItem: CartItem = {\n sku: formData.get('sku') as string,\n quantity,\n };\n\n const parentSku = formData.get('parentSku');\n if (parentSku) {\n cartItem.parentSku = parentSku as string;\n }\n\n const { optionUIDs, enteredOptions } = processFormOptions(formData);\n\n if (optionUIDs.length > 0) {\n cartItem.optionsUIDs = optionUIDs;\n }\n\n if (enteredOptions.length > 0) {\n cartItem.enteredOptions = enteredOptions;\n }\n\n return cartItem;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types/quickOrderItems.types';\n\nexport const DEFAULT_QUICK_ORDER_ITEM: OrderItem = {\n sku: '',\n quantity: 1,\n name: '',\n images: [],\n inStock: false,\n addToCartAllowed: false,\n isBundle: false,\n prices: {} as any,\n attributes: [],\n options: [],\n url: '',\n urlKey: '',\n externalId: '',\n productType: 'simple',\n shortDescription: '',\n metaDescription: '',\n metaKeyword: '',\n metaTitle: '',\n description: '',\n} as OrderItem;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem, OrderItemInput } from '@/b2b-quick-order/types';\nimport { DEFAULT_QUICK_ORDER_ITEM } from '@/b2b-quick-order/configs';\n\n/**\n * Maps fetched products to OrderItems\n * Creates error items for products not found in the response\n * @param requestedItems - Items that were requested\n * @param products - Products returned from API\n * @returns Array of OrderItems with proper quantity set\n */\nexport const mapProductsToOrderItems = (\n requestedItems: OrderItemInput[],\n products: OrderItem[]\n): OrderItem[] => {\n // Handle empty or undefined products array\n if (!products || !Array.isArray(products)) {\n return requestedItems.map((requestedItem) => ({\n ...DEFAULT_QUICK_ORDER_ITEM,\n sku: requestedItem.sku,\n quantity: requestedItem.quantity ?? 1,\n })) as OrderItem[];\n }\n\n return requestedItems.map((requestedItem) => {\n const foundProduct = products.find((p) => p?.sku === requestedItem?.sku);\n\n if (foundProduct) {\n return {\n ...foundProduct,\n ...(requestedItem.variantSku && {\n variantSku: requestedItem.variantSku,\n }),\n quantity: requestedItem.quantity ?? 1,\n };\n }\n\n // Product not found - create error item\n return {\n ...DEFAULT_QUICK_ORDER_ITEM,\n sku: requestedItem.sku,\n ...(requestedItem.variantSku && { variantSku: requestedItem.variantSku }),\n quantity: requestedItem.quantity ?? 1,\n } as OrderItem;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Validates order items to determine if all items are ready for cart addition\n * @param items - Array of order items to validate\n * @returns true if all items are valid, false otherwise\n */\nexport const validateOrderItems = (items: OrderItem[]): boolean => {\n if (items.length === 0) {\n return false;\n }\n\n return items.every((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n if (!hasBasicData) {\n return false;\n }\n\n if (item.inStock === false) {\n return false;\n }\n\n if (item.options && item.options.length > 0) {\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n return item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return hasSelectedOption;\n }\n\n return true;\n });\n};\n\n/**\n * Get items that are out of stock\n * @param items - Array of order items to check\n * @returns Array of out of stock items with their names\n */\nexport const getOutOfStockItems = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => item.inStock === false)\n .map((item) => ({\n sku: item.sku,\n name: item.name,\n }));\n};\n\n/**\n * Get items with missing required options\n * @param items - Array of order items to check\n * @returns Array of items missing required options\n */\nexport const getItemsMissingOptions = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => {\n if (!item.options || item.options.length === 0) {\n return false;\n }\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return !hasSelectedOption;\n })\n .map((item) => ({\n sku: item.sku,\n name: item.name,\n }));\n};\n\n/**\n * Get items with incomplete data\n * @param items - Array of order items to check\n * @returns Array of items with incomplete data\n */\nexport const getItemsWithIncompleteData = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n return !hasBasicData;\n })\n .map((item) => ({\n sku: item.sku,\n name: item.name || 'Unknown',\n }));\n};\n\n/**\n * Get all items with validation errors\n * @param items - Array of order items to check\n * @returns Array of all items with validation errors and their SKUs\n */\nexport const getInvalidItems = (\n items: OrderItem[]\n): Array<{ sku: string; name: string; reason: string }> => {\n const invalidItems: Array<{ sku: string; name: string; reason: string }> = [];\n\n items.forEach((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n\n if (!hasBasicData) {\n invalidItems.push({\n sku: item.sku,\n name: item.name || 'Unknown',\n reason: 'incomplete_data',\n });\n return;\n }\n\n if (item.inStock === false) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'out_of_stock',\n });\n return;\n }\n\n if (item.options && item.options.length > 0) {\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n const allRequiredSelected = item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n\n if (!allRequiredSelected) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'missing_required_options',\n });\n }\n return;\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n if (!hasSelectedOption) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'missing_options',\n });\n }\n }\n });\n\n return invalidItems;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Get unique scope identifier for an item\n * Uses unique id if available, otherwise falls back to variantSku or sku\n */\nexport const getItemScope = (item: OrderItem): string => {\n const scopeKey = item.id || item.variantSku || item.sku;\n return `quick-order-item-${scopeKey}`;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Generate unique ID for an item\n * Format: {sku}-{timestamp}-{random}\n */\nexport const generateItemId = (sku: string): string => {\n return `${sku}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Find duplicate item in the list based on multiple comparison strategies\n * Returns the index of the duplicate item, or -1 if not found\n *\n * Strategies:\n * 1. Both have variantSku - compare variants\n * 2. Existing has variantSku, new has sku - compare them\n * 3. New has variantSku, existing has sku - compare them\n * 4. Neither has variantSku - compare base SKU\n */\nexport const findDuplicateItem = (\n items: OrderItem[],\n newItem: OrderItem\n): number => {\n return items.findIndex((existing) => {\n // Strategy 1: Both have variantSku - compare variants\n if (newItem.variantSku && existing.variantSku) {\n return existing.variantSku === newItem.variantSku;\n }\n\n // Strategy 2: Existing has variantSku, new has sku - compare them\n // (e.g., existing configured product vs search result variant)\n if (existing.variantSku && !newItem.variantSku && newItem.sku) {\n return existing.variantSku === newItem.sku;\n }\n\n // Strategy 3: New has variantSku, existing has sku - compare them\n // (opposite of strategy 2)\n if (newItem.variantSku && !existing.variantSku && existing.sku) {\n return existing.sku === newItem.variantSku;\n }\n\n // Strategy 4: Neither has variantSku - compare base sku\n if (!newItem.variantSku && !existing.variantSku) {\n return existing.sku === newItem.sku;\n }\n\n return false;\n });\n};\n\n/**\n * Find duplicate item excluding a specific item by ID\n * Used when checking for duplicates after an item update\n */\nexport const findDuplicateItemExcluding = (\n items: OrderItem[],\n updatedItem: OrderItem,\n excludeItemId: string\n): number => {\n return items.findIndex((existing) => {\n // Skip the item being updated\n if (existing.id === excludeItemId) return false;\n\n // Check if updatedItem's variantSku matches existing item\n if (updatedItem.variantSku && existing.variantSku) {\n return existing.variantSku === updatedItem.variantSku;\n }\n\n // Check if updatedItem's variantSku matches existing item's sku\n if (updatedItem.variantSku && !existing.variantSku && existing.sku) {\n return existing.sku === updatedItem.variantSku;\n }\n\n return false;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Merge duplicate items by removing the item at removeIndex and\n * adding its quantity to the item at mergeIntoIndex\n */\nexport const mergeDuplicateItems = (\n items: OrderItem[],\n removeIndex: number,\n mergeIntoIndex: number,\n quantityToAdd: number = 1\n): OrderItem[] => {\n return items\n .map((item, index) => {\n if (index === mergeIntoIndex) {\n // Increase quantity of the duplicate\n return {\n ...item,\n quantity: item.quantity + quantityToAdd,\n };\n } else if (index === removeIndex) {\n // Remove the item being merged\n return null;\n }\n return item;\n })\n .filter(Boolean) as OrderItem[];\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem, OrderItemInput } from '@/b2b-quick-order/types';\nimport { findDuplicateItem } from './findDuplicateItem';\nimport { generateItemId } from './generateItemId';\n\nexport interface ReplaceOrAddItemsResult {\n updatedItems: OrderItem[];\n addedItems: OrderItem[];\n replacedItems: OrderItem[];\n mergedItems: OrderItem[];\n}\n\n/**\n * Replace, merge, or add items into existing list\n * Handles three scenarios:\n * 1. Replace: When inputItem has replaceItemSku, replace item at same position\n * - If new item already exists in list, collapse by removing replaced item and merging quantity\n * 2. Merge: When item exists, increase quantity\n * 3. Add: When item doesn't exist, add to end\n */\nexport const replaceOrAddItems = (\n existingItems: OrderItem[],\n newItems: OrderItem[],\n inputItems: OrderItemInput[]\n): ReplaceOrAddItemsResult => {\n const updatedItems = [...existingItems];\n const addedItems: OrderItem[] = [];\n const replacedItems: OrderItem[] = [];\n const mergedItems: OrderItem[] = [];\n\n newItems.forEach((newItem, index) => {\n const inputItem = inputItems[index];\n\n // Scenario 1: Replace existing item at same position\n if (inputItem?.replaceItemSku) {\n const replaceIndex = updatedItems.findIndex(\n (item) =>\n item.sku === inputItem.replaceItemSku ||\n item.id === inputItem.replaceItemSku\n );\n\n if (replaceIndex !== -1) {\n // Check if new item already exists elsewhere in the list (collapse case)\n const existingIndex = findDuplicateItem(updatedItems, newItem);\n\n if (existingIndex !== -1 && existingIndex !== replaceIndex) {\n // Item already exists - remove replaced item and merge quantity into existing\n updatedItems.splice(replaceIndex, 1);\n // Adjust index if existing item was after the removed one\n const adjustedIndex =\n existingIndex > replaceIndex ? existingIndex - 1 : existingIndex;\n updatedItems[adjustedIndex] = {\n ...updatedItems[adjustedIndex],\n quantity: updatedItems[adjustedIndex].quantity + newItem.quantity,\n };\n mergedItems.push(updatedItems[adjustedIndex]);\n } else {\n // Replace item at the same position\n const itemWithId = {\n ...newItem,\n id: generateItemId(newItem.sku),\n };\n updatedItems[replaceIndex] = itemWithId;\n replacedItems.push(itemWithId);\n }\n return;\n }\n // If item to replace not found, fall through to add logic\n }\n\n // Scenario 2 & 3: Merge or Add\n const existingIndex = findDuplicateItem(updatedItems, newItem);\n\n if (existingIndex !== -1) {\n // Item exists - merge by increasing quantity\n updatedItems[existingIndex] = {\n ...updatedItems[existingIndex],\n quantity: updatedItems[existingIndex].quantity + newItem.quantity,\n };\n mergedItems.push(updatedItems[existingIndex]);\n } else {\n // Item doesn't exist - add new with unique ID\n const itemWithId = {\n ...newItem,\n id: generateItemId(newItem.sku),\n };\n updatedItems.push(itemWithId);\n addedItems.push(itemWithId);\n }\n });\n\n return { updatedItems, addedItems, replacedItems, mergedItems };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\nimport { findDuplicateItemExcluding } from './findDuplicateItem';\nimport { mergeDuplicateItems } from './mergeDuplicateItems';\n\nexport interface UpdateItemResult {\n updatedItems: OrderItem[];\n wasMerged: boolean;\n mergedIntoIndex?: number;\n}\n\n/**\n * Update a specific item in the list and check for duplicates\n * If duplicate is found, merge the items\n */\nexport const updateItemInList = (\n items: OrderItem[],\n itemId: string,\n updatedItem: OrderItem,\n currentQuantity: number = 1\n): UpdateItemResult => {\n // Check if the updated item's variantSku matches another existing item\n const duplicateIndex = itemId\n ? findDuplicateItemExcluding(items, updatedItem, itemId)\n : -1;\n\n if (duplicateIndex !== -1) {\n // Find the index of the item being updated\n const removingIndex = items.findIndex((prevItem) => prevItem.id === itemId);\n\n // Duplicate found - merge items\n return {\n updatedItems: mergeDuplicateItems(\n items,\n removingIndex,\n duplicateIndex,\n currentQuantity\n ),\n wasMerged: true,\n mergedIntoIndex: duplicateIndex,\n };\n }\n\n // No duplicate - just update the item\n const updatedItems = items.map((prevItem) => {\n if (itemId && prevItem.id === itemId) {\n // Match by ID - update with preserved ID\n return {\n ...prevItem,\n ...updatedItem,\n id: itemId,\n };\n } else if (!itemId && prevItem.sku === updatedItem.sku) {\n // Fallback for items without ID (backward compatibility)\n return {\n ...prevItem,\n ...updatedItem,\n };\n }\n return prevItem;\n });\n\n return {\n updatedItems,\n wasMerged: false,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\nimport { buildCartItem } from './buildCartItem';\n\n/**\n * Build cart items from forms for all order items\n * Only includes valid items (items with valid forms)\n */\nexport const buildCartItemsFromForms = (items: OrderItem[]) => {\n return items.map((item) => {\n const formId = item.id || item.sku;\n const form = document.forms[`form-${formId}` as any] as HTMLFormElement;\n if (!form) return null;\n\n const formData = new FormData(form);\n const isValid = formData.get('valid') === 'true';\n\n return isValid ? buildCartItem(formData) : null;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Extract optionsUIDs from various data formats\n */\nexport const extractOptionsUIDs = (valuesData: any): string[] => {\n let optionsUIDs: string[] = [];\n\n if (valuesData && typeof valuesData === 'object') {\n if (valuesData.optionsUIDs && Array.isArray(valuesData.optionsUIDs)) {\n optionsUIDs = valuesData.optionsUIDs;\n } else if (Array.isArray(valuesData)) {\n optionsUIDs = valuesData;\n }\n } else if (typeof valuesData === 'string') {\n optionsUIDs = [valuesData];\n }\n\n return optionsUIDs;\n};\n\n/**\n * Get options from localStorage\n */\nexport const getOptionsFromStorage = (\n storageKey: string\n): Record<string, string[]> => {\n try {\n const stored = localStorage.getItem(storageKey);\n if (stored) {\n return JSON.parse(stored);\n }\n } catch (e) {\n console.error('Error reading from localStorage:', e);\n }\n return {};\n};\n\n/**\n * Save options to localStorage\n */\nexport const saveOptionsToStorage = (\n storageKey: string,\n itemId: string,\n optionsUIDs: string[]\n): void => {\n if (optionsUIDs.length === 0) {\n return;\n }\n\n try {\n const storageData = getOptionsFromStorage(storageKey);\n storageData[itemId] = optionsUIDs;\n localStorage.setItem(storageKey, JSON.stringify(storageData));\n } catch (e) {\n console.error('Error saving to localStorage:', e);\n }\n};\n\n/**\n * Enrich cart items with selected options from storage\n */\nexport const enrichCartItemsWithOptions = <T extends { sku: string }>(\n cartItems: T[],\n items: Array<{ id?: string; sku: string; variantSku?: string }>,\n storageData: Record<string, string[]>\n): Array<T & { optionsUIDs?: string[] }> => {\n return cartItems.map((cartItem) => {\n const item = items.find((i) => {\n return cartItem.sku === i.sku || cartItem.sku === i.variantSku;\n });\n\n if (item) {\n const itemId = item.id || item.sku;\n const selectedOptions = storageData[itemId];\n\n if (selectedOptions && selectedOptions.length > 0) {\n return {\n ...cartItem,\n optionsUIDs: selectedOptions,\n };\n }\n }\n\n return cartItem;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Check if an item is valid for adding to cart\n * @param item - The order item to validate\n * @returns true if item is invalid (should stay in notification), false if valid\n */\nexport const isItemInvalid = (item: OrderItem): boolean => {\n const hasBasicIssues = !item.inStock || !item.addToCartAllowed;\n\n if (item.options && item.options.length > 0) {\n // Options must be loaded before validation\n const optionsNotReady = item.options.some(\n (opt) => !opt.items || opt.items.length === 0\n );\n\n if (optionsNotReady) {\n return true;\n }\n\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n const allRequiredSelected = item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n return hasBasicIssues || !allRequiredSelected;\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return hasBasicIssues || !hasSelectedOption;\n }\n\n return hasBasicIssues;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\nimport {\n OrderItemInput,\n OrderItem,\n UseQuickOrderItemsProps,\n UseQuickOrderItemsReturn,\n} from '@/b2b-quick-order/types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n mapProductsToOrderItems,\n validateOrderItems,\n getItemScope,\n replaceOrAddItems,\n updateItemInList,\n buildCartItemsFromForms,\n extractOptionsUIDs,\n saveOptionsToStorage,\n getOptionsFromStorage,\n enrichCartItemsWithOptions,\n getInvalidItems,\n isItemInvalid,\n} from '@/b2b-quick-order/lib';\n\nexport const useQuickOrderItems = ({\n getProductsData,\n handleAddToCart,\n}: UseQuickOrderItemsProps = {}): UseQuickOrderItemsReturn => {\n const [items, setItems] = useState<OrderItem[]>([]);\n const [loading, setLoading] = useState(false);\n const [updatingItems, setUpdatingItems] = useState<Set<string>>(new Set());\n const [isDisabledButton, setIsDisabledButton] = useState(false);\n const [notification, setNotification] = useState<{\n type: 'validation' | 'partial-success' | 'success' | 'backend-error';\n variant: 'success' | 'warning' | 'neutral' | 'brand';\n message: string;\n details?: string;\n count?: number;\n clickableSkus?: string[];\n } | null>(null);\n const [attemptedSkus, setAttemptedSkus] = useState<string[]>([]);\n const attemptedSkusRef = useRef<string[]>([]);\n\n const t = useText({\n validationError: 'QuickOrder.QuickOrderItem.notification.validationError',\n backendError: 'QuickOrder.QuickOrderItem.notification.backendError',\n success: 'QuickOrder.QuickOrderItem.notification.success',\n partialSuccess: 'QuickOrder.QuickOrderItem.notification.partialSuccess',\n unexpectedError: 'QuickOrder.QuickOrderItem.notification.unexpectedError',\n });\n\n const STORAGE_KEY = 'quick-order-selected-options';\n\n const dismissNotification = useCallback(() => {\n setNotification(null);\n }, []);\n\n const setDisabledCartButton = useCallback((disabled: boolean) => {\n setIsDisabledButton(disabled);\n }, []);\n\n useEffect(() => {\n const loadingEvent = events.on(\n 'quick-order/loading',\n (loadingState) => {\n setLoading(loadingState);\n },\n {\n eager: true,\n }\n );\n return () => {\n loadingEvent?.off();\n };\n }, []);\n\n useEffect(() => {\n const itemsEvent = events.on(\n 'quick-order/add-items',\n async (eventPayload: OrderItemInput[]) => {\n if (eventPayload && eventPayload.length > 0) {\n if (!getProductsData) {\n return;\n }\n\n setLoading(true);\n events.emit('quick-order/loading', true);\n const requestedSkus = eventPayload\n .map((item) => item.sku)\n .filter(Boolean);\n setUpdatingItems(\n (prev) => new Set([...Array.from(prev), ...requestedSkus])\n );\n\n try {\n let newItems: OrderItem[] = [];\n try {\n const fetchedProducts =\n (await getProductsData(eventPayload)) ?? [];\n setDisabledCartButton(\n eventPayload.length !== fetchedProducts.length\n );\n newItems = mapProductsToOrderItems(eventPayload, fetchedProducts);\n } catch (error) {\n console.error('Error fetching products data:', error);\n newItems = mapProductsToOrderItems(eventPayload, []);\n }\n\n const invalidNewItems = getInvalidItems(newItems);\n if (invalidNewItems.length > 0) {\n const invalidSkus = invalidNewItems.map((item) => item.sku);\n setNotification((prev) => {\n if (prev?.type === 'validation' && prev.clickableSkus) {\n // Merge with existing validation SKUs\n const mergedSkus = [\n ...new Set([...prev.clickableSkus, ...invalidSkus]),\n ];\n return {\n ...prev,\n clickableSkus: mergedSkus,\n };\n }\n return {\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n };\n });\n }\n\n setItems((prevItems) => {\n const { updatedItems, addedItems, mergedItems, replacedItems } =\n replaceOrAddItems(prevItems, newItems, eventPayload);\n\n replacedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n mergedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n addedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n return updatedItems;\n });\n } finally {\n setLoading(false);\n events.emit('quick-order/loading', false);\n setUpdatingItems(\n (prev) =>\n new Set(\n Array.from(prev).filter((sku) => !requestedSkus.includes(sku))\n )\n );\n }\n }\n },\n {\n eager: true,\n }\n );\n\n return () => {\n itemsEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [getProductsData, setDisabledCartButton]);\n\n useEffect(() => {\n const scopesList = items.map((item) => {\n const scope = getItemScope(item);\n const itemId = item.id; // Capture the specific item's ID for this listener\n\n return events.on(`${scope}/pdp/data`, (updatedItem: OrderItem) => {\n setItems((prevItems) => {\n const result = updateItemInList(\n prevItems,\n itemId || '',\n updatedItem,\n item.quantity || 1\n );\n return result.updatedItems;\n });\n });\n });\n\n return () => {\n scopesList?.forEach((scope) => {\n scope?.off();\n });\n };\n }, [items]);\n\n useEffect(() => {\n const isValid = validateOrderItems(items);\n setDisabledCartButton(!isValid);\n }, [items, setDisabledCartButton]);\n\n useEffect(() => {\n setNotification((prev) => {\n // Only process notifications with clickable SKUs\n if (!prev || !prev.clickableSkus || prev.clickableSkus.length === 0) {\n return prev;\n }\n\n const stillInvalidSkus = prev.clickableSkus.filter((sku) => {\n // Find ALL items with this SKU (could be multiple for configurable products)\n const matchingItems = items.filter(\n (i) => i.sku === sku || i.variantSku === sku\n );\n if (matchingItems.length === 0) return false; // Item removed\n\n // Keep SKU in notification if ANY matching item is invalid\n return matchingItems.some((item) => isItemInvalid(item));\n });\n\n // Clear notification only if all SKUs are valid\n if (stillInvalidSkus.length === 0) {\n return null;\n }\n\n // Update notification if SKUs changed\n if (stillInvalidSkus.length !== prev.clickableSkus.length) {\n return {\n ...prev,\n clickableSkus: stillInvalidSkus,\n };\n }\n\n return prev;\n });\n }, [items]);\n\n useEffect(() => {\n // If Add to Cart button is disabled and there are items,\n // but no validation notification is shown - display it\n if (!isDisabledButton || items.length === 0) {\n return;\n }\n\n setNotification((prev) => {\n // Don't override existing validation/partial-success notifications\n if (\n prev &&\n (prev.type === 'validation' || prev.type === 'partial-success')\n ) {\n return prev;\n }\n\n const invalidItems = getInvalidItems(items);\n if (invalidItems.length === 0) {\n return prev;\n }\n\n const invalidSkus = [...new Set(invalidItems.map((item) => item.sku))];\n\n // Only set notification if it doesn't already have the same SKUs\n const existingSkus = prev?.clickableSkus || [];\n const hasChanges =\n invalidSkus.length !== existingSkus.length ||\n !invalidSkus.every((sku) => existingSkus.includes(sku));\n\n if (hasChanges) {\n return {\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n };\n }\n\n return prev;\n });\n }, [isDisabledButton, items, t.validationError]);\n\n useEffect(() => {\n const eventsList = items.map((item) => {\n const scope = getItemScope(item);\n const itemId = item.id || item.sku;\n\n return events.on(`${scope}/pdp/values`, (valuesData: any) => {\n const optionsUIDs = extractOptionsUIDs(valuesData);\n saveOptionsToStorage(STORAGE_KEY, itemId, optionsUIDs);\n });\n });\n\n return () => {\n eventsList.forEach((event) => {\n event?.off();\n });\n };\n }, [items, STORAGE_KEY]);\n\n useEffect(() => {\n attemptedSkusRef.current = attemptedSkus;\n }, [attemptedSkus]);\n\n useEffect(() => {\n const successEvent = events.on('cart/product/added', (products: any[]) => {\n const addedCount = Array.isArray(products) ? products.length : 0;\n const addedSkus = Array.isArray(products)\n ? products.map((p: any) => p.sku).filter(Boolean)\n : [];\n\n if (attemptedSkus.length > 0) {\n const failedSkus = attemptedSkus.filter(\n (sku) => !addedSkus.includes(sku)\n );\n\n if (failedSkus.length > 0 && addedCount > 0) {\n setNotification({\n type: 'partial-success',\n variant: 'warning',\n message: t.partialSuccess,\n count: addedCount,\n clickableSkus: failedSkus,\n });\n setAttemptedSkus([]);\n }\n } else {\n // No tracking context - ignore event\n return;\n }\n });\n\n const errorEvent = events.on(\n 'quick-order/add-to-cart-error',\n (error: { message: string }) => {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: error.message,\n });\n setAttemptedSkus([]);\n }\n );\n\n return () => {\n successEvent?.off();\n errorEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [attemptedSkus]);\n\n useEffect(() => {\n const cartDataEvent = events.on(\n 'cart/data',\n (cartData: any) => {\n if (\n attemptedSkusRef.current.length === 0 ||\n !cartData?.items ||\n cartData.items.length === 0\n ) {\n return;\n }\n\n // For configurable products, check both variant SKU and parent SKU\n const cartSkus = cartData.items.flatMap((item: any) => {\n const skus = [];\n if (item.sku) skus.push(item.sku);\n if (item.product?.sku) skus.push(item.product.sku);\n return skus;\n });\n\n const addedSkus = attemptedSkusRef.current.filter((sku) =>\n cartSkus.includes(sku)\n );\n\n if (addedSkus.length === 0) {\n return;\n }\n\n setNotification({\n type: 'success',\n variant: 'success',\n message: t.success,\n count: addedSkus.length,\n });\n\n setAttemptedSkus([]);\n events.emit('quick-order/loading', false);\n },\n {\n eager: true,\n }\n );\n\n return () => {\n cartDataEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const removeItem = useCallback((identifier: string) => {\n setItems((prevItems) =>\n prevItems.filter(\n (item) => item.id !== identifier && item.sku !== identifier\n )\n );\n }, []);\n\n const clearItems = useCallback(() => {\n setItems([]);\n setNotification(null);\n }, []);\n\n const updateItemQuantity = useCallback((sku: string, quantity: number) => {\n setItems((prevItems) =>\n prevItems.map((item) => (item.sku === sku ? { ...item, quantity } : item))\n );\n }, []);\n\n const isItemUpdating = useCallback(\n (sku: string) => {\n return updatingItems.has(sku);\n },\n [updatingItems]\n );\n\n const addToCart = useCallback(() => {\n const cartItems = buildCartItemsFromForms(items).filter(\n (item): item is NonNullable<typeof item> => item !== null\n );\n\n if (items.length > 0) {\n const isValid = validateOrderItems(items);\n\n if (!isValid) {\n const invalidItems = getInvalidItems(items);\n const invalidSkus = invalidItems.map((item) => item.sku);\n\n setNotification({\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n });\n return;\n }\n }\n\n if (cartItems.length === 0) {\n // Only show validation error if we have items in state\n if (items.length > 0) {\n const invalidItems = getInvalidItems(items);\n const invalidSkus = invalidItems.map((item) => item.sku);\n\n setNotification({\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n });\n }\n return;\n }\n\n setNotification(null);\n\n // Only track SKUs from valid cart items that will actually be added\n const skusToAdd = cartItems\n .map((item) => item.sku)\n .filter((sku): sku is string => Boolean(sku));\n setAttemptedSkus(skusToAdd);\n\n const storageData = getOptionsFromStorage(STORAGE_KEY);\n const enrichedCartItems = enrichCartItemsWithOptions(\n cartItems,\n items,\n storageData\n );\n\n if (handleAddToCart) {\n events.emit('quick-order/loading', true);\n Promise.resolve(handleAddToCart(enrichedCartItems, clearItems))\n .then((errorMessage) => {\n if (errorMessage && typeof errorMessage === 'string') {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: errorMessage,\n });\n setAttemptedSkus([]);\n }\n })\n .catch((error) => {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: error.message || t.unexpectedError,\n });\n setAttemptedSkus([]);\n })\n .finally(() => {\n events.emit('quick-order/loading', false); // Emit loading event after add to cart process completes\n });\n } else {\n events.emit('quick-order/add-to-cart', enrichedCartItems);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [items, handleAddToCart, STORAGE_KEY]);\n\n return {\n items,\n loading,\n removeItem,\n clearItems,\n updateItemQuantity,\n addToCart,\n isItemUpdating,\n isDisabledButton,\n setDisabledCartButton,\n notification,\n dismissNotification,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact/compat';\nimport { AlertBanner } from '@adobe-commerce/elsie/components';\nimport { QuickOrderNotificationBannerProps } from '@/b2b-quick-order/types';\nimport '@/b2b-quick-order/components/QuickOrderNotificationBanner/QuickOrderNotificationBanner.css';\nimport { classes } from '@adobe-commerce/elsie/lib';\n\nexport const QuickOrderNotificationBanner: FunctionComponent<\n QuickOrderNotificationBannerProps\n> = ({\n notification,\n onDismiss,\n onSkuClick,\n validationErrorText,\n backendErrorText,\n successText,\n partialSuccessText,\n}) => {\n if (!notification) {\n return null;\n }\n\n const getMessage = () => {\n switch (notification.type) {\n case 'validation':\n return renderValidationMessage(\n validationErrorText,\n notification.clickableSkus,\n notification.details,\n onSkuClick\n );\n\n case 'partial-success':\n return renderPartialSuccessMessage(\n partialSuccessText,\n notification.message,\n notification.count,\n notification.clickableSkus,\n onSkuClick\n );\n\n case 'backend-error':\n return renderBackendErrorMessage(\n backendErrorText,\n notification.details\n );\n\n case 'success':\n return renderSuccessMessage(successText, notification.count);\n\n default:\n return <span>{notification.message}</span>;\n }\n };\n\n return (\n <div\n className={classes([\n 'b2b-quick-order-notification-banner',\n [\n `b2b-quick-order-notification-banner--${notification.variant}`,\n notification.variant,\n ],\n ])}\n >\n <AlertBanner\n variant={notification.variant}\n message={getMessage()}\n onDismiss={onDismiss}\n />\n </div>\n );\n};\n\nfunction renderClickableSkus(\n skus: string[],\n onSkuClick: (sku: string) => void\n) {\n return skus.map((sku, index) => (\n <span key={sku}>\n <a\n href=\"#\"\n onClick={(e) => {\n e.preventDefault();\n onSkuClick(sku);\n }}\n style={{\n cursor: 'pointer',\n textDecoration: 'underline',\n color: 'white',\n }}\n >\n {sku}\n </a>\n {index < skus.length - 1 ? ', ' : ''}\n </span>\n ));\n}\n\nfunction renderValidationMessage(\n baseMessage: string,\n clickableSkus: string[] | undefined,\n details: string | undefined,\n onSkuClick?: (sku: string) => void\n) {\n if (clickableSkus?.length && onSkuClick) {\n return (\n <span>\n {baseMessage} - {renderClickableSkus(clickableSkus, onSkuClick)}\n </span>\n );\n }\n\n return (\n <span>\n {baseMessage} - {details}\n </span>\n );\n}\n\nfunction renderPartialSuccessMessage(\n partialSuccessText: string | undefined,\n message: string,\n count: number | undefined,\n clickableSkus: string[] | undefined,\n onSkuClick?: (sku: string) => void\n) {\n if (!partialSuccessText) {\n return <span>{message}</span>;\n }\n\n const partialMessage = partialSuccessText\n .replace('{count}', String(count || 0))\n .replace('{total}', String((count || 0) + (clickableSkus?.length || 0)));\n\n if (clickableSkus?.length && onSkuClick) {\n return (\n <span>\n {partialMessage}: {renderClickableSkus(clickableSkus, onSkuClick)}\n </span>\n );\n }\n\n return (\n <span>\n {partialMessage}: {clickableSkus?.join(', ') || 'Unknown'}\n </span>\n );\n}\n\nfunction renderBackendErrorMessage(\n backendErrorText: string,\n details: string | undefined\n) {\n return (\n <span>\n {backendErrorText}\n {details ? ` - ${details}` : ''}\n </span>\n );\n}\n\nfunction renderSuccessMessage(successText: string, count: number | undefined) {\n if (count !== undefined) {\n return <span>{successText.replace('{count}', String(count))}</span>;\n }\n return <span>{successText}</span>;\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n QuickOrderItemsList,\n QuickOrderNotificationBanner,\n QuickOrderDisabledOverlay,\n} from '@/b2b-quick-order/components';\nimport { useQuickOrderItems } from '@/b2b-quick-order/hooks';\nimport { QuickOrderItemsProps } from '@/b2b-quick-order/types';\nimport { config } from '@/b2b-quick-order/api/initialize';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, Container } from '@adobe-commerce/elsie/lib';\nimport { useRef, useEffect } from 'preact/hooks';\n\nexport const QuickOrderItems: Container<QuickOrderItemsProps> = ({\n className,\n slots,\n getProductsData,\n handleAddToCart,\n productsSearch,\n searchFilter,\n}) => {\n const isQuickOrderActive = config.getConfig().quickOrderActive;\n const notificationRef = useRef<HTMLDivElement>(null);\n\n const t = useText({\n title: 'QuickOrder.QuickOrderItem.title',\n quantity: 'QuickOrder.QuickOrderItem.quantity',\n price: 'QuickOrder.QuickOrderItem.price',\n remove: 'QuickOrder.QuickOrderItem.remove',\n removeItem: 'QuickOrder.QuickOrderItem.removeItem',\n showOptions: 'QuickOrder.QuickOrderItem.showOptions',\n hideOptions: 'QuickOrder.QuickOrderItem.hideOptions',\n additionalOptions: 'QuickOrder.QuickOrderItem.additionalOptions',\n noAdditionalOptions: 'QuickOrder.QuickOrderItem.noAdditionalOptions',\n emptyList: 'QuickOrder.QuickOrderItem.emptyList',\n sku: 'QuickOrder.QuickOrderItem.sku',\n loading: 'QuickOrder.QuickOrderItem.loading',\n productNotFound: 'QuickOrder.QuickOrderItem.productNotFound',\n productNotFoundDescription:\n 'QuickOrder.QuickOrderItem.productNotFoundDescription',\n productOptions: 'QuickOrder.QuickOrderItem.productOptions',\n configurableProductError:\n 'QuickOrder.QuickOrderItem.configurableProductError',\n configurableProductErrorDescription:\n 'QuickOrder.QuickOrderItem.configurableProductErrorDescription',\n addAllToCart: 'QuickOrder.QuickOrderItem.addAllToCart',\n configurableOptionsWarning:\n 'QuickOrder.QuickOrderItem.configurableOptionsWarning',\n configurableOptionsWarningDescription:\n 'QuickOrder.QuickOrderItem.configurableOptionsWarningDescription',\n outOfStock: 'QuickOrder.QuickOrderItem.outOfStock',\n searchPlaceholder: 'QuickOrder.Search.placeholder',\n searchAriaLabel: 'QuickOrder.Search.ariaLabel',\n searchEmptyState: 'QuickOrder.Search.emptyState',\n resultsAvailable: 'QuickOrder.Search.resultsAvailable',\n resultAvailable: 'QuickOrder.Search.resultAvailable',\n srInstructions: 'QuickOrder.Search.srInstructions',\n notificationValidationError:\n 'QuickOrder.QuickOrderItem.notification.validationError',\n notificationBackendError:\n 'QuickOrder.QuickOrderItem.notification.backendError',\n notificationSuccess: 'QuickOrder.QuickOrderItem.notification.success',\n notificationPartialSuccess:\n 'QuickOrder.QuickOrderItem.notification.partialSuccess',\n disabledMessage: 'QuickOrder.QuickOrderItem.disabledMessage',\n });\n\n const {\n items,\n loading,\n removeItem,\n clearItems,\n updateItemQuantity,\n addToCart,\n isItemUpdating,\n setDisabledCartButton,\n isDisabledButton,\n notification,\n dismissNotification,\n } = useQuickOrderItems({\n getProductsData,\n handleAddToCart,\n });\n\n // Auto-scroll to notification banner when error appears\n useEffect(() => {\n if (\n notification &&\n notification.variant === 'warning' &&\n notificationRef.current\n ) {\n notificationRef.current.scrollIntoView({\n behavior: 'smooth',\n block: 'start',\n });\n }\n }, [notification]);\n\n const handleSkuClick = (sku: string) => {\n // Find the form element with matching data-sku attribute\n const formElement = document.querySelector(\n `form[data-sku=\"${sku}\"]`\n ) as HTMLElement;\n\n if (formElement) {\n // Scroll to the element with smooth behavior\n formElement.scrollIntoView({\n behavior: 'smooth',\n block: 'center',\n });\n }\n };\n\n return (\n <div\n className={classes([\n 'b2b-quick-order-quick-order-items',\n !isQuickOrderActive && 'b2b-quick-order-disabled',\n className,\n ])}\n data-testid=\"quick-order-items\"\n style={{ position: 'relative' }}\n >\n <div ref={notificationRef}>\n <QuickOrderNotificationBanner\n notification={notification}\n onDismiss={dismissNotification}\n onSkuClick={handleSkuClick}\n validationErrorText={t.notificationValidationError}\n backendErrorText={t.notificationBackendError}\n successText={t.notificationSuccess}\n partialSuccessText={t.notificationPartialSuccess}\n />\n </div>\n <QuickOrderDisabledOverlay\n isDisabled={!isQuickOrderActive}\n message={t.disabledMessage}\n >\n <QuickOrderItemsList\n t={t}\n items={items}\n onRemove={removeItem}\n clearItems={clearItems}\n onUpdateQuantity={updateItemQuantity}\n handleAddToCart={addToCart}\n isItemUpdating={isItemUpdating}\n slots={slots}\n loading={loading}\n setDisabledCartButton={setDisabledCartButton}\n isDisabledButton={isDisabledButton}\n productsSearch={productsSearch}\n searchFilter={searchFilter}\n />\n </QuickOrderDisabledOverlay>\n </div>\n );\n};\n"],"names":["STANDARD_FIELDS","processFormOptions","formData","optionUIDs","enteredOptions","value","key","valueStr","buildCartItem","quantityValue","quantity","cartItem","parentSku","DEFAULT_QUICK_ORDER_ITEM","mapProductsToOrderItems","requestedItems","products","requestedItem","foundProduct","p","validateOrderItems","items","item","opt","_a","optItem","option","optionItem","getInvalidItems","invalidItems","getItemScope","generateItemId","sku","findDuplicateItem","newItem","existing","findDuplicateItemExcluding","updatedItem","excludeItemId","mergeDuplicateItems","removeIndex","mergeIntoIndex","quantityToAdd","index","replaceOrAddItems","existingItems","newItems","inputItems","updatedItems","addedItems","replacedItems","mergedItems","inputItem","replaceIndex","existingIndex","adjustedIndex","itemWithId","updateItemInList","itemId","currentQuantity","duplicateIndex","removingIndex","prevItem","buildCartItemsFromForms","formId","form","extractOptionsUIDs","valuesData","optionsUIDs","getOptionsFromStorage","storageKey","stored","e","saveOptionsToStorage","storageData","enrichCartItemsWithOptions","cartItems","selectedOptions","isItemInvalid","hasBasicIssues","allRequiredSelected","hasSelectedOption","useQuickOrderItems","getProductsData","handleAddToCart","setItems","useState","loading","setLoading","updatingItems","setUpdatingItems","isDisabledButton","setIsDisabledButton","notification","setNotification","attemptedSkus","setAttemptedSkus","attemptedSkusRef","useRef","t","useText","STORAGE_KEY","dismissNotification","useCallback","setDisabledCartButton","disabled","useEffect","loadingEvent","events","loadingState","itemsEvent","eventPayload","requestedSkus","prev","fetchedProducts","error","invalidNewItems","invalidSkus","mergedSkus","prevItems","scope","scopesList","isValid","stillInvalidSkus","matchingItems","i","existingSkus","eventsList","event","successEvent","addedCount","addedSkus","failedSkus","errorEvent","cartDataEvent","cartData","cartSkus","skus","removeItem","identifier","clearItems","updateItemQuantity","isItemUpdating","addToCart","skusToAdd","enrichedCartItems","errorMessage","QuickOrderNotificationBanner","onDismiss","onSkuClick","validationErrorText","backendErrorText","successText","partialSuccessText","getMessage","renderValidationMessage","renderPartialSuccessMessage","renderBackendErrorMessage","renderSuccessMessage","jsx","classes","AlertBanner","renderClickableSkus","baseMessage","clickableSkus","details","message","count","partialMessage","QuickOrderItems","className","slots","productsSearch","searchFilter","isQuickOrderActive","config","notificationRef","handleSkuClick","formElement","jsxs","QuickOrderDisabledOverlay","QuickOrderItemsList"],"mappings":"8jBAiBA,MAAMA,GAAkB,CACtB,MACA,YACA,WACA,cACA,QACA,aACF,EAWaC,GACXC,GACyB,CACzB,MAAMC,EAAuB,CAAA,EACvBC,EAAmD,CAAA,EAEzD,OAAAF,EAAS,QAAQ,CAACG,EAAOC,IAAQ,CAC/B,GAAIN,GAAgB,SAASM,CAAG,EAAG,OAEnC,MAAMC,EAAWF,EAEbE,GAAYA,EAAS,MAAM,mBAAmB,EAChDJ,EAAW,KAAKI,CAAQ,EAExBH,EAAe,KAAK,CAAE,IAAKE,EAAK,MAAOC,EAAU,CAErD,CAAC,EAEM,CAAE,WAAAJ,EAAY,eAAAC,CAAA,CACvB,ECvBaI,GAAiBN,GAAiC,CAC7D,MAAMO,EAAgB,OAAOP,EAAS,IAAI,UAAU,CAAC,EAC/CQ,EAAW,CAACD,GAAiBA,EAAgB,EAAI,EAAIA,EAErDE,EAAqB,CACzB,IAAKT,EAAS,IAAI,KAAK,EACvB,SAAAQ,CAAA,EAGIE,EAAYV,EA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,CAAA,CAAA,CAGN"}
1
+ {"version":3,"file":"QuickOrderItems.js","sources":["/@dropins/storefront-quick-order/src/lib/processFormOptions.ts","/@dropins/storefront-quick-order/src/lib/buildCartItem.ts","/@dropins/storefront-quick-order/src/configs/order-item.config.ts","/@dropins/storefront-quick-order/src/lib/mapProductsToOrderItems.ts","/@dropins/storefront-quick-order/src/lib/validateOrderItems.ts","/@dropins/storefront-quick-order/src/lib/getItemScope.ts","/@dropins/storefront-quick-order/src/lib/generateItemId.ts","/@dropins/storefront-quick-order/src/lib/findDuplicateItem.ts","/@dropins/storefront-quick-order/src/lib/mergeDuplicateItems.ts","/@dropins/storefront-quick-order/src/lib/replaceOrAddItems.ts","/@dropins/storefront-quick-order/src/lib/updateItemInList.ts","/@dropins/storefront-quick-order/src/lib/buildCartItemsFromForms.ts","/@dropins/storefront-quick-order/src/lib/productOptionsStorage.ts","/@dropins/storefront-quick-order/src/lib/isItemValid.ts","/@dropins/storefront-quick-order/src/hooks/useQuickOrderItems.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderNotificationBanner/QuickOrderNotificationBanner.tsx","/@dropins/storefront-quick-order/src/containers/QuickOrderItems/QuickOrderItems.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nconst STANDARD_FIELDS = [\n 'sku',\n 'parentSku',\n 'quantity',\n 'optionsUIDs',\n 'valid',\n 'productType',\n];\n\nexport interface ProcessedFormOptions {\n optionUIDs: string[];\n enteredOptions: { uid: string; value: string }[];\n}\n\n/**\n * Processes form data to extract product options\n * Separates base64-encoded configurable options (optionUIDs) from custom entered options\n */\nexport const processFormOptions = (\n formData: FormData\n): ProcessedFormOptions => {\n const optionUIDs: string[] = [];\n const enteredOptions: { uid: string; value: string }[] = [];\n\n formData.forEach((value, key) => {\n if (STANDARD_FIELDS.includes(key)) return;\n\n const valueStr = value as string;\n // Check if this is an option UID (base64 encoded configurable option)\n if (valueStr && valueStr.match(/^[A-Za-z0-9+/=]+$/)) {\n optionUIDs.push(valueStr);\n } else {\n enteredOptions.push({ uid: key, value: valueStr });\n }\n });\n\n return { optionUIDs, enteredOptions };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { processFormOptions } from './processFormOptions';\n\nexport interface CartItem {\n sku: string;\n quantity: number;\n parentSku?: string;\n optionsUIDs?: string[];\n enteredOptions?: { uid: string; value: string }[];\n}\n\n/**\n * Builds a cart item object from form data\n * Extracts SKU, quantity, parent SKU, and product options\n */\nexport const buildCartItem = (formData: FormData): CartItem => {\n const quantityValue = Number(formData.get('quantity'));\n const quantity = !quantityValue || quantityValue < 1 ? 1 : quantityValue;\n\n const cartItem: CartItem = {\n sku: formData.get('sku') as string,\n quantity,\n };\n\n const parentSku = formData.get('parentSku');\n if (parentSku) {\n cartItem.parentSku = parentSku as string;\n }\n\n const { optionUIDs, enteredOptions } = processFormOptions(formData);\n\n if (optionUIDs.length > 0) {\n cartItem.optionsUIDs = optionUIDs;\n }\n\n if (enteredOptions.length > 0) {\n cartItem.enteredOptions = enteredOptions;\n }\n\n return cartItem;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types/quickOrderItems.types';\n\nexport const DEFAULT_QUICK_ORDER_ITEM: OrderItem = {\n sku: '',\n quantity: 1,\n name: '',\n images: [],\n inStock: false,\n addToCartAllowed: false,\n isBundle: false,\n prices: {} as any,\n attributes: [],\n options: [],\n url: '',\n urlKey: '',\n externalId: '',\n productType: 'simple',\n shortDescription: '',\n metaDescription: '',\n metaKeyword: '',\n metaTitle: '',\n description: '',\n} as OrderItem;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem, OrderItemInput } from '@/b2b-quick-order/types';\nimport { DEFAULT_QUICK_ORDER_ITEM } from '@/b2b-quick-order/configs';\n\n/**\n * Maps fetched products to OrderItems\n * Creates error items for products not found in the response\n * @param requestedItems - Items that were requested\n * @param products - Products returned from API\n * @returns Array of OrderItems with proper quantity set\n */\nexport const mapProductsToOrderItems = (\n requestedItems: OrderItemInput[],\n products: OrderItem[]\n): OrderItem[] => {\n // Handle empty or undefined products array\n if (!products || !Array.isArray(products)) {\n return requestedItems.map((requestedItem) => ({\n ...DEFAULT_QUICK_ORDER_ITEM,\n sku: requestedItem.sku,\n quantity: requestedItem.quantity ?? 1,\n })) as OrderItem[];\n }\n\n return requestedItems.map((requestedItem) => {\n const foundProduct = products.find((p) => p?.sku === requestedItem?.sku);\n\n if (foundProduct) {\n return {\n ...foundProduct,\n ...(requestedItem.variantSku && {\n variantSku: requestedItem.variantSku,\n }),\n quantity: requestedItem.quantity ?? 1,\n };\n }\n\n // Product not found - create error item\n return {\n ...DEFAULT_QUICK_ORDER_ITEM,\n sku: requestedItem.sku,\n ...(requestedItem.variantSku && { variantSku: requestedItem.variantSku }),\n quantity: requestedItem.quantity ?? 1,\n } as OrderItem;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Validates order items to determine if all items are ready for cart addition\n * @param items - Array of order items to validate\n * @returns true if all items are valid, false otherwise\n */\nexport const validateOrderItems = (items: OrderItem[]): boolean => {\n if (items.length === 0) {\n return false;\n }\n\n return items.every((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n if (!hasBasicData) {\n return false;\n }\n\n if (item.inStock === false) {\n return false;\n }\n\n if (item.options && item.options.length > 0) {\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n return item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return hasSelectedOption;\n }\n\n return true;\n });\n};\n\n/**\n * Get items that are out of stock\n * @param items - Array of order items to check\n * @returns Array of out of stock items with their names\n */\nexport const getOutOfStockItems = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => item.inStock === false)\n .map((item) => ({\n sku: item.sku,\n name: item.name,\n }));\n};\n\n/**\n * Get items with missing required options\n * @param items - Array of order items to check\n * @returns Array of items missing required options\n */\nexport const getItemsMissingOptions = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => {\n if (!item.options || item.options.length === 0) {\n return false;\n }\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return !hasSelectedOption;\n })\n .map((item) => ({\n sku: item.sku,\n name: item.name,\n }));\n};\n\n/**\n * Get items with incomplete data\n * @param items - Array of order items to check\n * @returns Array of items with incomplete data\n */\nexport const getItemsWithIncompleteData = (\n items: OrderItem[]\n): Array<{ sku: string; name: string }> => {\n return items\n .filter((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n return !hasBasicData;\n })\n .map((item) => ({\n sku: item.sku,\n name: item.name || 'Unknown',\n }));\n};\n\n/**\n * Get all items with validation errors\n * @param items - Array of order items to check\n * @returns Array of all items with validation errors and their SKUs\n */\nexport const getInvalidItems = (\n items: OrderItem[]\n): Array<{ sku: string; name: string; reason: string }> => {\n const invalidItems: Array<{ sku: string; name: string; reason: string }> = [];\n\n items.forEach((item) => {\n const hasBasicData = (item.urlKey || item.url) && item.name;\n\n if (!hasBasicData) {\n invalidItems.push({\n sku: item.sku,\n name: item.name || 'Unknown',\n reason: 'incomplete_data',\n });\n return;\n }\n\n if (item.inStock === false) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'out_of_stock',\n });\n return;\n }\n\n if (item.options && item.options.length > 0) {\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n const allRequiredSelected = item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n\n if (!allRequiredSelected) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'missing_required_options',\n });\n }\n return;\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n if (!hasSelectedOption) {\n invalidItems.push({\n sku: item.sku,\n name: item.name,\n reason: 'missing_options',\n });\n }\n }\n });\n\n return invalidItems;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Get unique scope identifier for an item\n * Uses unique id if available, otherwise falls back to variantSku or sku\n */\nexport const getItemScope = (item: OrderItem): string => {\n const scopeKey = item.id || item.variantSku || item.sku;\n return `quick-order-item-${scopeKey}`;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Generate unique ID for an item\n * Format: {sku}-{timestamp}-{random}\n */\nexport const generateItemId = (sku: string): string => {\n return `${sku}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Find duplicate item in the list based on multiple comparison strategies\n * Returns the index of the duplicate item, or -1 if not found\n *\n * Strategies:\n * 1. Both have variantSku - compare variants\n * 2. Existing has variantSku, new has sku - compare them\n * 3. New has variantSku, existing has sku - compare them\n * 4. Neither has variantSku - compare base SKU\n */\nexport const findDuplicateItem = (\n items: OrderItem[],\n newItem: OrderItem\n): number => {\n return items.findIndex((existing) => {\n // Strategy 1: Both have variantSku - compare variants\n if (newItem.variantSku && existing.variantSku) {\n return existing.variantSku === newItem.variantSku;\n }\n\n // Strategy 2: Existing has variantSku, new has sku - compare them\n // (e.g., existing configured product vs search result variant)\n if (existing.variantSku && !newItem.variantSku && newItem.sku) {\n return existing.variantSku === newItem.sku;\n }\n\n // Strategy 3: New has variantSku, existing has sku - compare them\n // (opposite of strategy 2)\n if (newItem.variantSku && !existing.variantSku && existing.sku) {\n return existing.sku === newItem.variantSku;\n }\n\n // Strategy 4: Neither has variantSku - compare base sku\n if (!newItem.variantSku && !existing.variantSku) {\n return existing.sku === newItem.sku;\n }\n\n return false;\n });\n};\n\n/**\n * Find duplicate item excluding a specific item by ID\n * Used when checking for duplicates after an item update\n */\nexport const findDuplicateItemExcluding = (\n items: OrderItem[],\n updatedItem: OrderItem,\n excludeItemId: string\n): number => {\n return items.findIndex((existing) => {\n // Skip the item being updated\n if (existing.id === excludeItemId) return false;\n\n // Check if updatedItem's variantSku matches existing item\n if (updatedItem.variantSku && existing.variantSku) {\n return existing.variantSku === updatedItem.variantSku;\n }\n\n // Check if updatedItem's variantSku matches existing item's sku\n if (updatedItem.variantSku && !existing.variantSku && existing.sku) {\n return existing.sku === updatedItem.variantSku;\n }\n\n return false;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Merge duplicate items by removing the item at removeIndex and\n * adding its quantity to the item at mergeIntoIndex\n */\nexport const mergeDuplicateItems = (\n items: OrderItem[],\n removeIndex: number,\n mergeIntoIndex: number,\n quantityToAdd: number = 1\n): OrderItem[] => {\n return items\n .map((item, index) => {\n if (index === mergeIntoIndex) {\n // Increase quantity of the duplicate\n return {\n ...item,\n quantity: item.quantity + quantityToAdd,\n };\n } else if (index === removeIndex) {\n // Remove the item being merged\n return null;\n }\n return item;\n })\n .filter(Boolean) as OrderItem[];\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem, OrderItemInput } from '@/b2b-quick-order/types';\nimport { findDuplicateItem } from './findDuplicateItem';\nimport { generateItemId } from './generateItemId';\n\nexport interface ReplaceOrAddItemsResult {\n updatedItems: OrderItem[];\n addedItems: OrderItem[];\n replacedItems: OrderItem[];\n mergedItems: OrderItem[];\n}\n\n/**\n * Replace, merge, or add items into existing list\n * Handles three scenarios:\n * 1. Replace: When inputItem has replaceItemSku, replace item at same position\n * - If new item already exists in list, collapse by removing replaced item and merging quantity\n * 2. Merge: When item exists, increase quantity\n * 3. Add: When item doesn't exist, add to end\n */\nexport const replaceOrAddItems = (\n existingItems: OrderItem[],\n newItems: OrderItem[],\n inputItems: OrderItemInput[]\n): ReplaceOrAddItemsResult => {\n const updatedItems = [...existingItems];\n const addedItems: OrderItem[] = [];\n const replacedItems: OrderItem[] = [];\n const mergedItems: OrderItem[] = [];\n\n newItems.forEach((newItem, index) => {\n const inputItem = inputItems[index];\n\n // Scenario 1: Replace existing item at same position\n if (inputItem?.replaceItemSku) {\n const replaceIndex = updatedItems.findIndex(\n (item) =>\n item.sku === inputItem.replaceItemSku ||\n item.id === inputItem.replaceItemSku\n );\n\n if (replaceIndex !== -1) {\n // Check if new item already exists elsewhere in the list (collapse case)\n const existingIndex = findDuplicateItem(updatedItems, newItem);\n\n if (existingIndex !== -1 && existingIndex !== replaceIndex) {\n // Item already exists - remove replaced item and merge quantity into existing\n updatedItems.splice(replaceIndex, 1);\n // Adjust index if existing item was after the removed one\n const adjustedIndex =\n existingIndex > replaceIndex ? existingIndex - 1 : existingIndex;\n updatedItems[adjustedIndex] = {\n ...updatedItems[adjustedIndex],\n quantity: updatedItems[adjustedIndex].quantity + newItem.quantity,\n };\n mergedItems.push(updatedItems[adjustedIndex]);\n } else {\n // Replace item at the same position\n const itemWithId = {\n ...newItem,\n id: generateItemId(newItem.sku),\n };\n updatedItems[replaceIndex] = itemWithId;\n replacedItems.push(itemWithId);\n }\n return;\n }\n // If item to replace not found, fall through to add logic\n }\n\n // Scenario 2 & 3: Merge or Add\n const existingIndex = findDuplicateItem(updatedItems, newItem);\n\n if (existingIndex !== -1) {\n // Item exists - merge by increasing quantity\n updatedItems[existingIndex] = {\n ...updatedItems[existingIndex],\n quantity: updatedItems[existingIndex].quantity + newItem.quantity,\n };\n mergedItems.push(updatedItems[existingIndex]);\n } else {\n // Item doesn't exist - add new with unique ID\n const itemWithId = {\n ...newItem,\n id: generateItemId(newItem.sku),\n };\n updatedItems.push(itemWithId);\n addedItems.push(itemWithId);\n }\n });\n\n return { updatedItems, addedItems, replacedItems, mergedItems };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\nimport { findDuplicateItemExcluding } from './findDuplicateItem';\nimport { mergeDuplicateItems } from './mergeDuplicateItems';\n\nexport interface UpdateItemResult {\n updatedItems: OrderItem[];\n wasMerged: boolean;\n mergedIntoIndex?: number;\n}\n\n/**\n * Update a specific item in the list and check for duplicates\n * If duplicate is found, merge the items\n */\nexport const updateItemInList = (\n items: OrderItem[],\n itemId: string,\n updatedItem: OrderItem,\n currentQuantity: number = 1\n): UpdateItemResult => {\n // Check if the updated item's variantSku matches another existing item\n const duplicateIndex = itemId\n ? findDuplicateItemExcluding(items, updatedItem, itemId)\n : -1;\n\n if (duplicateIndex !== -1) {\n // Find the index of the item being updated\n const removingIndex = items.findIndex((prevItem) => prevItem.id === itemId);\n\n // Duplicate found - merge items\n return {\n updatedItems: mergeDuplicateItems(\n items,\n removingIndex,\n duplicateIndex,\n currentQuantity\n ),\n wasMerged: true,\n mergedIntoIndex: duplicateIndex,\n };\n }\n\n // No duplicate - just update the item\n const updatedItems = items.map((prevItem) => {\n if (itemId && prevItem.id === itemId) {\n // Match by ID - update with preserved ID\n return {\n ...prevItem,\n ...updatedItem,\n id: itemId,\n };\n } else if (!itemId && prevItem.sku === updatedItem.sku) {\n // Fallback for items without ID (backward compatibility)\n return {\n ...prevItem,\n ...updatedItem,\n };\n }\n return prevItem;\n });\n\n return {\n updatedItems,\n wasMerged: false,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\nimport { buildCartItem } from './buildCartItem';\n\n/**\n * Build cart items from forms for all order items\n * Only includes valid items (items with valid forms)\n */\nexport const buildCartItemsFromForms = (items: OrderItem[]) => {\n return items.map((item) => {\n const formId = item.id || item.sku;\n const form = document.forms[`form-${formId}` as any] as HTMLFormElement;\n if (!form) return null;\n\n const formData = new FormData(form);\n const isValid = formData.get('valid') === 'true';\n\n return isValid ? buildCartItem(formData) : null;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\n/**\n * Extract optionsUIDs from various data formats\n */\nexport const extractOptionsUIDs = (valuesData: any): string[] => {\n let optionsUIDs: string[] = [];\n\n if (valuesData && typeof valuesData === 'object') {\n if (valuesData.optionsUIDs && Array.isArray(valuesData.optionsUIDs)) {\n optionsUIDs = valuesData.optionsUIDs;\n } else if (Array.isArray(valuesData)) {\n optionsUIDs = valuesData;\n }\n } else if (typeof valuesData === 'string') {\n optionsUIDs = [valuesData];\n }\n\n return optionsUIDs;\n};\n\n/**\n * Get options from localStorage\n */\nexport const getOptionsFromStorage = (\n storageKey: string\n): Record<string, string[]> => {\n try {\n const stored = localStorage.getItem(storageKey);\n if (stored) {\n return JSON.parse(stored);\n }\n } catch (e) {\n console.error('Error reading from localStorage:', e);\n }\n return {};\n};\n\n/**\n * Save options to localStorage\n */\nexport const saveOptionsToStorage = (\n storageKey: string,\n itemId: string,\n optionsUIDs: string[]\n): void => {\n if (optionsUIDs.length === 0) {\n return;\n }\n\n try {\n const storageData = getOptionsFromStorage(storageKey);\n storageData[itemId] = optionsUIDs;\n localStorage.setItem(storageKey, JSON.stringify(storageData));\n } catch (e) {\n console.error('Error saving to localStorage:', e);\n }\n};\n\n/**\n * Enrich cart items with selected options from storage\n */\nexport const enrichCartItemsWithOptions = <T extends { sku: string }>(\n cartItems: T[],\n items: Array<{ id?: string; sku: string; variantSku?: string }>,\n storageData: Record<string, string[]>\n): Array<T & { optionsUIDs?: string[] }> => {\n return cartItems.map((cartItem) => {\n const item = items.find((i) => {\n return cartItem.sku === i.sku || cartItem.sku === i.variantSku;\n });\n\n if (item) {\n const itemId = item.id || item.sku;\n const selectedOptions = storageData[itemId];\n\n if (selectedOptions && selectedOptions.length > 0) {\n return {\n ...cartItem,\n optionsUIDs: selectedOptions,\n };\n }\n }\n\n return cartItem;\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { OrderItem } from '@/b2b-quick-order/types';\n\n/**\n * Check if an item is valid for adding to cart\n * @param item - The order item to validate\n * @returns true if item is invalid (should stay in notification), false if valid\n */\nexport const isItemInvalid = (item: OrderItem): boolean => {\n const hasBasicIssues = !item.inStock || !item.addToCartAllowed;\n\n if (item.options && item.options.length > 0) {\n // Options must be loaded before validation\n const optionsNotReady = item.options.some(\n (opt) => !opt.items || opt.items.length === 0\n );\n\n if (optionsNotReady) {\n return true;\n }\n\n const hasRequiredOptions = item.options.some((opt) => opt.required);\n\n if (hasRequiredOptions) {\n // Required options: all must be selected\n const allRequiredSelected = item.options.every((opt) => {\n if (!opt.required) return true;\n return opt.items?.some((optItem) => optItem.selected);\n });\n return hasBasicIssues || !allRequiredSelected;\n }\n\n // Optional options: at least one must be selected\n const hasSelectedOption = item.options.some(\n (option) =>\n option.items &&\n option.items.length > 0 &&\n option.items.some((optionItem) => optionItem.selected === true)\n );\n return hasBasicIssues || !hasSelectedOption;\n }\n\n return hasBasicIssues;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\nimport {\n OrderItemInput,\n OrderItem,\n UseQuickOrderItemsProps,\n UseQuickOrderItemsReturn,\n} from '@/b2b-quick-order/types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n mapProductsToOrderItems,\n validateOrderItems,\n getItemScope,\n replaceOrAddItems,\n updateItemInList,\n buildCartItemsFromForms,\n extractOptionsUIDs,\n saveOptionsToStorage,\n getOptionsFromStorage,\n enrichCartItemsWithOptions,\n getInvalidItems,\n isItemInvalid,\n} from '@/b2b-quick-order/lib';\n\nexport const useQuickOrderItems = ({\n getProductsData,\n handleAddToCart,\n}: UseQuickOrderItemsProps = {}): UseQuickOrderItemsReturn => {\n const [items, setItems] = useState<OrderItem[]>([]);\n const [loading, setLoading] = useState(false);\n const [updatingItems, setUpdatingItems] = useState<Set<string>>(new Set());\n const [isDisabledButton, setIsDisabledButton] = useState(false);\n const [notification, setNotification] = useState<{\n type: 'validation' | 'partial-success' | 'success' | 'backend-error';\n variant: 'success' | 'warning' | 'neutral' | 'brand';\n message: string;\n details?: string;\n count?: number;\n clickableSkus?: string[];\n } | null>(null);\n const [attemptedSkus, setAttemptedSkus] = useState<string[]>([]);\n const attemptedSkusRef = useRef<string[]>([]);\n\n const t = useText({\n validationError: 'QuickOrder.QuickOrderItem.notification.validationError',\n backendError: 'QuickOrder.QuickOrderItem.notification.backendError',\n success: 'QuickOrder.QuickOrderItem.notification.success',\n partialSuccess: 'QuickOrder.QuickOrderItem.notification.partialSuccess',\n unexpectedError: 'QuickOrder.QuickOrderItem.notification.unexpectedError',\n });\n\n const STORAGE_KEY = 'quick-order-selected-options';\n\n const dismissNotification = useCallback(() => {\n setNotification(null);\n }, []);\n\n const setDisabledCartButton = useCallback((disabled: boolean) => {\n setIsDisabledButton(disabled);\n }, []);\n\n useEffect(() => {\n const loadingEvent = events.on(\n 'quick-order/loading',\n (loadingState) => {\n setLoading(loadingState);\n },\n {\n eager: true,\n }\n );\n return () => {\n loadingEvent?.off();\n };\n }, []);\n\n useEffect(() => {\n const itemsEvent = events.on(\n 'quick-order/add-items',\n async (eventPayload: OrderItemInput[]) => {\n if (eventPayload && eventPayload.length > 0) {\n if (!getProductsData) {\n return;\n }\n\n setLoading(true);\n events.emit('quick-order/loading', true);\n const requestedSkus = eventPayload\n .map((item) => item.sku)\n .filter(Boolean);\n setUpdatingItems(\n (prev) => new Set([...Array.from(prev), ...requestedSkus])\n );\n\n try {\n let newItems: OrderItem[] = [];\n try {\n const fetchedProducts =\n (await getProductsData(eventPayload)) ?? [];\n setDisabledCartButton(\n eventPayload.length !== fetchedProducts.length\n );\n newItems = mapProductsToOrderItems(eventPayload, fetchedProducts);\n } catch (error) {\n console.error('Error fetching products data:', error);\n newItems = mapProductsToOrderItems(eventPayload, []);\n }\n\n const invalidNewItems = getInvalidItems(newItems);\n if (invalidNewItems.length > 0) {\n const invalidSkus = invalidNewItems.map((item) => item.sku);\n setNotification((prev) => {\n if (prev?.type === 'validation' && prev.clickableSkus) {\n // Merge with existing validation SKUs\n const mergedSkus = [\n ...new Set([...prev.clickableSkus, ...invalidSkus]),\n ];\n return {\n ...prev,\n clickableSkus: mergedSkus,\n };\n }\n return {\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n };\n });\n }\n\n setItems((prevItems) => {\n const { updatedItems, addedItems, mergedItems, replacedItems } =\n replaceOrAddItems(prevItems, newItems, eventPayload);\n\n replacedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n mergedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n addedItems.forEach((item) => {\n const scope = getItemScope(item);\n events.emit(`${scope}/pdp/data`, item);\n });\n\n return updatedItems;\n });\n } finally {\n setLoading(false);\n events.emit('quick-order/loading', false);\n setUpdatingItems(\n (prev) =>\n new Set(\n Array.from(prev).filter((sku) => !requestedSkus.includes(sku))\n )\n );\n }\n }\n },\n {\n eager: true,\n }\n );\n\n return () => {\n itemsEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [getProductsData, setDisabledCartButton]);\n\n useEffect(() => {\n const scopesList = items.map((item) => {\n const scope = getItemScope(item);\n const itemId = item.id; // Capture the specific item's ID for this listener\n\n return events.on(`${scope}/pdp/data`, (updatedItem: OrderItem) => {\n setItems((prevItems) => {\n const result = updateItemInList(\n prevItems,\n itemId || '',\n updatedItem,\n item.quantity || 1\n );\n return result.updatedItems;\n });\n });\n });\n\n return () => {\n scopesList?.forEach((scope) => {\n scope?.off();\n });\n };\n }, [items]);\n\n useEffect(() => {\n const isValid = validateOrderItems(items);\n setDisabledCartButton(!isValid);\n }, [items, setDisabledCartButton]);\n\n useEffect(() => {\n setNotification((prev) => {\n // Only process notifications with clickable SKUs\n if (!prev || !prev.clickableSkus || prev.clickableSkus.length === 0) {\n return prev;\n }\n\n const stillInvalidSkus = prev.clickableSkus.filter((sku) => {\n // Find ALL items with this SKU (could be multiple for configurable products)\n const matchingItems = items.filter(\n (i) => i.sku === sku || i.variantSku === sku\n );\n if (matchingItems.length === 0) return false; // Item removed\n\n // Keep SKU in notification if ANY matching item is invalid\n return matchingItems.some((item) => isItemInvalid(item));\n });\n\n // Clear notification only if all SKUs are valid\n if (stillInvalidSkus.length === 0) {\n return null;\n }\n\n // Update notification if SKUs changed\n if (stillInvalidSkus.length !== prev.clickableSkus.length) {\n return {\n ...prev,\n clickableSkus: stillInvalidSkus,\n };\n }\n\n return prev;\n });\n }, [items]);\n\n useEffect(() => {\n // If Add to Cart button is disabled and there are items,\n // but no validation notification is shown - display it\n if (!isDisabledButton || items.length === 0) {\n return;\n }\n\n setNotification((prev) => {\n // Don't override existing validation/partial-success notifications\n if (\n prev &&\n (prev.type === 'validation' || prev.type === 'partial-success')\n ) {\n return prev;\n }\n\n const invalidItems = getInvalidItems(items);\n if (invalidItems.length === 0) {\n return prev;\n }\n\n const invalidSkus = [...new Set(invalidItems.map((item) => item.sku))];\n\n // Only set notification if it doesn't already have the same SKUs\n const existingSkus = prev?.clickableSkus || [];\n const hasChanges =\n invalidSkus.length !== existingSkus.length ||\n !invalidSkus.every((sku) => existingSkus.includes(sku));\n\n if (hasChanges) {\n return {\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n };\n }\n\n return prev;\n });\n }, [isDisabledButton, items, t.validationError]);\n\n useEffect(() => {\n const eventsList = items.map((item) => {\n const scope = getItemScope(item);\n const itemId = item.id || item.sku;\n\n return events.on(`${scope}/pdp/values`, (valuesData: any) => {\n const optionsUIDs = extractOptionsUIDs(valuesData);\n saveOptionsToStorage(STORAGE_KEY, itemId, optionsUIDs);\n });\n });\n\n return () => {\n eventsList.forEach((event) => {\n event?.off();\n });\n };\n }, [items, STORAGE_KEY]);\n\n useEffect(() => {\n attemptedSkusRef.current = attemptedSkus;\n }, [attemptedSkus]);\n\n useEffect(() => {\n const successEvent = events.on('cart/product/added', (products: any[]) => {\n const addedCount = Array.isArray(products) ? products.length : 0;\n const addedSkus = Array.isArray(products)\n ? products.map((p: any) => p.sku).filter(Boolean)\n : [];\n\n if (attemptedSkus.length > 0) {\n const failedSkus = attemptedSkus.filter(\n (sku) => !addedSkus.includes(sku)\n );\n\n if (failedSkus.length > 0 && addedCount > 0) {\n setNotification({\n type: 'partial-success',\n variant: 'warning',\n message: t.partialSuccess,\n count: addedCount,\n clickableSkus: failedSkus,\n });\n setAttemptedSkus([]);\n }\n } else {\n // No tracking context - ignore event\n return;\n }\n });\n\n const errorEvent = events.on(\n 'quick-order/add-to-cart-error',\n (error: { message: string }) => {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: error.message,\n });\n setAttemptedSkus([]);\n }\n );\n\n return () => {\n successEvent?.off();\n errorEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [attemptedSkus]);\n\n useEffect(() => {\n const cartDataEvent = events.on(\n 'cart/data',\n (cartData: any) => {\n if (\n attemptedSkusRef.current.length === 0 ||\n !cartData?.items ||\n cartData.items.length === 0\n ) {\n return;\n }\n\n // For configurable products, check both variant SKU and parent SKU\n const cartSkus = cartData.items.flatMap((item: any) => {\n const skus = [];\n if (item.sku) skus.push(item.sku);\n if (item.product?.sku) skus.push(item.product.sku);\n return skus;\n });\n\n const addedSkus = attemptedSkusRef.current.filter((sku) =>\n cartSkus.includes(sku)\n );\n\n if (addedSkus.length === 0) {\n return;\n }\n\n setNotification({\n type: 'success',\n variant: 'success',\n message: t.success,\n count: addedSkus.length,\n });\n\n setAttemptedSkus([]);\n events.emit('quick-order/loading', false);\n },\n {\n eager: true,\n }\n );\n\n return () => {\n cartDataEvent?.off();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const removeItem = useCallback((identifier: string) => {\n setItems((prevItems) =>\n prevItems.filter(\n (item) => item.id !== identifier && item.sku !== identifier\n )\n );\n }, []);\n\n const clearItems = useCallback(() => {\n setItems([]);\n setNotification(null);\n }, []);\n\n const updateItemQuantity = useCallback((sku: string, quantity: number) => {\n setItems((prevItems) =>\n prevItems.map((item) => (item.sku === sku ? { ...item, quantity } : item))\n );\n }, []);\n\n const isItemUpdating = useCallback(\n (sku: string) => {\n return updatingItems.has(sku);\n },\n [updatingItems]\n );\n\n const addToCart = useCallback(() => {\n const cartItems = buildCartItemsFromForms(items).filter(\n (item): item is NonNullable<typeof item> => item !== null\n );\n\n if (items.length > 0) {\n const isValid = validateOrderItems(items);\n\n if (!isValid) {\n const invalidItems = getInvalidItems(items);\n const invalidSkus = invalidItems.map((item) => item.sku);\n\n setNotification({\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n });\n return;\n }\n }\n\n if (cartItems.length === 0) {\n // Only show validation error if we have items in state\n if (items.length > 0) {\n const invalidItems = getInvalidItems(items);\n const invalidSkus = invalidItems.map((item) => item.sku);\n\n setNotification({\n type: 'validation',\n variant: 'warning',\n message: t.validationError,\n clickableSkus: invalidSkus,\n });\n }\n return;\n }\n\n setNotification(null);\n\n // Only track SKUs from valid cart items that will actually be added\n const skusToAdd = cartItems\n .map((item) => item.sku)\n .filter((sku): sku is string => Boolean(sku));\n setAttemptedSkus(skusToAdd);\n\n const storageData = getOptionsFromStorage(STORAGE_KEY);\n const enrichedCartItems = enrichCartItemsWithOptions(\n cartItems,\n items,\n storageData\n );\n\n if (handleAddToCart) {\n events.emit('quick-order/loading', true);\n Promise.resolve(handleAddToCart(enrichedCartItems, clearItems))\n .then((errorMessage) => {\n if (errorMessage && typeof errorMessage === 'string') {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: errorMessage,\n });\n setAttemptedSkus([]);\n }\n })\n .catch((error) => {\n setNotification({\n type: 'backend-error',\n variant: 'warning',\n message: t.backendError,\n details: error.message || t.unexpectedError,\n });\n setAttemptedSkus([]);\n })\n .finally(() => {\n events.emit('quick-order/loading', false); // Emit loading event after add to cart process completes\n });\n } else {\n events.emit('quick-order/add-to-cart', enrichedCartItems);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [items, handleAddToCart, STORAGE_KEY]);\n\n return {\n items,\n loading,\n removeItem,\n clearItems,\n updateItemQuantity,\n addToCart,\n isItemUpdating,\n isDisabledButton,\n setDisabledCartButton,\n notification,\n dismissNotification,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact/compat';\nimport { AlertBanner } from '@adobe-commerce/elsie/components';\nimport { QuickOrderNotificationBannerProps } from '@/b2b-quick-order/types';\nimport '@/b2b-quick-order/components/QuickOrderNotificationBanner/QuickOrderNotificationBanner.css';\nimport { classes } from '@adobe-commerce/elsie/lib';\n\nexport const QuickOrderNotificationBanner: FunctionComponent<\n QuickOrderNotificationBannerProps\n> = ({\n notification,\n onDismiss,\n onSkuClick,\n validationErrorText,\n backendErrorText,\n successText,\n partialSuccessText,\n}) => {\n if (!notification) {\n return null;\n }\n\n const getMessage = () => {\n switch (notification.type) {\n case 'validation':\n return renderValidationMessage(\n validationErrorText,\n notification.clickableSkus,\n notification.details,\n onSkuClick\n );\n\n case 'partial-success':\n return renderPartialSuccessMessage(\n partialSuccessText,\n notification.message,\n notification.count,\n notification.clickableSkus,\n onSkuClick\n );\n\n case 'backend-error':\n return renderBackendErrorMessage(\n backendErrorText,\n notification.details\n );\n\n case 'success':\n return renderSuccessMessage(successText, notification.count);\n\n default:\n return <span>{notification.message}</span>;\n }\n };\n\n return (\n <div\n className={classes([\n 'b2b-quick-order-notification-banner',\n [\n `b2b-quick-order-notification-banner--${notification.variant}`,\n notification.variant,\n ],\n ])}\n >\n <AlertBanner\n variant={notification.variant}\n message={getMessage()}\n onDismiss={onDismiss}\n />\n </div>\n );\n};\n\nfunction renderClickableSkus(\n skus: string[],\n onSkuClick: (sku: string) => void\n) {\n return skus.map((sku, index) => (\n <span key={sku}>\n <a\n href=\"#\"\n onClick={(e) => {\n e.preventDefault();\n onSkuClick(sku);\n }}\n style={{\n cursor: 'pointer',\n textDecoration: 'underline',\n color: 'white',\n }}\n >\n {sku}\n </a>\n {index < skus.length - 1 ? ', ' : ''}\n </span>\n ));\n}\n\nfunction renderValidationMessage(\n baseMessage: string,\n clickableSkus: string[] | undefined,\n details: string | undefined,\n onSkuClick?: (sku: string) => void\n) {\n if (clickableSkus?.length && onSkuClick) {\n return (\n <span>\n {baseMessage} - {renderClickableSkus(clickableSkus, onSkuClick)}\n </span>\n );\n }\n\n return (\n <span>\n {baseMessage} - {details}\n </span>\n );\n}\n\nfunction renderPartialSuccessMessage(\n partialSuccessText: string | undefined,\n message: string,\n count: number | undefined,\n clickableSkus: string[] | undefined,\n onSkuClick?: (sku: string) => void\n) {\n if (!partialSuccessText) {\n return <span>{message}</span>;\n }\n\n const partialMessage = partialSuccessText\n .replace('{count}', String(count || 0))\n .replace('{total}', String((count || 0) + (clickableSkus?.length || 0)));\n\n if (clickableSkus?.length && onSkuClick) {\n return (\n <span>\n {partialMessage}: {renderClickableSkus(clickableSkus, onSkuClick)}\n </span>\n );\n }\n\n return (\n <span>\n {partialMessage}: {clickableSkus?.join(', ') || 'Unknown'}\n </span>\n );\n}\n\nfunction renderBackendErrorMessage(\n backendErrorText: string,\n details: string | undefined\n) {\n return (\n <span>\n {backendErrorText}\n {details ? ` - ${details}` : ''}\n </span>\n );\n}\n\nfunction renderSuccessMessage(successText: string, count: number | undefined) {\n if (count !== undefined) {\n return <span>{successText.replace('{count}', String(count))}</span>;\n }\n return <span>{successText}</span>;\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n QuickOrderItemsList,\n QuickOrderNotificationBanner,\n QuickOrderDisabledOverlay,\n} from '@/b2b-quick-order/components';\nimport { useQuickOrderItems } from '@/b2b-quick-order/hooks';\nimport { QuickOrderItemsProps } from '@/b2b-quick-order/types';\nimport { config } from '@/b2b-quick-order/api/initialize';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, Container } from '@adobe-commerce/elsie/lib';\nimport { useRef, useEffect } from 'preact/hooks';\n\nexport const QuickOrderItems: Container<QuickOrderItemsProps> = ({\n className,\n slots,\n getProductsData,\n handleAddToCart,\n productsSearch,\n searchFilter,\n}) => {\n const isQuickOrderActive = config.getConfig().quickOrderActive;\n const notificationRef = useRef<HTMLDivElement>(null);\n\n const t = useText({\n title: 'QuickOrder.QuickOrderItem.title',\n quantity: 'QuickOrder.QuickOrderItem.quantity',\n price: 'QuickOrder.QuickOrderItem.price',\n remove: 'QuickOrder.QuickOrderItem.remove',\n removeItem: 'QuickOrder.QuickOrderItem.removeItem',\n showOptions: 'QuickOrder.QuickOrderItem.showOptions',\n hideOptions: 'QuickOrder.QuickOrderItem.hideOptions',\n additionalOptions: 'QuickOrder.QuickOrderItem.additionalOptions',\n noAdditionalOptions: 'QuickOrder.QuickOrderItem.noAdditionalOptions',\n emptyList: 'QuickOrder.QuickOrderItem.emptyList',\n sku: 'QuickOrder.QuickOrderItem.sku',\n loading: 'QuickOrder.QuickOrderItem.loading',\n productNotFound: 'QuickOrder.QuickOrderItem.productNotFound',\n productNotFoundDescription:\n 'QuickOrder.QuickOrderItem.productNotFoundDescription',\n productOptions: 'QuickOrder.QuickOrderItem.productOptions',\n configurableProductError:\n 'QuickOrder.QuickOrderItem.configurableProductError',\n configurableProductErrorDescription:\n 'QuickOrder.QuickOrderItem.configurableProductErrorDescription',\n addAllToCart: 'QuickOrder.QuickOrderItem.addAllToCart',\n configurableOptionsWarning:\n 'QuickOrder.QuickOrderItem.configurableOptionsWarning',\n configurableOptionsWarningDescription:\n 'QuickOrder.QuickOrderItem.configurableOptionsWarningDescription',\n outOfStock: 'QuickOrder.QuickOrderItem.outOfStock',\n searchPlaceholder: 'QuickOrder.Search.placeholder',\n searchAriaLabel: 'QuickOrder.Search.ariaLabel',\n searchEmptyState: 'QuickOrder.Search.emptyState',\n resultsAvailable: 'QuickOrder.Search.resultsAvailable',\n resultAvailable: 'QuickOrder.Search.resultAvailable',\n srInstructions: 'QuickOrder.Search.srInstructions',\n notificationValidationError:\n 'QuickOrder.QuickOrderItem.notification.validationError',\n notificationBackendError:\n 'QuickOrder.QuickOrderItem.notification.backendError',\n notificationSuccess: 'QuickOrder.QuickOrderItem.notification.success',\n notificationPartialSuccess:\n 'QuickOrder.QuickOrderItem.notification.partialSuccess',\n disabledMessage: 'QuickOrder.QuickOrderItem.disabledMessage',\n });\n\n const {\n items,\n loading,\n removeItem,\n clearItems,\n updateItemQuantity,\n addToCart,\n isItemUpdating,\n setDisabledCartButton,\n isDisabledButton,\n notification,\n dismissNotification,\n } = useQuickOrderItems({\n getProductsData,\n handleAddToCart,\n });\n\n // Auto-scroll to notification banner when error appears\n useEffect(() => {\n if (\n notification &&\n notification.variant === 'warning' &&\n notificationRef.current\n ) {\n notificationRef.current.scrollIntoView({\n behavior: 'smooth',\n block: 'start',\n });\n }\n }, [notification]);\n\n const handleSkuClick = (sku: string) => {\n // Find the form element with matching data-sku attribute\n const formElement = document.querySelector(\n `form[data-sku=\"${sku}\"]`\n ) as HTMLElement;\n\n if (formElement) {\n // Scroll to the element with smooth behavior\n formElement.scrollIntoView({\n behavior: 'smooth',\n block: 'center',\n });\n }\n };\n\n return (\n <div\n className={classes([\n 'b2b-quick-order-quick-order-items',\n !isQuickOrderActive && 'b2b-quick-order-disabled',\n className,\n ])}\n data-testid=\"quick-order-items\"\n style={{ position: 'relative' }}\n >\n <div ref={notificationRef}>\n <QuickOrderNotificationBanner\n notification={notification}\n onDismiss={dismissNotification}\n onSkuClick={handleSkuClick}\n validationErrorText={t.notificationValidationError}\n backendErrorText={t.notificationBackendError}\n successText={t.notificationSuccess}\n partialSuccessText={t.notificationPartialSuccess}\n />\n </div>\n <QuickOrderDisabledOverlay\n isDisabled={!isQuickOrderActive}\n message={t.disabledMessage}\n >\n <QuickOrderItemsList\n t={t}\n items={items}\n onRemove={removeItem}\n clearItems={clearItems}\n onUpdateQuantity={updateItemQuantity}\n handleAddToCart={addToCart}\n isItemUpdating={isItemUpdating}\n slots={slots}\n loading={loading}\n setDisabledCartButton={setDisabledCartButton}\n isDisabledButton={isDisabledButton}\n productsSearch={productsSearch}\n searchFilter={searchFilter}\n />\n </QuickOrderDisabledOverlay>\n </div>\n );\n};\n"],"names":["STANDARD_FIELDS","processFormOptions","formData","optionUIDs","enteredOptions","value","key","valueStr","buildCartItem","quantityValue","quantity","cartItem","parentSku","DEFAULT_QUICK_ORDER_ITEM","mapProductsToOrderItems","requestedItems","products","requestedItem","foundProduct","p","validateOrderItems","items","item","opt","_a","optItem","option","optionItem","getInvalidItems","invalidItems","getItemScope","generateItemId","sku","findDuplicateItem","newItem","existing","findDuplicateItemExcluding","updatedItem","excludeItemId","mergeDuplicateItems","removeIndex","mergeIntoIndex","quantityToAdd","index","replaceOrAddItems","existingItems","newItems","inputItems","updatedItems","addedItems","replacedItems","mergedItems","inputItem","replaceIndex","existingIndex","adjustedIndex","itemWithId","updateItemInList","itemId","currentQuantity","duplicateIndex","removingIndex","prevItem","buildCartItemsFromForms","formId","form","extractOptionsUIDs","valuesData","optionsUIDs","getOptionsFromStorage","storageKey","stored","e","saveOptionsToStorage","storageData","enrichCartItemsWithOptions","cartItems","selectedOptions","isItemInvalid","hasBasicIssues","allRequiredSelected","hasSelectedOption","useQuickOrderItems","getProductsData","handleAddToCart","setItems","useState","loading","setLoading","updatingItems","setUpdatingItems","isDisabledButton","setIsDisabledButton","notification","setNotification","attemptedSkus","setAttemptedSkus","attemptedSkusRef","useRef","t","useText","STORAGE_KEY","dismissNotification","useCallback","setDisabledCartButton","disabled","useEffect","loadingEvent","events","loadingState","itemsEvent","eventPayload","requestedSkus","prev","fetchedProducts","error","invalidNewItems","invalidSkus","mergedSkus","prevItems","scope","scopesList","isValid","stillInvalidSkus","matchingItems","i","existingSkus","eventsList","event","successEvent","addedCount","addedSkus","failedSkus","errorEvent","cartDataEvent","cartData","cartSkus","skus","removeItem","identifier","clearItems","updateItemQuantity","isItemUpdating","addToCart","skusToAdd","enrichedCartItems","errorMessage","QuickOrderNotificationBanner","onDismiss","onSkuClick","validationErrorText","backendErrorText","successText","partialSuccessText","getMessage","renderValidationMessage","renderPartialSuccessMessage","renderBackendErrorMessage","renderSuccessMessage","jsx","classes","AlertBanner","renderClickableSkus","baseMessage","clickableSkus","details","message","count","partialMessage","QuickOrderItems","className","slots","productsSearch","searchFilter","isQuickOrderActive","config","notificationRef","handleSkuClick","formElement","jsxs","QuickOrderDisabledOverlay","QuickOrderItemsList"],"mappings":"gmBAiBA,MAAMA,GAAkB,CACtB,MACA,YACA,WACA,cACA,QACA,aACF,EAWaC,GACXC,GACyB,CACzB,MAAMC,EAAuB,CAAA,EACvBC,EAAmD,CAAA,EAEzD,OAAAF,EAAS,QAAQ,CAACG,EAAOC,IAAQ,CAC/B,GAAIN,GAAgB,SAASM,CAAG,EAAG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