@dropins/storefront-quick-order 0.1.2-alpha1 → 0.1.2-alpha2

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.
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2026 Adobe
2
2
  All Rights Reserved. */
3
- import{jsxs as w,jsx as t,Fragment as Q}from"@dropins/tools/preact-jsx-runtime.js";import{memo as F,useCallback as O,useState as V,useRef as D,useEffect as P,useMemo as L}from"@dropins/tools/preact-compat.js";import{InputFile as J,CartList as X,Divider as Y,Button as Z,CartItem as W,AccordionSection as U,Input as ee}from"@dropins/tools/components.js";import{Slot as T}from"@dropins/tools/lib.js";import{useState as H,useRef as re,useEffect as j,useMemo as te,useCallback as M}from"@dropins/tools/preact-hooks.js";import{events as ae}from"@dropins/tools/event-bus.js";const K=e=>e.reduce((a,s)=>{if(!s)return a;if(typeof s=="string"&&(a+=` ${s}`),Array.isArray(s)){const[o,n]=s;o&&n&&(a+=` ${o}`)}return a},"").trim(),se=({t:e,onFileUpload:r,error:a,fileName:s,onDownloadSample:o,showSampleDownload:n,disabled:l})=>{const u=O(m=>{var h;const b=(h=m.target.files)==null?void 0:h[0];b&&r(b)},[r]);return w("div",{className:"b2b-quick-order-csv-file-input",children:[t("div",{className:"b2b-quick-order-csv-file-input__title",children:e.title}),w("div",{className:"b2b-quick-order-csv-file-input__helper",children:[e.helperText,n&&t(Q,{children:t("button",{type:"button",className:"b2b-quick-order-csv-file-input__download-link",onClick:o,"data-testid":"download-sample",disabled:l,children:e.downloadSample})})]}),t("div",{className:`b2b-quick-order-csv-file-input__input-wrapper ${l?"b2b-quick-order-csv-file-input__input-wrapper--disabled":""}`,children:t(J,{id:"quick-order-csv-file-input",label:e.inputLabel,className:"b2b-quick-order-csv-file-input__input",onChange:u,accept:".csv",disabled:l})}),s&&w("div",{className:"b2b-quick-order-csv-file-input__file-name","data-testid":"file-name",children:[e.selectedFile,": ",s]}),a&&t("div",{className:"b2b-quick-order-csv-file-input__error","data-testid":"error-message",role:"alert",children:a})]})},$e=F(se),ne=(e,r)=>{let a;return function(...s){clearTimeout(a),a=setTimeout(()=>e.apply(this,s),r)}},ce=[{attribute:"visibility",in:["Search","Catalog, Search"]}],ie=e=>{const{containerRef:r,itemSelected:a,initialValue:s,currentValue:o,onValueRestore:n,onClose:l}=e,u=document.activeElement;(r==null?void 0:r.contains(u))||(l(),!a&&s!==o&&n(s))},le=(e,r=150)=>window.setTimeout(()=>{ie(e)},r),x=e=>{e&&clearTimeout(e)},ue=(e,r)=>r===0?-1:e<r-1?e+1:e,oe=e=>e>0?e-1:-1,de=()=>0,he=e=>Math.max(0,e-1),pe=(e,r,a)=>e>=0&&r[e]?(a(r[e]),!0):!1,be=(e,r,a,s)=>{a(e),s(),r&&"blur"in r&&typeof r.blur=="function"&&r.blur()},z=({productsSearch:e,initialSku:r,replaceItemSku:a,searchFilter:s=ce})=>{const[o,n]=H(r),[l,u]=H([]),[c,m]=H(!1),d=re(!0);j(()=>()=>{d.current=!1},[]),j(()=>{c||n(r)},[r,c]);const b=te(()=>ne(async f=>{if(!f||!e){d.current&&u([]);return}try{const k=await e({phrase:f,filter:s});d.current&&u(k.items||[])}catch(k){console.error("Error searching products:",k),d.current&&u([])}},300),[e,s]),h=M(f=>{const v=f.target.value;n(v),m(!0),b(v)},[b]),q=M(()=>{n(""),u([]),m(!1)},[]),y=M(f=>{const k={sku:f.sku,...f.variantSku&&{variantSku:f.variantSku},quantity:1,...a&&{replaceItemSku:a}};ae.emit("quick-order/add-items",[k]),q()},[a,q]);return{searchValue:o,searchResults:l,handleSearchChange:h,shouldShowResults:c,resetSearch:q,handleItemClick:y}},fe=({value:e,onChange:r,items:a,shouldShowResults:s=!0,onItemClick:o})=>{const[n,l]=V(-1),[u,c]=V(""),[m,d]=V(!1),[b,h]=V(!1),q=D(`search-results-${Math.random().toString(36).substr(2,9)}`),y=D(null),f=D([]),k=D(null),v=D(null),S=!!e&&!b,_=s&&S&&a.length>0,$=s&&S&&a.length===0;P(()=>{l(-1)},[a]),P(()=>()=>{x(v.current)},[]),P(()=>{if(n>=0&&f.current[n]){const p=f.current[n];p&&typeof p.scrollIntoView=="function"&&p.scrollIntoView({behavior:"smooth",block:"nearest"})}},[n]);const g=O(p=>{b&&h(!1),r==null||r(p)},[r,b]),N=O(p=>()=>{d(!0),h(!0),o==null||o(p),l(-1)},[o]),E=O(()=>{x(v.current),v.current=null,c(e||""),d(!1),h(!1)},[e]),B=O(()=>{v.current=le({containerRef:k.current,itemSelected:m,initialValue:u,currentValue:e||"",onValueRestore:p=>{r==null||r({target:{value:p}})},onClose:()=>{h(!0)}})},[m,u,e,r]),C=O(p=>{if(_)switch(p.key){case"ArrowDown":p.preventDefault(),l(i=>ue(i,a.length));break;case"ArrowUp":p.preventDefault(),l(i=>oe(i));break;case"Home":_&&a.length>0&&(p.preventDefault(),l(de()));break;case"End":_&&a.length>0&&(p.preventDefault(),l(he(a.length)));break;case"Tab":x(v.current),v.current=null,h(!0),r==null||r({target:{value:u}});break;case"Enter":{pe(n,a,A=>{d(!0),h(!0),o==null||o(A),l(-1)})&&p.preventDefault();break}case"Escape":p.preventDefault(),be(u,y.current,i=>{r==null||r({target:{value:i}}),l(-1),h(!0)},()=>{h(!0)});break}},[_,a,n,o,r,u]),I=O(()=>{if(n>=0&&_)return`${q.current}-item-${n}`},[n,_]);return{activeIndex:n,showResults:_,showEmptyState:$,resultsId:q,inputRef:y,itemRefs:f,containerRef:k,handleChange:g,handleFocus:E,handleBlur:B,handleKeyDown:C,createItemClickHandler:N,getActiveDescendant:I}},me=({t:e,items:r,onRemove:a,clearItems:s,onUpdateQuantity:o,slots:n,handleAddToCart:l,isItemUpdating:u,loading:c,isDisabledButton:m,productsSearch:d,searchFilter:b})=>{const{searchValue:h,searchResults:q,handleSearchChange:y,shouldShowResults:f,handleItemClick:k}=z({productsSearch:d,initialSku:"",searchFilter:b});return w("div",{className:K(["b2b-quick-order-form-quick-order-items-list"]),role:"region","aria-label":e.title,children:[t("div",{className:"b2b-quick-order-form-quick-order-items-list__title",children:e.title}),r.length>0&&w(Q,{children:[t(X,{role:"list",className:"b2b-quick-order-form-quick-order-items-list__list",children:r.map(v=>t(ve,{item:v,t:e,onRemove:a,onUpdateQuantity:o,isUpdating:u==null?void 0:u(v.sku),loading:c,productsSearch:d,searchFilter:b,slots:n},v.sku))}),t(Y,{variant:"secondary"})]}),t("div",{className:"b2b-quick-order-form-quick-order-items-list__global-search",children:t(G,{t:e,onChange:y,items:q,value:h,shouldShowResults:f,onItemClick:k,className:"b2b-quick-order-form-quick-order-items-list__search"})}),r.length===0&&t("div",{className:"b2b-quick-order-form-quick-order-items-list__empty","data-testid":"empty-items",children:e.emptyList}),t(T,{slot:n==null?void 0:n.AddAllToCartButton,name:"AddAllToCartButton",context:{handleAddToCart:l,clearItems:s,loading:c,isDisabledButton:m},"data-testid":"addAllToCart",children:t("div",{className:"b2b-quick-order-form-quick-order-items-list__actions",children:t(Z,{variant:"primary",onClick:l,"data-testid":"add-all-to-cart-button",disabled:c||m,children:e.addAllToCart})})})]})},Ee=F(me),ke=({item:e,t:r,onRemove:a,onUpdateQuantity:s,isUpdating:o,loading:n,productsSearch:l,searchFilter:u,slots:c})=>{var I,p;const m=`quick-order-item-${e.id||e.variantSku||e.sku}`,d=(e==null?void 0:e.variantSku)??(e==null?void 0:e.sku),{searchValue:b,searchResults:h,handleSearchChange:q,shouldShowResults:y,handleItemClick:f}=z({productsSearch:l,initialSku:d,replaceItemSku:e.sku,searchFilter:u}),k=`form-${e.id||d}`,v=e.inStock&&e.addToCartAllowed,S=e.options&&e.options.length>0,_=L(()=>S&&e.options.some(i=>i.required),[S,e.options]),$=L(()=>S&&e.options.some(i=>i.items&&i.items.some(A=>A.selected)),[S,e.options]),g=L(()=>_?e.options.every(i=>i.required?i.items&&i.items.some(A=>A.selected):!0):$,[_,$,e.options]),N=L(()=>{var i;return(i=e.images)==null?void 0:i.find(A=>{var R;return(R=A.roles)==null?void 0:R.includes("image")})},[e.images]),E=O(()=>{a==null||a(e.id||e.sku)},[a,e.id,e.sku]),B=O(i=>{s==null||s(e.sku,i);const A=document.forms[k];if(A){const R=A.querySelector('input[name="quantity"]');R&&(R.value=String(i))}},[s,e.sku,k]),C=t(T,{name:"QuickOrderItemSearch",slot:c==null?void 0:c.QuickOrderItemSearch,context:{item:e,scope:m,handleSearchChange:q,searchResults:h,searchValue:b,shouldShowResults:y,handleItemClick:f},children:t(G,{t:r,onChange:q,items:h,value:b,shouldShowResults:y,className:"b2b-quick-order-form-quick-order-items__item-search",onItemClick:f,slots:c})});return!e.name&&!((I=e.images)!=null&&I.length)?w("form",{name:k,className:"b2b-quick-order-form-quick-order-items__item-form",onSubmit:i=>i.preventDefault(),"data-sku":e.sku,children:[t("input",{type:"hidden",name:"sku",value:e.sku}),t("input",{type:"hidden",name:"quantity",value:e.quantity}),t("input",{type:"hidden",name:"valid",value:"false"}),t("input",{type:"hidden",name:"productType",value:""}),C,t(W,{sku:t("span",{children:e.sku}),title:t("span",{children:r.productNotFound}),quantity:e.quantity,alert:t("div",{className:"b2b-quick-order-items__error",children:(p=r.productNotFoundDescription)==null?void 0:p.replace("{sku}",e.sku)}),disabled:n,onRemove:E,ariaLabel:`${r.productNotFound} - ${e.sku}`})]},e.sku):w("form",{name:k,className:"b2b-quick-order-form-quick-order-items__item-form",onSubmit:i=>i.preventDefault(),"data-sku":d,children:[t("input",{type:"hidden",name:"sku",value:d}),t("input",{type:"hidden",name:"quantity",value:e.quantity}),t("input",{type:"hidden",name:"valid",value:v?"true":"false"}),t("input",{type:"hidden",name:"productType",value:e.productType||""}),C,t(W,{title:t("span",{children:e.name}),sku:t("span",{children:d}),image:N?t("img",{src:N.url,alt:N.label||e.name}):void 0,price:t(T,{name:"ProductPrice",slot:c==null?void 0:c.ProductPrice,context:{item:e,scope:m}}),quantity:e.quantity,alert:e.inStock===!1?t("div",{className:"b2b-quick-order-items__alert",children:r.outOfStock}):void 0,warning:S&&!g?t("div",{className:"b2b-quick-order-items__warning",children:r.configurableOptionsWarning}):void 0,footer:S?t(U,{title:r.productOptions,ariaLabelTitle:r.productOptions,defaultOpen:!g,className:"b2b-quick-order-list-item__accordion",actionIconPosition:"left",children:t(T,{name:"ProductOptions",slot:c==null?void 0:c.ProductOptions,context:{item:e,scope:m},children:t("div",{className:"b2b-quick-order-items__configurable-error",children:r.configurableProductErrorDescription})})}):void 0,updating:o,disabled:n,loading:n,onRemove:E,onQuantity:B,ariaLabel:`${e.name} - ${e.sku}`})]},d)},ve=F(ke),qe={cursor:"pointer"},_e={cursor:"default"},ye=({t:e,value:r,onChange:a,items:s,shouldShowResults:o=!0,className:n,onItemClick:l,slots:u})=>{const{activeIndex:c,showResults:m,showEmptyState:d,resultsId:b,inputRef:h,itemRefs:q,containerRef:y,handleChange:f,handleFocus:k,handleBlur:v,handleKeyDown:S,createItemClickHandler:_,getActiveDescendant:$}=fe({value:r,onChange:a,items:s,shouldShowResults:o,onItemClick:l});return w("div",{ref:y,className:K(["b2b-quick-order-search",n]),children:[t(ee,{ref:h,className:"b2b-quick-order-search__input",value:r,onChange:f,onFocus:k,onBlur:v,placeholder:e.searchPlaceholder,"aria-label":e.searchAriaLabel,role:"combobox","aria-autocomplete":"list","aria-expanded":m,"aria-controls":b.current,"aria-activedescendant":$(),onKeyDown:S}),m&&t("div",{id:b.current,role:"listbox",className:"b2b-quick-order-search__results","aria-label":e.searchAriaLabel,children:s.map((g,N)=>t(T,{slot:u==null?void 0:u.QuickOrderSearchAutocompleteItem,name:"QuickOrderSearchAutocompleteItem",context:{item:g,index:N,createItemClickHandler:_,activeIndex:c},children:t("div",{id:`${b.current}-item-${N}`,ref:E=>q.current[N]=E,role:"option","aria-selected":N===c,className:K(["b2b-quick-order-search__result-item",N===c&&"b2b-quick-order-search__result-item--active"]),onClick:_(g),style:l?qe:_e,children:`${g.sku} ${g.name}`})},g.sku))}),d&&t("div",{className:"b2b-quick-order-search__empty-state",role:"status","aria-live":"polite",children:e.searchEmptyState}),m&&w("div",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:[s.length," ",s.length===1?e.resultAvailable:e.resultsAvailable,"."," ",e.srInstructions]})]})},G=F(ye),Re=({isDisabled:e,message:r,children:a})=>w("div",{className:"b2b-quick-order-disabled-overlay",children:[t("div",{className:"b2b-quick-order-disabled-overlay__content",style:{pointerEvents:e?"none":"auto"},children:a}),e&&w(Q,{children:[t("div",{className:"b2b-quick-order-disabled-overlay__blur"}),t("div",{className:"b2b-quick-order-disabled-overlay__message",children:r})]})]});export{$e as C,Re as Q,Ee as a,K as c,ne as d};
3
+ import{jsxs as w,jsx as t,Fragment as Q}from"@dropins/tools/preact-jsx-runtime.js";import{memo as F,useCallback as O,useState as V,useRef as T,useEffect as x,useMemo as L}from"@dropins/tools/preact-compat.js";import{InputFile as J,CartList as X,Divider as Y,Button as Z,CartItem as W,AccordionSection as U,PriceRange as ee,Input as re}from"@dropins/tools/components.js";import{Slot as D}from"@dropins/tools/lib.js";import{useState as B,useRef as te,useEffect as j,useMemo as ae,useCallback as H}from"@dropins/tools/preact-hooks.js";import{events as se}from"@dropins/tools/event-bus.js";const K=e=>e.reduce((a,s)=>{if(!s)return a;if(typeof s=="string"&&(a+=` ${s}`),Array.isArray(s)){const[i,n]=s;i&&n&&(a+=` ${i}`)}return a},"").trim(),ne=({t:e,onFileUpload:r,error:a,fileName:s,onDownloadSample:i,showSampleDownload:n,disabled:u})=>{const o=O(m=>{var h;const f=(h=m.target.files)==null?void 0:h[0];f&&r(f)},[r]);return w("div",{className:"b2b-quick-order-csv-file-input",children:[t("div",{className:"b2b-quick-order-csv-file-input__title",children:e.title}),w("div",{className:"b2b-quick-order-csv-file-input__helper",children:[e.helperText,n&&t(Q,{children:t("button",{type:"button",className:"b2b-quick-order-csv-file-input__download-link",onClick:i,"data-testid":"download-sample",disabled:u,children:e.downloadSample})})]}),t("div",{className:`b2b-quick-order-csv-file-input__input-wrapper ${u?"b2b-quick-order-csv-file-input__input-wrapper--disabled":""}`,children:t(J,{id:"quick-order-csv-file-input",label:e.inputLabel,className:"b2b-quick-order-csv-file-input__input",onChange:o,accept:".csv",disabled:u})}),s&&w("div",{className:"b2b-quick-order-csv-file-input__file-name","data-testid":"file-name",children:[e.selectedFile,": ",s]}),a&&t("div",{className:"b2b-quick-order-csv-file-input__error","data-testid":"error-message",role:"alert",children:a})]})},Re=F(ne),ce=(e,r)=>{let a;const s=function(...i){clearTimeout(a),a=setTimeout(()=>e.apply(this,i),r)};return s.cancel=()=>{clearTimeout(a)},s},ie=[{attribute:"visibility",in:["Search","Catalog, Search"]}],le=e=>{const{containerRef:r,itemSelected:a,initialValue:s,currentValue:i,onValueRestore:n,onClose:u}=e,o=document.activeElement;(r==null?void 0:r.contains(o))||(u(),!a&&s!==i&&n(s))},ue=(e,r=150)=>window.setTimeout(()=>{le(e)},r),M=e=>{e&&clearTimeout(e)},oe=(e,r)=>r===0?-1:e<r-1?e+1:e,de=e=>e>0?e-1:-1,he=()=>0,pe=e=>Math.max(0,e-1),fe=(e,r,a)=>e>=0&&r[e]?(a(r[e]),!0):!1,be=(e,r,a,s)=>{a(e),s(),r&&"blur"in r&&typeof r.blur=="function"&&r.blur()},z=({productsSearch:e,initialSku:r,replaceItemSku:a,searchFilter:s=ie})=>{const[i,n]=B(r),[u,o]=B([]),[c,m]=B(!1),d=te(!0);j(()=>()=>{d.current=!1},[]),j(()=>{c||n(r)},[r,c]);const f=ae(()=>ce(async b=>{if(!b||!e){d.current&&o([]);return}try{const k=await e({phrase:b,filter:s});d.current&&o(k.items||[])}catch(k){console.error("Error searching products:",k),d.current&&o([])}},300),[e,s]),h=H(b=>{const v=b.target.value;n(v),m(!0),f(v)},[f]),q=H(()=>{n(""),o([]),m(!1)},[]),_=H(b=>{const k={sku:b.sku,...b.variantSku&&{variantSku:b.variantSku},quantity:1,...a&&{replaceItemSku:a}};se.emit("quick-order/add-items",[k]),q()},[a,q]);return{searchValue:i,searchResults:u,handleSearchChange:h,shouldShowResults:c,resetSearch:q,handleItemClick:_}},me=({value:e,onChange:r,items:a,shouldShowResults:s=!0,onItemClick:i})=>{const[n,u]=V(-1),[o,c]=V(""),[m,d]=V(!1),[f,h]=V(!1),q=T(`search-results-${Math.random().toString(36).substr(2,9)}`),_=T(null),b=T([]),k=T(null),v=T(null),S=!!e&&!f,y=s&&S&&a.length>0,$=s&&S&&a.length===0;x(()=>{u(-1)},[a]),x(()=>()=>{M(v.current)},[]),x(()=>{if(n>=0&&b.current[n]){const p=b.current[n];p&&typeof p.scrollIntoView=="function"&&p.scrollIntoView({behavior:"smooth",block:"nearest"})}},[n]);const g=O(p=>{f&&h(!1),r==null||r(p)},[r,f]),N=O(p=>()=>{d(!0),h(!0),i==null||i(p),u(-1)},[i]),R=O(()=>{M(v.current),v.current=null,c(e||""),d(!1),h(!1)},[e]),P=O(()=>{v.current=ue({containerRef:k.current,itemSelected:m,initialValue:o,currentValue:e||"",onValueRestore:p=>{r==null||r({target:{value:p}})},onClose:()=>{h(!0)}})},[m,o,e,r]),C=O(p=>{if(y)switch(p.key){case"ArrowDown":p.preventDefault(),u(l=>oe(l,a.length));break;case"ArrowUp":p.preventDefault(),u(l=>de(l));break;case"Home":y&&a.length>0&&(p.preventDefault(),u(he()));break;case"End":y&&a.length>0&&(p.preventDefault(),u(pe(a.length)));break;case"Tab":M(v.current),v.current=null,h(!0),r==null||r({target:{value:o}});break;case"Enter":{fe(n,a,A=>{d(!0),h(!0),i==null||i(A),u(-1)})&&p.preventDefault();break}case"Escape":p.preventDefault(),be(o,_.current,l=>{r==null||r({target:{value:l}}),u(-1),h(!0)},()=>{h(!0)});break}},[y,a,n,i,r,o]),I=O(()=>{if(n>=0&&y)return`${q.current}-item-${n}`},[n,y]);return{activeIndex:n,showResults:y,showEmptyState:$,resultsId:q,inputRef:_,itemRefs:b,containerRef:k,handleChange:g,handleFocus:R,handleBlur:P,handleKeyDown:C,createItemClickHandler:N,getActiveDescendant:I}},ke=({t:e,items:r,onRemove:a,clearItems:s,onUpdateQuantity:i,slots:n,handleAddToCart:u,isItemUpdating:o,loading:c,isDisabledButton:m,productsSearch:d,searchFilter:f})=>{const{searchValue:h,searchResults:q,handleSearchChange:_,shouldShowResults:b,handleItemClick:k}=z({productsSearch:d,initialSku:"",searchFilter:f});return w("div",{className:K(["b2b-quick-order-form-quick-order-items-list"]),role:"region","aria-label":e.title,children:[t("div",{className:"b2b-quick-order-form-quick-order-items-list__title",children:e.title}),r.length>0&&w(Q,{children:[t(X,{role:"list",className:"b2b-quick-order-form-quick-order-items-list__list",children:r.map(v=>t(qe,{item:v,t:e,onRemove:a,onUpdateQuantity:i,isUpdating:o==null?void 0:o(v.sku),loading:c,productsSearch:d,searchFilter:f,slots:n},v.sku))}),t(Y,{variant:"secondary"})]}),t("div",{className:"b2b-quick-order-form-quick-order-items-list__global-search",children:t(G,{t:e,onChange:_,items:q,value:h,shouldShowResults:b,onItemClick:k,className:"b2b-quick-order-form-quick-order-items-list__search"})}),r.length===0&&t("div",{className:"b2b-quick-order-form-quick-order-items-list__empty","data-testid":"empty-items",children:e.emptyList}),t(D,{slot:n==null?void 0:n.AddAllToCartButton,name:"AddAllToCartButton",context:{handleAddToCart:u,clearItems:s,loading:c,isDisabledButton:m},"data-testid":"addAllToCart",children:t("div",{className:"b2b-quick-order-form-quick-order-items-list__actions",children:t(Z,{variant:"primary",onClick:u,"data-testid":"add-all-to-cart-button",disabled:c||m,children:e.addAllToCart})})})]})},Ee=F(ke),ve=({item:e,t:r,onRemove:a,onUpdateQuantity:s,isUpdating:i,loading:n,productsSearch:u,searchFilter:o,slots:c})=>{var I,p;const m=`quick-order-item-${e.id||e.variantSku||e.sku}`,d=(e==null?void 0:e.variantSku)??(e==null?void 0:e.sku),{searchValue:f,searchResults:h,handleSearchChange:q,shouldShowResults:_,handleItemClick:b}=z({productsSearch:u,initialSku:d,replaceItemSku:e.sku,searchFilter:o}),k=`form-${e.id||d}`,v=e.inStock&&e.addToCartAllowed,S=e.options&&e.options.length>0,y=L(()=>S&&e.options.some(l=>l.required),[S,e.options]),$=L(()=>S&&e.options.some(l=>l.items&&l.items.some(A=>A.selected)),[S,e.options]),g=L(()=>y?e.options.every(l=>l.required?l.items&&l.items.some(A=>A.selected):!0):$,[y,$,e.options]),N=L(()=>{var l;return(l=e.images)==null?void 0:l.find(A=>{var E;return(E=A.roles)==null?void 0:E.includes("image")})},[e.images]),R=O(()=>{a==null||a(e.id||e.sku)},[a,e.id,e.sku]),P=O(l=>{s==null||s(e.sku,l);const A=document.forms[k];if(A){const E=A.querySelector('input[name="quantity"]');E&&(E.value=String(l))}},[s,e.sku,k]),C=t(D,{name:"QuickOrderItemSearch",slot:c==null?void 0:c.QuickOrderItemSearch,context:{item:e,scope:m,handleSearchChange:q,searchResults:h,searchValue:f,shouldShowResults:_,handleItemClick:b},children:t(G,{t:r,onChange:q,items:h,value:f,shouldShowResults:_,className:"b2b-quick-order-form-quick-order-items__item-search",onItemClick:b,slots:c})});return!e.name&&!((I=e.images)!=null&&I.length)?w("form",{name:k,className:"b2b-quick-order-form-quick-order-items__item-form",onSubmit:l=>l.preventDefault(),"data-sku":e.sku,children:[t("input",{type:"hidden",name:"sku",value:e.sku}),t("input",{type:"hidden",name:"quantity",value:e.quantity}),t("input",{type:"hidden",name:"valid",value:"false"}),t("input",{type:"hidden",name:"productType",value:""}),C,t(W,{sku:t("span",{children:e.sku}),title:t("span",{children:r.productNotFound}),quantity:e.quantity,alert:t("div",{className:"b2b-quick-order-items__error",children:(p=r.productNotFoundDescription)==null?void 0:p.replace("{sku}",e.sku)}),disabled:n,onRemove:R,ariaLabel:`${r.productNotFound} - ${e.sku}`})]},e.sku):w("form",{name:k,className:"b2b-quick-order-form-quick-order-items__item-form",onSubmit:l=>l.preventDefault(),"data-sku":d,children:[t("input",{type:"hidden",name:"sku",value:d}),t("input",{type:"hidden",name:"quantity",value:e.quantity}),t("input",{type:"hidden",name:"valid",value:v?"true":"false"}),t("input",{type:"hidden",name:"productType",value:e.productType||""}),C,t(W,{title:t("span",{children:e.name}),sku:t("span",{children:d}),image:N?t("img",{src:N.url,alt:N.label||e.name}):void 0,price:t(D,{name:"ProductPrice",slot:c==null?void 0:c.ProductPrice,context:{item:e,scope:m},children:t(ee,{minimumAmount:e.prices.final.minimumAmount,maximumAmount:e.prices.final.maximumAmount,amount:e.prices.final.amount,currency:e.prices.final.currency})}),quantity:e.quantity,alert:e.inStock===!1?t("div",{className:"b2b-quick-order-items__alert",children:r.outOfStock}):void 0,warning:S&&!g?t("div",{className:"b2b-quick-order-items__warning",children:r.configurableOptionsWarning}):void 0,footer:S?t(U,{title:r.productOptions,ariaLabelTitle:r.productOptions,defaultOpen:!g,className:"b2b-quick-order-list-item__accordion",actionIconPosition:"left",children:t(D,{name:"ProductOptions",slot:c==null?void 0:c.ProductOptions,context:{item:e,scope:m},children:t("div",{className:"b2b-quick-order-items__configurable-error",children:r.configurableProductErrorDescription})})}):void 0,updating:i,disabled:n,loading:n,onRemove:R,onQuantity:P,ariaLabel:`${e.name} - ${e.sku}`})]},d)},qe=F(ve),ye={cursor:"pointer"},_e={cursor:"default"},Se=({t:e,value:r,onChange:a,items:s,shouldShowResults:i=!0,className:n,onItemClick:u,slots:o})=>{const{activeIndex:c,showResults:m,showEmptyState:d,resultsId:f,inputRef:h,itemRefs:q,containerRef:_,handleChange:b,handleFocus:k,handleBlur:v,handleKeyDown:S,createItemClickHandler:y,getActiveDescendant:$}=me({value:r,onChange:a,items:s,shouldShowResults:i,onItemClick:u});return w("div",{ref:_,className:K(["b2b-quick-order-search",n]),children:[t(re,{ref:h,className:"b2b-quick-order-search__input",value:r,onChange:b,onFocus:k,onBlur:v,placeholder:e.searchPlaceholder,"aria-label":e.searchAriaLabel,role:"combobox","aria-autocomplete":"list","aria-expanded":m,"aria-controls":f.current,"aria-activedescendant":$(),onKeyDown:S}),m&&t("div",{id:f.current,role:"listbox",className:"b2b-quick-order-search__results","aria-label":e.searchAriaLabel,children:s.map((g,N)=>t(D,{slot:o==null?void 0:o.QuickOrderSearchAutocompleteItem,name:"QuickOrderSearchAutocompleteItem",context:{item:g,index:N,createItemClickHandler:y,activeIndex:c},children:t("div",{id:`${f.current}-item-${N}`,ref:R=>q.current[N]=R,role:"option","aria-selected":N===c,className:K(["b2b-quick-order-search__result-item",N===c&&"b2b-quick-order-search__result-item--active"]),onClick:y(g),style:u?ye:_e,children:`${g.sku} ${g.name}`})},g.sku))}),d&&t("div",{className:"b2b-quick-order-search__empty-state",role:"status","aria-live":"polite",children:e.searchEmptyState}),m&&w("div",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:[s.length," ",s.length===1?e.resultAvailable:e.resultsAvailable,"."," ",e.srInstructions]})]})},G=F(Se),Te=({isDisabled:e,message:r,children:a})=>w("div",{className:"b2b-quick-order-disabled-overlay",children:[t("div",{className:"b2b-quick-order-disabled-overlay__content",style:{pointerEvents:e?"none":"auto"},children:a}),e&&w(Q,{children:[t("div",{className:"b2b-quick-order-disabled-overlay__blur"}),t("div",{className:"b2b-quick-order-disabled-overlay__message",children:r})]})]});export{Re as C,Te as Q,Ee as a,K as c,ce as d};
4
4
  //# sourceMappingURL=QuickOrderDisabledOverlay.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"QuickOrderDisabledOverlay.js","sources":["../../node_modules/@adobe-commerce/elsie/src/lib/classes.ts","/@dropins/storefront-quick-order/src/components/CsvFileInput/CsvFileInput.tsx","../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-quick-order/src/configs/search-filter.config.ts","/@dropins/storefront-quick-order/src/lib/searchBlurHandler.ts","/@dropins/storefront-quick-order/src/lib/searchKeyboardNavigation.ts","/@dropins/storefront-quick-order/src/hooks/useItemSearch.tsx","/@dropins/storefront-quick-order/src/hooks/useSearch.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderItemsList/QuickOrderItemsList.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderListItem/QuickOrderListItem.tsx","/@dropins/storefront-quick-order/src/components/Search/Search.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderDisabledOverlay/QuickOrderDisabledOverlay.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\n// @ts-ignore\nimport { JSXInternal } from 'preact/src/jsx';\n\ntype ClassName = string | JSXInternal.SignalLike<string | undefined>;\n\nexport const classes = (\n classes: Array<ClassName | [ClassName, boolean] | undefined>\n) => {\n const result = classes.reduce((result, item) => {\n if (!item) return result;\n\n if (typeof item === 'string') result += ` ${item}`;\n\n if (Array.isArray(item)) {\n const [className, isActive] = item;\n if (className && isActive) {\n result += ` ${className}`;\n }\n }\n\n return result;\n }, '') as string;\n\n return result.trim();\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, useCallback, memo } from 'preact/compat';\nimport { InputFile } from '@adobe-commerce/elsie/components';\nimport { CsvFileInputProps } from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport '@/b2b-quick-order/components/CsvFileInput/CsvFileInput.css';\n\nconst CsvFileInputComponent: FunctionComponent<CsvFileInputProps> = ({\n t,\n onFileUpload,\n error,\n fileName,\n onDownloadSample,\n showSampleDownload,\n disabled,\n}) => {\n const handleFileChange = useCallback(\n (e: Event) => {\n const target = e.target as HTMLInputElement;\n const file = target.files?.[0];\n if (file) {\n onFileUpload(file);\n }\n },\n [onFileUpload]\n );\n\n const inputClassName = 'b2b-quick-order-csv-file-input__input';\n\n return (\n <div className=\"b2b-quick-order-csv-file-input\">\n <div className=\"b2b-quick-order-csv-file-input__title\">{t.title}</div>\n\n <div className=\"b2b-quick-order-csv-file-input__helper\">\n {t.helperText}\n {showSampleDownload && (\n <>\n <button\n type=\"button\"\n className=\"b2b-quick-order-csv-file-input__download-link\"\n onClick={onDownloadSample}\n data-testid=\"download-sample\"\n disabled={disabled}\n >\n {t.downloadSample}\n </button>\n </>\n )}\n </div>\n\n <div\n className={`b2b-quick-order-csv-file-input__input-wrapper ${\n disabled\n ? 'b2b-quick-order-csv-file-input__input-wrapper--disabled'\n : ''\n }`}\n >\n <InputFile\n id={'quick-order-csv-file-input'}\n label={t.inputLabel}\n className={inputClassName}\n onChange={handleFileChange}\n accept={'.csv'}\n disabled={disabled}\n />\n </div>\n\n {fileName && (\n <div\n className=\"b2b-quick-order-csv-file-input__file-name\"\n data-testid=\"file-name\"\n >\n {t.selectedFile}: {fileName}\n </div>\n )}\n\n {error && (\n <div\n className=\"b2b-quick-order-csv-file-input__error\"\n data-testid=\"error-message\"\n role=\"alert\"\n >\n {error}\n </div>\n )}\n </div>\n );\n};\n\nexport const CsvFileInput = memo(CsvFileInputComponent);\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n return function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n};\n","export const SEARCH_FILTER = [\n {\n attribute: 'visibility',\n in: ['Search', 'Catalog, Search'],\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\nexport interface BlurHandlerOptions {\n containerRef: HTMLElement | null;\n itemSelected: boolean;\n initialValue: string;\n currentValue: string;\n onValueRestore: (value: string) => void;\n onClose: () => void;\n}\n\n/**\n * Handles blur logic for search component\n * Checks if focus moved outside component and restores initial value if needed\n */\nexport const handleSearchBlur = (options: BlurHandlerOptions): void => {\n const {\n containerRef,\n itemSelected,\n initialValue,\n currentValue,\n onValueRestore,\n onClose,\n } = options;\n\n const activeElement = document.activeElement;\n const isWithinComponent = containerRef?.contains(activeElement);\n\n if (!isWithinComponent) {\n onClose();\n\n if (!itemSelected && initialValue !== currentValue) {\n onValueRestore(initialValue);\n }\n }\n};\n\n/**\n * Creates a blur handler with timeout\n */\nexport const createBlurHandler = (\n options: BlurHandlerOptions,\n delay: number = 150\n): number => {\n return window.setTimeout(() => {\n handleSearchBlur(options);\n }, delay);\n};\n\n/**\n * Clears blur timeout if exists\n */\nexport const clearBlurTimeout = (timeoutRef: number | null): void => {\n if (timeoutRef) {\n clearTimeout(timeoutRef);\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 * WCAG 2.1 compliant keyboard navigation for combobox with listbox pattern.\n * Focus always remains on the input element, visual indication via aria-activedescendant.\n * Reference: https://www.w3.org/WAI/ARIA/apg/patterns/combobox/\n */\n\n/**\n * Calculates next active index when ArrowDown is pressed\n * Returns next index in list or current if at end\n */\nexport const handleArrowDown = (\n currentIndex: number,\n itemsLength: number\n): number => {\n if (itemsLength === 0) return -1;\n return currentIndex < itemsLength - 1 ? currentIndex + 1 : currentIndex;\n};\n\n/**\n * Calculates next active index when ArrowUp is pressed\n * Returns previous index or -1 to return focus to input\n */\nexport const handleArrowUp = (currentIndex: number): number => {\n return currentIndex > 0 ? currentIndex - 1 : -1;\n};\n\n/**\n * Moves visual focus to first item in list (Home key)\n */\nexport const handleHomeKey = (): number => {\n return 0;\n};\n\n/**\n * Moves visual focus to last item in list (End key)\n */\nexport const handleEndKey = (itemsLength: number): number => {\n return Math.max(0, itemsLength - 1);\n};\n\n/**\n * Handles Enter key press on active item\n * Returns true if item was selected, false otherwise\n */\nexport const handleEnterKey = <T>(\n activeIndex: number,\n items: T[],\n onItemSelect: (item: T) => void\n): boolean => {\n if (activeIndex >= 0 && items[activeIndex]) {\n onItemSelect(items[activeIndex]);\n return true;\n }\n return false;\n};\n\n/**\n * Handles Escape key press - restores initial value and closes results\n */\nexport const handleEscapeKey = (\n initialValue: string,\n inputRef: HTMLElement | null,\n onValueRestore: (value: string) => void,\n onClose: () => void\n): void => {\n onValueRestore(initialValue);\n onClose();\n if (inputRef && 'blur' in inputRef && typeof inputRef.blur === 'function') {\n inputRef.blur();\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 {\n useCallback,\n useState,\n useMemo,\n useRef,\n useEffect,\n} from 'preact/hooks';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\nimport { OrderItem, UseItemSearchProps } from '@/b2b-quick-order/types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { SEARCH_FILTER } from '@/b2b-quick-order/configs';\n\nexport const useItemSearch = ({\n productsSearch,\n initialSku,\n replaceItemSku,\n searchFilter = SEARCH_FILTER,\n}: UseItemSearchProps) => {\n const [searchValue, setSearchValue] = useState(initialSku);\n const [searchResults, setSearchResults] = useState<OrderItem[]>([]);\n const [isTouched, setIsTouched] = useState(false);\n\n // Track if component is mounted to prevent state updates after unmount\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n // Update search value when initialSku changes (e.g., after merge)\n useEffect(() => {\n if (!isTouched) {\n setSearchValue(initialSku);\n }\n }, [initialSku, isTouched]);\n\n const debouncedSearch = useMemo(\n () =>\n debounce(async (searchTerm: string) => {\n if (!searchTerm || !productsSearch) {\n if (isMountedRef.current) {\n setSearchResults([]);\n }\n return;\n }\n\n try {\n const result = await productsSearch({\n phrase: searchTerm,\n filter: searchFilter,\n });\n if (isMountedRef.current) {\n setSearchResults(result.items || []);\n }\n } catch (error) {\n console.error('Error searching products:', error);\n if (isMountedRef.current) {\n setSearchResults([]);\n }\n }\n }, 300),\n [productsSearch, searchFilter]\n );\n\n const handleSearchChange = useCallback(\n (e: Event) => {\n const target = e.target as HTMLInputElement;\n const value = target.value;\n setSearchValue(value);\n setIsTouched(true);\n debouncedSearch(value);\n },\n [debouncedSearch]\n );\n\n const resetSearch = useCallback(() => {\n setSearchValue('');\n setSearchResults([]);\n setIsTouched(false);\n }, []);\n\n const handleItemClick = useCallback(\n (clickedItem: OrderItem) => {\n // Build item data for emission\n // Just send the data as-is from the search result\n // The deduplication logic will handle matching correctly\n const itemData = {\n sku: clickedItem.sku,\n ...(clickedItem.variantSku && { variantSku: clickedItem.variantSku }),\n quantity: 1,\n ...(replaceItemSku && { replaceItemSku }),\n };\n\n events.emit('quick-order/add-items', [itemData]);\n resetSearch();\n },\n [replaceItemSku, resetSearch]\n );\n\n return {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults: isTouched,\n resetSearch,\n handleItemClick,\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 React, { useCallback, useState, useRef, useEffect } from 'preact/compat';\nimport { SearchItem } from '@/b2b-quick-order/types/search.types';\nimport {\n createBlurHandler,\n clearBlurTimeout,\n handleArrowDown,\n handleArrowUp,\n handleEnterKey,\n handleEscapeKey,\n handleHomeKey,\n handleEndKey,\n} from '@/b2b-quick-order/lib';\n\nexport interface UseSearchOptions<T extends SearchItem> {\n value: string;\n onChange?: (e: any) => void;\n items: T[];\n shouldShowResults?: boolean;\n onItemClick?: (item: T) => void;\n}\n\nexport interface UseSearchReturn<T extends SearchItem> {\n // State\n activeIndex: number;\n showResults: boolean;\n showEmptyState: boolean;\n\n // Refs\n resultsId: React.MutableRefObject<string>;\n inputRef: React.RefObject<HTMLInputElement>;\n itemRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;\n containerRef: React.RefObject<HTMLDivElement>;\n\n // Handlers\n handleChange: (e: any) => void;\n handleFocus: () => void;\n handleBlur: () => void;\n handleKeyDown: (e: KeyboardEvent) => void;\n createItemClickHandler: (item: T) => () => void;\n getActiveDescendant: () => string | undefined;\n}\n\nexport const useSearch = <T extends SearchItem = SearchItem>({\n value,\n onChange,\n items,\n shouldShowResults = true,\n onItemClick,\n}: UseSearchOptions<T>): UseSearchReturn<T> => {\n const [activeIndex, setActiveIndex] = useState(-1);\n const [initialValue, setInitialValue] = useState('');\n const [itemSelected, setItemSelected] = useState(false);\n const [isClosedManually, setIsClosedManually] = useState(false);\n\n const resultsId = useRef(\n `search-results-${Math.random().toString(36).substr(2, 9)}`\n );\n const inputRef = useRef<HTMLInputElement>(null);\n const itemRefs = useRef<(HTMLDivElement | null)[]>([]);\n const containerRef = useRef<HTMLDivElement>(null);\n const blurTimeoutRef = useRef<number | null>(null);\n\n const isOpen = Boolean(value) && !isClosedManually;\n const showResults = shouldShowResults && isOpen && items.length > 0;\n const showEmptyState = shouldShowResults && isOpen && items.length === 0;\n\n useEffect(() => {\n setActiveIndex(-1);\n // Don't reset isClosedManually here - only reset on focus\n // This prevents results from reopening after Tab\n }, [items]);\n\n useEffect(() => {\n return () => {\n clearBlurTimeout(blurTimeoutRef.current);\n };\n }, []);\n\n useEffect(() => {\n // Auto-scroll active item into view when navigating with keyboard\n if (activeIndex >= 0 && itemRefs.current[activeIndex]) {\n const element = itemRefs.current[activeIndex];\n if (element && typeof element.scrollIntoView === 'function') {\n element.scrollIntoView({\n behavior: 'smooth',\n block: 'nearest',\n });\n }\n }\n }, [activeIndex]);\n\n const handleChange = useCallback(\n (e: any) => {\n // Reset isClosedManually when user types\n if (isClosedManually) {\n setIsClosedManually(false);\n }\n onChange?.(e);\n },\n [onChange, isClosedManually]\n );\n\n const createItemClickHandler = useCallback(\n (item: T) => () => {\n setItemSelected(true);\n setIsClosedManually(true);\n onItemClick?.(item);\n setActiveIndex(-1);\n },\n [onItemClick]\n );\n\n const handleFocus = useCallback(() => {\n clearBlurTimeout(blurTimeoutRef.current);\n blurTimeoutRef.current = null;\n setInitialValue(value || '');\n setItemSelected(false);\n setIsClosedManually(false);\n }, [value]);\n\n const handleBlur = useCallback(() => {\n blurTimeoutRef.current = createBlurHandler({\n containerRef: containerRef.current,\n itemSelected,\n initialValue,\n currentValue: value || '',\n onValueRestore: (restoredValue) => {\n onChange?.({ target: { value: restoredValue } } as any);\n },\n onClose: () => {\n setIsClosedManually(true);\n },\n });\n }, [itemSelected, initialValue, value, onChange]);\n\n const handleKeyDown = useCallback(\n (e: KeyboardEvent) => {\n if (!showResults) return;\n\n switch (e.key) {\n case 'ArrowDown':\n e.preventDefault();\n setActiveIndex((prev) => handleArrowDown(prev, items.length));\n break;\n case 'ArrowUp':\n e.preventDefault();\n setActiveIndex((prev) => handleArrowUp(prev));\n break;\n case 'Home':\n if (showResults && items.length > 0) {\n e.preventDefault();\n setActiveIndex(handleHomeKey());\n }\n break;\n case 'End':\n if (showResults && items.length > 0) {\n e.preventDefault();\n setActiveIndex(handleEndKey(items.length));\n }\n break;\n case 'Tab':\n clearBlurTimeout(blurTimeoutRef.current);\n blurTimeoutRef.current = null;\n setIsClosedManually(true);\n onChange?.({ target: { value: initialValue } } as any);\n break;\n case 'Enter': {\n const wasHandled = handleEnterKey(activeIndex, items, (item) => {\n setItemSelected(true);\n setIsClosedManually(true);\n onItemClick?.(item);\n setActiveIndex(-1);\n });\n if (wasHandled) {\n e.preventDefault();\n }\n break;\n }\n case 'Escape':\n e.preventDefault();\n handleEscapeKey(\n initialValue,\n inputRef.current,\n (restoredValue) => {\n onChange?.({ target: { value: restoredValue } } as any);\n setActiveIndex(-1);\n setIsClosedManually(true);\n },\n () => {\n setIsClosedManually(true);\n }\n );\n break;\n }\n },\n [showResults, items, activeIndex, onItemClick, onChange, initialValue]\n );\n\n const getActiveDescendant = useCallback(() => {\n if (activeIndex >= 0 && showResults) {\n return `${resultsId.current}-item-${activeIndex}`;\n }\n return undefined;\n }, [activeIndex, showResults]);\n\n return {\n activeIndex,\n showResults,\n showEmptyState,\n resultsId,\n inputRef,\n itemRefs,\n containerRef,\n handleChange,\n handleFocus,\n handleBlur,\n handleKeyDown,\n createItemClickHandler,\n getActiveDescendant,\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, memo } from 'preact/compat';\nimport { Button, CartList, Divider } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { QuickOrderItemsListProps } from '@/b2b-quick-order/types';\nimport { Slot } from '@adobe-commerce/elsie/lib';\nimport { QuickOrderListItem, Search } from '@/b2b-quick-order/components';\nimport { useItemSearch } from '@/b2b-quick-order/hooks';\nimport '@/b2b-quick-order/components/QuickOrderItemsList/QuickOrderItemsList.css';\n\nconst QuickOrderItemsListComponent: FunctionComponent<\n QuickOrderItemsListProps\n> = ({\n t,\n items,\n onRemove,\n clearItems,\n onUpdateQuantity,\n slots,\n handleAddToCart,\n isItemUpdating,\n loading,\n isDisabledButton,\n productsSearch,\n searchFilter,\n}) => {\n const {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults,\n handleItemClick,\n } = useItemSearch({\n productsSearch,\n initialSku: '',\n searchFilter,\n });\n\n return (\n <div\n className={classes(['b2b-quick-order-form-quick-order-items-list'])}\n role=\"region\"\n aria-label={t.title}\n >\n <div className=\"b2b-quick-order-form-quick-order-items-list__title\">\n {t.title}\n </div>\n\n {items.length > 0 && (\n <>\n <CartList\n role=\"list\"\n className=\"b2b-quick-order-form-quick-order-items-list__list\"\n >\n {items.map((item) => (\n <QuickOrderListItem\n key={item.sku}\n item={item}\n t={t}\n onRemove={onRemove}\n onUpdateQuantity={onUpdateQuantity}\n isUpdating={isItemUpdating?.(item.sku)}\n loading={loading}\n productsSearch={productsSearch}\n searchFilter={searchFilter}\n slots={slots}\n />\n ))}\n </CartList>\n <Divider variant={'secondary'} />\n </>\n )}\n <div className=\"b2b-quick-order-form-quick-order-items-list__global-search\">\n <Search\n t={t}\n onChange={handleSearchChange}\n items={searchResults}\n value={searchValue}\n shouldShowResults={shouldShowResults}\n onItemClick={handleItemClick}\n className=\"b2b-quick-order-form-quick-order-items-list__search\"\n />\n </div>\n {items.length === 0 && (\n <div\n className=\"b2b-quick-order-form-quick-order-items-list__empty\"\n data-testid=\"empty-items\"\n >\n {t.emptyList}\n </div>\n )}\n <Slot\n slot={slots?.AddAllToCartButton}\n name=\"AddAllToCartButton\"\n context={{\n handleAddToCart,\n clearItems,\n loading,\n isDisabledButton,\n }}\n data-testid=\"addAllToCart\"\n >\n <div className=\"b2b-quick-order-form-quick-order-items-list__actions\">\n <Button\n variant=\"primary\"\n onClick={handleAddToCart}\n data-testid=\"add-all-to-cart-button\"\n disabled={loading || isDisabledButton}\n >\n {t.addAllToCart}\n </Button>\n </div>\n </Slot>\n </div>\n );\n};\n\nexport const QuickOrderItemsList = memo(QuickOrderItemsListComponent);\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, useMemo, useCallback, memo } from 'preact/compat';\nimport { CartItem, AccordionSection } from '@adobe-commerce/elsie/components';\nimport { Slot } from '@adobe-commerce/elsie/lib';\nimport { QuickOrderListItemProps } from '@/b2b-quick-order/types';\nimport { useItemSearch } from '@/b2b-quick-order/hooks';\nimport '@/b2b-quick-order/components/QuickOrderListItem/QuickOrderListItem.css';\nimport { Search } from '@/b2b-quick-order/components';\n\nconst QuickOrderListItemComponent: FunctionComponent<\n QuickOrderListItemProps\n> = ({\n item,\n t,\n onRemove,\n onUpdateQuantity,\n isUpdating,\n loading,\n productsSearch,\n searchFilter,\n slots,\n}) => {\n // Generate unique scope identifier Dropins - use item.id if available to distinguish multiple items with same sku\n const scope = `quick-order-item-${item.id || item.variantSku || item.sku}`;\n const currentSku = item?.variantSku ?? item?.sku;\n\n const {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults,\n handleItemClick,\n } = useItemSearch({\n productsSearch,\n initialSku: currentSku,\n replaceItemSku: item.sku,\n searchFilter,\n });\n\n const formName = `form-${item.id || currentSku}`;\n const isValid = item.inStock && item.addToCartAllowed;\n const hasOptions = item.options && item.options.length > 0;\n\n const hasRequiredOptions = useMemo(\n () => hasOptions && item.options.some((option) => option.required),\n [hasOptions, item.options]\n );\n\n const hasSelectedOptions = useMemo(\n () =>\n hasOptions &&\n item.options.some(\n (option) =>\n option.items && option.items.some((optionItem) => optionItem.selected)\n ),\n [hasOptions, item.options]\n );\n\n // Check if all required options are selected\n const allRequiredOptionsSelected = useMemo(() => {\n if (hasRequiredOptions) {\n // If there are required options, check that all are selected\n return item.options.every((option) => {\n if (!option.required) return true;\n return (\n option.items && option.items.some((optionItem) => optionItem.selected)\n );\n });\n }\n // If no required options, return hasSelectedOptions\n return hasSelectedOptions;\n }, [hasRequiredOptions, hasSelectedOptions, item.options]);\n\n const mainImage = useMemo(\n () => item.images?.find((img) => img.roles?.includes('image')),\n [item.images]\n );\n\n // Memoize handlers\n const handleRemove = useCallback(() => {\n // Use item.id if available, otherwise fall back to sku\n onRemove?.(item.id || item.sku);\n }, [onRemove, item.id, item.sku]);\n\n const handleQuantityChange = useCallback(\n (newQty: number) => {\n onUpdateQuantity?.(item.sku, newQty);\n // Update hidden quantity field\n const form = document.forms[formName as any] as HTMLFormElement;\n if (form) {\n const qtyInput = form.querySelector(\n 'input[name=\"quantity\"]'\n ) as HTMLInputElement;\n if (qtyInput) qtyInput.value = String(newQty);\n }\n },\n [onUpdateQuantity, item.sku, formName]\n );\n\n const searchSlot = (\n <Slot\n name=\"QuickOrderItemSearch\"\n slot={slots?.QuickOrderItemSearch}\n context={{\n item,\n scope,\n handleSearchChange,\n searchResults,\n searchValue,\n shouldShowResults,\n handleItemClick,\n }}\n >\n <Search\n t={t}\n onChange={handleSearchChange}\n items={searchResults}\n value={searchValue}\n shouldShowResults={shouldShowResults}\n className=\"b2b-quick-order-form-quick-order-items__item-search\"\n onItemClick={handleItemClick}\n slots={slots}\n />\n </Slot>\n );\n\n if (!item.name && !item.images?.length) {\n return (\n <form\n key={item.sku}\n name={formName}\n className=\"b2b-quick-order-form-quick-order-items__item-form\"\n onSubmit={(e) => e.preventDefault()}\n data-sku={item.sku}\n >\n <input type=\"hidden\" name=\"sku\" value={item.sku} />\n <input type=\"hidden\" name=\"quantity\" value={item.quantity} />\n <input type=\"hidden\" name=\"valid\" value=\"false\" />\n <input type=\"hidden\" name=\"productType\" value=\"\" />\n {searchSlot}\n\n <CartItem\n sku={<span>{item.sku}</span>}\n title={<span>{t.productNotFound}</span>}\n quantity={item.quantity}\n alert={\n <div className=\"b2b-quick-order-items__error\">\n {t.productNotFoundDescription?.replace('{sku}', item.sku)}\n </div>\n }\n disabled={loading}\n onRemove={handleRemove}\n ariaLabel={`${t.productNotFound} - ${item.sku}`}\n />\n </form>\n );\n }\n\n return (\n <form\n key={currentSku}\n name={formName}\n className=\"b2b-quick-order-form-quick-order-items__item-form\"\n onSubmit={(e) => e.preventDefault()}\n data-sku={currentSku}\n >\n <input type=\"hidden\" name=\"sku\" value={currentSku} />\n <input type=\"hidden\" name=\"quantity\" value={item.quantity} />\n <input type=\"hidden\" name=\"valid\" value={isValid ? 'true' : 'false'} />\n <input type=\"hidden\" name=\"productType\" value={item.productType || ''} />\n {searchSlot}\n <CartItem\n title={<span>{item.name}</span>}\n sku={<span>{currentSku}</span>}\n image={\n mainImage ? (\n <img src={mainImage.url} alt={mainImage.label || item.name} />\n ) : undefined\n }\n price={\n <Slot\n name=\"ProductPrice\"\n slot={slots?.ProductPrice}\n context={{\n item,\n scope,\n }}\n />\n }\n quantity={item.quantity}\n alert={\n item.inStock === false ? (\n <div className=\"b2b-quick-order-items__alert\">{t.outOfStock}</div>\n ) : undefined\n }\n warning={\n hasOptions && !allRequiredOptionsSelected ? (\n <div className=\"b2b-quick-order-items__warning\">\n {t.configurableOptionsWarning}\n </div>\n ) : undefined\n }\n footer={\n hasOptions ? (\n <AccordionSection\n title={t.productOptions}\n ariaLabelTitle={t.productOptions}\n defaultOpen={!allRequiredOptionsSelected}\n className=\"b2b-quick-order-list-item__accordion\"\n actionIconPosition=\"left\"\n >\n <Slot\n name=\"ProductOptions\"\n slot={slots?.ProductOptions}\n context={{\n item,\n scope,\n }}\n >\n <div className=\"b2b-quick-order-items__configurable-error\">\n {t.configurableProductErrorDescription}\n </div>\n </Slot>\n </AccordionSection>\n ) : undefined\n }\n updating={isUpdating}\n disabled={loading}\n loading={loading}\n onRemove={handleRemove}\n onQuantity={handleQuantityChange}\n ariaLabel={`${item.name} - ${item.sku}`}\n />\n </form>\n );\n};\n\nexport const QuickOrderListItem = memo(QuickOrderListItemComponent);\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 { memo } from 'preact/compat';\nimport { Input } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { SearchProps, SearchItem } from '@/b2b-quick-order/types/search.types';\nimport { useSearch } from '@/b2b-quick-order/hooks/useSearch';\nimport '@/b2b-quick-order/components/Search/Search.css';\nimport { Slot } from '@adobe-commerce/elsie/lib';\n\nconst cursorStyle = { cursor: 'pointer' as const };\nconst defaultCursorStyle = { cursor: 'default' as const };\n\nconst SearchComponent = <T extends SearchItem = SearchItem>({\n t,\n value,\n onChange,\n items,\n shouldShowResults = true,\n className,\n onItemClick,\n slots,\n}: SearchProps<T>) => {\n const {\n activeIndex,\n showResults,\n showEmptyState,\n resultsId,\n inputRef,\n itemRefs,\n containerRef,\n handleChange,\n handleFocus,\n handleBlur,\n handleKeyDown,\n createItemClickHandler,\n getActiveDescendant,\n } = useSearch({\n value,\n onChange,\n items,\n shouldShowResults,\n onItemClick,\n });\n\n return (\n <div\n ref={containerRef}\n className={classes(['b2b-quick-order-search', className])}\n >\n <Input\n ref={inputRef}\n className=\"b2b-quick-order-search__input\"\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n placeholder={t.searchPlaceholder}\n aria-label={t.searchAriaLabel}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={showResults}\n aria-controls={resultsId.current}\n aria-activedescendant={getActiveDescendant()}\n onKeyDown={handleKeyDown}\n />\n\n {showResults && (\n <div\n id={resultsId.current}\n role=\"listbox\"\n className=\"b2b-quick-order-search__results\"\n aria-label={t.searchAriaLabel}\n >\n {items.map((item, index) => (\n <Slot\n key={item.sku}\n slot={slots?.QuickOrderSearchAutocompleteItem}\n name={'QuickOrderSearchAutocompleteItem'}\n context={{\n item,\n index,\n createItemClickHandler,\n activeIndex,\n }}\n >\n <div\n id={`${resultsId.current}-item-${index}`}\n ref={(el) => (itemRefs.current[index] = el)}\n role=\"option\"\n aria-selected={index === activeIndex}\n className={classes([\n 'b2b-quick-order-search__result-item',\n index === activeIndex &&\n 'b2b-quick-order-search__result-item--active',\n ])}\n onClick={createItemClickHandler(item)}\n style={onItemClick ? cursorStyle : defaultCursorStyle}\n >\n {`${item.sku} ${item.name}`}\n </div>\n </Slot>\n ))}\n </div>\n )}\n\n {showEmptyState && (\n <div\n className=\"b2b-quick-order-search__empty-state\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {t.searchEmptyState}\n </div>\n )}\n\n {showResults && (\n <div\n className=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n >\n {items.length}{' '}\n {items.length === 1 ? t.resultAvailable : t.resultsAvailable}.{' '}\n {t.srInstructions}\n </div>\n )}\n </div>\n );\n};\n\nexport const Search = memo(SearchComponent) as typeof SearchComponent;\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 { QuickOrderDisabledOverlayProps } from '@/b2b-quick-order/types';\nimport '@/b2b-quick-order/components/QuickOrderDisabledOverlay/QuickOrderDisabledOverlay.css';\n\nexport const QuickOrderDisabledOverlay: FunctionComponent<\n QuickOrderDisabledOverlayProps\n> = ({ isDisabled, message, children }) => {\n return (\n <div className=\"b2b-quick-order-disabled-overlay\">\n <div\n className=\"b2b-quick-order-disabled-overlay__content\"\n style={{ pointerEvents: isDisabled ? 'none' : 'auto' }}\n >\n {children}\n </div>\n {isDisabled && (\n <>\n <div className=\"b2b-quick-order-disabled-overlay__blur\" />\n <div className=\"b2b-quick-order-disabled-overlay__message\">\n {message}\n </div>\n </>\n )}\n </div>\n );\n};\n"],"names":["classes","result","item","className","isActive","CsvFileInputComponent","t","onFileUpload","error","fileName","onDownloadSample","showSampleDownload","disabled","handleFileChange","useCallback","e","file","_a","jsxs","jsx","Fragment","InputFile","CsvFileInput","memo","debounce","fn","ms","timeoutId","args","SEARCH_FILTER","handleSearchBlur","options","containerRef","itemSelected","initialValue","currentValue","onValueRestore","onClose","activeElement","createBlurHandler","delay","clearBlurTimeout","timeoutRef","handleArrowDown","currentIndex","itemsLength","handleArrowUp","handleHomeKey","handleEndKey","handleEnterKey","activeIndex","items","onItemSelect","handleEscapeKey","inputRef","useItemSearch","productsSearch","initialSku","replaceItemSku","searchFilter","searchValue","setSearchValue","useState","searchResults","setSearchResults","isTouched","setIsTouched","isMountedRef","useRef","useEffect","debouncedSearch","useMemo","searchTerm","handleSearchChange","value","resetSearch","handleItemClick","clickedItem","itemData","events","useSearch","onChange","shouldShowResults","onItemClick","setActiveIndex","setInitialValue","setItemSelected","isClosedManually","setIsClosedManually","resultsId","itemRefs","blurTimeoutRef","isOpen","showResults","showEmptyState","element","handleChange","createItemClickHandler","handleFocus","handleBlur","restoredValue","handleKeyDown","prev","getActiveDescendant","QuickOrderItemsListComponent","onRemove","clearItems","onUpdateQuantity","slots","handleAddToCart","isItemUpdating","loading","isDisabledButton","CartList","QuickOrderListItem","Divider","Search","Slot","Button","QuickOrderItemsList","QuickOrderListItemComponent","isUpdating","scope","currentSku","formName","isValid","hasOptions","hasRequiredOptions","option","hasSelectedOptions","optionItem","allRequiredOptionsSelected","mainImage","img","handleRemove","handleQuantityChange","newQty","form","qtyInput","searchSlot","CartItem","_b","AccordionSection","cursorStyle","defaultCursorStyle","SearchComponent","Input","index","el","QuickOrderDisabledOverlay","isDisabled","message","children"],"mappings":"yjBAcO,MAAMA,EACXA,GAEeA,EAAQ,OAAO,CAACC,EAAQC,IAAS,CAC9C,GAAI,CAACA,EAAM,OAAOD,EAIlB,GAFI,OAAOC,GAAS,WAAUD,GAAU,IAAIC,CAAI,IAE5C,MAAM,QAAQA,CAAI,EAAG,CACvB,KAAM,CAACC,EAAWC,CAAQ,EAAIF,EAC1BC,GAAaC,IACfH,GAAU,IAAIE,CAAS,GAE3B,CAEA,OAAOF,CACT,EAAG,EAAE,EAES,KAAA,ECVVI,GAA8D,CAAC,CACnE,EAAAC,EACA,aAAAC,EACA,MAAAC,EACA,SAAAC,EACA,iBAAAC,EACA,mBAAAC,EACA,SAAAC,CACF,IAAM,CACJ,MAAMC,EAAmBC,EACtBC,GAAa,OAEZ,MAAMC,GAAOC,EADEF,EAAE,OACG,QAAP,YAAAE,EAAe,GACxBD,GACFT,EAAaS,CAAI,CAErB,EACA,CAACT,CAAY,CAAA,EA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/lib/classes.ts","/@dropins/storefront-quick-order/src/components/CsvFileInput/CsvFileInput.tsx","../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-quick-order/src/configs/search-filter.config.ts","/@dropins/storefront-quick-order/src/lib/searchBlurHandler.ts","/@dropins/storefront-quick-order/src/lib/searchKeyboardNavigation.ts","/@dropins/storefront-quick-order/src/hooks/useItemSearch.tsx","/@dropins/storefront-quick-order/src/hooks/useSearch.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderItemsList/QuickOrderItemsList.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderListItem/QuickOrderListItem.tsx","/@dropins/storefront-quick-order/src/components/Search/Search.tsx","/@dropins/storefront-quick-order/src/components/QuickOrderDisabledOverlay/QuickOrderDisabledOverlay.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\n// @ts-ignore\nimport { JSXInternal } from 'preact/src/jsx';\n\ntype ClassName = string | JSXInternal.SignalLike<string | undefined>;\n\nexport const classes = (\n classes: Array<ClassName | [ClassName, boolean] | undefined>\n) => {\n const result = classes.reduce((result, item) => {\n if (!item) return result;\n\n if (typeof item === 'string') result += ` ${item}`;\n\n if (Array.isArray(item)) {\n const [className, isActive] = item;\n if (className && isActive) {\n result += ` ${className}`;\n }\n }\n\n return result;\n }, '') as string;\n\n return result.trim();\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, useCallback, memo } from 'preact/compat';\nimport { InputFile } from '@adobe-commerce/elsie/components';\nimport { CsvFileInputProps } from '@/b2b-quick-order/types/quickOrderCsvUpload.types';\nimport '@/b2b-quick-order/components/CsvFileInput/CsvFileInput.css';\n\nconst CsvFileInputComponent: FunctionComponent<CsvFileInputProps> = ({\n t,\n onFileUpload,\n error,\n fileName,\n onDownloadSample,\n showSampleDownload,\n disabled,\n}) => {\n const handleFileChange = useCallback(\n (e: Event) => {\n const target = e.target as HTMLInputElement;\n const file = target.files?.[0];\n if (file) {\n onFileUpload(file);\n }\n },\n [onFileUpload]\n );\n\n const inputClassName = 'b2b-quick-order-csv-file-input__input';\n\n return (\n <div className=\"b2b-quick-order-csv-file-input\">\n <div className=\"b2b-quick-order-csv-file-input__title\">{t.title}</div>\n\n <div className=\"b2b-quick-order-csv-file-input__helper\">\n {t.helperText}\n {showSampleDownload && (\n <>\n <button\n type=\"button\"\n className=\"b2b-quick-order-csv-file-input__download-link\"\n onClick={onDownloadSample}\n data-testid=\"download-sample\"\n disabled={disabled}\n >\n {t.downloadSample}\n </button>\n </>\n )}\n </div>\n\n <div\n className={`b2b-quick-order-csv-file-input__input-wrapper ${\n disabled\n ? 'b2b-quick-order-csv-file-input__input-wrapper--disabled'\n : ''\n }`}\n >\n <InputFile\n id={'quick-order-csv-file-input'}\n label={t.inputLabel}\n className={inputClassName}\n onChange={handleFileChange}\n accept={'.csv'}\n disabled={disabled}\n />\n </div>\n\n {fileName && (\n <div\n className=\"b2b-quick-order-csv-file-input__file-name\"\n data-testid=\"file-name\"\n >\n {t.selectedFile}: {fileName}\n </div>\n )}\n\n {error && (\n <div\n className=\"b2b-quick-order-csv-file-input__error\"\n data-testid=\"error-message\"\n role=\"alert\"\n >\n {error}\n </div>\n )}\n </div>\n );\n};\n\nexport const CsvFileInput = memo(CsvFileInputComponent);\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n const debouncedFn = function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n debouncedFn.cancel = () => {\n clearTimeout(timeoutId);\n };\n return debouncedFn;\n};\n","export const SEARCH_FILTER = [\n {\n attribute: 'visibility',\n in: ['Search', 'Catalog, Search'],\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\nexport interface BlurHandlerOptions {\n containerRef: HTMLElement | null;\n itemSelected: boolean;\n initialValue: string;\n currentValue: string;\n onValueRestore: (value: string) => void;\n onClose: () => void;\n}\n\n/**\n * Handles blur logic for search component\n * Checks if focus moved outside component and restores initial value if needed\n */\nexport const handleSearchBlur = (options: BlurHandlerOptions): void => {\n const {\n containerRef,\n itemSelected,\n initialValue,\n currentValue,\n onValueRestore,\n onClose,\n } = options;\n\n const activeElement = document.activeElement;\n const isWithinComponent = containerRef?.contains(activeElement);\n\n if (!isWithinComponent) {\n onClose();\n\n if (!itemSelected && initialValue !== currentValue) {\n onValueRestore(initialValue);\n }\n }\n};\n\n/**\n * Creates a blur handler with timeout\n */\nexport const createBlurHandler = (\n options: BlurHandlerOptions,\n delay: number = 150\n): number => {\n return window.setTimeout(() => {\n handleSearchBlur(options);\n }, delay);\n};\n\n/**\n * Clears blur timeout if exists\n */\nexport const clearBlurTimeout = (timeoutRef: number | null): void => {\n if (timeoutRef) {\n clearTimeout(timeoutRef);\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 * WCAG 2.1 compliant keyboard navigation for combobox with listbox pattern.\n * Focus always remains on the input element, visual indication via aria-activedescendant.\n * Reference: https://www.w3.org/WAI/ARIA/apg/patterns/combobox/\n */\n\n/**\n * Calculates next active index when ArrowDown is pressed\n * Returns next index in list or current if at end\n */\nexport const handleArrowDown = (\n currentIndex: number,\n itemsLength: number\n): number => {\n if (itemsLength === 0) return -1;\n return currentIndex < itemsLength - 1 ? currentIndex + 1 : currentIndex;\n};\n\n/**\n * Calculates next active index when ArrowUp is pressed\n * Returns previous index or -1 to return focus to input\n */\nexport const handleArrowUp = (currentIndex: number): number => {\n return currentIndex > 0 ? currentIndex - 1 : -1;\n};\n\n/**\n * Moves visual focus to first item in list (Home key)\n */\nexport const handleHomeKey = (): number => {\n return 0;\n};\n\n/**\n * Moves visual focus to last item in list (End key)\n */\nexport const handleEndKey = (itemsLength: number): number => {\n return Math.max(0, itemsLength - 1);\n};\n\n/**\n * Handles Enter key press on active item\n * Returns true if item was selected, false otherwise\n */\nexport const handleEnterKey = <T>(\n activeIndex: number,\n items: T[],\n onItemSelect: (item: T) => void\n): boolean => {\n if (activeIndex >= 0 && items[activeIndex]) {\n onItemSelect(items[activeIndex]);\n return true;\n }\n return false;\n};\n\n/**\n * Handles Escape key press - restores initial value and closes results\n */\nexport const handleEscapeKey = (\n initialValue: string,\n inputRef: HTMLElement | null,\n onValueRestore: (value: string) => void,\n onClose: () => void\n): void => {\n onValueRestore(initialValue);\n onClose();\n if (inputRef && 'blur' in inputRef && typeof inputRef.blur === 'function') {\n inputRef.blur();\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 {\n useCallback,\n useState,\n useMemo,\n useRef,\n useEffect,\n} from 'preact/hooks';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\nimport { OrderItem, UseItemSearchProps } from '@/b2b-quick-order/types';\nimport { events } from '@adobe-commerce/event-bus';\nimport { SEARCH_FILTER } from '@/b2b-quick-order/configs';\n\nexport const useItemSearch = ({\n productsSearch,\n initialSku,\n replaceItemSku,\n searchFilter = SEARCH_FILTER,\n}: UseItemSearchProps) => {\n const [searchValue, setSearchValue] = useState(initialSku);\n const [searchResults, setSearchResults] = useState<OrderItem[]>([]);\n const [isTouched, setIsTouched] = useState(false);\n\n // Track if component is mounted to prevent state updates after unmount\n const isMountedRef = useRef(true);\n\n useEffect(() => {\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n // Update search value when initialSku changes (e.g., after merge)\n useEffect(() => {\n if (!isTouched) {\n setSearchValue(initialSku);\n }\n }, [initialSku, isTouched]);\n\n const debouncedSearch = useMemo(\n () =>\n debounce(async (searchTerm: string) => {\n if (!searchTerm || !productsSearch) {\n if (isMountedRef.current) {\n setSearchResults([]);\n }\n return;\n }\n\n try {\n const result = await productsSearch({\n phrase: searchTerm,\n filter: searchFilter,\n });\n if (isMountedRef.current) {\n setSearchResults(result.items || []);\n }\n } catch (error) {\n console.error('Error searching products:', error);\n if (isMountedRef.current) {\n setSearchResults([]);\n }\n }\n }, 300),\n [productsSearch, searchFilter]\n );\n\n const handleSearchChange = useCallback(\n (e: Event) => {\n const target = e.target as HTMLInputElement;\n const value = target.value;\n setSearchValue(value);\n setIsTouched(true);\n debouncedSearch(value);\n },\n [debouncedSearch]\n );\n\n const resetSearch = useCallback(() => {\n setSearchValue('');\n setSearchResults([]);\n setIsTouched(false);\n }, []);\n\n const handleItemClick = useCallback(\n (clickedItem: OrderItem) => {\n // Build item data for emission\n // Just send the data as-is from the search result\n // The deduplication logic will handle matching correctly\n const itemData = {\n sku: clickedItem.sku,\n ...(clickedItem.variantSku && { variantSku: clickedItem.variantSku }),\n quantity: 1,\n ...(replaceItemSku && { replaceItemSku }),\n };\n\n events.emit('quick-order/add-items', [itemData]);\n resetSearch();\n },\n [replaceItemSku, resetSearch]\n );\n\n return {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults: isTouched,\n resetSearch,\n handleItemClick,\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 React, { useCallback, useState, useRef, useEffect } from 'preact/compat';\nimport { SearchItem } from '@/b2b-quick-order/types/search.types';\nimport {\n createBlurHandler,\n clearBlurTimeout,\n handleArrowDown,\n handleArrowUp,\n handleEnterKey,\n handleEscapeKey,\n handleHomeKey,\n handleEndKey,\n} from '@/b2b-quick-order/lib';\n\nexport interface UseSearchOptions<T extends SearchItem> {\n value: string;\n onChange?: (e: any) => void;\n items: T[];\n shouldShowResults?: boolean;\n onItemClick?: (item: T) => void;\n}\n\nexport interface UseSearchReturn<T extends SearchItem> {\n // State\n activeIndex: number;\n showResults: boolean;\n showEmptyState: boolean;\n\n // Refs\n resultsId: React.MutableRefObject<string>;\n inputRef: React.RefObject<HTMLInputElement>;\n itemRefs: React.MutableRefObject<(HTMLDivElement | null)[]>;\n containerRef: React.RefObject<HTMLDivElement>;\n\n // Handlers\n handleChange: (e: any) => void;\n handleFocus: () => void;\n handleBlur: () => void;\n handleKeyDown: (e: KeyboardEvent) => void;\n createItemClickHandler: (item: T) => () => void;\n getActiveDescendant: () => string | undefined;\n}\n\nexport const useSearch = <T extends SearchItem = SearchItem>({\n value,\n onChange,\n items,\n shouldShowResults = true,\n onItemClick,\n}: UseSearchOptions<T>): UseSearchReturn<T> => {\n const [activeIndex, setActiveIndex] = useState(-1);\n const [initialValue, setInitialValue] = useState('');\n const [itemSelected, setItemSelected] = useState(false);\n const [isClosedManually, setIsClosedManually] = useState(false);\n\n const resultsId = useRef(\n `search-results-${Math.random().toString(36).substr(2, 9)}`\n );\n const inputRef = useRef<HTMLInputElement>(null);\n const itemRefs = useRef<(HTMLDivElement | null)[]>([]);\n const containerRef = useRef<HTMLDivElement>(null);\n const blurTimeoutRef = useRef<number | null>(null);\n\n const isOpen = Boolean(value) && !isClosedManually;\n const showResults = shouldShowResults && isOpen && items.length > 0;\n const showEmptyState = shouldShowResults && isOpen && items.length === 0;\n\n useEffect(() => {\n setActiveIndex(-1);\n // Don't reset isClosedManually here - only reset on focus\n // This prevents results from reopening after Tab\n }, [items]);\n\n useEffect(() => {\n return () => {\n clearBlurTimeout(blurTimeoutRef.current);\n };\n }, []);\n\n useEffect(() => {\n // Auto-scroll active item into view when navigating with keyboard\n if (activeIndex >= 0 && itemRefs.current[activeIndex]) {\n const element = itemRefs.current[activeIndex];\n if (element && typeof element.scrollIntoView === 'function') {\n element.scrollIntoView({\n behavior: 'smooth',\n block: 'nearest',\n });\n }\n }\n }, [activeIndex]);\n\n const handleChange = useCallback(\n (e: any) => {\n // Reset isClosedManually when user types\n if (isClosedManually) {\n setIsClosedManually(false);\n }\n onChange?.(e);\n },\n [onChange, isClosedManually]\n );\n\n const createItemClickHandler = useCallback(\n (item: T) => () => {\n setItemSelected(true);\n setIsClosedManually(true);\n onItemClick?.(item);\n setActiveIndex(-1);\n },\n [onItemClick]\n );\n\n const handleFocus = useCallback(() => {\n clearBlurTimeout(blurTimeoutRef.current);\n blurTimeoutRef.current = null;\n setInitialValue(value || '');\n setItemSelected(false);\n setIsClosedManually(false);\n }, [value]);\n\n const handleBlur = useCallback(() => {\n blurTimeoutRef.current = createBlurHandler({\n containerRef: containerRef.current,\n itemSelected,\n initialValue,\n currentValue: value || '',\n onValueRestore: (restoredValue) => {\n onChange?.({ target: { value: restoredValue } } as any);\n },\n onClose: () => {\n setIsClosedManually(true);\n },\n });\n }, [itemSelected, initialValue, value, onChange]);\n\n const handleKeyDown = useCallback(\n (e: KeyboardEvent) => {\n if (!showResults) return;\n\n switch (e.key) {\n case 'ArrowDown':\n e.preventDefault();\n setActiveIndex((prev) => handleArrowDown(prev, items.length));\n break;\n case 'ArrowUp':\n e.preventDefault();\n setActiveIndex((prev) => handleArrowUp(prev));\n break;\n case 'Home':\n if (showResults && items.length > 0) {\n e.preventDefault();\n setActiveIndex(handleHomeKey());\n }\n break;\n case 'End':\n if (showResults && items.length > 0) {\n e.preventDefault();\n setActiveIndex(handleEndKey(items.length));\n }\n break;\n case 'Tab':\n clearBlurTimeout(blurTimeoutRef.current);\n blurTimeoutRef.current = null;\n setIsClosedManually(true);\n onChange?.({ target: { value: initialValue } } as any);\n break;\n case 'Enter': {\n const wasHandled = handleEnterKey(activeIndex, items, (item) => {\n setItemSelected(true);\n setIsClosedManually(true);\n onItemClick?.(item);\n setActiveIndex(-1);\n });\n if (wasHandled) {\n e.preventDefault();\n }\n break;\n }\n case 'Escape':\n e.preventDefault();\n handleEscapeKey(\n initialValue,\n inputRef.current,\n (restoredValue) => {\n onChange?.({ target: { value: restoredValue } } as any);\n setActiveIndex(-1);\n setIsClosedManually(true);\n },\n () => {\n setIsClosedManually(true);\n }\n );\n break;\n }\n },\n [showResults, items, activeIndex, onItemClick, onChange, initialValue]\n );\n\n const getActiveDescendant = useCallback(() => {\n if (activeIndex >= 0 && showResults) {\n return `${resultsId.current}-item-${activeIndex}`;\n }\n return undefined;\n }, [activeIndex, showResults]);\n\n return {\n activeIndex,\n showResults,\n showEmptyState,\n resultsId,\n inputRef,\n itemRefs,\n containerRef,\n handleChange,\n handleFocus,\n handleBlur,\n handleKeyDown,\n createItemClickHandler,\n getActiveDescendant,\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, memo } from 'preact/compat';\nimport { Button, CartList, Divider } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { QuickOrderItemsListProps } from '@/b2b-quick-order/types';\nimport { Slot } from '@adobe-commerce/elsie/lib';\nimport { QuickOrderListItem, Search } from '@/b2b-quick-order/components';\nimport { useItemSearch } from '@/b2b-quick-order/hooks';\nimport '@/b2b-quick-order/components/QuickOrderItemsList/QuickOrderItemsList.css';\n\nconst QuickOrderItemsListComponent: FunctionComponent<\n QuickOrderItemsListProps\n> = ({\n t,\n items,\n onRemove,\n clearItems,\n onUpdateQuantity,\n slots,\n handleAddToCart,\n isItemUpdating,\n loading,\n isDisabledButton,\n productsSearch,\n searchFilter,\n}) => {\n const {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults,\n handleItemClick,\n } = useItemSearch({\n productsSearch,\n initialSku: '',\n searchFilter,\n });\n\n return (\n <div\n className={classes(['b2b-quick-order-form-quick-order-items-list'])}\n role=\"region\"\n aria-label={t.title}\n >\n <div className=\"b2b-quick-order-form-quick-order-items-list__title\">\n {t.title}\n </div>\n\n {items.length > 0 && (\n <>\n <CartList\n role=\"list\"\n className=\"b2b-quick-order-form-quick-order-items-list__list\"\n >\n {items.map((item) => (\n <QuickOrderListItem\n key={item.sku}\n item={item}\n t={t}\n onRemove={onRemove}\n onUpdateQuantity={onUpdateQuantity}\n isUpdating={isItemUpdating?.(item.sku)}\n loading={loading}\n productsSearch={productsSearch}\n searchFilter={searchFilter}\n slots={slots}\n />\n ))}\n </CartList>\n <Divider variant={'secondary'} />\n </>\n )}\n <div className=\"b2b-quick-order-form-quick-order-items-list__global-search\">\n <Search\n t={t}\n onChange={handleSearchChange}\n items={searchResults}\n value={searchValue}\n shouldShowResults={shouldShowResults}\n onItemClick={handleItemClick}\n className=\"b2b-quick-order-form-quick-order-items-list__search\"\n />\n </div>\n {items.length === 0 && (\n <div\n className=\"b2b-quick-order-form-quick-order-items-list__empty\"\n data-testid=\"empty-items\"\n >\n {t.emptyList}\n </div>\n )}\n <Slot\n slot={slots?.AddAllToCartButton}\n name=\"AddAllToCartButton\"\n context={{\n handleAddToCart,\n clearItems,\n loading,\n isDisabledButton,\n }}\n data-testid=\"addAllToCart\"\n >\n <div className=\"b2b-quick-order-form-quick-order-items-list__actions\">\n <Button\n variant=\"primary\"\n onClick={handleAddToCart}\n data-testid=\"add-all-to-cart-button\"\n disabled={loading || isDisabledButton}\n >\n {t.addAllToCart}\n </Button>\n </div>\n </Slot>\n </div>\n );\n};\n\nexport const QuickOrderItemsList = memo(QuickOrderItemsListComponent);\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, useMemo, useCallback, memo } from 'preact/compat';\nimport {\n CartItem,\n AccordionSection,\n PriceRange,\n} from '@adobe-commerce/elsie/components';\nimport { Slot } from '@adobe-commerce/elsie/lib';\nimport { QuickOrderListItemProps } from '@/b2b-quick-order/types';\nimport { useItemSearch } from '@/b2b-quick-order/hooks';\nimport '@/b2b-quick-order/components/QuickOrderListItem/QuickOrderListItem.css';\nimport { Search } from '@/b2b-quick-order/components';\n\nconst QuickOrderListItemComponent: FunctionComponent<\n QuickOrderListItemProps\n> = ({\n item,\n t,\n onRemove,\n onUpdateQuantity,\n isUpdating,\n loading,\n productsSearch,\n searchFilter,\n slots,\n}) => {\n // Generate unique scope identifier Dropins - use item.id if available to distinguish multiple items with same sku\n const scope = `quick-order-item-${item.id || item.variantSku || item.sku}`;\n const currentSku = item?.variantSku ?? item?.sku;\n\n const {\n searchValue,\n searchResults,\n handleSearchChange,\n shouldShowResults,\n handleItemClick,\n } = useItemSearch({\n productsSearch,\n initialSku: currentSku,\n replaceItemSku: item.sku,\n searchFilter,\n });\n\n const formName = `form-${item.id || currentSku}`;\n const isValid = item.inStock && item.addToCartAllowed;\n const hasOptions = item.options && item.options.length > 0;\n\n const hasRequiredOptions = useMemo(\n () => hasOptions && item.options.some((option) => option.required),\n [hasOptions, item.options]\n );\n\n const hasSelectedOptions = useMemo(\n () =>\n hasOptions &&\n item.options.some(\n (option) =>\n option.items && option.items.some((optionItem) => optionItem.selected)\n ),\n [hasOptions, item.options]\n );\n\n // Check if all required options are selected\n const allRequiredOptionsSelected = useMemo(() => {\n if (hasRequiredOptions) {\n // If there are required options, check that all are selected\n return item.options.every((option) => {\n if (!option.required) return true;\n return (\n option.items && option.items.some((optionItem) => optionItem.selected)\n );\n });\n }\n // If no required options, return hasSelectedOptions\n return hasSelectedOptions;\n }, [hasRequiredOptions, hasSelectedOptions, item.options]);\n\n const mainImage = useMemo(\n () => item.images?.find((img) => img.roles?.includes('image')),\n [item.images]\n );\n\n // Memoize handlers\n const handleRemove = useCallback(() => {\n // Use item.id if available, otherwise fall back to sku\n onRemove?.(item.id || item.sku);\n }, [onRemove, item.id, item.sku]);\n\n const handleQuantityChange = useCallback(\n (newQty: number) => {\n onUpdateQuantity?.(item.sku, newQty);\n // Update hidden quantity field\n const form = document.forms[formName as any] as HTMLFormElement;\n if (form) {\n const qtyInput = form.querySelector(\n 'input[name=\"quantity\"]'\n ) as HTMLInputElement;\n if (qtyInput) qtyInput.value = String(newQty);\n }\n },\n [onUpdateQuantity, item.sku, formName]\n );\n\n const searchSlot = (\n <Slot\n name=\"QuickOrderItemSearch\"\n slot={slots?.QuickOrderItemSearch}\n context={{\n item,\n scope,\n handleSearchChange,\n searchResults,\n searchValue,\n shouldShowResults,\n handleItemClick,\n }}\n >\n <Search\n t={t}\n onChange={handleSearchChange}\n items={searchResults}\n value={searchValue}\n shouldShowResults={shouldShowResults}\n className=\"b2b-quick-order-form-quick-order-items__item-search\"\n onItemClick={handleItemClick}\n slots={slots}\n />\n </Slot>\n );\n\n if (!item.name && !item.images?.length) {\n return (\n <form\n key={item.sku}\n name={formName}\n className=\"b2b-quick-order-form-quick-order-items__item-form\"\n onSubmit={(e) => e.preventDefault()}\n data-sku={item.sku}\n >\n <input type=\"hidden\" name=\"sku\" value={item.sku} />\n <input type=\"hidden\" name=\"quantity\" value={item.quantity} />\n <input type=\"hidden\" name=\"valid\" value=\"false\" />\n <input type=\"hidden\" name=\"productType\" value=\"\" />\n {searchSlot}\n\n <CartItem\n sku={<span>{item.sku}</span>}\n title={<span>{t.productNotFound}</span>}\n quantity={item.quantity}\n alert={\n <div className=\"b2b-quick-order-items__error\">\n {t.productNotFoundDescription?.replace('{sku}', item.sku)}\n </div>\n }\n disabled={loading}\n onRemove={handleRemove}\n ariaLabel={`${t.productNotFound} - ${item.sku}`}\n />\n </form>\n );\n }\n\n return (\n <form\n key={currentSku}\n name={formName}\n className=\"b2b-quick-order-form-quick-order-items__item-form\"\n onSubmit={(e) => e.preventDefault()}\n data-sku={currentSku}\n >\n <input type=\"hidden\" name=\"sku\" value={currentSku} />\n <input type=\"hidden\" name=\"quantity\" value={item.quantity} />\n <input type=\"hidden\" name=\"valid\" value={isValid ? 'true' : 'false'} />\n <input type=\"hidden\" name=\"productType\" value={item.productType || ''} />\n {searchSlot}\n <CartItem\n title={<span>{item.name}</span>}\n sku={<span>{currentSku}</span>}\n image={\n mainImage ? (\n <img src={mainImage.url} alt={mainImage.label || item.name} />\n ) : undefined\n }\n price={\n <Slot\n name=\"ProductPrice\"\n slot={slots?.ProductPrice}\n context={{\n item,\n scope,\n }}\n >\n <PriceRange\n minimumAmount={item.prices.final.minimumAmount}\n maximumAmount={item.prices.final.maximumAmount}\n amount={item.prices.final.amount}\n currency={item.prices.final.currency}\n />\n </Slot>\n }\n quantity={item.quantity}\n alert={\n item.inStock === false ? (\n <div className=\"b2b-quick-order-items__alert\">{t.outOfStock}</div>\n ) : undefined\n }\n warning={\n hasOptions && !allRequiredOptionsSelected ? (\n <div className=\"b2b-quick-order-items__warning\">\n {t.configurableOptionsWarning}\n </div>\n ) : undefined\n }\n footer={\n hasOptions ? (\n <AccordionSection\n title={t.productOptions}\n ariaLabelTitle={t.productOptions}\n defaultOpen={!allRequiredOptionsSelected}\n className=\"b2b-quick-order-list-item__accordion\"\n actionIconPosition=\"left\"\n >\n <Slot\n name=\"ProductOptions\"\n slot={slots?.ProductOptions}\n context={{\n item,\n scope,\n }}\n >\n <div className=\"b2b-quick-order-items__configurable-error\">\n {t.configurableProductErrorDescription}\n </div>\n </Slot>\n </AccordionSection>\n ) : undefined\n }\n updating={isUpdating}\n disabled={loading}\n loading={loading}\n onRemove={handleRemove}\n onQuantity={handleQuantityChange}\n ariaLabel={`${item.name} - ${item.sku}`}\n />\n </form>\n );\n};\n\nexport const QuickOrderListItem = memo(QuickOrderListItemComponent);\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 { memo } from 'preact/compat';\nimport { Input } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { SearchProps, SearchItem } from '@/b2b-quick-order/types/search.types';\nimport { useSearch } from '@/b2b-quick-order/hooks/useSearch';\nimport '@/b2b-quick-order/components/Search/Search.css';\nimport { Slot } from '@adobe-commerce/elsie/lib';\n\nconst cursorStyle = { cursor: 'pointer' as const };\nconst defaultCursorStyle = { cursor: 'default' as const };\n\nconst SearchComponent = <T extends SearchItem = SearchItem>({\n t,\n value,\n onChange,\n items,\n shouldShowResults = true,\n className,\n onItemClick,\n slots,\n}: SearchProps<T>) => {\n const {\n activeIndex,\n showResults,\n showEmptyState,\n resultsId,\n inputRef,\n itemRefs,\n containerRef,\n handleChange,\n handleFocus,\n handleBlur,\n handleKeyDown,\n createItemClickHandler,\n getActiveDescendant,\n } = useSearch({\n value,\n onChange,\n items,\n shouldShowResults,\n onItemClick,\n });\n\n return (\n <div\n ref={containerRef}\n className={classes(['b2b-quick-order-search', className])}\n >\n <Input\n ref={inputRef}\n className=\"b2b-quick-order-search__input\"\n value={value}\n onChange={handleChange}\n onFocus={handleFocus}\n onBlur={handleBlur}\n placeholder={t.searchPlaceholder}\n aria-label={t.searchAriaLabel}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={showResults}\n aria-controls={resultsId.current}\n aria-activedescendant={getActiveDescendant()}\n onKeyDown={handleKeyDown}\n />\n\n {showResults && (\n <div\n id={resultsId.current}\n role=\"listbox\"\n className=\"b2b-quick-order-search__results\"\n aria-label={t.searchAriaLabel}\n >\n {items.map((item, index) => (\n <Slot\n key={item.sku}\n slot={slots?.QuickOrderSearchAutocompleteItem}\n name={'QuickOrderSearchAutocompleteItem'}\n context={{\n item,\n index,\n createItemClickHandler,\n activeIndex,\n }}\n >\n <div\n id={`${resultsId.current}-item-${index}`}\n ref={(el) => (itemRefs.current[index] = el)}\n role=\"option\"\n aria-selected={index === activeIndex}\n className={classes([\n 'b2b-quick-order-search__result-item',\n index === activeIndex &&\n 'b2b-quick-order-search__result-item--active',\n ])}\n onClick={createItemClickHandler(item)}\n style={onItemClick ? cursorStyle : defaultCursorStyle}\n >\n {`${item.sku} ${item.name}`}\n </div>\n </Slot>\n ))}\n </div>\n )}\n\n {showEmptyState && (\n <div\n className=\"b2b-quick-order-search__empty-state\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {t.searchEmptyState}\n </div>\n )}\n\n {showResults && (\n <div\n className=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n >\n {items.length}{' '}\n {items.length === 1 ? t.resultAvailable : t.resultsAvailable}.{' '}\n {t.srInstructions}\n </div>\n )}\n </div>\n );\n};\n\nexport const Search = memo(SearchComponent) as typeof SearchComponent;\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 { QuickOrderDisabledOverlayProps } from '@/b2b-quick-order/types';\nimport '@/b2b-quick-order/components/QuickOrderDisabledOverlay/QuickOrderDisabledOverlay.css';\n\nexport const QuickOrderDisabledOverlay: FunctionComponent<\n QuickOrderDisabledOverlayProps\n> = ({ isDisabled, message, children }) => {\n return (\n <div className=\"b2b-quick-order-disabled-overlay\">\n <div\n className=\"b2b-quick-order-disabled-overlay__content\"\n style={{ pointerEvents: isDisabled ? 'none' : 'auto' }}\n >\n {children}\n </div>\n {isDisabled && (\n <>\n <div className=\"b2b-quick-order-disabled-overlay__blur\" />\n <div className=\"b2b-quick-order-disabled-overlay__message\">\n {message}\n </div>\n </>\n )}\n </div>\n );\n};\n"],"names":["classes","result","item","className","isActive","CsvFileInputComponent","t","onFileUpload","error","fileName","onDownloadSample","showSampleDownload","disabled","handleFileChange","useCallback","e","file","_a","jsxs","jsx","Fragment","InputFile","CsvFileInput","memo","debounce","fn","ms","timeoutId","debouncedFn","args","SEARCH_FILTER","handleSearchBlur","options","containerRef","itemSelected","initialValue","currentValue","onValueRestore","onClose","activeElement","createBlurHandler","delay","clearBlurTimeout","timeoutRef","handleArrowDown","currentIndex","itemsLength","handleArrowUp","handleHomeKey","handleEndKey","handleEnterKey","activeIndex","items","onItemSelect","handleEscapeKey","inputRef","useItemSearch","productsSearch","initialSku","replaceItemSku","searchFilter","searchValue","setSearchValue","useState","searchResults","setSearchResults","isTouched","setIsTouched","isMountedRef","useRef","useEffect","debouncedSearch","useMemo","searchTerm","handleSearchChange","value","resetSearch","handleItemClick","clickedItem","itemData","events","useSearch","onChange","shouldShowResults","onItemClick","setActiveIndex","setInitialValue","setItemSelected","isClosedManually","setIsClosedManually","resultsId","itemRefs","blurTimeoutRef","isOpen","showResults","showEmptyState","element","handleChange","createItemClickHandler","handleFocus","handleBlur","restoredValue","handleKeyDown","prev","getActiveDescendant","QuickOrderItemsListComponent","onRemove","clearItems","onUpdateQuantity","slots","handleAddToCart","isItemUpdating","loading","isDisabledButton","CartList","QuickOrderListItem","Divider","Search","Slot","Button","QuickOrderItemsList","QuickOrderListItemComponent","isUpdating","scope","currentSku","formName","isValid","hasOptions","hasRequiredOptions","option","hasSelectedOptions","optionItem","allRequiredOptionsSelected","mainImage","img","handleRemove","handleQuantityChange","newQty","form","qtyInput","searchSlot","CartItem","_b","PriceRange","AccordionSection","cursorStyle","defaultCursorStyle","SearchComponent","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AC3B,EAxBKA,EAAK,GAAA,CA0Bb,CAAA,CAAA,EAIJ6F,GACC5E,EAAC,MAAA,CACC,UAAU,sCACV,KAAK,SACL,YAAU,SAET,SAAAb,EAAE,gBAAA,CAAA,EAINwF,GACC5E,EAAC,MAAA,CACC,UAAU,UACV,KAAK,SACL,YAAU,SACV,cAAY,OAEX,SAAA,CAAAkC,EAAM,OAAQ,IACdA,EAAM,SAAW,EAAI9C,EAAE,gBAAkBA,EAAE,iBAAiB,IAAE,IAC9DA,EAAE,cAAA,CAAA,CAAA,CACL,CAAA,CAAA,CAIR,EAEa+G,EAAS9F,EAAK4H,EAAe,EC9H7BI,GAET,CAAC,CAAE,WAAAC,EAAY,QAAAC,EAAS,SAAAC,KAExBxI,EAAC,MAAA,CAAI,UAAU,mCACb,SAAA,CAAAC,EAAC,MAAA,CACC,UAAU,4CACV,MAAO,CAAE,cAAeqI,EAAa,OAAS,MAAA,EAE7C,SAAAE,CAAA,CAAA,EAEFF,GACCtI,EAAAE,EAAA,CACE,SAAA,CAAAD,EAAC,MAAA,CAAI,UAAU,wCAAA,CAAyC,EACxDA,EAAC,MAAA,CAAI,UAAU,4CACZ,SAAAsI,CAAA,CACH,CAAA,CAAA,CACF,CAAA,EAEJ","x_google_ignoreList":[0,2]}
@@ -1,6 +1,6 @@
1
1
  /*! Copyright 2026 Adobe
2
2
  All Rights Reserved. */
3
- import{jsx as v}from"@dropins/tools/preact-jsx-runtime.js";import{Q as V,C as S}from"../chunks/QuickOrderDisabledOverlay.js";import"@dropins/tools/components.js";import{classes as w}from"@dropins/tools/lib.js";import{useState as k,useCallback as f}from"@dropins/tools/preact-hooks.js";import{events as h}from"@dropins/tools/event-bus.js";import{useText as Q}from"@dropins/tools/i18n.js";import{c as y}from"../chunks/initialize.js";import"@dropins/tools/preact-compat.js";import"@dropins/tools/fetch-graphql.js";const F=n=>n.trim().replace(/^["']|["']$/g,""),O=200,I=(n,t)=>{const i=n.replace(/^\uFEFF/,"").trim().split(/\r?\n|\r/);if(!i.some(e=>e.trim()))return{isValid:!1,error:t.emptyFile};const a=i[0].split(",").map(e=>F(e).toLowerCase()),r=a.indexOf("sku"),c=a.indexOf("qty");if(r===-1||c===-1)return{isValid:!1,error:t.missingColumns};if(a.length!==2)return{isValid:!1,error:t.extraColumns};if(i.length-1>O)return{isValid:!1,error:t.maxRowsExceeded.replace("{maxRows}",O.toString())};const d=[];for(let e=1;e<i.length;e++){const s=i[e].trim();if(!s)continue;const u=s.split(",").map(x=>F(x)),l=u[r],C=u[c];if(!l)return{isValid:!1,error:t.skuRequired.replace("{rowNumber}",e.toString())};const o=parseInt(C,10);if(isNaN(o)||o<=0||!Number.isInteger(o))return{isValid:!1,error:t.invalidQuantity.replace("{rowNumber}",e.toString())};d.push({sku:l,quantity:o})}return d.length===0?{isValid:!1,error:t.noValidData}:{isValid:!0,data:d}},b=({routeSampleCSV:n,onFileUpload:t})=>{const[m,i]=k(null),[p,a]=k(null),r=Q({invalidFile:"QuickOrder.CsvFileInput.uploadCSVErrors.invalidFile",emptyFile:"QuickOrder.CsvFileInput.uploadCSVErrors.emptyFile",missingColumns:"QuickOrder.CsvFileInput.uploadCSVErrors.missingColumns",extraColumns:"QuickOrder.CsvFileInput.uploadCSVErrors.extraColumns",maxRowsExceeded:"QuickOrder.CsvFileInput.uploadCSVErrors.maxRowsExceeded",skuRequired:"QuickOrder.CsvFileInput.uploadCSVErrors.skuRequired",invalidQuantity:"QuickOrder.CsvFileInput.uploadCSVErrors.invalidQuantity",noValidData:"QuickOrder.CsvFileInput.uploadCSVErrors.noValidData",onlyCSV:"QuickOrder.CsvFileInput.uploadCSVErrors.onlyCSV",failedToRead:"QuickOrder.CsvFileInput.uploadCSVErrors.failedToRead",failedToParse:"QuickOrder.CsvFileInput.uploadCSVErrors.failedToParse"}),c=f(e=>{if(i(null),a(e.name),!e.name.toLowerCase().endsWith(".csv")){i(r.onlyCSV);return}const s=new FileReader;s.onload=u=>{var l;try{const C=(l=u.target)==null?void 0:l.result,o=I(C,{emptyFile:r.emptyFile,missingColumns:r.missingColumns,extraColumns:r.extraColumns,maxRowsExceeded:r.maxRowsExceeded,skuRequired:r.skuRequired,invalidQuantity:r.invalidQuantity,noValidData:r.noValidData});if(!o.isValid){i(o.error);return}t?t(o.data):h.emit("quick-order/add-items",o.data),a(null),i(null)}catch{i(r.failedToParse)}},s.onerror=()=>{i(r.failedToRead)},s.readAsText(e)},[t,r]),d=f(()=>{if(n)window.open(n,"_blank");else{const e=`SKU,QTY
3
+ import{jsx as v}from"@dropins/tools/preact-jsx-runtime.js";import{Q as V,C as S}from"../chunks/QuickOrderDisabledOverlay.js";import"@dropins/tools/components.js";import{classes as w}from"@dropins/tools/lib.js";import{useState as k,useCallback as f}from"@dropins/tools/preact-hooks.js";import{events as h}from"@dropins/tools/event-bus.js";import{useText as Q}from"@dropins/tools/i18n.js";import{c as y}from"../chunks/initialize.js";import"@dropins/tools/preact-compat.js";import"@dropins/tools/fetch-graphql.js";const F=n=>n.trim().replace(/^["']|["']$/g,""),O=200,I=(n,t)=>{const i=n.replace(/^\uFEFF/,"").trim().split(/\r?\n|\r/);if(!i.some(e=>e.trim()))return{isValid:!1,error:t.emptyFile};const a=i[0].split(",").map(e=>F(e).toLowerCase()),r=a.indexOf("sku"),c=a.indexOf("qty");if(r===-1||c===-1)return{isValid:!1,error:t.missingColumns};if(a.length!==2)return{isValid:!1,error:t.extraColumns};if(i.length-1>O)return{isValid:!1,error:t.maxRowsExceeded.replace("{maxRows}",O.toString())};const d=[];for(let e=1;e<i.length;e++){const s=i[e].trim();if(!s)continue;const u=s.split(",").map(x=>F(x)),l=u[r],C=u[c];if(!l)return{isValid:!1,error:t.skuRequired.replace("{rowNumber}",e.toString())};const o=parseInt(C,10);if(isNaN(o)||o<=0||!Number.isInteger(o))return{isValid:!1,error:t.invalidQuantity.replace("{rowNumber}",e.toString())};d.push({sku:l,quantity:o})}return d.length===0?{isValid:!1,error:t.noValidData}:{isValid:!0,data:d}},b=({routeSampleCSV:n,onFileUpload:t})=>{const[m,i]=k(null),[p,a]=k(null),r=Q({invalidFile:"QuickOrder.CsvFileInput.uploadCSVErrors.invalidFile",emptyFile:"QuickOrder.CsvFileInput.uploadCSVErrors.emptyFile",missingColumns:"QuickOrder.CsvFileInput.uploadCSVErrors.missingColumns",extraColumns:"QuickOrder.CsvFileInput.uploadCSVErrors.extraColumns",maxRowsExceeded:"QuickOrder.CsvFileInput.uploadCSVErrors.maxRowsExceeded",skuRequired:"QuickOrder.CsvFileInput.uploadCSVErrors.skuRequired",invalidQuantity:"QuickOrder.CsvFileInput.uploadCSVErrors.invalidQuantity",noValidData:"QuickOrder.CsvFileInput.uploadCSVErrors.noValidData",onlyCSV:"QuickOrder.CsvFileInput.uploadCSVErrors.onlyCSV",failedToRead:"QuickOrder.CsvFileInput.uploadCSVErrors.failedToRead",failedToParse:"QuickOrder.CsvFileInput.uploadCSVErrors.failedToParse"}),c=f(e=>{if(i(null),a(e.name),!e.name.toLowerCase().endsWith(".csv")){i(r.onlyCSV);return}const s=new FileReader;s.onload=u=>{var l;try{const C=(l=u.target)==null?void 0:l.result,o=I(C,{emptyFile:r.emptyFile,missingColumns:r.missingColumns,extraColumns:r.extraColumns,maxRowsExceeded:r.maxRowsExceeded,skuRequired:r.skuRequired,invalidQuantity:r.invalidQuantity,noValidData:r.noValidData});if(!o.isValid){i(o.error);return}t?t(o.data):h.emit("quick-order/add-items",o.data),a(null),i(null)}catch{i(r.failedToParse)}},s.onerror=()=>{i(r.failedToRead)},s.readAsText(e)},[t,r]),d=f(()=>{if(n)window.open(n(),"_blank");else{const e=`SKU,QTY
4
4
  SKU123,1
5
5
  SKU456,2
6
6
  SKU789,3`,s=new Blob([e],{type:"text/csv"}),u=URL.createObjectURL(s),l=document.createElement("a");l.href=u,l.download="sample-quick-order.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(u)}},[n]);return{handleFileUpload:c,error:m,fileName:p,handleDownloadSample:d,showSampleDownload:!0}},K=({className:n,routeSampleCSV:t,onFileUpload:m})=>{const i=y.getConfig().quickOrderActive,p=Q({title:"QuickOrder.CsvFileInput.title",helperText:"QuickOrder.CsvFileInput.helperText",downloadSample:"QuickOrder.CsvFileInput.downloadSample",inputLabel:"QuickOrder.CsvFileInput.inputLabel",selectedFile:"QuickOrder.CsvFileInput.selectedFile",disabledMessage:"QuickOrder.QuickOrderItem.disabledMessage"}),{handleFileUpload:a,error:r,fileName:c,handleDownloadSample:d,showSampleDownload:e}=b({routeSampleCSV:t,onFileUpload:m});return v("div",{className:w(["b2b-quick-order-quick-order-upload-csv",n]),"data-testid":"quick-order-upload-csv",children:v(V,{isDisabled:!i,message:p.disabledMessage,children:v(S,{t:p,onFileUpload:a,error:r,fileName:c,onDownloadSample:d,showSampleDownload:e})})})};export{K as QuickOrderCsvUpload,K as default};
@@ -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","config","showSampleDownload","jsx","classes","QuickOrderDisabledOverlay","CsvFileInput"],"mappings":"+fAuBO,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,Q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AAAY,EACA,mBAAoB,EAAA,CAExB,ECpGaK,EAA2D,CAAC,CACvE,UAAAC,EACA,eAAAvB,EACA,aAAAC,CACF,IAAM,CACJ,MAAMuB,EAAqBC,EAAO,UAAA,EAAY,iBAExClB,EAAIC,EAAQ,CAChB,MAAO,gCACP,WAAY,qCACZ,eAAgB,yCAChB,WAAY,qCACZ,aAAc,uCACd,gBAAiB,2CAAA,CAClB,EAEK,CACJ,iBAAAC,EACA,MAAAP,EACA,SAAAG,EACA,qBAAAY,EACA,mBAAAS,CAAA,EACE3B,EAAuB,CACzB,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
+ {"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":"+fAuBO,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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L,SAAS,KAAK,YAAYA,CAAI,EAC9B,IAAI,gBAAgBD,CAAG,CACzB,CACF,EAAG,CAACpB,CAAc,CAAC,EAEnB,MAAO,CACL,iBAAAS,EACA,MAAAP,EACA,SAAAG,EACA,qBAAAY,EACA,mBAAoB,EAAA,CAExB,ECpGaK,EAA2D,CAAC,CACvE,UAAAC,EACA,eAAAvB,EACA,aAAAC,CACF,IAAM,CACJ,MAAMuB,EAAqBC,EAAO,UAAA,EAAY,iBAExClB,EAAIC,EAAQ,CAChB,MAAO,gCACP,WAAY,qCACZ,eAAgB,yCAChB,WAAY,qCACZ,aAAc,uCACd,gBAAiB,2CAAA,CAClB,EAEK,CACJ,iBAAAC,EACA,MAAAP,EACA,SAAAG,EACA,qBAAAY,EACA,mBAAAS,CAAA,EACE3B,EAAuB,CACzB,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 er,a as tr}from"../chunks/QuickOrderDisabledOverlay.js";import{classes as j}from"@dropins/tools/lib.js";import{useState as R,useRef as J,useCallback as A,useEffect as Q}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=t=>{const e=[],r=[];return t.forEach((n,u)=>{if(sr.includes(u))return;const i=n;i&&i.match(/^[A-Za-z0-9+/=]+$/)?e.push(i):r.push({uid:u,value:i})}),{optionUIDs:e,enteredOptions:r}},or=t=>{const e=Number(t.get("quantity")),r=!e||e<1?1:e,n={sku:t.get("sku"),quantity:r},u=t.get("parentSku");u&&(n.parentSku=u);const{optionUIDs:i,enteredOptions:a}=ir(t);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=(t,e)=>!e||!Array.isArray(e)?t.map(r=>({..._,sku:r.sku,quantity:r.quantity??1})):t.map(r=>{const n=e.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}}),P=t=>t.length===0?!1:t.every(e=>!((e.urlKey||e.url)&&e.name)||e.inStock===!1?!1:e.options&&e.options.length>0?e.options.some(i=>i.required)?e.options.every(i=>{var a;return i.required?(a=i.items)==null?void 0:a.some(l=>l.selected):!0}):e.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0)):!0),x=t=>{const e=[];return t.forEach(r=>{if(!((r.urlKey||r.url)&&r.name)){e.push({sku:r.sku,name:r.name||"Unknown",reason:"incomplete_data"});return}if(r.inStock===!1){e.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(y=>y.selected):!0})||e.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))||e.push({sku:r.sku,name:r.name,reason:"missing_options"})}}),e},w=t=>`quick-order-item-${t.id||t.variantSku||t.sku}`,K=t=>`${t}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,W=(t,e)=>t.findIndex(r=>e.variantSku&&r.variantSku?r.variantSku===e.variantSku:r.variantSku&&!e.variantSku&&e.sku?r.variantSku===e.sku:e.variantSku&&!r.variantSku&&r.sku?r.sku===e.variantSku:!e.variantSku&&!r.variantSku?r.sku===e.sku:!1),ar=(t,e,r)=>t.findIndex(n=>n.id===r?!1:e.variantSku&&n.variantSku?n.variantSku===e.variantSku:e.variantSku&&!n.variantSku&&n.sku?n.sku===e.variantSku:!1),ur=(t,e,r,n=1)=>t.map((u,i)=>i===r?{...u,quantity:u.quantity+n}:i===e?null:u).filter(Boolean),cr=(t,e,r)=>{const n=[...t],u=[],i=[],a=[];return e.forEach((l,h)=>{const y=r[h];if(y!=null&&y.replaceItemSku){const p=n.findIndex(g=>g.sku===y.replaceItemSku||g.id===y.replaceItemSku);if(p!==-1){const g=W(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:K(l.sku)};n[p]=O,i.push(O)}return}}const q=W(n,l);if(q!==-1)n[q]={...n[q],quantity:n[q].quantity+l.quantity},a.push(n[q]);else{const p={...l,id:K(l.sku)};n.push(p),u.push(p)}}),{updatedItems:n,addedItems:u,replacedItems:i,mergedItems:a}},dr=(t,e,r,n=1)=>{const u=e?ar(t,r,e):-1;if(u!==-1){const a=t.findIndex(l=>l.id===e);return{updatedItems:ur(t,a,u,n),wasMerged:!0,mergedIntoIndex:u}}return{updatedItems:t.map(a=>e&&a.id===e?{...a,...r,id:e}:!e&&a.sku===r.sku?{...a,...r}:a),wasMerged:!1}},lr=t=>t.map(e=>{const r=e.id||e.sku,n=document.forms[`form-${r}`];if(!n)return null;const u=new FormData(n);return u.get("valid")==="true"?or(u):null}),kr=t=>{let e=[];return t&&typeof t=="object"?t.optionsUIDs&&Array.isArray(t.optionsUIDs)?e=t.optionsUIDs:Array.isArray(t)&&(e=t):typeof t=="string"&&(e=[t]),e},G=t=>{try{const e=localStorage.getItem(t);if(e)return JSON.parse(e)}catch(e){console.error("Error reading from localStorage:",e)}return{}},fr=(t,e,r)=>{if(r.length!==0)try{const n=G(t);n[e]=r,localStorage.setItem(t,JSON.stringify(n))}catch(n){console.error("Error saving to localStorage:",n)}},pr=(t,e,r)=>t.map(n=>{const u=e.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=t=>{const e=!t.inStock||!t.addToCartAllowed;if(t.options&&t.options.length>0){if(t.options.some(i=>!i.items||i.items.length===0))return!0;if(t.options.some(i=>i.required)){const i=t.options.every(a=>{var l;return a.required?(l=a.items)==null?void 0:l.some(h=>h.selected):!0});return e||!i}const u=t.options.some(i=>i.items&&i.items.length>0&&i.items.some(a=>a.selected===!0));return e||!u}return e},hr=({getProductsData:t,handleAddToCart:e}={})=>{const[r,n]=R([]),[u,i]=R(!1),[a,l]=R(new Set),[h,y]=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=>{y(s)},[]);Q(()=>{const s=S.on("quick-order/loading",o=>{i(o)},{eager:!0});return()=>{s==null||s.off()}},[]),Q(()=>{const s=S.on("quick-order/add-items",async o=>{if(o&&o.length>0){if(!t)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 t(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()}},[t,b]),Q(()=>{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]),Q(()=>{const s=P(r);b(!s)},[r,b]),Q(()=>{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]),Q(()=>{!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]),Q(()=>{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]),Q(()=>{C.current=g},[g]),Q(()=>{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]),Q(()=>{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&&!P(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);e?(S.emit("quick-order/loading",!0),Promise.resolve(e(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,e,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:t,onDismiss:e,onSkuClick:r,validationErrorText:n,backendErrorText:u,successText:i,partialSuccessText:a})=>{if(!t)return null;const l=()=>{switch(t.type){case"validation":return Or(n,t.clickableSkus,t.details,r);case"partial-success":return Sr(a,t.message,t.count,t.clickableSkus,r);case"backend-error":return Ir(u,t.details);case"success":return yr(i,t.count);default:return v("span",{children:t.message})}};return v("div",{className:j(["b2b-quick-order-notification-banner",[`b2b-quick-order-notification-banner--${t.variant}`,t.variant]]),children:v(rr,{variant:t.variant,message:l(),onDismiss:e})})};function Y(t,e){return t.map((r,n)=>D("span",{children:[v("a",{href:"#",onClick:u=>{u.preventDefault(),e(r)},style:{cursor:"pointer",textDecoration:"underline",color:"white"},children:r}),n<t.length-1?", ":""]},r))}function Or(t,e,r,n){return e!=null&&e.length&&n?D("span",{children:[t," - ",Y(e,n)]}):D("span",{children:[t," - ",r]})}function Sr(t,e,r,n,u){if(!t)return v("span",{children:e});const i=t.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(t,e){return D("span",{children:[t,e?` - ${e}`:""]})}function yr(t,e){return e!==void 0?v("span",{children:t.replace("{count}",String(e))}):v("span",{children:t})}const Tr=({className:t,slots:e,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:y,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});Q(()=>{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:j(["b2b-quick-order-quick-order-items",!a&&"b2b-quick-order-disabled",t]),"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(er,{isDisabled:!a,message:h.disabledMessage,children:v(tr,{t:h,items:y,onRemove:p,clearItems:g,onUpdateQuantity:O,handleAddToCart:C,isItemUpdating:I,slots:e,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{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};
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 (data: OrderItemInput[]) => {\n if (data && data.length > 0) {\n if (!getProductsData) {\n return;\n }\n\n setLoading(true);\n events.emit('quick-order/loading', true);\n const requestedSkus = data.map((item) => item.sku).filter(Boolean);\n setUpdatingItems(\n (prev) => new Set([...Array.from(prev), ...requestedSkus])\n );\n\n try {\n let newItems: OrderItem[] = [];\n try {\n const products = await getProductsData(data);\n setDisabledCartButton(data.length !== products.length);\n newItems = mapProductsToOrderItems(data, products);\n } catch (error) {\n console.error('Error fetching products data:', error);\n newItems = mapProductsToOrderItems(data, []);\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, data);\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); // Emit loading event before starting add to cart process\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","saveOptionsToStorage","storageData","e","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","data","requestedSkus","prev","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,MA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EAAE,4BACvB,iBAAkBA,EAAE,yBACpB,YAAaA,EAAE,oBACf,mBAAoBA,EAAE,0BAAA,CAAA,EAE1B,EACA2D,EAACqB,GAAA,CACC,WAAY,CAACN,EACb,QAAS1E,EAAE,gBAEX,SAAA2D,EAACsB,GAAA,CACC,EAAAjF,EACA,MAAA9E,EACA,SAAUoH,EACV,WAAAE,EACA,iBAAkBC,EAClB,gBAAiBE,EACjB,eAAAD,EACA,MAAA6B,EACA,QAAAnF,EACA,sBAAAiB,EACA,iBAAAb,EACA,eAAAgF,EACA,aAAAC,CAAA,CAAA,CACF,CAAA,CACF,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":"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,EAAS,IAAI,WAAW,EACtCU,IACFD,EAAS,UAAYC,GAGvB,KAAM,CAAE,WAAAT,EAAY,eAAAC,GAAmBH,GAAmBC,CAAQ,EAElE,OAAIC,EAAW,OAAS,IACtBQ,EAAS,YAAcR,GAGrBC,EAAe,OAAS,IAC1BO,EAAS,eAAiBP,GAGrBO,CACT,ECrCaE,EAAsC,CACjD,IAAK,GACL,SAAU,EACV,KAAM,GACN,OAAQ,CAAA,EACR,QAAS,GACT,iBAAkB,GAClB,SAAU,GACV,OAAQ,CAAA,EACR,WAAY,CAAA,EACZ,QAAS,CAAA,EACT,IAAK,GACL,OAAQ,GACR,WAAY,GACZ,YAAa,SACb,iBAAkB,GAClB,gBAAiB,GACjB,YA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AAkBjJ,GAAgB,CAEtC,MAAMkJ,EAAc,SAAS,cAC3B,kBAAkBlJ,CAAG,IAAA,EAGnBkJ,GAEFA,EAAY,eAAe,CACzB,SAAU,SACV,MAAO,QAAA,CACR,CAEL,EAEA,OACEC,EAAC,MAAA,CACC,UAAWnB,EAAQ,CACjB,oCACA,CAACc,GAAsB,2BACvBJ,CAAA,CACD,EACD,cAAY,oBACZ,MAAO,CAAE,SAAU,UAAA,EAEnB,SAAA,CAAAX,EAAC,MAAA,CAAI,IAAKiB,EACR,SAAAjB,EAACZ,GAAA,CACC,aAAAtD,EACA,UAAWS,EACX,WAAY2E,EACZ,oBAAqB9E,EAAE,4BACvB,iBAAkBA,EAAE,yBACpB,YAAaA,EAAE,oBACf,mBAAoBA,EAAE,0BAAA,CAAA,EAE1B,EACA4D,EAACqB,GAAA,CACC,WAAY,CAACN,EACb,QAAS3E,EAAE,gBAEX,SAAA4D,EAACsB,GAAA,CACC,EAAAlF,EACA,MAAA9E,EACA,SAAUqH,EACV,WAAAE,EACA,iBAAkBC,EAClB,gBAAiBE,EACjB,eAAAD,EACA,MAAA6B,EACA,QAAApF,EACA,sBAAAiB,EACA,iBAAAb,EACA,eAAAiF,EACA,aAAAC,CAAA,CAAA,CACF,CAAA,CACF,CAAA,CAAA,CAGN"}
@@ -53,7 +53,7 @@ declare const _default: {
53
53
  "productNotFound": "Product not found",
54
54
  "productNotFoundDescription": "The product with SKU {sku} could not be found",
55
55
  "configurableProductError": "Configuration required",
56
- "configurableProductErrorDescription": "Configurable products aren’t supported here. Use the correct component for products with options. ",
56
+ "configurableProductErrorDescription": "Use ProductOptions Slot in QuickOrderItems container to enable configurable product options.",
57
57
  "configurableOptionsWarning": "Product configuration required",
58
58
  "configurableOptionsWarningDescription": "Please select all required product options before adding to cart",
59
59
  "productOptions": "Product Options",
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name": "@dropins/storefront-quick-order", "version": "0.1.2-alpha1", "@dropins/tools": "~1.6.0", "license": "SEE LICENSE IN LICENSE.md"}
1
+ {"name": "@dropins/storefront-quick-order", "version": "0.1.2-alpha2", "@dropins/tools": "~1.7.0", "license": "SEE LICENSE IN LICENSE.md"}
package/render.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*! Copyright 2026 Adobe
2
2
  All Rights Reserved. */
3
3
  (function(i,o){try{if(typeof document<"u"){const r=document.createElement("style"),a=o.styleId;for(const e in o.attributes)r.setAttribute(e,o.attributes[e]);r.setAttribute("data-dropin",a),r.appendChild(document.createTextNode(i));const t=document.querySelector('style[data-dropin="sdk"]');if(t)t.after(r);else{const e=document.querySelector('link[rel="stylesheet"], style');e?e.before(r):document.head.append(r)}}}catch(r){console.error("dropin-styles (injectCodeFunction)",r)}})(".b2b-quick-order-quick-order-multiple-sku{display:flex;flex-direction:column;gap:var(--grid-1-gutters)}.b2b-quick-order-sku-list-input__title{color:var(--color-neutral-800);font:var(--type-headline-2-font);letter-spacing:var(--type-headline-2-letter-spacing);margin-bottom:var(--spacing-small)}.b2b-quick-order-sku-list-input__textarea{margin-bottom:var(--spacing-xsmall)}.b2b-quick-order-sku-list-input__message{font:var(--type-details-caption-2-font);letter-spacing:var(--type-details-caption-2-letter-spacing);margin-bottom:var(--spacing-xsmall);text-align:left}.b2b-quick-order-csv-file-input{display:flex;flex-direction:column;gap:var(--grid-1-gutters)}.b2b-quick-order-csv-file-input__title{color:var(--color-neutral-800);font:var(--type-headline-2-font);letter-spacing:var(--type-headline-2-letter-spacing)}.b2b-quick-order-csv-file-input__helper{font:var(--type-details-caption-2-font);letter-spacing:var(--type-details-caption-2-letter-spacing);text-align:left}.b2b-quick-order-csv-file-input__download-link{color:var(--color-informational-800);text-decoration:underline;background:none;border:none;padding:0;cursor:pointer;font-size:inherit}.b2b-quick-order-csv-file-input__download-link:hover{color:var(--color-informational-500)}.b2b-quick-order-csv-file-input__input-wrapper{margin-top:var(--spacing-xsmall);width:max-content}.b2b-quick-order-csv-file-input__input{width:100%}.b2b-quick-order-csv-file-input__input-wrapper--disabled button,.b2b-quick-order-csv-file-input__input-wrapper--disabled label,.b2b-quick-order-csv-file-input__input-wrapper--disabled .dropin-button{background:var(--color-neutral-300) 0 0% no-repeat padding-box!important;color:var(--color-neutral-500)!important;fill:var(--color-neutral-300)!important;pointer-events:none;-webkit-user-select:none;user-select:none;cursor:not-allowed!important}.b2b-quick-order-csv-file-input__input:has(input:disabled) button,.b2b-quick-order-csv-file-input__input:has(input:disabled) label{background:var(--color-neutral-300) 0 0% no-repeat padding-box;color:var(--color-neutral-500);fill:var(--color-neutral-300);pointer-events:none;-webkit-user-select:none;user-select:none;cursor:not-allowed}.b2b-quick-order-csv-file-input__input--loading{cursor:not-allowed;opacity:.3}.b2b-quick-order-csv-file-input__file-name{font:var(--type-body-2-default-font);letter-spacing:var(--type-body-2-default-letter-spacing)}.b2b-quick-order-csv-file-input__error{font:var(--type-details-caption-2-font);letter-spacing:var(--type-details-caption-2-letter-spacing);padding-top:var(--spacing-xsmall);text-align:left;color:var(--color-alert-800)}.b2b-quick-order-form-quick-order-items-list{width:100%}.b2b-quick-order-form-quick-order-items-list__title{color:var(--color-neutral-800);font:var(--type-headline-2-font);letter-spacing:var(--type-headline-2-letter-spacing);margin-bottom:var(--spacing-small)}.b2b-quick-order-form-quick-order-items-list__empty{color:var(--color-neutral-600);font:var(--type-body-1-font);letter-spacing:var(--type-body-1-letter-spacing);text-align:center;padding:var(--spacing-large)}.b2b-quick-order-form-quick-order-items-list__actions{display:flex;justify-content:flex-start;margin-top:var(--spacing-medium)}.b2b-quick-order-form-quick-order-items-list__warning{background-color:var(--color-warning-200, #fef3cd);border:1px solid var(--color-warning-500, #ff9800);border-radius:var(--shape-border-radius-2);padding:var(--spacing-medium);margin-bottom:var(--spacing-medium)}.b2b-quick-order-form-quick-order-items-list__warning-title{color:var(--color-warning-800, #e65100);font:var(--type-body-1-strong-font);letter-spacing:var(--type-body-1-strong-letter-spacing);margin-bottom:var(--spacing-xsmall)}.b2b-quick-order-form-quick-order-items-list__warning-description{color:var(--color-warning-700, #f57c00);font:var(--type-body-2-font);letter-spacing:var(--type-body-2-letter-spacing)}.b2b-quick-order-form-quick-order-items-list .dropin-divider--secondary{border-width:var(--shape-border-width-3);margin-top:0}@media screen and (max-width: 1285px){.b2b-quick-order-form-quick-order-items-list .dropin-divider--secondary{display:none}}.b2b-quick-order-form-quick-order-items-list__actions--disabled{background-color:red}.b2b-quick-order-form-quick-order-items__item-form{min-height:170px}.b2b-quick-order-form-quick-order-items__item-form .dropin-accordion-section__content-container{margin-bottom:0}.b2b-quick-order-form-quick-order-items__item-form:last-child{margin-bottom:var(--spacing-medium)}.b2b-quick-order-list-item__accordion .dropin-accordion-section__title{color:var(--color-neutral-800);font:var(--type-body-2-default-font);letter-spacing:var(--type-body-2-default-letter-spacing)}.b2b-quick-order-items__error{color:var(--color-alert-800);font:var(--type-details-caption-2-font);letter-spacing:var(--type-details-caption-2-letter-spacing)}.b2b-quick-order-form-quick-order-items__item-search{margin-bottom:var(--spacing-big)}.b2b-quick-order-items__configurable-error{color:var(--color-alert-500);font:var(--type-details-caption-2-font);letter-spacing:var(--type-details-caption-2-letter-spacing)}.b2b-quick-order-search{position:relative;width:100%}.b2b-quick-order-search__input{width:100%}.b2b-quick-order-search__results{position:absolute;top:100%;left:0;right:0;background-color:var(--color-neutral-50);border:var(--shape-border-width-1) solid var(--color-neutral-300);border-radius:var(--spacing-xxsmall);margin-top:var(--spacing-xxsmall);max-height:300px;overflow-y:auto;z-index:10;box-shadow:0 2px 8px #0000001a}.b2b-quick-order-search__result-item{padding:var(--spacing-xsmall) var(--spacing-small);cursor:pointer;transition:background-color .2s,outline .2s}.b2b-quick-order-search__result-item:hover{background-color:var(--color-neutral-100)}.b2b-quick-order-search__result-item--active,.b2b-quick-order-search__result-item[aria-selected=true]{background-color:var(--color-neutral-100);outline:2px solid var(--color-brand-500);outline-offset:-2px}.b2b-quick-order-search__result-item:not(:last-child){border-bottom:var(--shape-border-width-1) solid var(--color-neutral-200)}.b2b-quick-order-search__empty-state{position:absolute;top:100%;left:0;right:0;z-index:10;text-align:center;background-color:var(--color-neutral-50);border:var(--shape-border-width-1) solid var(--color-neutral-300);border-radius:var(--shape-border-radius-1);margin-top:var(--spacing-xxsmall);padding:var(--spacing-small);color:var(--color-neutral-600);box-shadow:0 2px 8px #0000001a}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.b2b-quick-order-notification-banner{margin-bottom:20px}.b2b-quick-order-notification-banner .dropin-alert-banner__message{max-width:500px}.b2b-quick-order-notification-banner--warning .dropin-alert-banner{background-color:var(--color-warning-500)}.b2b-quick-order-notification-banner--success .dropin-alert-banner{background-color:var(--color-positive-500)}.b2b-quick-order-notification-banner--neutral .dropin-alert-banner{background-color:var(--color-neutral-600)}.b2b-quick-order-notification-banner--brand .dropin-alert-banner{background-color:var(--color-brand-500)}.b2b-quick-order-disabled-overlay{position:relative}.b2b-quick-order-disabled-overlay__blur{position:absolute;top:0;right:0;bottom:0;left:0;-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);background-color:#ffffffb3;z-index:1}.b2b-quick-order-disabled-overlay__message{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;font-size:16px;font-weight:500;color:#666;text-align:center;padding:20px}",{styleId:"b2b-quick-order"});
4
- import{jsx as o}from"@dropins/tools/preact-jsx-runtime.js";import{Render as n}from"@dropins/tools/lib.js";import{useState as d,useEffect as s}from"@dropins/tools/preact-hooks.js";import{UIProvider as l}from"@dropins/tools/components.js";import{events as u}from"@dropins/tools/event-bus.js";const c={Search:{placeholder:"Search by SKU...",ariaLabel:"Search for products by SKU",emptyState:"No results found",resultsAvailable:"results available",resultAvailable:"result available",srInstructions:"Use arrow keys or Tab to navigate, Enter or Space to select, Escape to close."},SkuListInput:{title:"Add Products by SKU",helperText:"Use commas or paragraphs to separate SKUs.",textArea:{label:"Enter Multiple SKUs",placeholder:"Enter SKUs here..."},button:"Add to List"},CsvFileInput:{title:"Add from File",helperText:'File must be in .csv format and include "SKU" and "QTY" columns ',downloadSample:"Download sample",inputLabel:"Choose File",selectedFile:"Selected file",uploadCSVErrors:{invalidFile:"Invalid CSV file",emptyFile:"File is empty",missingColumns:'Must contain "SKU" and "QTY" columns',extraColumns:'Must contain only "SKU" and "QTY" columns',maxRowsExceeded:"File exceeds maximum of {maxRows} rows",skuRequired:"Row {rowNumber}: SKU is required",invalidQuantity:"Row {rowNumber}: QTY must be a positive integer",noValidData:"File contains no valid data rows",onlyCSV:"Only CSV files are allowed",failedToRead:"Failed to read file",failedToParse:"Failed to parse CSV file"}},QuickOrderItem:{title:"Enter SKU or search by Product Name",quantity:"Quantity: ",price:"Price: ",sku:"SKU",remove:"Remove",removeItem:"Remove item",showOptions:"Show additional options",hideOptions:"Hide additional options",additionalOptions:"Additional options",noAdditionalOptions:"No additional options available",emptyList:"No products in the list",loading:"Loading...",productNotFound:"Product not found",productNotFoundDescription:"The product with SKU {sku} could not be found",configurableProductError:"Configuration required",configurableProductErrorDescription:"Configurable products aren’t supported here. Use the correct component for products with options. ",configurableOptionsWarning:"Product configuration required",configurableOptionsWarningDescription:"Please select all required product options before adding to cart",productOptions:"Product Options",outOfStock:"Out of Stock",addAllToCart:"Add to Cart",disabledMessage:"Quick Order feature disabled",notification:{validationError:"Product(s) require(s) your attention",backendError:"An error occurred while adding products to the cart",success:"{count} product(s) successfully added to the cart",partialSuccess:"{count} of {total} products were added to the cart. Some products could not be added",unexpectedError:"An unexpected error has occurred"}}},p={QuickOrder:c},m={default:p},f=({children:t})=>{const[r,i]=d("en_US");return s(()=>{const e=u.on("locale",a=>{i(a)},{eager:!0});return()=>{e==null||e.off()}},[]),o(l,{lang:r,langDefinitions:m,children:t})},w=new n(o(f,{}));export{w as render};
4
+ import{jsx as o}from"@dropins/tools/preact-jsx-runtime.js";import{Render as n}from"@dropins/tools/lib.js";import{useState as d,useEffect as s}from"@dropins/tools/preact-hooks.js";import{UIProvider as l}from"@dropins/tools/components.js";import{events as u}from"@dropins/tools/event-bus.js";const c={Search:{placeholder:"Search by SKU...",ariaLabel:"Search for products by SKU",emptyState:"No results found",resultsAvailable:"results available",resultAvailable:"result available",srInstructions:"Use arrow keys or Tab to navigate, Enter or Space to select, Escape to close."},SkuListInput:{title:"Add Products by SKU",helperText:"Use commas or paragraphs to separate SKUs.",textArea:{label:"Enter Multiple SKUs",placeholder:"Enter SKUs here..."},button:"Add to List"},CsvFileInput:{title:"Add from File",helperText:'File must be in .csv format and include "SKU" and "QTY" columns ',downloadSample:"Download sample",inputLabel:"Choose File",selectedFile:"Selected file",uploadCSVErrors:{invalidFile:"Invalid CSV file",emptyFile:"File is empty",missingColumns:'Must contain "SKU" and "QTY" columns',extraColumns:'Must contain only "SKU" and "QTY" columns',maxRowsExceeded:"File exceeds maximum of {maxRows} rows",skuRequired:"Row {rowNumber}: SKU is required",invalidQuantity:"Row {rowNumber}: QTY must be a positive integer",noValidData:"File contains no valid data rows",onlyCSV:"Only CSV files are allowed",failedToRead:"Failed to read file",failedToParse:"Failed to parse CSV file"}},QuickOrderItem:{title:"Enter SKU or search by Product Name",quantity:"Quantity: ",price:"Price: ",sku:"SKU",remove:"Remove",removeItem:"Remove item",showOptions:"Show additional options",hideOptions:"Hide additional options",additionalOptions:"Additional options",noAdditionalOptions:"No additional options available",emptyList:"No products in the list",loading:"Loading...",productNotFound:"Product not found",productNotFoundDescription:"The product with SKU {sku} could not be found",configurableProductError:"Configuration required",configurableProductErrorDescription:"Use ProductOptions Slot in QuickOrderItems container to enable configurable product options.",configurableOptionsWarning:"Product configuration required",configurableOptionsWarningDescription:"Please select all required product options before adding to cart",productOptions:"Product Options",outOfStock:"Out of Stock",addAllToCart:"Add to Cart",disabledMessage:"Quick Order feature disabled",notification:{validationError:"Product(s) require(s) your attention",backendError:"An error occurred while adding products to the cart",success:"{count} product(s) successfully added to the cart",partialSuccess:"{count} of {total} products were added to the cart. Some products could not be added",unexpectedError:"An unexpected error has occurred"}}},p={QuickOrder:c},m={default:p},f=({children:t})=>{const[r,i]=d("en_US");return s(()=>{const e=u.on("locale",a=>{i(a)},{eager:!0});return()=>{e==null||e.off()}},[]),o(l,{lang:r,langDefinitions:m,children:t})},U=new n(o(f,{}));export{U as render};
5
5
  //# sourceMappingURL=render.js.map
package/render.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","sources":["/@dropins/storefront-quick-order/src/render/Provider.tsx","/@dropins/storefront-quick-order/src/render/render.tsx"],"sourcesContent":["import { FunctionComponent } from 'preact';\nimport { useState, useEffect } from 'preact/hooks';\nimport { UIProvider } from '@adobe-commerce/elsie/components';\nimport { Lang } from '@adobe-commerce/elsie/i18n';\nimport { events } from '@adobe-commerce/event-bus';\n\nimport en_US from '../i18n/en_US.json';\n\n// Langs\nconst langDefinitions = {\n default: en_US,\n};\n\ninterface CartProviderProps {\n children?: any;\n}\n\nexport const Provider: FunctionComponent<CartProviderProps> = ({\n children,\n}) => {\n const [lang, setLang] = useState<Lang>('en_US');\n\n // Events\n useEffect(() => {\n const localeEvent = events.on(\n 'locale',\n (locale: string) => {\n setLang(locale as Lang);\n },\n { eager: true }\n );\n return () => {\n localeEvent?.off();\n };\n }, []);\n\n return (\n <UIProvider lang={lang} langDefinitions={langDefinitions}>\n {children}\n </UIProvider>\n );\n};\n","import { Render } from '@adobe-commerce/elsie/lib';\nimport { Provider } from './Provider';\n\nexport const render = new Render(<Provider />);\n"],"names":["langDefinitions","en_US","Provider","children","lang","setLang","useState","useEffect","localeEvent","events","locale","jsx","UIProvider","render","Render"],"mappings":"oxFASMA,EAAkB,CACtB,QAASC,CACX,EAMaC,EAAiD,CAAC,CAC7D,SAAAC,CACF,IAAM,CACJ,KAAM,CAACC,EAAMC,CAAO,EAAIC,EAAe,OAAO,EAG9C,OAAAC,EAAU,IAAM,CACd,MAAMC,EAAcC,EAAO,GACzB,SACCC,GAAmB,CAClBL,EAAQK,CAAc,CACxB,EACA,CAAE,MAAO,EAAA,CAAK,EAEhB,MAAO,IAAM,CACXF,GAAA,MAAAA,EAAa,KACf,CACF,EAAG,CAAA,CAAE,EAGHG,EAACC,EAAA,CAAW,KAAAR,EAAY,gBAAAJ,EACrB,SAAAG,CAAA,CACH,CAEJ,ECtCaU,EAAS,IAAIC,EAAOH,EAACT,IAAS,CAAE"}
1
+ {"version":3,"file":"render.js","sources":["/@dropins/storefront-quick-order/src/render/Provider.tsx","/@dropins/storefront-quick-order/src/render/render.tsx"],"sourcesContent":["import { FunctionComponent } from 'preact';\nimport { useState, useEffect } from 'preact/hooks';\nimport { UIProvider } from '@adobe-commerce/elsie/components';\nimport { Lang } from '@adobe-commerce/elsie/i18n';\nimport { events } from '@adobe-commerce/event-bus';\n\nimport en_US from '../i18n/en_US.json';\n\n// Langs\nconst langDefinitions = {\n default: en_US,\n};\n\ninterface CartProviderProps {\n children?: any;\n}\n\nexport const Provider: FunctionComponent<CartProviderProps> = ({\n children,\n}) => {\n const [lang, setLang] = useState<Lang>('en_US');\n\n // Events\n useEffect(() => {\n const localeEvent = events.on(\n 'locale',\n (locale: string) => {\n setLang(locale as Lang);\n },\n { eager: true }\n );\n return () => {\n localeEvent?.off();\n };\n }, []);\n\n return (\n <UIProvider lang={lang} langDefinitions={langDefinitions}>\n {children}\n </UIProvider>\n );\n};\n","import { Render } from '@adobe-commerce/elsie/lib';\nimport { Provider } from './Provider';\n\nexport const render = new Render(<Provider />);\n"],"names":["langDefinitions","en_US","Provider","children","lang","setLang","useState","useEffect","localeEvent","events","locale","jsx","UIProvider","render","Render"],"mappings":"mwFASMA,EAAkB,CACtB,QAASC,CACX,EAMaC,EAAiD,CAAC,CAC7D,SAAAC,CACF,IAAM,CACJ,KAAM,CAACC,EAAMC,CAAO,EAAIC,EAAe,OAAO,EAG9C,OAAAC,EAAU,IAAM,CACd,MAAMC,EAAcC,EAAO,GACzB,SACCC,GAAmB,CAClBL,EAAQK,CAAc,CACxB,EACA,CAAE,MAAO,EAAA,CAAK,EAEhB,MAAO,IAAM,CACXF,GAAA,MAAAA,EAAa,KACf,CACF,EAAG,CAAA,CAAE,EAGHG,EAACC,EAAA,CAAW,KAAAR,EAAY,gBAAAJ,EACrB,SAAAG,CAAA,CACH,CAEJ,ECtCaU,EAAS,IAAIC,EAAOH,EAACT,IAAS,CAAE"}
@@ -2,7 +2,7 @@ import { SubmitSkuValue } from './quickOrderMultipleSku.types';
2
2
 
3
3
  export interface QuickOrderCsvUploadProps {
4
4
  className?: string;
5
- routeSampleCSV?: string;
5
+ routeSampleCSV?: () => string;
6
6
  onFileUpload?: (values: SubmitSkuValue) => void;
7
7
  }
8
8
  export interface CsvFileInputProps {
@@ -15,7 +15,7 @@ export interface CsvFileInputProps {
15
15
  disabled?: boolean;
16
16
  }
17
17
  export interface UseQuickOrderCsvUploadProps {
18
- routeSampleCSV?: string;
18
+ routeSampleCSV?: () => string;
19
19
  onFileUpload?: (values: SubmitSkuValue) => void;
20
20
  }
21
21
  export interface UseQuickOrderCsvUploadReturn {