@spiffcommerce/core 34.1.0-beta.687d4e89-1a38-5004-92ab-0c957e1c63b0 → 34.1.0-beta.7aa1a99d-0a8c-5121-9077-e86bd0250c3d
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.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +9 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2442,7 +2442,7 @@
|
|
|
2442
2442
|
quoteId
|
|
2443
2443
|
}
|
|
2444
2444
|
}
|
|
2445
|
-
`;class xn{constructor(t,e,a,r,i,o,s){this.workflowExperiences=[],this.eventEmitter=new zc,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 $c(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new Oc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Mc(this),this.setPreviewService(a);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()===L.ColorOption||m.getType()===L.Option){const p=m;if(!A.aspects.find(E=>E.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 a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(i=>(e.integrationProductIds??[]).includes(i));if(a.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(i=>!a.includes(i));const r=JSON.stringify(e);this.bundleStateManager.setState(r),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:a}),await S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,bundleStateData:r},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await S.getShadowGraphqlClient().mutate({mutation:Wc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await S.getShadowGraphqlClient().mutate({mutation:Gc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await S.getShadowGraphqlClient().mutate({mutation:jc,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 a of t.aspects){const r=a?.name;await this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case L.FileUpload:{const o=i,s=await ke([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.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 L.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case L.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case L.Text:{await i.setText(a.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(a=>a.getType()===L.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new rn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(b.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===L.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=Nc(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 a of e)await a.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),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=D.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await S.getShadowGraphqlClient().mutate({mutation:nc,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 a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(D.getMap("transactionOwnerIds")||new Map).get(a);await S.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionId:a},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(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!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 S.getShadowGraphqlClient().mutate({mutation:rc,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}}),a){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 a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await S.getShadowGraphqlClient().mutate({mutation:ic,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:a}),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 a=await this.getGlobalProperties();await Promise.all(a.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 a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.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 a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,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 a=await S.getShadowGraphqlClient().mutate({mutation:oc,variables:{id:this.id,details:t,type:e||ne.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await S.getShadowGraphqlClient().mutate({mutation:sc,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await S.getShadowGraphqlClient().mutate({mutation:lc,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await S.getShadowGraphqlClient().query({query:In,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 S.getShadowGraphqlClient().query({query:In,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,a){this.completed&&await S.getShadowGraphqlClient().mutate({mutation:hc,variables:{bundleId:this.id}});let r=!1;if(this.workflowExperiences.length>100&&(await this.client.getIntegration()).partner.beta&&(r=!0),r){const o=await S.getShadowGraphqlClient().mutate({mutation:vc,variables:{id:this.id},errorPolicy:"all"});if(o.data?.designCreateBundle?.id){let s=o.data.designCreateBundle;const c=await(async()=>{let d=0;for(;d<121;){if(d+=1,s.status===Wt.Failed||s.children.some(g=>g.status===Wt.Failed))return;if(s.status===Wt.Completed)return s;await new Promise(g=>setTimeout(g,300));const u=await S.getShadowGraphqlClient().mutate({mutation:Hl,variables:{ids:[o.data.designCreateBundle.id]},errorPolicy:"all"});if(!u.data?.jobs||u.data.jobs.length===0){console.error("failed to refetch jobs",u.errors);return}s=u.data.jobs[0];let A=0,h=0;for(const g of s.children)g.status===Wt.Completed&&(A+=g.data.transactionCount),h+=g.data.transactionCount;a&&a(A,h)}})();if(c){const d=await S.getShadowGraphqlClient().mutate({mutation:Ec,variables:{ids:this.workflowExperiences.map(u=>u.getTransaction().id)},errorPolicy:"all"});if(d.data?.transactions&&d.data.transactions.length===this.workflowExperiences.length){const u=d.data.transactions.map(A=>{const h=this.workflowExperiences.find(m=>m.getTransaction().id===A.id),g=h.getWorkflowManager().getWorkflowMetadata();return Qr(A,h.getProduct(),h.getWorkflow(),Da(!0,h.getWorkflow(),h.getWorkflowManager().getWorkflowSelections())[0],A.design?.sku,g&&Fa(g,h.getWorkflow(),!0),c.data?.processExecutions?.[0]?.id)});return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:u,bundleOwnerId:this.ownerId}}else console.error("failed to read transactions after job")}else console.error("failed to ensure job completed")}else console.error("designCreateBundle failed",o.errors)}const i=await Rr(this.workflowExperiences.map(o=>{const s=o.getWorkflow();if(!s)throw new Error("Unable to create designs - Workflow not found!");const l=o.getProduct();if(!l)throw new Error("Unable to create designs - Product not found!");return{workflowManager:o.getWorkflowManager(),workflow:s,layouts:o.getWorkflowManager().getLayouts(),getReducerState:()=>o.getCommandContext().getState(),product:l,transaction:o.getTransaction(),workflowSelections:o.getWorkflowManager().getWorkflowSelections(),designName:s.name,workflowMetadata:o.getWorkflowManager().getWorkflowMetadata()}}),e?(o,s)=>{const l=this.workflowExperiences.find(c=>c.getTransaction().id===s);return l?e(l,o):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+s),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:i,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,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await S.getShadowGraphqlClient().mutate({mutation:uc,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await S.getShadowGraphqlClient().mutate({mutation:dc(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 a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.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(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const r=await this.client.getWorkflowExperiences(t.map(i=>({type:"transaction",transactionId:i})),e,void 0,a);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 S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),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 S.getShadowGraphqlClient().mutate({mutation:cc,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 a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)i.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=i.map(u=>{if(u.getType()===L.ColorOption||u.getType()===L.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(a,c);ee(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 a=[],r=[],i=[],o=Xr(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)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,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 S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await S.getShadowGraphqlClient().mutate({mutation:mc,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 Hc=C.gql`
|
|
2445
|
+
`;class xn{constructor(t,e,a,r,i,o,s){this.workflowExperiences=[],this.eventEmitter=new zc,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 $c(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new Oc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Mc(this),this.setPreviewService(a);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()===L.ColorOption||m.getType()===L.Option){const p=m;if(!A.aspects.find(E=>E.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 a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(i=>(e.integrationProductIds??[]).includes(i));if(a.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(i=>!a.includes(i));const r=JSON.stringify(e);this.bundleStateManager.setState(r),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:a}),await S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,bundleStateData:r},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await S.getShadowGraphqlClient().mutate({mutation:Wc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await S.getShadowGraphqlClient().mutate({mutation:Gc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await S.getShadowGraphqlClient().mutate({mutation:jc,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 a of t.aspects){const r=a?.name;await this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case L.FileUpload:{const o=i,s=await ke([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.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 L.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case L.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case L.Text:{await i.setText(a.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(a=>a.getType()===L.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new rn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(b.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===L.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=Nc(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 a of e)await a.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),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=D.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await S.getShadowGraphqlClient().mutate({mutation:nc,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 a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(D.getMap("transactionOwnerIds")||new Map).get(a);await S.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionId:a},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(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!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 S.getShadowGraphqlClient().mutate({mutation:rc,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}}),a){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 a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await S.getShadowGraphqlClient().mutate({mutation:ic,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:a}),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 a=await this.getGlobalProperties();await Promise.all(a.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 a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.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 a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,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 a=await S.getShadowGraphqlClient().mutate({mutation:oc,variables:{id:this.id,details:t,type:e||ne.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await S.getShadowGraphqlClient().mutate({mutation:sc,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await S.getShadowGraphqlClient().mutate({mutation:lc,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await S.getShadowGraphqlClient().query({query:In,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 S.getShadowGraphqlClient().query({query:In,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,a){this.completed&&await S.getShadowGraphqlClient().mutate({mutation:hc,variables:{bundleId:this.id}});let r=!1;if(this.workflowExperiences.length>100&&(await this.client.getIntegration()).partner.beta&&(r=!0),r){const o=await S.getShadowGraphqlClient().mutate({mutation:vc,variables:{id:this.id},errorPolicy:"all"});if(o.data?.designCreateBundle?.id){let s=o.data.designCreateBundle;const c=await(async()=>{let d=0;for(;d<121;){if(d+=1,s.status===Wt.Failed||s.children.some(A=>A.status===Wt.Failed))return;if(s.status===Wt.Completed)return s;await new Promise(A=>setTimeout(A,300));const u=await S.getShadowGraphqlClient().mutate({mutation:Hl,variables:{ids:[o.data.designCreateBundle.id]},errorPolicy:"all"});if(!u.data?.jobs||u.data.jobs.length===0){console.error("failed to refetch jobs",u.errors);return}if(s=u.data.jobs[0],a){let A=0,h=0;for(const g of s.children)g.status===Wt.Completed&&(A+=g.data.transactionCount),h+=g.data.transactionCount;a(A,h)}}})();if(c){const d=await S.getShadowGraphqlClient().mutate({mutation:Ec,variables:{ids:this.workflowExperiences.map(u=>u.getTransaction().id)},errorPolicy:"all"});if(d.data?.transactions&&d.data.transactions.length===this.workflowExperiences.length){const u=d.data.transactions.map(A=>{const h=this.workflowExperiences.find(m=>m.getTransaction().id===A.id),g=h.getWorkflowManager().getWorkflowMetadata();return Qr(A,h.getProduct(),h.getWorkflow(),Da(!0,h.getWorkflow(),h.getWorkflowManager().getWorkflowSelections())[0],A.design?.sku,g&&Fa(g,h.getWorkflow(),!0),c.data?.processExecutions?.[0]?.id)});return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:u,bundleOwnerId:this.ownerId}}else console.error("failed to read transactions after job")}else console.error("failed to ensure job completed")}else console.error("designCreateBundle failed",o.errors)}const i=await Rr(this.workflowExperiences.map(o=>{const s=o.getWorkflow();if(!s)throw new Error("Unable to create designs - Workflow not found!");const l=o.getProduct();if(!l)throw new Error("Unable to create designs - Product not found!");return{workflowManager:o.getWorkflowManager(),workflow:s,layouts:o.getWorkflowManager().getLayouts(),getReducerState:()=>o.getCommandContext().getState(),product:l,transaction:o.getTransaction(),workflowSelections:o.getWorkflowManager().getWorkflowSelections(),designName:s.name,workflowMetadata:o.getWorkflowManager().getWorkflowMetadata()}}),e?(o,s)=>{const l=this.workflowExperiences.find(c=>c.getTransaction().id===s);return l?e(l,o):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+s),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:i,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,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await S.getShadowGraphqlClient().mutate({mutation:uc,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await S.getShadowGraphqlClient().mutate({mutation:dc(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 a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.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(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const r=await this.client.getWorkflowExperiences(t.map(i=>({type:"transaction",transactionId:i})),e,void 0,a);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 S.getShadowGraphqlClient().mutate({mutation:Aa,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),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 S.getShadowGraphqlClient().mutate({mutation:cc,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 a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)i.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=i.map(u=>{if(u.getType()===L.ColorOption||u.getType()===L.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(a,c);ee(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 a=[],r=[],i=[],o=Xr(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)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,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 S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await S.getShadowGraphqlClient().mutate({mutation:mc,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 Hc=C.gql`
|
|
2446
2446
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2447
2447
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2448
2448
|
id
|
|
@@ -2571,7 +2571,7 @@
|
|
|
2571
2571
|
}
|
|
2572
2572
|
}
|
|
2573
2573
|
}
|
|
2574
|
-
`;class Zc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){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 td{init(t,e,a){this.cognitoClient=new ye.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new ye.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new ye.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,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 ye.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new td;class oi{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Oi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=An.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(An.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new oi;class si{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,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,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const ed=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:es(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});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 a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&$.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&$.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&$.cacheAsset(o.asset),o.thumbnail&&$.cacheAsset(o.thumbnail),o.material&&$.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}),a},ad=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},ln=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=ed(a,t),i=a.map(s=>$t.set({id:s,options:t},ad(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},li=async(n,t)=>(await ln([n],t))[0],nd=async n=>{const t=await S.getShadowGraphqlClient().query({query:$o,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class rd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.1.0-beta.43cfee3b-4919-5016-a98d-a425aec20fb8"),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&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return $}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new ni}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await S.getShadowGraphqlClient().query({query:cs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new si(o,s,a,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=ci(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 a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.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=S.getShadowGraphqlClient(),a=await e.query({query:as,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.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:ns,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 S.getShadowGraphqlClient().query({query:Be,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(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),r=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Kc,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"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)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 S.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);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 S.getShadowGraphqlClient().query({query:Be,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 a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await S.getShadowGraphqlClient().mutate({mutation:tc(a?.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 xn(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,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(([E,w])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Yl(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 xn(this,u,e,a,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,a,r){const o={...await di(t),...r?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:ec(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},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,...a}=t;return(await S.getShadowGraphqlClient().query({query:Ac(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:Kl,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 a=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[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)),a[0]}async getWorkflowExperiences(t,e,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((B,N)=>({option:B,index:N})),o=i.filter(B=>B.option.type==="transaction"),s=i.filter(B=>B.option.type==="integration"||B.option.type==="external"||B.option.type==="blank"),l=50,c=fa(o,l),d=fa(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async B=>{if(B.length===0)return[];const N=B.map(X=>X.option.transactionId),J=await A.query({query:Uo,variables:{ids:N},errorPolicy:"all",fetchPolicy:"no-cache"}),M=J.data.transactions;if(u=u+M.length,r&&r(u,o.length),M.length!==B.length){const X=J.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&M[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(M[0].integrationProduct.integration)),M.map((X,Ze)=>({transaction:X,workflowId:X.workflowId,readOnly:B.find(At=>At.option.transactionId===X.id)?.option.readOnly??!1,index:B[Ze].index}))},g=async B=>{if(B.length===0)return[];const N=await A.mutate({mutation:Oo,variables:{inputs:B.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0,quantity:M.option.quantity,recipient:M.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),J=N.data?.transactionCreateMany;if(!J||J.length===0){const M=N.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${M}`)}return u=u+J.length,r&&r(u,o.length),J.map((M,X)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:B[X].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(B=>B.transaction.integrationProductId))].filter(B=>B!==void 0),f=[...new Set(m.map(B=>B.workflowId))].filter(B=>B!==void 0),[E,w]=await Promise.all([(async()=>p.length>0?await nd(p):[])(),(async()=>f.length>0?await ln(f,e):[])()]),F=new Map(E.map(B=>[B.id,B])),y=new Map(w.map(B=>[B.id,B])),v=m.map(async B=>{const{transaction:N,workflowId:J,readOnly:M,index:X}=B,Ze=J?y.get(J):void 0,At=t[X];if(N.integrationProductId){const ot=F.get(N.integrationProductId);N.integrationProduct=ot,N.product=ot?.product,N.integrationProduct||console.error("failed to find transaction's product")}const Ce=D.getMap("transactionOwnerIds")||new Map;!Ce.get(N.id)&&N.transactionOwnerId&&(Ce.set(N.id,N.transactionOwnerId),D.setMap("transactionOwnerIds",Ce));const ta=Ce.get(N.id)||void 0,yi=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),we={workflow:Ze,transaction:N,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:M?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yi,readOnly:M,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&N.workflowState){const ot=JSON.parse(N.workflowState);await Ba(ot),we.reloadedState=ot}else if(!M&&At.workflowState){const ot=JSON.parse(At.workflowState);await Ba(ot),we.reloadedState=ot}return we.delayWorkflowStateSync=!0,{experienceOptions:we,index:X,options:At}}),T=(await Promise.all(v)).sort((B,N)=>B.index-N.index);let G=[];for(const B of T){const{experienceOptions:N,options:J}=B,M=new Yr(this,N);await M.getWorkflowManager().getInitializationPromise(),a&&a(),J.type!=="transaction"&&this.customer&&await M.attachCustomerDetails({email:this.customer.emailAddress}),G=[...G,M],M.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return G}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 S.getShadowGraphqlClient().query({query:Ho(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 Na(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Na(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});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 S.getShadowGraphqlClient().mutate({mutation:ls,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 ci=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(n,t)=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function di(n){const e=D.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Oe(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const cd=async n=>{const t=await di(n),e=await S.getShadowGraphqlClient().mutate({mutation:Sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function ui(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(n.x,t.width-c,0),s.y=Pe(n.y,t.height-d,0),s}const o=n;return o.x=Pe(o.x,-r,t.width),o.y=Pe(o.y,-i,t.height),o}function Pe(n,t,e){return Math.min(Math.max(n,t),e)}class Ai{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(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 a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await pe(s),c=this.frameData?this.frameData[o]:void 0;ee(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,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return Ge(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,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=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[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,a){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))&&!a){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]=ui(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,a,r,i){if(!a||a.length===0||a.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 O([new Hs(l,e,t[d]),new Js(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((a,r)=>{const i=Math.max(a.width/t.width,a.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,a)=>{this.offsets[a]=Wa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class dd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,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,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hi=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(hi||{});class gi extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Ai(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,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await gt.selectImage(this.step,t,this.manager,a),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(Ue.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 a=await $.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}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,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||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 $.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return $.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 a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!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 ud=C.gql`
|
|
2574
|
+
`;class Zc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){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 td{init(t,e,a){this.cognitoClient=new ye.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new ye.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new ye.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,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 ye.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new td;class oi{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Oi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=An.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(An.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new oi;class si{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,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,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const ed=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:es(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});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 a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&$.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&$.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&$.cacheAsset(o.asset),o.thumbnail&&$.cacheAsset(o.thumbnail),o.material&&$.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}),a},ad=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},ln=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=ed(a,t),i=a.map(s=>$t.set({id:s,options:t},ad(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},li=async(n,t)=>(await ln([n],t))[0],nd=async n=>{const t=await S.getShadowGraphqlClient().query({query:$o,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class rd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.1.0-beta.687d4e89-1a38-5004-92ab-0c957e1c63b0"),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&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return $}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new ni}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await S.getShadowGraphqlClient().query({query:cs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new si(o,s,a,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=ci(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 a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.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=S.getShadowGraphqlClient(),a=await e.query({query:as,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.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:ns,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 S.getShadowGraphqlClient().query({query:Be,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(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),r=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Kc,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"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)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 S.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);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 S.getShadowGraphqlClient().query({query:Be,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 a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await S.getShadowGraphqlClient().mutate({mutation:tc(a?.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 xn(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,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(([E,w])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Yl(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 xn(this,u,e,a,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,a,r){const o={...await di(t),...r?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:ec(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},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,...a}=t;return(await S.getShadowGraphqlClient().query({query:Ac(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:Kl,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 a=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[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)),a[0]}async getWorkflowExperiences(t,e,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((B,N)=>({option:B,index:N})),o=i.filter(B=>B.option.type==="transaction"),s=i.filter(B=>B.option.type==="integration"||B.option.type==="external"||B.option.type==="blank"),l=50,c=fa(o,l),d=fa(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async B=>{if(B.length===0)return[];const N=B.map(X=>X.option.transactionId),J=await A.query({query:Uo,variables:{ids:N},errorPolicy:"all",fetchPolicy:"no-cache"}),M=J.data.transactions;if(u=u+M.length,r&&r(u,o.length),M.length!==B.length){const X=J.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&M[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(M[0].integrationProduct.integration)),M.map((X,Ze)=>({transaction:X,workflowId:X.workflowId,readOnly:B.find(At=>At.option.transactionId===X.id)?.option.readOnly??!1,index:B[Ze].index}))},g=async B=>{if(B.length===0)return[];const N=await A.mutate({mutation:Oo,variables:{inputs:B.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0,quantity:M.option.quantity,recipient:M.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),J=N.data?.transactionCreateMany;if(!J||J.length===0){const M=N.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${M}`)}return u=u+J.length,r&&r(u,o.length),J.map((M,X)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:B[X].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(B=>B.transaction.integrationProductId))].filter(B=>B!==void 0),f=[...new Set(m.map(B=>B.workflowId))].filter(B=>B!==void 0),[E,w]=await Promise.all([(async()=>p.length>0?await nd(p):[])(),(async()=>f.length>0?await ln(f,e):[])()]),F=new Map(E.map(B=>[B.id,B])),y=new Map(w.map(B=>[B.id,B])),v=m.map(async B=>{const{transaction:N,workflowId:J,readOnly:M,index:X}=B,Ze=J?y.get(J):void 0,At=t[X];if(N.integrationProductId){const ot=F.get(N.integrationProductId);N.integrationProduct=ot,N.product=ot?.product,N.integrationProduct||console.error("failed to find transaction's product")}const Ce=D.getMap("transactionOwnerIds")||new Map;!Ce.get(N.id)&&N.transactionOwnerId&&(Ce.set(N.id,N.transactionOwnerId),D.setMap("transactionOwnerIds",Ce));const ta=Ce.get(N.id)||void 0,yi=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),we={workflow:Ze,transaction:N,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:M?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yi,readOnly:M,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&N.workflowState){const ot=JSON.parse(N.workflowState);await Ba(ot),we.reloadedState=ot}else if(!M&&At.workflowState){const ot=JSON.parse(At.workflowState);await Ba(ot),we.reloadedState=ot}return we.delayWorkflowStateSync=!0,{experienceOptions:we,index:X,options:At}}),T=(await Promise.all(v)).sort((B,N)=>B.index-N.index);let G=[];for(const B of T){const{experienceOptions:N,options:J}=B,M=new Yr(this,N);await M.getWorkflowManager().getInitializationPromise(),a&&a(),J.type!=="transaction"&&this.customer&&await M.attachCustomerDetails({email:this.customer.emailAddress}),G=[...G,M],M.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return G}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 S.getShadowGraphqlClient().query({query:Ho(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 Na(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Na(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});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 S.getShadowGraphqlClient().mutate({mutation:ls,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 ci=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(n,t)=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function di(n){const e=D.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Oe(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const cd=async n=>{const t=await di(n),e=await S.getShadowGraphqlClient().mutate({mutation:Sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function ui(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(n.x,t.width-c,0),s.y=Pe(n.y,t.height-d,0),s}const o=n;return o.x=Pe(o.x,-r,t.width),o.y=Pe(o.y,-i,t.height),o}function Pe(n,t,e){return Math.min(Math.max(n,t),e)}class Ai{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(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 a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await pe(s),c=this.frameData?this.frameData[o]:void 0;ee(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,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return Ge(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,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=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[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,a){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))&&!a){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]=ui(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,a,r,i){if(!a||a.length===0||a.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 O([new Hs(l,e,t[d]),new Js(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((a,r)=>{const i=Math.max(a.width/t.width,a.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,a)=>{this.offsets[a]=Wa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class dd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,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,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hi=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(hi||{});class gi extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Ai(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,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await gt.selectImage(this.step,t,this.manager,a),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(Ue.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 a=await $.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}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,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||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 $.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return $.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 a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!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 ud=C.gql`
|
|
2575
2575
|
query GetLoggedInCustomer($email: String!) {
|
|
2576
2576
|
customer(emailAddress: $email) {
|
|
2577
2577
|
id
|