@claspo/renderer 18.13.0-mto1 → 18.13.1-pag1

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.
@@ -21,7 +21,7 @@ export default class BaseRequestAction {
21
21
  initiatorComponentId: any;
22
22
  constructor(eventEmitter: any, form: any, config: any, httpClient: any, configService: any, tracking: any, state: any, context: any, getServices: any);
23
23
  skipHttpRequest: boolean;
24
- routingIgnoresSubmitActionParams: boolean;
24
+ isGameSubmitInFlight: boolean;
25
25
  setInitiatorComponentId(componentId: any): void;
26
26
  emitSubmitLifecycleEvent(eventName: any, payload?: any): void;
27
27
  getTrackingMessageBeforeSentData(): string;
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import{SYSTEM_RESULT_STATE_LABELS,submitAdvancesToNextStep}from"@claspo/common/document/ViewNavigationGraph";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import{constructDataToSent,constructRequestHeaders,constructRequestPayload,extractContextValue}from"../RequestPayloadBuilder";function componentModelHasSubmitAction(t){var e,i;try{return!!(null===(i=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===i?void 0:i.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isResultView(t,e){return!!t&&(SYSTEM_RESULT_STATE_LABELS.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,i,s,o,n,r,a,c){this.skipHttpRequest=!0,this.routingIgnoresSubmitActionParams=!1,this.id=i.id,this.params=i.params,this.form=e,this.eventEmitter=t,this.httpClient=s,this.configService=o,this.formEventsListener=null,this.tracking=n,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}setInitiatorComponentId(t){this.initiatorComponentId=t}emitSubmitLifecycleEvent(t,e=void 0){this.eventEmitter.emit(t,e,{initiatorComponentId:this.initiatorComponentId})}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,i,s){var o;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const n=new Promise(t=>{this.submit(t,i,s)});return null===(o=this.getServices().submitState)||void 0===o||o.trackSubmission(n),n}submit(t,e,i){var s,o,n;const r=this.getServices().viewRouter.getCurrentViewIndex(),a=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),c=submitAdvancesToNextStep(this.getServices().documentModel.getNavigationGraph(),this.getServices().documentModel.getViews(),r,a),u=Object.assign(Object.assign({},this.params),i),S=!!u.isGameSubmit,d=this.getServices().documentModel.getViews(),m=S&&u.prizeNavigateToViewId?d.findIndex(t=>t.id===u.prizeNavigateToViewId):-1;if(this.routingIgnoresSubmitActionParams=S,this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!u.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const E=this.stateService,h=E.getState().conditionalRedirectViewId,l=u.conditionalRedirectViewId||h;h&&(u.conditionalRedirectViewId=h,E.setState({conditionalRedirectViewId:null}));let g=-1!==m?d[m]:d[r+1];const v=d[r];if(!u.skipNavigation&&l&&getComponentCountOnView(v,"SysNetPromoterScoreComponent")+getComponentCountOnView(v,"SysFeedbackComponent")===1&&(g=this.getServices().documentModel.getViews().find(t=>t.id===u.conditionalRedirectViewId),viewHasControls(g)||isResultView(g,a)))return this.goToView(g.path[0],u),void t(!0);const T=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),R=this.getContextValue(u);if(!u.skipNavigation&&c&&g&&(viewHasControls(g)||!Object.keys(T).length&&!Object.keys(R).length))return this.goToView(g.path[0],u),void t(!0);if(!Object.keys(T).length&&!Object.keys(R).length)return void t(!0);const C=UTMParamsExtractor.extractTrackingParams(this.context),I=this.constructRequestPayload({contextValue:R,formValue:T,utmParams:C}),f=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);f&&(I.navigationData=f),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,I),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",I);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(I).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{var i,s;const o=this.getTrackingMessageByStatus(e.state);if(o&&this.tracking.send(o),u.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state!==RequestStatus.SUCCESS&&e.state!==RequestStatus.ALREADY_SUBSCRIBED||null===(s=null===(i=this.getServices().navigationLeadCollector)||void 0===i?void 0:i.recordCommittedLead)||void 0===s||s.call(i),e.state){case RequestStatus.SUCCESS:(S||c)&&g?this.goToView(g.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:(S||l)&&g?this.goToView(g.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:l&&g?this.goToView(g.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:S?this.handleErrorResponse():this.goToView(l&&g?g.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),u.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){return extractContextValue(this.context,t.excludeFormContext)}constructDataToSent({contextValue:t,formValue:e,utmParams:i}){return constructDataToSent({contextValue:t,formValue:e,utmParams:i})}constructRequestPayload({contextValue:t,formValue:e,utmParams:i}){return constructRequestPayload({contextValue:t,formValue:e,utmParams:i,referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy"),widgetDebugMode:this.configService.getConfig("widgetDebugMode")})}constructRequestHeaders(){return constructRequestHeaders({clCustomerId:this.configService.getConfig("clCustomerId")})}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,Object.assign(Object.assign({},e),{isForward:!0}))}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute({url:this.configService.getConfig("subscribeContactUrl"),method:"POST",body:t,headers:this.constructRequestHeaders()})}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",["DOCUMENT_VIEW_TYPE_SUBSCRIBED"])}resolveResultViewIndex(t,e){var i;const s=this.getServices().documentModel.getViews(),o=null===(i=this.getActiveSubmitActionParams())||void 0===i?void 0:i[t];if(o){const t=s.findIndex(t=>t.id===o);if(-1!==t)return t}return s.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(!this.routingIgnoresSubmitActionParams&&this.hasFormControls())return this.getServices().documentModel.getShared().submitActionParams}runPostSubmitActionOrGoToView(t){var e;const i=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;i?setTimeout(()=>{this.getServices().actionFactory.get(i).execute(this.stateService.getState())},1500):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
1
+ import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import{ALREADY_SUBSCRIBED_LEGACY_LABELS,SYSTEM_RESULT_STATE_LABELS,submitAdvancesToNextStep}from"@claspo/common/document/ViewNavigationGraph";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import{constructDataToSent,constructRequestHeaders,constructRequestPayload,extractContextValue}from"../RequestPayloadBuilder";function componentModelHasSubmitAction(t){var e,i;try{return!!(null===(i=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===i?void 0:i.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isResultView(t,e){return!!t&&(SYSTEM_RESULT_STATE_LABELS.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,i,s,o,n,r,a,c){this.skipHttpRequest=!0,this.isGameSubmitInFlight=!1,this.id=i.id,this.params=i.params,this.form=e,this.eventEmitter=t,this.httpClient=s,this.configService=o,this.formEventsListener=null,this.tracking=n,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}setInitiatorComponentId(t){this.initiatorComponentId=t}emitSubmitLifecycleEvent(t,e=void 0){this.eventEmitter.emit(t,e,{initiatorComponentId:this.initiatorComponentId})}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,i,s){var o;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const n=new Promise(t=>{this.submit(t,i,s)});return null===(o=this.getServices().submitState)||void 0===o||o.trackSubmission(n),n}submit(t,e,i){var s,o,n;const r=this.getServices().viewRouter.getCurrentViewIndex(),a=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),c=submitAdvancesToNextStep(this.getServices().documentModel.getNavigationGraph(),this.getServices().documentModel.getViews(),r,a),u=Object.assign(Object.assign({},this.params),i),S=!!u.isGameSubmit,d=this.getServices().documentModel.getViews(),m=S&&u.prizeNavigateToViewId?d.findIndex(t=>t.id===u.prizeNavigateToViewId):-1;if(this.isGameSubmitInFlight=S,this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!u.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const E=this.stateService,l=E.getState().conditionalRedirectViewId,h=u.conditionalRedirectViewId||l;l&&(u.conditionalRedirectViewId=l,E.setState({conditionalRedirectViewId:null}));let g=-1!==m?d[m]:d[r+1];const R=d[r];if(!u.skipNavigation&&h&&getComponentCountOnView(R,"SysNetPromoterScoreComponent")+getComponentCountOnView(R,"SysFeedbackComponent")===1&&(g=this.getServices().documentModel.getViews().find(t=>t.id===u.conditionalRedirectViewId),viewHasControls(g)||isResultView(g,a)))return this.goToView(g.path[0],u),void t(!0);const v=null!==(s=u.formValue)&&void 0!==s?s:this.form.getControlsMap(),T=this.getContextValue(u);if(!u.skipNavigation&&c&&g&&(viewHasControls(g)||!Object.keys(v).length&&!Object.keys(T).length))return this.goToView(g.path[0],u),void t(!0);if(!Object.keys(v).length&&!Object.keys(T).length)return void t(!0);const C=UTMParamsExtractor.extractTrackingParams(this.context),I=this.constructRequestPayload({contextValue:T,formValue:v,utmParams:C}),A=null===(n=null===(o=this.getServices().navigationLeadCollector)||void 0===o?void 0:o.getLatestNavigationData)||void 0===n?void 0:n.call(o);A&&(I.navigationData=A),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_STARTED,I),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",I);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(I).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{var i,s;const o=this.getTrackingMessageByStatus(e.state);if(o&&this.tracking.send(o),u.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state!==RequestStatus.SUCCESS&&e.state!==RequestStatus.ALREADY_SUBSCRIBED||null===(s=null===(i=this.getServices().navigationLeadCollector)||void 0===i?void 0:i.recordCommittedLead)||void 0===s||s.call(i),e.state){case RequestStatus.SUCCESS:(S||c)&&g?this.goToView(g.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:if(S){const t=this.resolveResultViewIndex("alreadySubscribedViewId",ALREADY_SUBSCRIBED_LEGACY_LABELS);-1!==t?this.goToView(t):g?this.goToView(g.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex())}else h&&g?this.goToView(g.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:h&&g?this.goToView(g.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:S?this.handleErrorResponse():this.goToView(h&&g?g.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),u.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){return extractContextValue(this.context,t.excludeFormContext)}constructDataToSent({contextValue:t,formValue:e,utmParams:i}){return constructDataToSent({contextValue:t,formValue:e,utmParams:i})}constructRequestPayload({contextValue:t,formValue:e,utmParams:i}){return constructRequestPayload({contextValue:t,formValue:e,utmParams:i,referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy"),widgetDebugMode:this.configService.getConfig("widgetDebugMode")})}constructRequestHeaders(){return constructRequestHeaders({clCustomerId:this.configService.getConfig("clCustomerId")})}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,Object.assign(Object.assign({},e),{isForward:!0}))}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute({url:this.configService.getConfig("subscribeContactUrl"),method:"POST",body:t,headers:this.constructRequestHeaders()})}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",ALREADY_SUBSCRIBED_LEGACY_LABELS)}resolveResultViewIndex(t,e){var i;const s=this.getServices().documentModel.getViews(),o=null===(i=this.getActiveSubmitActionParams())||void 0===i?void 0:i[t];if(o){const t=s.findIndex(t=>t.id===o);if(-1!==t)return t}return s.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(!this.hasFormControls())return;const t=this.getServices().documentModel.getShared().submitActionParams;return this.isGameSubmitInFlight&&t?Object.assign(Object.assign({},t),{successViewId:null,runAction:null}):t}runPostSubmitActionOrGoToView(t){var e;const i=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;i?setTimeout(()=>{this.getServices().actionFactory.get(i).execute(this.stateService.getState())},1500):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.emitSubmitLifecycleEvent(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "18.13.0-mto1",
3
+ "version": "18.13.1-pag1",
4
4
  "sideEffects": false,
5
5
  "scripts": {
6
6
  "dev": " tsc --project tsconfig.json --watch",
@@ -16,7 +16,7 @@
16
16
  "node": ">=18.16.0"
17
17
  },
18
18
  "dependencies": {
19
- "@claspo/common": "7.5.11-mto1",
19
+ "@claspo/common": "7.5.12-pag1",
20
20
  "@testing-library/dom": "^10.4.0"
21
21
  },
22
22
  "devDependencies": {
@@ -18,6 +18,8 @@ export default class PrizePool {
18
18
  _findPoolOption(rewardOrReservation: any, options: any): any;
19
19
  _mergeRewardIntoOption(reward: any, options: any): any;
20
20
  _fetchPool(url: string, prizePoolId: string): Promise<any>;
21
+ _assertPoolAvailable(pool: any, prizePoolId: string): any;
22
+ _findPoolFromScript(prizePoolId: string): any;
21
23
  _fetchJson(url: any, headers?: any): Promise<any>;
22
24
  getModel(): any;
23
25
  getPrize(): Promise<any>;
@@ -1 +1 @@
1
- import sum from"@claspo/common/math/sum";import RandomDistributor from"@claspo/common/math/RandomDistributor";import{PrizeCodeType,PrizeOptionValueType,PrizeSourceType}from"@claspo/common/PrizePool.interface";import{PreviewMode}from"../sdk/PreviewMode";import ErrorLogger from"../error/ErrorLogger";const FETCHABLE_SOURCE_TYPES=[PrizeSourceType.MANUAL,PrizeSourceType.SHOPIFY],drawnPrizeCodePlaceholder="CLXXXXXXXX";export default class PrizePool{constructor(e,o,i){if(this.httpClient=o,this.configService=i,this.instanceModel=e||{},"FIXED"!==this.instanceModel.model){const e=this.configService.getConfig("prizePoolModels");if(e&&this.instanceModel.id){const o=e.find(e=>e.id===this.instanceModel.id);o&&(this.instanceModel=o)}}this.prizeOption=null,this.randomDistributor=new RandomDistributor,this._loadPromise=null,this._claimPromise=null,this._reserved=!1}async load(){return this._loadPromise||(this._loadPromise=this._load()),this._loadPromise}async claimCode(){return this._claimPromise||(this._claimPromise=this._claim()),this._claimPromise}async _claim(){if(await this.load(),!this._reserved)return;const{id:e}=this.instanceModel,o=this.configService.getConfig("hostUrl"),i=this.configService.getConfig("widgetId"),t=`${o}forms/v1/prizePool/${e}/reward?widgetId=${i}`;try{this.prizeOption=await this._fetchReward(t,this.instanceModel.options,e)}catch(o){throw console.error(`PrizePool: failed to claim a code for widgetId "${i}" with poolId "${e}"`,o),o}}async _load(){const{id:e,model:o,sourceType:i,options:t}=this.instanceModel;if(!(!t&&!!e&&"FIXED"!==o&&(!i||FETCHABLE_SOURCE_TYPES.includes(i))))return;const r=this.configService.getConfig("widgetId");try{const o=this.configService.getConfig("hostUrl"),t=`${o}forms/v2/prize/pool/${e}`,n=`${o}forms/v1/prizePool/${e}/reward?widgetId=${r}`,s=`${o}forms/v1/prizePool/${e}/reserve-reward?widgetId=${r}`;if(this._isPreview()){const o=await this._fetchPool(t,e);if(this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:i||o.sourceType,options:o.options}),this._mintsCodePerWinner(o.options))return;return void(this.prizeOption=await this._fetchReward(n,o.options,e))}const[a,l]=await Promise.all([this._fetchPool(t,e),this._fetchJson(s,{"cl-customer-id":this.configService.getConfig("clCustomerId")})]);this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:i||a.sourceType,options:a.options}),this.prizeOption=this._resolveReservation(l,a.options,e),this._reserved=!0}catch(o){throw console.error(`PrizePool: failed to load pool or reservation for widgetId "${r}" with poolId "${e}"`,o),o}}_resolveReservation(e,o,i){if(!this._findPoolOption(e,o))throw ErrorLogger.log(`PrizePool: the pool ${i} does not hold the reserved option ${null==e?void 0:e.id}`),new Error("PrizePool: the reserved option is not in the pool");return this._mergeRewardIntoOption(e,o)}async _fetchReward(e,o,i){const t=await this._fetchJson(e,{"cl-customer-id":this.configService.getConfig("clCustomerId")});return this._resolveReward(t,o,i)}_resolveReward(e,o,i){const t=this._mergeRewardIntoOption(e,o);if(null==e?void 0:e.unavailableReason)throw ErrorLogger.log(`PrizePool: the reward from pool ${i} cannot be handed out with a reason "${e.unavailableReason}"`),new Error("PrizePool: the reward cannot be handed out");if(t.valueType===PrizeOptionValueType.PROMOCODE&&!t.code)throw ErrorLogger.log(`PrizePool: the reward from pool ${i} came back without a promo code`),new Error("PrizePool: the reward cannot be handed out");return t}_findPoolOption(e,o){return(o||[]).find(o=>o.id===(null==e?void 0:e.id))}_mergeRewardIntoOption(e,o){return Object.assign(Object.assign({},this._findPoolOption(e,o)),e)}async _fetchPool(e,o){const i=await this._fetchJson(e);if(!1===(null==i?void 0:i.available))throw ErrorLogger.log(`PrizePool: the pool ${o} is not available and cannot be handed out with a reason "${i.unavailableReason}"`),new Error("PrizePool: the pool is not available and cannot be handed out");return i}async _fetchJson(e,o){const i=await this.httpClient.execute({url:e,headers:o});if(!i.ok)throw new Error(`PrizePool: request failed with status ${i.status} - ${e}`);return i.json()}getModel(){return this.instanceModel}async getPrize(){return this.instanceModel?"FIXED"===this.instanceModel.model?this.instanceModel.data:FETCHABLE_SOURCE_TYPES.includes(this.instanceModel.sourceType)?(this.instanceModel.options&&!this.prizeOption&&(this.prizeOption=this._calculatePrize()),this.prizeOption?this.mapPrizeOption(this.prizeOption):null):null:null}submitPrize(){}mapPrizeOption(e){var o,i;const t=e.valueType===PrizeOptionValueType.PROMOCODE?e.value||"":this._mapLabelSuffix(e.value,e.valueType);return{id:e.id,label:t,value:e.code,navigateToViewId:null!==(i=null===(o=e.config)||void 0===o?void 0:o.navigateToViewId)&&void 0!==i?i:null}}_calculatePrize(){const e=sum(this.instanceModel.options.map(e=>parseFloat(e.weight))),o=this.randomDistributor.calculateFromWeights(this.instanceModel.options,e);return o&&this._isCodeMintedPerWinner(o)?Object.assign(Object.assign({},o),{code:"CLXXXXXXXX"}):o}_mintsCodePerWinner(e){return(e||[]).some(e=>this._isCodeMintedPerWinner(e))}_isPreview(){return!!(this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO))}_isCodeMintedPerWinner(e){var o;return(null===(o=null==e?void 0:e.config)||void 0===o?void 0:o.codeType)===PrizeCodeType.UNIQUE}_mapLabelSuffix(e,o){return o===PrizeOptionValueType.DISCOUNT_PERCENTAGE?`${e}%`:e}}
1
+ import sum from"@claspo/common/math/sum";import RandomDistributor from"@claspo/common/math/RandomDistributor";import{PrizeCodeType,PrizeOptionValueType}from"@claspo/common/PrizePool.interface";import{PreviewMode}from"../sdk/PreviewMode";import ErrorLogger from"../error/ErrorLogger";import{FETCHABLE_SOURCE_TYPES,isFetchedPrizePoolReference}from"./isFetchedPrizePoolReference";const drawnPrizeCodePlaceholder="CLXXXXXXXX";export default class PrizePool{constructor(e,o,i){if(this.httpClient=o,this.configService=i,this.instanceModel=e||{},"FIXED"!==this.instanceModel.model){const e=this.configService.getConfig("prizePoolModels");if(e&&this.instanceModel.id){const o=e.find(e=>e.id===this.instanceModel.id);o&&(this.instanceModel=o)}}this.prizeOption=null,this.randomDistributor=new RandomDistributor,this._loadPromise=null,this._claimPromise=null,this._reserved=!1}async load(){return this._loadPromise||(this._loadPromise=this._load()),this._loadPromise}async claimCode(){return this._claimPromise||(this._claimPromise=this._claim()),this._claimPromise}async _claim(){if(await this.load(),!this._reserved)return;const{id:e}=this.instanceModel,o=this.configService.getConfig("hostUrl"),i=this.configService.getConfig("widgetId"),t=`${o}forms/v1/prizePool/${e}/reward?widgetId=${i}`;try{this.prizeOption=await this._fetchReward(t,this.instanceModel.options,e)}catch(o){throw console.error(`PrizePool: failed to claim a code for widgetId "${i}" with poolId "${e}"`,o),o}}async _load(){const{id:e,sourceType:o}=this.instanceModel;if(!isFetchedPrizePoolReference(this.instanceModel))return;const i=this.configService.getConfig("widgetId");try{const t=this.configService.getConfig("hostUrl"),r=`${t}forms/v2/prize/pool/${e}`,n=`${t}forms/v1/prizePool/${e}/reward?widgetId=${i}`,s=`${t}forms/v1/prizePool/${e}/reserve-reward?widgetId=${i}`;if(this._isPreview()){const i=await this._fetchPool(r,e);if(this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:o||i.sourceType,options:i.options}),this._mintsCodePerWinner(i.options))return;return void(this.prizeOption=await this._fetchReward(n,i.options,e))}const a=this._findPoolFromScript(e);a&&this._assertPoolAvailable(a,e);const[l,d]=await Promise.all([a||this._fetchPool(r,e),this._fetchJson(s,{"cl-customer-id":this.configService.getConfig("clCustomerId")})]);this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:o||l.sourceType,options:l.options}),this.prizeOption=this._resolveReservation(d,l.options,e),this._reserved=!0}catch(o){throw console.error(`PrizePool: failed to load pool or reservation for widgetId "${i}" with poolId "${e}"`,o),o}}_resolveReservation(e,o,i){if(!this._findPoolOption(e,o))throw ErrorLogger.log(`PrizePool: the pool ${i} does not hold the reserved option ${null==e?void 0:e.id}`),new Error("PrizePool: the reserved option is not in the pool");return this._mergeRewardIntoOption(e,o)}async _fetchReward(e,o,i){const t=await this._fetchJson(e,{"cl-customer-id":this.configService.getConfig("clCustomerId")});return this._resolveReward(t,o,i)}_resolveReward(e,o,i){const t=this._mergeRewardIntoOption(e,o);if(null==e?void 0:e.unavailableReason)throw ErrorLogger.log(`PrizePool: the reward from pool ${i} cannot be handed out with a reason "${e.unavailableReason}"`),new Error("PrizePool: the reward cannot be handed out");if(t.valueType===PrizeOptionValueType.PROMOCODE&&!t.code)throw ErrorLogger.log(`PrizePool: the reward from pool ${i} came back without a promo code`),new Error("PrizePool: the reward cannot be handed out");return t}_findPoolOption(e,o){return(o||[]).find(o=>o.id===(null==e?void 0:e.id))}_mergeRewardIntoOption(e,o){return Object.assign(Object.assign({},this._findPoolOption(e,o)),e)}async _fetchPool(e,o){const i=await this._fetchJson(e);return this._assertPoolAvailable(i,o)}_assertPoolAvailable(e,o){if(!1===(null==e?void 0:e.available))throw ErrorLogger.log(`PrizePool: the pool ${o} is not available and cannot be handed out with a reason "${e.unavailableReason}"`),new Error("PrizePool: the pool is not available and cannot be handed out");return e}_findPoolFromScript(e){const o=this.configService.getConfig("prizePoolModelsFromScript");return null==o?void 0:o.find(o=>o.id===e)}async _fetchJson(e,o){const i=await this.httpClient.execute({url:e,headers:o});if(!i.ok)throw new Error(`PrizePool: request failed with status ${i.status} - ${e}`);return i.json()}getModel(){return this.instanceModel}async getPrize(){return this.instanceModel?"FIXED"===this.instanceModel.model?this.instanceModel.data:FETCHABLE_SOURCE_TYPES.includes(this.instanceModel.sourceType)?(this.instanceModel.options&&!this.prizeOption&&(this.prizeOption=this._calculatePrize()),this.prizeOption?this.mapPrizeOption(this.prizeOption):null):null:null}submitPrize(){}mapPrizeOption(e){var o,i;const t=e.valueType===PrizeOptionValueType.PROMOCODE?e.value||"":this._mapLabelSuffix(e.value,e.valueType);return{id:e.id,label:t,value:e.code,navigateToViewId:null!==(i=null===(o=e.config)||void 0===o?void 0:o.navigateToViewId)&&void 0!==i?i:null}}_calculatePrize(){const e=sum(this.instanceModel.options.map(e=>parseFloat(e.weight))),o=this.randomDistributor.calculateFromWeights(this.instanceModel.options,e);return o&&this._isCodeMintedPerWinner(o)?Object.assign(Object.assign({},o),{code:"CLXXXXXXXX"}):o}_mintsCodePerWinner(e){return(e||[]).some(e=>this._isCodeMintedPerWinner(e))}_isPreview(){return!!(this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO))}_isCodeMintedPerWinner(e){var o;return(null===(o=null==e?void 0:e.config)||void 0===o?void 0:o.codeType)===PrizeCodeType.UNIQUE}_mapLabelSuffix(e,o){return o===PrizeOptionValueType.DISCOUNT_PERCENTAGE?`${e}%`:e}}
@@ -0,0 +1,2 @@
1
+ import { ClDocumentI } from "@claspo/common/document/Document.interface";
2
+ export default function getDocumentPrizePoolIds(documentModel: ClDocumentI | null | undefined): string[];
@@ -0,0 +1 @@
1
+ import DocumentUtils from"@claspo/common/document/DocumentUtils";import{isFetchedPrizePoolReference}from"./isFetchedPrizePoolReference";export default function getDocumentPrizePoolIds(e){const o=new Set;return((null==e?void 0:e.views)||[]).forEach(e=>{DocumentUtils.iterateDepthFirst(e,e=>{var t,i;const n=null===(i=null===(t=e.props)||void 0===t?void 0:t.content)||void 0===i?void 0:i.prize;isFetchedPrizePoolReference(n)&&o.add(n.id)})}),[...o]}
@@ -0,0 +1,9 @@
1
+ export declare const FETCHABLE_SOURCE_TYPES: string[];
2
+ interface PrizePoolReferenceI {
3
+ id?: string;
4
+ model?: string;
5
+ sourceType?: string;
6
+ options?: unknown[];
7
+ }
8
+ export declare function isFetchedPrizePoolReference(reference: PrizePoolReferenceI | null | undefined): boolean;
9
+ export {};
@@ -0,0 +1 @@
1
+ import{PrizeSourceType}from"@claspo/common/PrizePool.interface";export const FETCHABLE_SOURCE_TYPES=[PrizeSourceType.MANUAL,PrizeSourceType.SHOPIFY];export function isFetchedPrizePoolReference(e){if(!e)return!1;const{id:o,model:r,sourceType:c,options:i}=e;return!i&&!!o&&"FIXED"!==r&&(!c||FETCHABLE_SOURCE_TYPES.includes(c))}