@spiffcommerce/core 34.1.0-beta.7a56a636-d7cf-54ee-8dfc-5407b655bd46 → 34.1.0-beta.7d1062f1-7d67-5ea3-8640-5d0681c80907
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.
- package/dist/index.d.ts +0 -9
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +20 -15
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1095,10 +1095,6 @@ interface WorkflowExperience {
|
|
|
1095
1095
|
* Get the bundle this experience is part of. May be undefined.
|
|
1096
1096
|
*/
|
|
1097
1097
|
getBundle(): Bundle$1 | undefined;
|
|
1098
|
-
/**
|
|
1099
|
-
* The index of this transaction against its bundle, if part of one.
|
|
1100
|
-
*/
|
|
1101
|
-
getBundleIndex(): number | undefined;
|
|
1102
1098
|
/**
|
|
1103
1099
|
* Set the bundle this experience is part of. Can be cleared using undefined.
|
|
1104
1100
|
*/
|
|
@@ -1346,7 +1342,6 @@ declare class WorkflowExperienceImpl implements WorkflowExperience {
|
|
|
1346
1342
|
attachAddress(streetAddress?: string, apartment?: string, city?: string, country?: string, state?: string, postCode?: string): Promise<void>;
|
|
1347
1343
|
attachOrganization(name: string): Promise<void>;
|
|
1348
1344
|
getBundle(): Bundle$1 | undefined;
|
|
1349
|
-
getBundleIndex(): number | undefined;
|
|
1350
1345
|
setBundle(bundle: Bundle$1): void;
|
|
1351
1346
|
getClient(): SpiffCommerceClient;
|
|
1352
1347
|
getIsReadOnly(): boolean;
|
|
@@ -3774,10 +3769,6 @@ interface Transaction {
|
|
|
3774
3769
|
* modifying state of the transaction.
|
|
3775
3770
|
*/
|
|
3776
3771
|
id: string;
|
|
3777
|
-
/**
|
|
3778
|
-
* The index of this transaction against its bundle, if part of one.
|
|
3779
|
-
*/
|
|
3780
|
-
bundleIndex?: number;
|
|
3781
3772
|
/**
|
|
3782
3773
|
* User-supplied name for the associated design.
|
|
3783
3774
|
*/
|
package/dist/index.js
CHANGED
|
@@ -419,7 +419,6 @@
|
|
|
419
419
|
externalCartProductId
|
|
420
420
|
externalCartProductVariantId
|
|
421
421
|
id
|
|
422
|
-
bundleIndex
|
|
423
422
|
completed
|
|
424
423
|
lastSyncedAt
|
|
425
424
|
priceModifierTotal
|
|
@@ -2338,7 +2337,7 @@
|
|
|
2338
2337
|
}
|
|
2339
2338
|
}
|
|
2340
2339
|
}
|
|
2341
|
-
`;var Oe=(a=>(a.PriceBreakChanged="PriceBreakChanged",a.ProductChanged="ProductChanged",a.QuantityChanged="QuantityChanged",a.RecipientChanged="RecipientChanged",a.SelectionChanged="SelectionChanged",a))(Oe||{});class Gr{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Oa(async()=>{await xe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async n=>new Promise((r,i)=>{try{n.toBlob(o=>{if(o){const s=URL.createObjectURL(o);r(s)}})}catch(o){i(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(n=>n.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Fn(this,t,n=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(n)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(n=>{const r=n.traversableScenes.map(i=>{const o=i.renderableSteps.map(s=>s.stepName);return{id:i.name,title:i.title,renderableSteps:o,workflowScene:i}});this.renderableScenes=r,this.renderableSceneCallbacks.forEach(i=>i(r)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Ia,variables:{id:this.getTransaction().id,integrationProductId:t}}),n=e.data?.transactionUpdateIntegrationProduct.product;if(!n)throw new Q("Failed to set product. No product returned from server.");if(!this.bundle)throw new Q("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const r=(await this.bundle.getProductCollection().fetchProducts()).find(i=>i.getId()===n.id);try{const i=r?.getDefaultWorkflow();if(i){const o=await ai(i.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new Q("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Ia,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:Oo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,n,r,i,o){await this.graphQlClient().mutate({mutation:vc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:n||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Ec,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}getBundleIndex(){return this.transaction.bundleIndex}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const n=this.getWorkflow(),r=n?.finalizeStepConfig?.lookAtAnimation;if(!n)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!r)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=Ct(i,i),s=this.workflowManager.getCommandContext().getAllLayouts(),l=n.defaultPreviewPanelIndex||0,c=n.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Le("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),m=Ye(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),p=Ya(m);await(await Nn.Pith.from(h,p,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:Ct,createImage:ce,DOMParser:$n(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const n=this.cachedStepHandles.get(e.stepName);if(n)return n;const r=Ee.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let n=0;return Object.values(e).forEach(r=>{n+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(n,t)}getBasePriceSubunits(t,e){const n=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return n+r}return n}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const n=e?1:this.priceBreakToBeApplied(),r=t*n;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),n=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=n)return r.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,n=this.getTransaction().id,r=t.getProduct()?.id,i=this.getProduct()?.id;return e!==n&&r===i})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,n){const r=await t.getGlobalProperties(),i=n?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&m?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&m?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(n=>n.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Ee.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>Ee.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){if(!this.getWorkflow()?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>this.getWorkflow()?.steps.find(r=>r.stepName===n)).filter(n=>this.stepHasHandle(n)).map(n=>Ee.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const n=(await this.graphQlClient().mutate({mutation:Sc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(n?.customer){this.getWorkflowManager().setTransactionCustomer(n.customer);const r=D.getMap("transactionCustomerIds")||new Map;r.set(this.getTransaction().id,n.customer.id),D.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),n=this.getWorkflow(),r=this.getCommandContext().getState();if(!e)throw new Q("Product undefined!");if(!n)throw new Q("Workflow undefined!");if(!r)throw new Q("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await xe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:n.name,workflowId:n.id,lastEdited:new Date};return await xe.addDesign(o),o}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new Q("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),n=this.getWorkflow();if(!n)throw new Q("Workflow is undefined! Cannot copy experience!");const r=this.getTransaction().integrationProduct?.id;if(!r)throw new Q("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:n.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),n=this.getProduct(),r=this.getWorkflow();if(!n)throw new Q("Product undefined! Cannot finish an experience without a product.");if(!r)throw new Q("Workflow undefined! Cannot finish an experience without a workflow.");return e.completed?(await this.graphQlClient().mutate({mutation:jo,variables:{transactionId:e.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):(await qr([{workflowManager:this.workflowManager,workflow:r,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:n,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:r.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0)))[0]}stepHasHandle(t){return t.type!==b.SilentIllustration&&t.type!==b.ProductOverlay}getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),n=this.getWorkflowManager().getWorkflowSelections(),r=[];return t?.steps.forEach(i=>{const o=i.stepName,s=e[o],l=n[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Ic(i,n)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case b.Frame:{const d=i.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case b.Illustration:{const d=i.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case b.Module:{const d=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case b.Text:{const d=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Ro,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const n=this.eventCallbacks.get(t)||[];n.push(e),this.eventCallbacks.set(t,n)}removeEventListener(t,e){const n=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,n.filter(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const bc=a=>{if([b.Question,b.Frame,b.Illustration,b.Material,b.Model,b.Picture,b.Shape,b.Text].includes(a.type)){const e=a.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Ic=(a,t)=>{if(!bc(a))return!1;if(a.option&&(a.option.variants||[]).length>1){const e=t[a.stepName];return!!(e&&e.selections.length>0)}return!1};class Bc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(n=>this.aspectConditionsSatisfied(n.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===$a.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(r=>{const i=e.aspects.find(o=>o.name===r.targetAspectName);return i?r.requiredVariantSelections.some(o=>o===i.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new jr(this.bundle,t).initialize();case z.ColorOption:return new Dn(this.bundle,t,t.entityId?await Y.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await Y.getOption(t.entityId):void 0;return e?.type==="Color"?new Dn(this.bundle,t,e):new ea(this.bundle,t,e)}case z.Text:return new Wr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class _e{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class jr extends _e{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await Y.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),n=await jn(t?.fileLink),r=n.width,i=n.height,o=await it(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon($e.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const n=this.bundle.getGlobalPropertyStateManager(),r=await U.removeBackgroundFromAsset(e),o={...n.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?n.setAspect(this.property.name,r.key,o):n.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?qe(je(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const n=this.bundle.getGlobalPropertyStateManager(),r=n.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[n.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const n=await U.getLocalOrFromServer(e);if(!n)return;await this.applyImageSelection(n,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await it(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),n=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(n)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,n=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,n,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(n=>n.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&n.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Wr extends _e{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class ea extends _e{constructor(t,e,n){super(t,e),this.optionResource=n}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new at(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(n=>n.id===t);return e?new at(e):void 0}else{const e=this.optionResource.variants?.find(n=>n.id===this.optionResource?.defaultVariant?.id);return e?new at(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new at(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new at(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const n=this.optionResource?.variants?.find(r=>r.id===e);return n?this.applyVariantSelection(new at(n),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class Dn extends ea{constructor(t,e,n){super(t,e,n)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const n=this.optionResource?.variants?.find(i=>i.id===e);if(!n)return Promise.resolve();await this.applyColorVariant(new at(n),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,n){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case b.Shape:return o.selectVariant(t);case b.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case b.Illustration:return o.setColor(n?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Pc=(a,t,e,n)=>a.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===n),xc=(a,t,e)=>{const r=Pc(a,t,e,b.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function kn(a,t){function e(n){if(typeof n>"u"||!Array.isArray(n)&&!Dc(n))return n;if(Array.isArray(n))return kn(n,t);let r={};for(const[i,o]of Object.entries(n))r[i]=Fc(o)?o:kn(o,t);return Ni(r,t)}return Array.isArray(a)?a.map(e):e(a)}function Fc(a){return a==null}function Dc(a){return typeof a=="object"&&!Array.isArray(a)&&a!==null}function Hr(a){const t=new Map;return a?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function be(a){return kn(a,["__typename"])}class kc{constructor(t,e,n,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=n,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=be(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=be(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(n=>!t.includes(n.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Hr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...be(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const n=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(n)return n.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e)?.storage}async setAspect(t,e,n,r){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,n!==void 0&&(l.storage=n!==null?n:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:n!==null?n:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,n!==void 0&&(l.storage=n!==null?n:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:n!==null?n:void 0,channel:r});te(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(n){const s=o.find(l=>l.channel===n);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:n});te(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Nl,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let n=e.type&&e.storage?{}:void 0;if(n)switch(e.type){case z.FileUpload:{n.fileUpload=e.storage;break}case z.Option:{n.option=e.storage;break}case z.ColorOption:{n=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:n,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=be(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Tl,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Mc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getTransaction().id);if(!e)return;const n=this.getTransformToApply(e);if(!n)return;const r=this.flipTransform(n,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,n){const r=t.getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=n):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:n}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const n=t.getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===n),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(n=>n.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const n in t)n===e?delete t[n]:this.deleteFieldNameFromObjectRecursive(t[n],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const Tc=C.gql`
|
|
2340
|
+
`;var Oe=(a=>(a.PriceBreakChanged="PriceBreakChanged",a.ProductChanged="ProductChanged",a.QuantityChanged="QuantityChanged",a.RecipientChanged="RecipientChanged",a.SelectionChanged="SelectionChanged",a))(Oe||{});class Gr{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Oa(async()=>{await xe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async n=>new Promise((r,i)=>{try{n.toBlob(o=>{if(o){const s=URL.createObjectURL(o);r(s)}})}catch(o){i(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(n=>n.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Fn(this,t,n=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(n)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(n=>{const r=n.traversableScenes.map(i=>{const o=i.renderableSteps.map(s=>s.stepName);return{id:i.name,title:i.title,renderableSteps:o,workflowScene:i}});this.renderableScenes=r,this.renderableSceneCallbacks.forEach(i=>i(r)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Ia,variables:{id:this.getTransaction().id,integrationProductId:t}}),n=e.data?.transactionUpdateIntegrationProduct.product;if(!n)throw new Q("Failed to set product. No product returned from server.");if(!this.bundle)throw new Q("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const r=(await this.bundle.getProductCollection().fetchProducts()).find(i=>i.getId()===n.id);try{const i=r?.getDefaultWorkflow();if(i){const o=await ai(i.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new Q("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Ia,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:Oo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,n,r,i,o){await this.graphQlClient().mutate({mutation:vc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:n||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Ec,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const n=this.getWorkflow(),r=n?.finalizeStepConfig?.lookAtAnimation;if(!n)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!r)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=Ct(i,i),s=this.workflowManager.getCommandContext().getAllLayouts(),l=n.defaultPreviewPanelIndex||0,c=n.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Le("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),m=Ye(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),p=Ya(m);await(await Nn.Pith.from(h,p,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:Ct,createImage:ce,DOMParser:$n(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const n=this.cachedStepHandles.get(e.stepName);if(n)return n;const r=Ee.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let n=0;return Object.values(e).forEach(r=>{n+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(n,t)}getBasePriceSubunits(t,e){const n=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return n+r}return n}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const n=e?1:this.priceBreakToBeApplied(),r=t*n;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),n=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=n)return r.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,n=this.getTransaction().id,r=t.getProduct()?.id,i=this.getProduct()?.id;return e!==n&&r===i})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,n){const r=await t.getGlobalProperties(),i=n?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&m?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&m?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(n=>n.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Ee.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>Ee.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){if(!this.getWorkflow()?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>this.getWorkflow()?.steps.find(r=>r.stepName===n)).filter(n=>this.stepHasHandle(n)).map(n=>Ee.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const n=(await this.graphQlClient().mutate({mutation:Sc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(n?.customer){this.getWorkflowManager().setTransactionCustomer(n.customer);const r=D.getMap("transactionCustomerIds")||new Map;r.set(this.getTransaction().id,n.customer.id),D.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),n=this.getWorkflow(),r=this.getCommandContext().getState();if(!e)throw new Q("Product undefined!");if(!n)throw new Q("Workflow undefined!");if(!r)throw new Q("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await xe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:n.name,workflowId:n.id,lastEdited:new Date};return await xe.addDesign(o),o}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new Q("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),n=this.getWorkflow();if(!n)throw new Q("Workflow is undefined! Cannot copy experience!");const r=this.getTransaction().integrationProduct?.id;if(!r)throw new Q("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:n.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),n=this.getProduct(),r=this.getWorkflow();if(!n)throw new Q("Product undefined! Cannot finish an experience without a product.");if(!r)throw new Q("Workflow undefined! Cannot finish an experience without a workflow.");return e.completed?(await this.graphQlClient().mutate({mutation:jo,variables:{transactionId:e.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):(await qr([{workflowManager:this.workflowManager,workflow:r,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:n,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:r.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0)))[0]}stepHasHandle(t){return t.type!==b.SilentIllustration&&t.type!==b.ProductOverlay}getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),n=this.getWorkflowManager().getWorkflowSelections(),r=[];return t?.steps.forEach(i=>{const o=i.stepName,s=e[o],l=n[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Ic(i,n)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case b.Frame:{const d=i.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case b.Illustration:{const d=i.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case b.Module:{const d=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case b.Text:{const d=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Ro,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const n=this.eventCallbacks.get(t)||[];n.push(e),this.eventCallbacks.set(t,n)}removeEventListener(t,e){const n=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,n.filter(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const bc=a=>{if([b.Question,b.Frame,b.Illustration,b.Material,b.Model,b.Picture,b.Shape,b.Text].includes(a.type)){const e=a.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Ic=(a,t)=>{if(!bc(a))return!1;if(a.option&&(a.option.variants||[]).length>1){const e=t[a.stepName];return!!(e&&e.selections.length>0)}return!1};class Bc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(n=>this.aspectConditionsSatisfied(n.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===$a.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(r=>{const i=e.aspects.find(o=>o.name===r.targetAspectName);return i?r.requiredVariantSelections.some(o=>o===i.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new jr(this.bundle,t).initialize();case z.ColorOption:return new Dn(this.bundle,t,t.entityId?await Y.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await Y.getOption(t.entityId):void 0;return e?.type==="Color"?new Dn(this.bundle,t,e):new ea(this.bundle,t,e)}case z.Text:return new Wr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class _e{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class jr extends _e{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await Y.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),n=await jn(t?.fileLink),r=n.width,i=n.height,o=await it(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon($e.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const n=this.bundle.getGlobalPropertyStateManager(),r=await U.removeBackgroundFromAsset(e),o={...n.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?n.setAspect(this.property.name,r.key,o):n.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?qe(je(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const n=this.bundle.getGlobalPropertyStateManager(),r=n.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[n.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const n=await U.getLocalOrFromServer(e);if(!n)return;await this.applyImageSelection(n,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await it(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),n=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(n)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,n=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,n,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(n=>n.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&n.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Wr extends _e{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class ea extends _e{constructor(t,e,n){super(t,e),this.optionResource=n}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new at(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(n=>n.id===t);return e?new at(e):void 0}else{const e=this.optionResource.variants?.find(n=>n.id===this.optionResource?.defaultVariant?.id);return e?new at(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new at(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new at(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const n=this.optionResource?.variants?.find(r=>r.id===e);return n?this.applyVariantSelection(new at(n),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class Dn extends ea{constructor(t,e,n){super(t,e,n)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const n=this.optionResource?.variants?.find(i=>i.id===e);if(!n)return Promise.resolve();await this.applyColorVariant(new at(n),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,n){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case b.Shape:return o.selectVariant(t);case b.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case b.Illustration:return o.setColor(n?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Pc=(a,t,e,n)=>a.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===n),xc=(a,t,e)=>{const r=Pc(a,t,e,b.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function kn(a,t){function e(n){if(typeof n>"u"||!Array.isArray(n)&&!Dc(n))return n;if(Array.isArray(n))return kn(n,t);let r={};for(const[i,o]of Object.entries(n))r[i]=Fc(o)?o:kn(o,t);return Ni(r,t)}return Array.isArray(a)?a.map(e):e(a)}function Fc(a){return a==null}function Dc(a){return typeof a=="object"&&!Array.isArray(a)&&a!==null}function Hr(a){const t=new Map;return a?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function be(a){return kn(a,["__typename"])}class kc{constructor(t,e,n,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=n,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=be(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=be(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(n=>!t.includes(n.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Hr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...be(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const n=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(n)return n.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e)?.storage}async setAspect(t,e,n,r){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,n!==void 0&&(l.storage=n!==null?n:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:n!==null?n:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,n!==void 0&&(l.storage=n!==null?n:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:n!==null?n:void 0,channel:r});te(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(n){const s=o.find(l=>l.channel===n);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:n});te(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Nl,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let n=e.type&&e.storage?{}:void 0;if(n)switch(e.type){case z.FileUpload:{n.fileUpload=e.storage;break}case z.Option:{n.option=e.storage;break}case z.ColorOption:{n=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:n,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=be(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Tl,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Mc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getTransaction().id);if(!e)return;const n=this.getTransformToApply(e);if(!n)return;const r=this.flipTransform(n,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,n){const r=t.getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=n):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:n}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const n=t.getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===n),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(n=>n.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const n in t)n===e?delete t[n]:this.deleteFieldNameFromObjectRecursive(t[n],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const Tc=C.gql`
|
|
2342
2341
|
query GetManyMetafields($entityIds: [String!]!) {
|
|
2343
2342
|
metafieldsMany(entityIds: $entityIds) {
|
|
2344
2343
|
id
|
|
@@ -2391,7 +2390,7 @@
|
|
|
2391
2390
|
quoteId
|
|
2392
2391
|
}
|
|
2393
2392
|
}
|
|
2394
|
-
`;class Ba{constructor(t,e,n,r,i,o,s){this.workflowExperiences=[],this.eventEmitter=new Oc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(d=>[d.key,d.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Mc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new kc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Bc(this),this.setPreviewService(n);const c=new Promise((d,u)=>{if(o?.readonly){d([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(h=>{const g=h.map(m=>{if(m.getType()===z.ColorOption||m.getType()===z.Option){const p=m;if(!A.aspects.find(S=>S.name===p.getName()))return p.initDefaultVariant()}});Promise.all(g).then(d).catch(u)}):(console.log("Attempted to set global default variant before state was initialized."),d([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...r,bundleOwnerId:i},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>c),this.initializationPromise.catch(d=>{console.error(`Bundle initialization failed: ${d}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(d=>this.checkMandatoryHandlesChanged(void 0,d))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}async addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.integrationProductIds)e.integrationProductIds=[];else if(e.integrationProductIds.some(r=>r===t)){this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds});return}e.integrationProductIds=[...e.integrationProductIds,t];const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const n=t.filter(i=>(e.integrationProductIds??[]).includes(i));if(n.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(i=>!n.includes(i));const r=JSON.stringify(e);this.bundleStateManager.setState(r),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:n}),await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,bundleStateData:r},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Lc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,n,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:$c,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:n||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Uc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const n of t.aspects){const r=n?.name;await this.getGlobalPropertyStateManager().setAspect(r,n.value)}for(const n of t.aspects){const r=n?.name,i=e.find(o=>o.getName()===r);if(i)switch(n.type){case z.FileUpload:{const o=i,s=await De([n.value]);s.length>0&&await o.selectImage(s[0]);const l=n.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case z.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===n.value),c=n.storage?n.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case z.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===n.value);l&&await o.selectVariant(l);break}case z.Text:{await i.setText(n.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(n=>n.getType()===z.Option).map(n=>n.getCurrentVariant()?.getPrice()||0).reduce((n,r)=>n+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new na(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(b.Illustration)){const n=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of n){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===z.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=xc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===A);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const n of e)await n.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),n=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(n.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+n.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=D.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:Wl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const n=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===n))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(D.getMap("transactionOwnerIds")||new Map).get(n);await y.getShadowGraphqlClient().mutate({mutation:jl,variables:{id:this.id,transactionId:n},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(n=>n.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,n=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:Hl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),n){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const n=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);n.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...n].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&n.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:Yl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:n}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const n=this.workflowExperiences[t];if(n.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,n.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const n=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=n,await this.updateTransactionOrder()}getWorkflowExperiences(){const t=[...this.workflowExperiences],e=(n,r)=>{const i=n.getBundleIndex(),o=r.getBundleIndex();return i===void 0||o===void 0?0:i<o?-1:1};return t.sort(e),t}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const n=await y.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,details:t,type:e||ne.Owner},context:{bundleOwnerId:this.ownerId}});if(!n.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=n.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const n=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:nc,variables:{bundleId:this.id}});const n=await qr(this.workflowExperiences.map(r=>{const i=r.getWorkflow();if(!i)throw new Error("Unable to create designs - Workflow not found!");const o=r.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:r.getWorkflowManager(),workflow:i,layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:o,transaction:r.getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:i.name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()}}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:n,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,n){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,n),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:tc,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Zl(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const n=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(n),this.globalConfigurationPropertyId=n?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),i=this.workflowExperiences.find(o=>o.getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(n){console.error(`Unable to apply state to workflow experience: ${n}`)}await e}}async loadExistingWorkflowExperiences(t,e,n){if(t.length===0)return;const r=await this.client.getWorkflowExperiences(t.map(i=>({type:"transaction",transactionId:i})),e,void 0,n);if(r.forEach(i=>i.setBundle(this)),r.forEach(i=>i.checkForPriceBreakChanges()),this.workflowExperiences=r,this.previewService)for(const i of r)await this.injectExperienceIntoPreviewService(i)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,n])=>({key:e,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const n=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(n,t),i=this.globalPropertyHandleService.applyConditionsFromState(n,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of n)i.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=i.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(i.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(n,c);te(i.sort(),d.sort())||(this.checkConditionalHandlesChanged(i,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let i=0;i<t.length;i++)if(t[i].getName()!==e[i].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const n=[],r=[],i=[],o=Hr(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&n.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:n,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:rc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Vc=C.gql`
|
|
2393
|
+
`;class Ba{constructor(t,e,n,r,i,o,s){this.workflowExperiences=[],this.eventEmitter=new Oc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(d=>[d.key,d.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Mc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new kc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Bc(this),this.setPreviewService(n);const c=new Promise((d,u)=>{if(o?.readonly){d([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(h=>{const g=h.map(m=>{if(m.getType()===z.ColorOption||m.getType()===z.Option){const p=m;if(!A.aspects.find(S=>S.name===p.getName()))return p.initDefaultVariant()}});Promise.all(g).then(d).catch(u)}):(console.log("Attempted to set global default variant before state was initialized."),d([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...r,bundleOwnerId:i},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>c),this.initializationPromise.catch(d=>{console.error(`Bundle initialization failed: ${d}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(d=>this.checkMandatoryHandlesChanged(void 0,d))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}async addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.integrationProductIds)e.integrationProductIds=[];else if(e.integrationProductIds.some(r=>r===t)){this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds});return}e.integrationProductIds=[...e.integrationProductIds,t];const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const n=t.filter(i=>(e.integrationProductIds??[]).includes(i));if(n.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(i=>!n.includes(i));const r=JSON.stringify(e);this.bundleStateManager.setState(r),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:n}),await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,bundleStateData:r},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Lc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,n,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:$c,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:n||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Uc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const n of t.aspects){const r=n?.name;await this.getGlobalPropertyStateManager().setAspect(r,n.value)}for(const n of t.aspects){const r=n?.name,i=e.find(o=>o.getName()===r);if(i)switch(n.type){case z.FileUpload:{const o=i,s=await De([n.value]);s.length>0&&await o.selectImage(s[0]);const l=n.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case z.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===n.value),c=n.storage?n.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case z.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===n.value);l&&await o.selectVariant(l);break}case z.Text:{await i.setText(n.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(n=>n.getType()===z.Option).map(n=>n.getCurrentVariant()?.getPrice()||0).reduce((n,r)=>n+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new na(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(b.Illustration)){const n=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of n){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===z.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=xc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===A);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const n of e)await n.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),n=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(n.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+n.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=D.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:Wl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const n=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===n))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(D.getMap("transactionOwnerIds")||new Map).get(n);await y.getShadowGraphqlClient().mutate({mutation:jl,variables:{id:this.id,transactionId:n},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(n=>n.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,n=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:Hl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),n){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const n=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);n.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...n].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&n.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:Yl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:n}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const n=this.workflowExperiences[t];if(n.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,n.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const n=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=n,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const n=await y.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,details:t,type:e||ne.Owner},context:{bundleOwnerId:this.ownerId}});if(!n.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=n.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const n=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:nc,variables:{bundleId:this.id}});const n=await qr(this.workflowExperiences.map(r=>{const i=r.getWorkflow();if(!i)throw new Error("Unable to create designs - Workflow not found!");const o=r.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:r.getWorkflowManager(),workflow:i,layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:o,transaction:r.getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:i.name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()}}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:n,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,n){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,n),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:tc,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Zl(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const n=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(n),this.globalConfigurationPropertyId=n?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),i=this.workflowExperiences.find(o=>o.getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(n){console.error(`Unable to apply state to workflow experience: ${n}`)}await e}}async loadExistingWorkflowExperiences(t,e,n){if(t.length===0)return;const r=await this.client.getWorkflowExperiences(t.map(s=>({type:"transaction",transactionId:s})),e,void 0,n);if(r.forEach(s=>s.setBundle(this)),r.forEach(s=>s.checkForPriceBreakChanges()),this.workflowExperiences=r,this.previewService)for(const s of r)await this.injectExperienceIntoPreviewService(s);const i=this.getIntegrationProductIds()||[],o=this.getProductCollection();if(o){const s=o.getProducts();if(s.length>0){await o.fetchProducts();for(const l of i)if(!s.find(d=>d.getCurrentIntegration().id===l)){for(const d of r)d.getProduct()?.integrationProducts?.map(u=>u.id)?.includes(l)&&await d.clearProduct();await this.removeIntegrationProductIds([l])}}}}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:An,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,n])=>({key:e,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const n=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(n,t),i=this.globalPropertyHandleService.applyConditionsFromState(n,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of n)i.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=i.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(i.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(n,c);te(i.sort(),d.sort())||(this.checkConditionalHandlesChanged(i,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let i=0;i<t.length;i++)if(t[i].getName()!==e[i].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const n=[],r=[],i=[],o=Hr(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&n.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:n,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:rc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Vc=C.gql`
|
|
2395
2394
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2396
2395
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2397
2396
|
id
|
|
@@ -2520,7 +2519,7 @@
|
|
|
2520
2519
|
}
|
|
2521
2520
|
}
|
|
2522
2521
|
}
|
|
2523
|
-
`;class Hc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Yc{init(t,e,n){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=n}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,n){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Yc;class ei{formatCurrencyForDisplay(t,e){const n={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Mi(n).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,n=ca.code(e);return n?n.digits:2}getSpecialFormat(t){const e=t;if(ca.code(e)?.code==="CLP")return"USD0,0"}}const Pa=new ei;class ni{constructor(t,e,n,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=n,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Pa.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Pa.getPrecisionForCurrency(e))}}const Jc=async(a,t)=>{const e=await y.getShadowGraphqlClient().query({query:Ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:a}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const n=e.data.workflows;if(n===void 0||n.length!==a.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return n.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),n},Kc=async(a,t)=>{const n=(await t).find(r=>r.id===a);if(!n)throw new Error(`Workflow not found: ${a}`);return n},ia=async(a,t)=>{const e=a.map(s=>$t.get({id:s,options:t})),n=a.filter((s,l)=>e[l]===void 0);if(n.length===0)return Promise.all(e);const r=Jc(n,t),i=n.map(s=>$t.set({id:s,options:t},Kc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ai=async(a,t)=>(await ia([a],t))[0],_c=async a=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:a},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Xc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(n){throw console.error(n),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.1.0-beta.3fb0da60-1da5-5e84-b959-ca75a31ba2e9"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&_a(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new Xr}async getCurrencyContext(t){const n=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ni(o,s,n,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=ri(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ne.Owner});const n=D.getMap("bundlePartnerIds")||new Map;if(n.has(t)){const r=n.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),n=await e.query({query:_o,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!n.data.transactions||n.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=n.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ne.Owner});const s=D.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(n=>n.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!t||!e||!n)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const n=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,n);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const n=JSON.parse(e),r=new Date().getTime()/1e3,i=!n?.AccessToken||Re(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Wc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,n){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new Ba(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,n,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new Ba(this,u,e,n,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,n,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...n}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const n=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return n.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),n}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([t],t.graphql),r=n[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),n[0]}async getWorkflowExperiences(t,e,n,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=fn(o,l),d=fn(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(W=>W.option.transactionId),V=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=V.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const W=V.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${W}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((W,Xe)=>({transaction:W,workflowId:W.workflowId,readOnly:P.find(At=>At.option.transactionId===W.id)?.option.readOnly??!1,index:P[Xe].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),V=T.data?.transactionCreateMany;if(!V||V.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+V.length,r&&r(u,o.length),V.map((k,W)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[W].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await _c(p):[])(),(async()=>f.length>0?await ia(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:V,readOnly:k,index:W}=P,Xe=V?v.get(V):void 0,At=t[W];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=D.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",fe));const Ze=fe.get(T.id)||void 0,mi=new Hc({onMutate:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:Xe,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Bn(ot),Ce.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await Bn(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:W,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:V}=P,k=new Gr(this,T);await k.getWorkflowManager().getInitializationPromise(),n&&n(),V.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new Mn(i[0])}async getIntegrationProductFromExternalIds(t,e,n){const o=(await y.getShadowGraphqlClient().query({query:qo(n),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Mn(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const n=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:n}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:as,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const ri=async(a,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":a}},variables:{themeConfigurationId:t}})).data.currentIntegration,Zc=async a=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:a}});if(e.data.transactions.length!==0)return e.data.transactions[0]},td=async(a,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:a,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ed=async a=>(await y.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{id:a}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,nd=async a=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:a}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ii(a){const e=D.getMap("bundleOwnerIds")?.get(a),n={};try{const r=await this.loggedInBearerToken();n.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Re(s)&&(n.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...n}}const ad=async a=>{const t=await ii(a),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:a},context:{headers:t}});if(e.data?.bundleDelete!==a)throw new Error(`Failed to delete bundle: ${e.errors}`)};function oi(a,t,e,n){const r=e.width*a.zoom,i=e.height*a.zoom;if(n){const s=a,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,a.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(a.x,t.width-c,0),s.y=Be(a.y,t.height-d,0),s}const o=a;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(a,t,e){return Math.min(Math.max(a,t),e)}class si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Oa(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async n=>{if(n){const r=n;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,n)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[n]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=je(this.imageData.svg,this.imageData.colors||{},!1);return qe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,n,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(n[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=n[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,n){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new Q("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!n){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=oi(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,n,r,i){if(!n||n.length===0||n.some(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((n,r)=>{const i=Math.max(n.width/t.width,n.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,n)=>{this.offsets[n]=Gn(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class rd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,n,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,n){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,n){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var li=(a=>(a.SelectFrame="SelectFrame",a.SelectImage="SelectImage",a.Position="Position",a))(li||{});class ci extends Z{constructor(t,e,n){super(t,e,n);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.selectVariant(this.step,t.getResource(),e,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,n=!0){if(await gt.selectImage(this.step,t,this.manager,n),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon($e.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await U.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,n,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:n.key,useOriginalAsset:!t}}),n}changeColors(t){gt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?gt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return gt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,n,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(n,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const id=C.gql`
|
|
2522
|
+
`;class Hc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Yc{init(t,e,n){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=n}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,n){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Yc;class ei{formatCurrencyForDisplay(t,e){const n={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Mi(n).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,n=ca.code(e);return n?n.digits:2}getSpecialFormat(t){const e=t;if(ca.code(e)?.code==="CLP")return"USD0,0"}}const Pa=new ei;class ni{constructor(t,e,n,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=n,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Pa.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Pa.getPrecisionForCurrency(e))}}const Jc=async(a,t)=>{const e=await y.getShadowGraphqlClient().query({query:Ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:a}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const n=e.data.workflows;if(n===void 0||n.length!==a.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return n.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),n},Kc=async(a,t)=>{const n=(await t).find(r=>r.id===a);if(!n)throw new Error(`Workflow not found: ${a}`);return n},ia=async(a,t)=>{const e=a.map(s=>$t.get({id:s,options:t})),n=a.filter((s,l)=>e[l]===void 0);if(n.length===0)return Promise.all(e);const r=Jc(n,t),i=n.map(s=>$t.set({id:s,options:t},Kc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ai=async(a,t)=>(await ia([a],t))[0],_c=async a=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:a},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Xc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(n){throw console.error(n),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.1.0-beta.b737d236-4f23-52f6-9704-e61e958b8bf8"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&_a(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new Xr}async getCurrencyContext(t){const n=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ni(o,s,n,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=ri(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ne.Owner});const n=D.getMap("bundlePartnerIds")||new Map;if(n.has(t)){const r=n.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),n=await e.query({query:_o,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!n.data.transactions||n.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=n.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ne.Owner});const s=D.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(n=>n.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!t||!e||!n)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const n=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,n);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const n=JSON.parse(e),r=new Date().getTime()/1e3,i=!n?.AccessToken||Re(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Wc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,n){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new Ba(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,n,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new Ba(this,u,e,n,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,n,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...n}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const n=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return n.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),n}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([t],t.graphql),r=n[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),n[0]}async getWorkflowExperiences(t,e,n,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=fn(o,l),d=fn(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(W=>W.option.transactionId),V=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=V.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const W=V.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${W}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((W,Xe)=>({transaction:W,workflowId:W.workflowId,readOnly:P.find(At=>At.option.transactionId===W.id)?.option.readOnly??!1,index:P[Xe].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),V=T.data?.transactionCreateMany;if(!V||V.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+V.length,r&&r(u,o.length),V.map((k,W)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[W].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await _c(p):[])(),(async()=>f.length>0?await ia(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:V,readOnly:k,index:W}=P,Xe=V?v.get(V):void 0,At=t[W];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=D.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",fe));const Ze=fe.get(T.id)||void 0,mi=new Hc({onMutate:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:Xe,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Bn(ot),Ce.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await Bn(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:W,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:V}=P,k=new Gr(this,T);await k.getWorkflowManager().getInitializationPromise(),n&&n(),V.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new Mn(i[0])}async getIntegrationProductFromExternalIds(t,e,n){const o=(await y.getShadowGraphqlClient().query({query:qo(n),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Mn(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const n=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:n}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:as,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const ri=async(a,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":a}},variables:{themeConfigurationId:t}})).data.currentIntegration,Zc=async a=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:a}});if(e.data.transactions.length!==0)return e.data.transactions[0]},td=async(a,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:a,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ed=async a=>(await y.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{id:a}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,nd=async a=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:a}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ii(a){const e=D.getMap("bundleOwnerIds")?.get(a),n={};try{const r=await this.loggedInBearerToken();n.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Re(s)&&(n.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...n}}const ad=async a=>{const t=await ii(a),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:a},context:{headers:t}});if(e.data?.bundleDelete!==a)throw new Error(`Failed to delete bundle: ${e.errors}`)};function oi(a,t,e,n){const r=e.width*a.zoom,i=e.height*a.zoom;if(n){const s=a,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,a.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(a.x,t.width-c,0),s.y=Be(a.y,t.height-d,0),s}const o=a;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(a,t,e){return Math.min(Math.max(a,t),e)}class si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Oa(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async n=>{if(n){const r=n;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,n)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[n]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=je(this.imageData.svg,this.imageData.colors||{},!1);return qe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,n,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(n[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=n[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,n){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new Q("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!n){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=oi(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,n,r,i){if(!n||n.length===0||n.some(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((n,r)=>{const i=Math.max(n.width/t.width,n.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,n)=>{this.offsets[n]=Gn(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class rd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,n,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,n){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,n){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var li=(a=>(a.SelectFrame="SelectFrame",a.SelectImage="SelectImage",a.Position="Position",a))(li||{});class ci extends Z{constructor(t,e,n){super(t,e,n);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.selectVariant(this.step,t.getResource(),e,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,n=!0){if(await gt.selectImage(this.step,t,this.manager,n),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon($e.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await U.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,n,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:n.key,useOriginalAsset:!t}}),n}changeColors(t){gt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?gt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return gt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,n,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(n,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const id=C.gql`
|
|
2524
2523
|
query GetLoggedInCustomer($email: String!) {
|
|
2525
2524
|
customer(emailAddress: $email) {
|
|
2526
2525
|
id
|