@spiffcommerce/core 14.8.0 → 14.8.1
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/main.js +18 -18
- package/dist/module.js +17 -17
- package/package.json +1 -1
package/dist/module.js
CHANGED
|
@@ -487,7 +487,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
487
487
|
id
|
|
488
488
|
}
|
|
489
489
|
}
|
|
490
|
-
`;class va extends Ma{constructor(t,e){super(t,e),Fa(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:Sa,variables:{transactionId:this.manager.getTransaction().id,designName:t}});const e=this.manager.getTransaction();this.manager.setTransaction({...e,designName:t})}addVariationRecord(){const t=this.manager.addVariationRecord({transactionId:this.transaction.id,values:[]});return this.manager.setCurrentVariationRecord(t),t}updateBulkIsConnected(t){this.manager.updateStorage(this.getId(),{bulkIsConnected:t})}openBulkSourceUrl(){window.open(this.transaction.bulkSourceUrl,"_blank")}async sendGoogleSheetLinkToEmail(t){await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.transaction.id,details:{emailAddress:t},type:"Owner"}}),this.openBulkSourceUrl()}deleteVariationRecord(t){this.manager.removeVariationRecord(t)}getAspects(){return this.step.data.aspects}}class xa extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return oa.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],(t=>this.setUpdateState(t)),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(0!==t.length)try{return y(t[0].id,this.manager.getAllLayoutData()).colors}catch(t){console.error(t)}}setColor(t,e){const A=new Map;return A.set(t,e),oa.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,(()=>this.manager.getCommandContext().getAllLayouts()),A)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?oa.availableColors(this.step,this.manager):Promise.resolve([])}hasVaryingSelection(){return this.step.data.varySelection}hasVaryingColors(){return this.step.data.varyColors}isColorPickerEnabled(){return this.step.data.colorPickerEnabled}}class Na extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ra.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Pa extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return sa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ra extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ga.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ha extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await la.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Ua extends Ma{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Ba.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ba.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ba.availableColours(this.step)}}class ba extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){ua.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=this.manager.getInformationResults().filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}}),(t=>{}))}getAvailableFillColors(){return this.step.data.colorPickerEnabled?ua.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await ua.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ua.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await ua.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",A=void 0!==this.step.data.replaceableText?this.step.data.replaceableText.replace("{{}}",e):e,n=t?A:this.step.data.defaultText;this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1});return this.setText(n)}setText(t){const e={input:t},A=ua.findLayoutElements(this.manager,this.step),n=ua.filterUnsupportedCharacters(t,A[0]?.fontData);!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength||(e.input=n);const a=A.length<=0,i=a?{inputText:n,text:n}:{inputText:n};if(this.manager.updateStorage(this.step.stepName,i),this.manager.updateMetadata(this.step.stepName,{text:n}),a)return e;const{command:o,errors:r,helperText:s}=ua.updateInputText(n,A,this.step,this.manager);o&&this.manager.getCommandDispatcher()(o);const c=this.manager.getInformationResults(),g=r[0]?.localizationKey;if(g)this.manager.setInformationResults([...c,{message:`${g} - ${this.step.stepTitle}`,messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=c.filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}return e.helperText=g||s,e.errorText=g,e}getText(){const t=this.step.data.defaultText;return this.manager.getStepStorage(this.step.stepName)?.text||t||""}isReplaceable(){return this.step.data.userCanReplaceText}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");return this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""}),t}}hasVaryingText(){return this.step.data.varyText}hasVaryingColor(){return this.step.data.varyColor}hasVaryingSelection(){return this.step.data.varySelection}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(void 0===t)return;return t-this.getText().length}}class ka{static get(t,e){switch(e.type){case m.Question:return new Ha(t,e);case m.Text:return new ba(t,e);case m.Illustration:return new xa(t,e);case m.Picture:return new Ra(t,e);case m.Shape:return new Ua(t,e);case m.Material:return new Na(t,e);case m.Model:return new Pa(t,e);case m.Frame:return new
|
|
490
|
+
`;class va extends Ma{constructor(t,e){super(t,e),Fa(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:Sa,variables:{transactionId:this.manager.getTransaction().id,designName:t}});const e=this.manager.getTransaction();this.manager.setTransaction({...e,designName:t})}addVariationRecord(){const t=this.manager.addVariationRecord({transactionId:this.transaction.id,values:[]});return this.manager.setCurrentVariationRecord(t),t}updateBulkIsConnected(t){this.manager.updateStorage(this.getId(),{bulkIsConnected:t})}openBulkSourceUrl(){window.open(this.transaction.bulkSourceUrl,"_blank")}async sendGoogleSheetLinkToEmail(t){await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.transaction.id,details:{emailAddress:t},type:"Owner"}}),this.openBulkSourceUrl()}deleteVariationRecord(t){this.manager.removeVariationRecord(t)}getAspects(){return this.step.data.aspects}}class xa extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return oa.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],(t=>this.setUpdateState(t)),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(0!==t.length)try{return y(t[0].id,this.manager.getAllLayoutData()).colors}catch(t){console.error(t)}}setColor(t,e){const A=new Map;return A.set(t,e),oa.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,(()=>this.manager.getCommandContext().getAllLayouts()),A)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?oa.availableColors(this.step,this.manager):Promise.resolve([])}hasVaryingSelection(){return this.step.data.varySelection}hasVaryingColors(){return this.step.data.varyColors}isColorPickerEnabled(){return this.step.data.colorPickerEnabled}}class Na extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ra.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Pa extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return sa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ra extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ga.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ha extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await la.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Ua extends Ma{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Ba.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ba.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ba.availableColours(this.step)}}class ba extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){ua.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=this.manager.getInformationResults().filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}}),(t=>{}))}getAvailableFillColors(){return this.step.data.colorPickerEnabled?ua.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await ua.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ua.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await ua.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",A=void 0!==this.step.data.replaceableText?this.step.data.replaceableText.replace("{{}}",e):e,n=t?A:this.step.data.defaultText;this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1});return this.setText(n)}setText(t){const e={input:t},A=ua.findLayoutElements(this.manager,this.step),n=ua.filterUnsupportedCharacters(t,A[0]?.fontData);!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength||(e.input=n);const a=A.length<=0,i=a?{inputText:n,text:n}:{inputText:n};if(this.manager.updateStorage(this.step.stepName,i),this.manager.updateMetadata(this.step.stepName,{text:n}),a)return e;const{command:o,errors:r,helperText:s}=ua.updateInputText(n,A,this.step,this.manager);o&&this.manager.getCommandDispatcher()(o);const c=this.manager.getInformationResults(),g=r[0]?.localizationKey;if(g)this.manager.setInformationResults([...c,{message:`${g} - ${this.step.stepTitle}`,messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=c.filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}return e.helperText=g||s,e.errorText=g,e}getText(){const t=this.step.data.defaultText;return this.manager.getStepStorage(this.step.stepName)?.text||t||""}isReplaceable(){return this.step.data.userCanReplaceText}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");return this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""}),t}}hasVaryingText(){return this.step.data.varyText}hasVaryingColor(){return this.step.data.varyColor}hasVaryingSelection(){return this.step.data.varySelection}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(void 0===t)return;return t-this.getText().length}}class ka{static get(t,e){switch(e.type){case m.Question:return new Ha(t,e);case m.Text:return new ba(t,e);case m.Illustration:return new xa(t,e);case m.Picture:return new Ra(t,e);case m.Shape:return new Ua(t,e);case m.Material:return new Na(t,e);case m.Model:return new Pa(t,e);case m.Frame:return new _i(t,e);case m.Bulk:return new va(t,e);default:throw new re(`Step type ${e.type} not yet supported in Core SDK`)}}}function Ga(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Ja=It`
|
|
491
491
|
mutation CreateDesign(
|
|
492
492
|
$name: String!
|
|
493
493
|
$layouts: [LayoutInput]!
|
|
@@ -519,7 +519,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
519
519
|
}
|
|
520
520
|
}
|
|
521
521
|
}
|
|
522
|
-
`,La=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Ta=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Oa=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=La(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Ta(t,e,s,c,i,g,o,n,a,r)},za=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:Jn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=e?.finalizeStepConfig?.lookAtAnimation,C=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!u,Q=B&&La(B,e,!0),p=B&&La(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await m(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(C);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!C,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(f){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:Gn,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Ta(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Oa(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let ja;var Ka;(Ka=ja||(ja={})).Local="Local",Ka.Remote="Remote";const Va=new class{constructor(){Ga(this,"localPersistenceKey","designTransactions"),Ga(this,"storageMethod",ja.Local),Ga(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===ja.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==ja.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function Wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Xa{constructor(e,A){if(Wa(this,"client",void 0),Wa(this,"commandContext",void 0),Wa(this,"workflowManager",void 0),Wa(this,"isReadOnly",void 0),Wa(this,"renderableScenes",[]),Wa(this,"renderableSceneCallbacks",[]),Wa(this,"debouncedSavedDesignUpdate",Xt((async()=>{await Va.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),Wa(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Da(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:kn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return ka.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:Ln(this.getWorkflowManager().getWorkflow())},conditions:[]};return ka.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return ka.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>ka.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>ka.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((e=>e!==t))}async save(t){if(!this.getCommandContext().getState())throw new re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await Va.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Va.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new ji({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return za(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const qa=Zt`
|
|
522
|
+
`,La=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Ta=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Oa=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=La(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Ta(t,e,s,c,i,g,o,n,a,r)},za=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:Jn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),u=e?.finalizeStepConfig?.lookAtAnimation,C=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!u,Q=B&&La(B,e,!0),p=B&&La(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),f=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[I]=await m(!1),y=Object.fromEntries(Object.keys(I).map((t=>[t,I[t].map((t=>t.id))]))),M=await l(C);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!C,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(f){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:Gn,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Ta(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Oa(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let ja;var Ka;(Ka=ja||(ja={})).Local="Local",Ka.Remote="Remote";const Va=new class{constructor(){Ga(this,"localPersistenceKey","designTransactions"),Ga(this,"storageMethod",ja.Local),Ga(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===ja.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==ja.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function Wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Xa{constructor(e,A){if(Wa(this,"client",void 0),Wa(this,"commandContext",void 0),Wa(this,"workflowManager",void 0),Wa(this,"isReadOnly",void 0),Wa(this,"renderableScenes",[]),Wa(this,"renderableSceneCallbacks",[]),Wa(this,"debouncedSavedDesignUpdate",Xt((async()=>{await Va.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),Wa(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Da(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:kn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return ka.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:Ln(this.getWorkflowManager().getWorkflow())},conditions:[]};return ka.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return ka.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>ka.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.name===t.name)))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>ka.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter((e=>e!==t))}async save(t){if(!this.getCommandContext().getState())throw new re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await Va.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Va.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new Vi({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return za(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const qa=Zt`
|
|
523
523
|
${Zt`
|
|
524
524
|
fragment ProductCollectionProductFields on Product {
|
|
525
525
|
id
|
|
@@ -767,7 +767,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
767
767
|
}
|
|
768
768
|
}
|
|
769
769
|
}
|
|
770
|
-
`,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class yi{constructor(t){Di(this,"value",void 0),this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):JSON.stringify(t)}}let Mi;var Fi;(Fi=Mi||(Mi={})).Transaction="Transaction",Fi.Bundle="Bundle",Fi.Product="Product",Fi.Variant="Variant",Fi.Option="Option",Fi.LineItem="LineItem",Fi.Asset="Asset";class Yi extends yi{constructor(t,e){if("Asset"!==e&&!Yi.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class Si extends yi{constructor(t){super(t)}}function vi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}
|
|
770
|
+
`,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class yi{constructor(t){Di(this,"value",void 0),this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):JSON.stringify(t)}}let Mi;var Fi;(Fi=Mi||(Mi={})).Transaction="Transaction",Fi.Bundle="Bundle",Fi.Product="Product",Fi.Variant="Variant",Fi.Option="Option",Fi.LineItem="LineItem",Fi.Asset="Asset";class Yi extends yi{constructor(t,e){if("Asset"!==e&&!Yi.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class Si extends yi{constructor(t){super(t)}}function vi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}var xi=new class{constructor(){vi(this,"cache",{})}get(t){return this.cache[t]}has(t){return t in this.cache}set(t,e){return this.cache[t]=e,e}delete(t){delete this.cache[t]}};function Ni(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Pi=It`
|
|
771
771
|
fragment RegionFields on Region {
|
|
772
772
|
width
|
|
773
773
|
top
|
|
@@ -785,7 +785,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
785
785
|
height
|
|
786
786
|
}
|
|
787
787
|
}
|
|
788
|
-
`,
|
|
788
|
+
`,Ri=It`
|
|
789
789
|
fragment LookAtAnimationFields on LookAtAnimation {
|
|
790
790
|
latDeg
|
|
791
791
|
lonDeg
|
|
@@ -796,7 +796,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
796
796
|
z
|
|
797
797
|
}
|
|
798
798
|
}
|
|
799
|
-
`,
|
|
799
|
+
`,Hi=It`
|
|
800
800
|
fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
|
|
801
801
|
antiAliasing {
|
|
802
802
|
samples
|
|
@@ -880,21 +880,21 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
880
880
|
weight
|
|
881
881
|
}
|
|
882
882
|
}
|
|
883
|
-
`,
|
|
883
|
+
`,Ui=It`
|
|
884
884
|
fragment ModelAnimationFields on ModelAnimation {
|
|
885
885
|
from
|
|
886
886
|
to
|
|
887
887
|
loop
|
|
888
888
|
name
|
|
889
889
|
}
|
|
890
|
-
`,
|
|
890
|
+
`,bi=It`
|
|
891
891
|
${Fe}
|
|
892
892
|
${Se}
|
|
893
893
|
${be}
|
|
894
|
-
${xi}
|
|
895
|
-
${Ni}
|
|
896
894
|
${Pi}
|
|
897
895
|
${Ri}
|
|
896
|
+
${Hi}
|
|
897
|
+
${Ui}
|
|
898
898
|
query GetWorkflow($id: String!) {
|
|
899
899
|
workflow(id: $id) {
|
|
900
900
|
allowProofDownload
|
|
@@ -1272,7 +1272,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1272
1272
|
}
|
|
1273
1273
|
}
|
|
1274
1274
|
}
|
|
1275
|
-
`,
|
|
1275
|
+
`,ki=It`
|
|
1276
1276
|
query GetTransactionForPartner($id: String!) {
|
|
1277
1277
|
transactions(ids: [$id]) {
|
|
1278
1278
|
id
|
|
@@ -1289,7 +1289,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1289
1289
|
}
|
|
1290
1290
|
}
|
|
1291
1291
|
}
|
|
1292
|
-
`,
|
|
1292
|
+
`,Gi=It`
|
|
1293
1293
|
${Fe}
|
|
1294
1294
|
query GetWorkflowForTheme($id: String!) {
|
|
1295
1295
|
workflow(id: $id) {
|
|
@@ -1311,21 +1311,21 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1311
1311
|
}
|
|
1312
1312
|
}
|
|
1313
1313
|
}
|
|
1314
|
-
`,
|
|
1314
|
+
`,Ji=It`
|
|
1315
1315
|
query GetCustomer($emailAddress: String!) {
|
|
1316
1316
|
customer(emailAddress: $emailAddress) {
|
|
1317
1317
|
id
|
|
1318
1318
|
emailAddress
|
|
1319
1319
|
}
|
|
1320
1320
|
}
|
|
1321
|
-
`,
|
|
1321
|
+
`,Li=It`
|
|
1322
1322
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
|
1323
1323
|
customerCreate(details: $details) {
|
|
1324
1324
|
id
|
|
1325
1325
|
emailAddress
|
|
1326
1326
|
}
|
|
1327
1327
|
}
|
|
1328
|
-
`,
|
|
1328
|
+
`,Ti=It`
|
|
1329
1329
|
mutation CustomerAuthenticate($loginToken: String!) {
|
|
1330
1330
|
customerAuthenticate(loginToken: $loginToken) {
|
|
1331
1331
|
id
|
|
@@ -1349,11 +1349,11 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1349
1349
|
}
|
|
1350
1350
|
}
|
|
1351
1351
|
}
|
|
1352
|
-
`,
|
|
1352
|
+
`,Oi=It`
|
|
1353
1353
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
|
1354
1354
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
|
1355
1355
|
}
|
|
1356
|
-
`,
|
|
1356
|
+
`,zi=It`
|
|
1357
1357
|
mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
|
|
1358
1358
|
customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
|
|
1359
1359
|
id
|
|
@@ -1381,5 +1381,5 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1381
1381
|
}
|
|
1382
1382
|
}
|
|
1383
1383
|
}
|
|
1384
|
-
`,Oi=async t=>{const e=(await ye.getShadowGraphqlClient().query({query:Hi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return e.steps.forEach((t=>{delete t.data.__typename})),e},zi=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})))};class ji{constructor(t){var e;vi(this,"options",void 0),vi(this,"initialized",void 0),vi(this,"currencyCode",void 0),vi(this,"customer",void 0),vi(this,"experienceOptions",void 0),vi(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Un})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,Ie=e)}getAssetManager(){return He}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new Ii}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:Ui,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:bi,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:Gi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:Ji,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(fe(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:Li,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:Ti,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),fe(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new mi(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:Za,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new mi(this,a,e);return await i.getInitializationPromise(),i}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:_a,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||0===t.data.customers.length)throw new Error("Unable to find customer.");return t.data.customers[0].bundleStakeholders||[]}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Hn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await Oi(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:Pn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=Oi(n.workflowId),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:this.updateTransactionState,readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=zi(s.transaction,s.workflow);if(s.renderableContextService=new In(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new Xa(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Pn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Hn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Hn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:Rn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await Oi(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new In(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new Xa(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:bn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=Oi(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=zi(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new In(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new Xa(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function Ki(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Vi{constructor(){Ki(this,"getProduct",void 0),Ki(this,"getCommandContext",void 0),Ki(this,"getAllLayoutData",void 0),Ki(this,"getMetadata",void 0),Ki(this,"getWorkflowMetadata",void 0),Ki(this,"getStepStorage",void 0),Ki(this,"setModelContainer",void 0),Ki(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}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{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function Wi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Xi;var qi;(qi=Xi||(Xi={})).SelectFrame="SelectFrame",qi.SelectImage="SelectImage",qi.Position="Position";class Zi extends Ma{constructor(t,e){super(t,e),Wi(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ia.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ia.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?Xi.SelectFrame:e||A||this.getImageData()?Xi.Position:Xi.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const $i=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=Le(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=Ze(),h=Rt((t=>{const e=t;d(new qe({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new qe({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),C=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new qe({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),JA([" "],(()=>{B(!0),d(new qe({selectedElement:void 0}))}),(()=>B(!1))),JA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=kt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{ji as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,zA as PromiseQueue,OA as QueueablePromise,Vi as MockWorkflowManager,Qa as InformationMessageType,Ma as StepHandle,ba as TextStepHandle,Zi as FrameStepHandle,va as BulkStepHandle,Ua as ShapeStepHandle,xa as IllustrationStepHandle,Na as MaterialStepHandle,Pa as ModelStepHandle,Ra as PictureStepHandle,Ha as QuestionStepHandle,tA as BulkPriceCalculationStrategy,Ia as Variant,Xa as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,He as assetService,Va as designService,za as createDesign,Ge as optionService,de as persistenceService,ye as graphQlManager,gA as toast,Zn as FrameService,Xn as getBoundedOffsets,ia as frameStepService,sa as modelStepService,ra as materialStepService,Ba as shapeStepService,la as questionStepService,na as digitalContentStepService,ca as moduleStepService,ga as pictureStepService,ua as textStepService,oa as illustrationStepService,$e as ProductCameraRig,Xi as FrameStep,AA as ConversionLocation,aA as ConversionDataType,Oi as getWorkflow,ta as shortenUrl,Yi as ObjectInput,Si as TextInput,Mi as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,oA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,f as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Dn as generateCommands,k as registerJSDOM,bA as minZoom,Nn as AdvancedEditor,$i as TransformWrapper,xn as EditorCore,Te as useLayouts,Ze as useEditorState,GA as useEditorInteraction,JA as useShortcutCombination,Ve as commandReducer,Ke as getDefaultState,Je as CommandContextContext,Xe as AdvancedEditorStateProvider,We as AdvancedEditorContext,qe as UICommand,ze as EditorSubMenu,lA as ElementEventType,wA as KeyEvent,Ln as gatherVaryingStepAspects};
|
|
1384
|
+
`,ji=async t=>{const e=xi.get(t);return e||xi.set(t,(async t=>{const e=(await ye.getShadowGraphqlClient().query({query:bi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return e.steps.forEach((t=>{delete t.data.__typename})),e})(t))},Ki=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})))};class Vi{constructor(t){var e;Ni(this,"options",void 0),Ni(this,"initialized",void 0),Ni(this,"currencyCode",void 0),Ni(this,"customer",void 0),Ni(this,"experienceOptions",void 0),Ni(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Un})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,Ie=e)}getAssetManager(){return He}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new Ii}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:Gi,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:Ji,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:Li,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:Ti,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(fe(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:Oi,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:zi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),fe(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new mi(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:Za,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new mi(this,a,e);return await i.getInitializationPromise(),i}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:_a,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||0===t.data.customers.length)throw new Error("Unable to find customer.");return t.data.customers[0].bundleStakeholders||[]}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Hn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await ji(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:Pn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=ji(n.workflowId),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:this.updateTransactionState,readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=Ki(s.transaction,s.workflow);if(s.renderableContextService=new In(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new Xa(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Pn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Hn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Hn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:Rn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await ji(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new In(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new Xa(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:bn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=ji(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=Ki(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new In(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new Xa(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function Wi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Xi{constructor(){Wi(this,"getProduct",void 0),Wi(this,"getCommandContext",void 0),Wi(this,"getAllLayoutData",void 0),Wi(this,"getMetadata",void 0),Wi(this,"getWorkflowMetadata",void 0),Wi(this,"getStepStorage",void 0),Wi(this,"setModelContainer",void 0),Wi(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}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{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function qi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Zi;var $i;($i=Zi||(Zi={})).SelectFrame="SelectFrame",$i.SelectImage="SelectImage",$i.Position="Position";class _i extends Ma{constructor(t,e){super(t,e),qi(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ia.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ia.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?Zi.SelectFrame:e||A||this.getImageData()?Zi.Position:Zi.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const to=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=Le(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=Ze(),h=Rt((t=>{const e=t;d(new qe({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new qe({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),C=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new qe({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),JA([" "],(()=>{B(!0),d(new qe({selectedElement:void 0}))}),(()=>B(!1))),JA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=kt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{Vi as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,zA as PromiseQueue,OA as QueueablePromise,Xi as MockWorkflowManager,Qa as InformationMessageType,Ma as StepHandle,ba as TextStepHandle,_i as FrameStepHandle,va as BulkStepHandle,Ua as ShapeStepHandle,xa as IllustrationStepHandle,Na as MaterialStepHandle,Pa as ModelStepHandle,Ra as PictureStepHandle,Ha as QuestionStepHandle,tA as BulkPriceCalculationStrategy,Ia as Variant,Xa as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,He as assetService,Va as designService,za as createDesign,Ge as optionService,de as persistenceService,ye as graphQlManager,gA as toast,Zn as FrameService,Xn as getBoundedOffsets,ia as frameStepService,sa as modelStepService,ra as materialStepService,Ba as shapeStepService,la as questionStepService,na as digitalContentStepService,ca as moduleStepService,ga as pictureStepService,ua as textStepService,oa as illustrationStepService,$e as ProductCameraRig,Zi as FrameStep,AA as ConversionLocation,aA as ConversionDataType,ji as getWorkflow,ta as shortenUrl,Yi as ObjectInput,Si as TextInput,Mi as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,oA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,f as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Dn as generateCommands,k as registerJSDOM,bA as minZoom,Nn as AdvancedEditor,to as TransformWrapper,xn as EditorCore,Te as useLayouts,Ze as useEditorState,GA as useEditorInteraction,JA as useShortcutCombination,Ve as commandReducer,Ke as getDefaultState,Je as CommandContextContext,Xe as AdvancedEditorStateProvider,We as AdvancedEditorContext,qe as UICommand,ze as EditorSubMenu,lA as ElementEventType,wA as KeyEvent,Ln as gatherVaryingStepAspects};
|
|
1385
1385
|
//# sourceMappingURL=module.js.map
|