@claspo/renderer 18.10.0-dsp3 → 18.10.0-grp1
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/action/ActionFactory.js +1 -1
- package/action/InAppActionFactory.js +1 -1
- package/action/actions/BaseRequestAction.d.ts +1 -0
- package/action/actions/BaseRequestAction.js +1 -1
- package/action/actions/DispatchEventAction.d.ts +4 -1
- package/action/actions/DispatchEventAction.js +1 -1
- package/document-model/DocumentModelService.d.ts +3 -0
- package/document-model/DocumentModelService.js +1 -1
- package/lead-capture/FinishCoordinator.d.ts +2 -1
- package/lead-capture/FinishCoordinator.js +1 -1
- package/lead-capture/NavigationLeadCollector.d.ts +2 -1
- package/lead-capture/NavigationLeadCollector.js +1 -1
- package/package.json +2 -2
- package/prize-pool/PrizePool.d.ts +2 -12
- package/prize-pool/PrizePool.js +1 -1
package/action/ActionFactory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"./SysActionTypes";import SubscribeContactAction from"./actions/SubscribeContactAction";import RequestAction from"./actions/RequestAction";import DispatchEventAction from"./actions/DispatchEventAction";import GoToPreviousViewAction from"./actions/GoToPreviousViewAction";import GoToNextViewAction from"./actions/GoToNextViewAction";import GoToViewAction from"./actions/GoToViewAction";import HttpClient from"@claspo/common/network/HttpClient";import ShowWidgetAction from"./actions/ShowWidgetAction";import OpenLinkAction from"./actions/OpenLinkAction";import CloseWidgetAction from"./actions/CloseWidgetAction";export default class ActionFactory{constructor(t,i,e,o,n,c,s){this.eventEmitter=t,this.form=i,this.configService=e,this.tracking=o,this.stateService=n,this.context=c,this.getServices=s}get(t){switch(t.type){case SysActionTypes.SUBSCRIBE_CONTACT:return new SubscribeContactAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.REQUEST:return new RequestAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t);case SysActionTypes.GO_TO_VIEW:return new GoToViewAction(this.eventEmitter,t,this.configService,this.form,this.getServices().viewRouter,this.getServices().documentModel,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_PREVIOUS_VIEW:return new GoToPreviousViewAction(this.eventEmitter,t,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_NEXT_VIEW:return new GoToNextViewAction(this.eventEmitter,this.form,t,this.tracking);case SysActionTypes.SHOW_WIDGET:return new ShowWidgetAction(this.eventEmitter,t,this.tracking);case SysActionTypes.OPEN_LINK:return new OpenLinkAction(t,this.configService,this.tracking);case SysActionTypes.CLOSE_WIDGET:return new CloseWidgetAction(this.eventEmitter,t,this.configService,this.tracking);default:throw new Error(`Not supported action type ${t.type}`)}}}
|
|
1
|
+
import SysActionTypes from"./SysActionTypes";import SubscribeContactAction from"./actions/SubscribeContactAction";import RequestAction from"./actions/RequestAction";import DispatchEventAction from"./actions/DispatchEventAction";import GoToPreviousViewAction from"./actions/GoToPreviousViewAction";import GoToNextViewAction from"./actions/GoToNextViewAction";import GoToViewAction from"./actions/GoToViewAction";import HttpClient from"@claspo/common/network/HttpClient";import ShowWidgetAction from"./actions/ShowWidgetAction";import OpenLinkAction from"./actions/OpenLinkAction";import CloseWidgetAction from"./actions/CloseWidgetAction";export default class ActionFactory{constructor(t,i,e,o,n,c,s){this.eventEmitter=t,this.form=i,this.configService=e,this.tracking=o,this.stateService=n,this.context=c,this.getServices=s}get(t){switch(t.type){case SysActionTypes.SUBSCRIBE_CONTACT:return new SubscribeContactAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.REQUEST:return new RequestAction(this.eventEmitter,this.form,t,HttpClient,this.configService,this.tracking,this.stateService,this.context,this.getServices);case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t,this.form,this.configService,this.context);case SysActionTypes.GO_TO_VIEW:return new GoToViewAction(this.eventEmitter,t,this.configService,this.form,this.getServices().viewRouter,this.getServices().documentModel,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_PREVIOUS_VIEW:return new GoToPreviousViewAction(this.eventEmitter,t,this.tracking,this.getServices().activePathTracker);case SysActionTypes.GO_TO_NEXT_VIEW:return new GoToNextViewAction(this.eventEmitter,this.form,t,this.tracking);case SysActionTypes.SHOW_WIDGET:return new ShowWidgetAction(this.eventEmitter,t,this.tracking);case SysActionTypes.OPEN_LINK:return new OpenLinkAction(t,this.configService,this.tracking);case SysActionTypes.CLOSE_WIDGET:return new CloseWidgetAction(this.eventEmitter,t,this.configService,this.tracking);default:throw new Error(`Not supported action type ${t.type}`)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"./SysActionTypes";import DispatchEventAction from"./actions/DispatchEventAction";import InAppOpenLinkAction from"./actions/InAppOpenLinkAction";import ActionFactory from"./ActionFactory";export default class InAppActionFactory extends ActionFactory{executeAction(t,{params:e}={}){return{execute:(n,i)=>{var s;return this.eventEmitter.emit(t,Object.assign(Object.assign({},e),{targetComponentId:null===(s=null==i?void 0:i.target)||void 0===s?void 0:s.getAttribute("cl-id")})),Promise.resolve(!0)}}}get(t){switch(t.type){case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t);case SysActionTypes.OPEN_LINK:return new InAppOpenLinkAction(this.eventEmitter,t);case SysActionTypes.CLOSE_WIDGET:return this.executeAction(SysActionTypes.CLOSE_WIDGET,t);case SysActionTypes.CLICK:return this.executeAction(SysActionTypes.CLICK,t);case SysActionTypes.GO_TO_VIEW:case SysActionTypes.GO_TO_NEXT_VIEW:case SysActionTypes.GO_TO_PREVIOUS_VIEW:return super.get(t);default:throw new Error(`Not supported action type ${t.type}`)}}}
|
|
1
|
+
import SysActionTypes from"./SysActionTypes";import DispatchEventAction from"./actions/DispatchEventAction";import InAppOpenLinkAction from"./actions/InAppOpenLinkAction";import ActionFactory from"./ActionFactory";export default class InAppActionFactory extends ActionFactory{executeAction(t,{params:e}={}){return{execute:(n,i)=>{var s;return this.eventEmitter.emit(t,Object.assign(Object.assign({},e),{targetComponentId:null===(s=null==i?void 0:i.target)||void 0===s?void 0:s.getAttribute("cl-id")})),Promise.resolve(!0)}}}get(t){switch(t.type){case SysActionTypes.DISPATCH_EVENT:return new DispatchEventAction(this.eventEmitter,t,this.form,this.configService,this.context);case SysActionTypes.OPEN_LINK:return new InAppOpenLinkAction(this.eventEmitter,t);case SysActionTypes.CLOSE_WIDGET:return this.executeAction(SysActionTypes.CLOSE_WIDGET,t);case SysActionTypes.CLICK:return this.executeAction(SysActionTypes.CLICK,t);case SysActionTypes.GO_TO_VIEW:case SysActionTypes.GO_TO_NEXT_VIEW:case SysActionTypes.GO_TO_PREVIOUS_VIEW:return super.get(t);default:throw new Error(`Not supported action type ${t.type}`)}}}
|
|
@@ -21,6 +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
25
|
setInitiatorComponentId(componentId: any): void;
|
|
25
26
|
emitSubmitLifecycleEvent(eventName: any, payload?: any): void;
|
|
26
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.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);if(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
|
|
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)}}
|
|
@@ -2,7 +2,10 @@ import SysActionTypes from "../SysActionTypes";
|
|
|
2
2
|
export default class DispatchEventAction {
|
|
3
3
|
eventEmitter: any;
|
|
4
4
|
config: any;
|
|
5
|
+
form: any;
|
|
6
|
+
configService: any;
|
|
7
|
+
context: any;
|
|
5
8
|
type: SysActionTypes;
|
|
6
|
-
constructor(eventEmitter: any, config: any);
|
|
9
|
+
constructor(eventEmitter: any, config: any, form: any, configService: any, context: any);
|
|
7
10
|
execute(payload: any): Promise<boolean>;
|
|
8
11
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysActionTypes from"../SysActionTypes";export default class DispatchEventAction{constructor(t,e){this.type=SysActionTypes.DISPATCH_EVENT,this.eventEmitter=t,this.config=e}execute(t){return this.eventEmitter.emit(this.config.params.eventName,
|
|
1
|
+
import SysActionTypes from"../SysActionTypes";import UTMParamsExtractor from"../UTMParamsExtractor";import{constructRequestPayload,extractContextValue}from"../RequestPayloadBuilder";export default class DispatchEventAction{constructor(t,e,o,i,r){this.type=SysActionTypes.DISPATCH_EVENT,this.eventEmitter=t,this.config=e,this.form=o,this.configService=i,this.context=r}execute(t){var e,o,i,r,s,a,c;const n=constructRequestPayload({contextValue:this.context?extractContextValue(this.context):{},formValue:null!==(i=null===(o=null===(e=this.form)||void 0===e?void 0:e.getControlsMap)||void 0===o?void 0:o.call(e))&&void 0!==i?i:{},utmParams:this.context?UTMParamsExtractor.extractTrackingParams(this.context):{},referrer:window.location.href,triggeredBy:null===(s=null===(r=this.configService)||void 0===r?void 0:r.getConfig)||void 0===s?void 0:s.call(r,"triggeredBy"),widgetDebugMode:null===(c=null===(a=this.configService)||void 0===a?void 0:a.getConfig)||void 0===c?void 0:c.call(a,"widgetDebugMode")});return this.eventEmitter.emit(this.config.params.eventName,n),Promise.resolve(!0)}}
|
|
@@ -25,6 +25,7 @@ export default class DocumentModelService extends DefaultEventEmitter {
|
|
|
25
25
|
json: ClDocumentI;
|
|
26
26
|
flatJson: ClDocumentI;
|
|
27
27
|
private navigationGraph;
|
|
28
|
+
private prizeNavigationTargetsByViewId;
|
|
28
29
|
constructor(json: any);
|
|
29
30
|
setComponentRef(targetComponentId: string, componentRef: any): void;
|
|
30
31
|
getModel(): ClDocumentI;
|
|
@@ -32,6 +33,8 @@ export default class DocumentModelService extends DefaultEventEmitter {
|
|
|
32
33
|
getViews(): ClBaseComponentI[];
|
|
33
34
|
getShared(): ClDocumentSharedI;
|
|
34
35
|
getNavigationGraph(): ViewNavGraphI;
|
|
36
|
+
setPrizeNavigationTargets(fromViewId: string, toViewIds: Array<string | null | undefined>): void;
|
|
37
|
+
private buildPrizeNavigationTargets;
|
|
35
38
|
iterateViewModelAndExecute(viewIndex: number, callback: (node: ClBaseComponentI) => void): void;
|
|
36
39
|
destroy(): void;
|
|
37
40
|
destroyView(viewIndex: number): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){if(!this.navigationGraph)try{this.navigationGraph=buildViewNavigationGraph(this.getViews(),this.getShared())}catch(t){ErrorLogger.log(`buildViewNavigationGraph failed: ${(null==t?void 0:t.stack)||t}`),this.navigationGraph={nodes:[],edges:[]}}return this.navigationGraph}iterateViewModelAndExecute(t,e){const
|
|
1
|
+
import ModulesComponentExtractor from"./ModulesComponentExtractor";import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import DocumentUtils from"@claspo/common/document/DocumentUtils";import{buildViewNavigationGraph}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export const EditorToWidgetEventType={COMPONENT_INSERT:"COMPONENT_INSERT",COMPONENT_REMOVE:"COMPONENT_REMOVE",COMPONENT_MOVE:"COMPONENT_MOVE",COMPONENT_UPDATE:"COMPONENT_UPDATE",COMPONENT_PROPS_UPDATE:"COMPONENT_PROPS_UPDATE",REMOVE_FOCUS:"REMOVE_FOCUS",SET_FOCUS:"SET_FOCUS",SHARED_UPDATE:"SHARED_UPDATE",MOBILE_BREAKPOINT_UPDATE:"MOBILE_BREAKPOINT_UPDATE",ENVIRONMENT_UPDATE:"ENVIRONMENT_UPDATE",TEXT_CLASS_ADDED:"TEXT_CLASS_ADDED",TEXT_CLASS_UPDATED:"TEXT_CLASS_UPDATED",TEXT_CLASS_REMOVED:"TEXT_CLASS_REMOVED",HEADER_FONT_FAMILY_UPDATE:"HEADER_FONT_FAMILY_UPDATE",TEXT_FONT_FAMILY_UPDATE:"TEXT_FONT_FAMILY_UPDATE",SHARED_UPDATE_ALL:"SHARED_UPDATE_ALL",COLOR_SCHEMA_UPDATE:"COLOR_SCHEMA_UPDATE",THEME_UPDATE:"THEME_UPDATE"};export default class DocumentModelService extends DefaultEventEmitter{constructor(t){super(),this.navigationGraph=null,this.prizeNavigationTargetsByViewId=new Map,this.json=t,this.flatJson=ModulesComponentExtractor.extract(this.json)}setComponentRef(t,e){DocumentUtils.getNodeById(this.getViews(),t).componentRef=e}getModel(){return this.flatJson}getView(t){return this.flatJson.views[t]}getViews(){return this.flatJson.views}getShared(){return this.flatJson.shared}getNavigationGraph(){if(!this.navigationGraph)try{this.navigationGraph=buildViewNavigationGraph(this.getViews(),this.getShared(),this.buildPrizeNavigationTargets())}catch(t){ErrorLogger.log(`buildViewNavigationGraph failed: ${(null==t?void 0:t.stack)||t}`),this.navigationGraph={nodes:[],edges:[]}}return this.navigationGraph}setPrizeNavigationTargets(t,e){const i=e.filter(t=>!!t);this.prizeNavigationTargetsByViewId.set(t,i),this.navigationGraph=null}buildPrizeNavigationTargets(){const t=[];return this.prizeNavigationTargetsByViewId.forEach((e,i)=>{e.forEach(e=>t.push({fromViewId:i,toViewId:e}))}),t}iterateViewModelAndExecute(t,e){const i=this.getView(t);DocumentUtils.iterateDepthFirst(i,e)}destroy(){}destroyView(t){console.warn("destroyView now should do nothing"),this.iterateViewModelAndExecute(t,t=>{t.componentRef&&(t.componentRef.remove(),t.componentRef=null)})}}
|
|
@@ -9,13 +9,14 @@ export interface FinishCommitOptionsI {
|
|
|
9
9
|
}
|
|
10
10
|
export default class FinishCoordinator {
|
|
11
11
|
private getServices;
|
|
12
|
-
private
|
|
12
|
+
private documentModel;
|
|
13
13
|
private finished;
|
|
14
14
|
private inFlight;
|
|
15
15
|
private executingCommit;
|
|
16
16
|
private lastSubmitAttemptWasOwnFailedCommit;
|
|
17
17
|
private subscriptions;
|
|
18
18
|
constructor(eventEmitter: DefaultEventEmitter, documentModel: DocumentModelService, getServices: () => any);
|
|
19
|
+
private getGraph;
|
|
19
20
|
destroy(): void;
|
|
20
21
|
attemptCommit(trigger: FinishTrigger, options?: FinishCommitOptionsI): Promise<boolean>;
|
|
21
22
|
private onNavigationEnd;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import SysActionTypes from"../action/SysActionTypes";import ActionCategory from"../action/actions/ActionCategory";import{SubmitState}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export var FinishTrigger;!function(t){t.TERMINAL="terminal",t.CLOSE="close"}(FinishTrigger||(FinishTrigger={}));export default class FinishCoordinator{constructor(t,i,e){this.finished=!1,this.inFlight=!1,this.executingCommit=!1,this.lastSubmitAttemptWasOwnFailedCommit=!1,this.getServices=e,this.
|
|
1
|
+
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import SysActionTypes from"../action/SysActionTypes";import ActionCategory from"../action/actions/ActionCategory";import{SubmitState}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";export var FinishTrigger;!function(t){t.TERMINAL="terminal",t.CLOSE="close"}(FinishTrigger||(FinishTrigger={}));export default class FinishCoordinator{constructor(t,i,e){this.finished=!1,this.inFlight=!1,this.executingCommit=!1,this.lastSubmitAttemptWasOwnFailedCommit=!1,this.getServices=e,this.documentModel=i,this.subscriptions=[t.on(SysRouterEvent.NAVIGATION_END,t=>this.onNavigationEnd(t)),t.on(SysEventTypes.SUBMIT_REQUEST_STARTED,()=>{this.executingCommit||(this.lastSubmitAttemptWasOwnFailedCommit=!1)}),t.on(SysEventTypes.SUBMIT_REQUEST_FINISHED,t=>{(null==t?void 0:t.success)&&(this.finished=!0,this.lastSubmitAttemptWasOwnFailedCommit=!1)})]}getGraph(){return this.documentModel.getNavigationGraph()}destroy(){this.subscriptions.forEach(t=>{var i;return null===(i=null==t?void 0:t.off)||void 0===i?void 0:i.call(t)}),this.subscriptions=[]}async attemptCommit(t,i){var e,o;const r=this.getServices(),s=null==r?void 0:r.submitState;if(!s||this.finished||this.inFlight)return!1;if(s.hasSubmitAttemptSinceLastChange()&&!this.lastSubmitAttemptWasOwnFailedCommit)return!1;if(t===FinishTrigger.CLOSE&&(!s.hasDirtyFormData()||s.getState()!==SubmitState.DIRTY&&!this.lastSubmitAttemptWasOwnFailedCommit))return!1;this.inFlight=!0;try{const t=await s.prepareAutoSubmitFormValue();if(this.finished||s.hasSubmitAttemptSinceLastChange()&&!this.lastSubmitAttemptWasOwnFailedCommit)return!1;if(!t||!Object.values(t).length)return!1;this.lastSubmitAttemptWasOwnFailedCommit=!1,null===(e=null==i?void 0:i.beforeExecute)||void 0===e||e.call(i,t);const n=(null===(o=r.actionRegister)||void 0===o?void 0:o.getRegisteredActions().find(t=>t.category===ActionCategory.SUBMIT))||r.actionFactory.get({type:SysActionTypes.REQUEST});let a;this.executingCommit=!0;try{a=await n.execute(void 0,void 0,!0,{skipValidation:!0,skipNavigation:!0,excludeFormContext:!0,formValue:t})}catch(t){ErrorLogger.log(`FinishCoordinator commit execute failed: ${(null==t?void 0:t.stack)||t}`),a=!1}finally{this.executingCommit=!1}return!1===a?(this.lastSubmitAttemptWasOwnFailedCommit=!0,!1):(this.finished=!0,!0)}catch(t){return ErrorLogger.log(`FinishCoordinator.attemptCommit failed: ${(null==t?void 0:t.stack)||t}`),!1}finally{this.inFlight=!1}}onNavigationEnd(t){try{if(!isMultiViewFlow(this.getGraph()))return;if(!isAutoCommitTerminal(this.getGraph(),t))return;this.attemptCommit(FinishTrigger.TERMINAL).catch(t=>{ErrorLogger.log(`FinishCoordinator terminal commit rejected: ${(null==t?void 0:t.stack)||t}`)})}catch(t){ErrorLogger.log(`FinishCoordinator.onNavigationEnd failed: ${(null==t?void 0:t.stack)||t}`)}}}
|
|
@@ -8,7 +8,7 @@ export default class NavigationLeadCollector {
|
|
|
8
8
|
private form;
|
|
9
9
|
private context;
|
|
10
10
|
private views;
|
|
11
|
-
private
|
|
11
|
+
private documentModel;
|
|
12
12
|
private triggeredBy;
|
|
13
13
|
private previousViewIndex;
|
|
14
14
|
private lastSentSignature;
|
|
@@ -16,6 +16,7 @@ export default class NavigationLeadCollector {
|
|
|
16
16
|
private latestForwardNavigationData;
|
|
17
17
|
private subscriptions;
|
|
18
18
|
constructor(eventEmitter: DefaultEventEmitter, documentModel: DocumentModelService, form: FormGroup, context: ContextSDK, triggeredBy: string);
|
|
19
|
+
private getGraph;
|
|
19
20
|
destroy(): void;
|
|
20
21
|
getLatestNavigationData(): RequestNavigationDataI | null;
|
|
21
22
|
private onNavigationEnd;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import UTMParamsExtractor from"../action/UTMParamsExtractor";import{constructRequestPayload,extractContextValue}from"../action/RequestPayloadBuilder";import{hasMeaningfulValue}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";function stableStringify(t){var
|
|
1
|
+
import SysRouterEvent from"../RouterEvent";import SysEventTypes from"../common/SysEventTypes";import UTMParamsExtractor from"../action/UTMParamsExtractor";import{constructRequestPayload,extractContextValue}from"../action/RequestPayloadBuilder";import{hasMeaningfulValue}from"../submit-state/SubmitStateService";import{isAutoCommitTerminal,isMultiViewFlow}from"@claspo/common/document/ViewNavigationGraph";import ErrorLogger from"../error/ErrorLogger";function stableStringify(t){var e;if(Array.isArray(t))return`[${t.map(stableStringify).join(",")}]`;if(t&&"object"==typeof t){return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${stableStringify(t[e])}`).join(",")}}`}return null!==(e=JSON.stringify(t))&&void 0!==e?e:"undefined"}export default class NavigationLeadCollector{constructor(t,e,i,r,a){this.previousViewIndex=null,this.lastSentSignature=null,this.lastCompletedSubscribeSignature=null,this.latestForwardNavigationData=null,this.eventEmitter=t,this.form=i,this.context=r,this.views=e.getViews(),this.documentModel=e,this.triggeredBy=a,this.subscriptions=[t.on(SysRouterEvent.NAVIGATION_END,(t,e,i)=>this.onNavigationEnd(t,i))]}getGraph(){return this.documentModel.getNavigationGraph()}destroy(){this.subscriptions.forEach(t=>{var e;return null===(e=null==t?void 0:t.off)||void 0===e?void 0:e.call(t)}),this.subscriptions=[]}getLatestNavigationData(){return this.latestForwardNavigationData}onNavigationEnd(t,e){var i,r;try{const a=this.previousViewIndex;if(this.previousViewIndex=t,!isMultiViewFlow(this.getGraph()))return;const o="boolean"==typeof(null==e?void 0:e.isForward)?e.isForward:null!==a&&t>a;if(null===a||!o)return;if(this.latestForwardNavigationData={previousViewId:null===(i=this.views[a])||void 0===i?void 0:i.id,currentViewId:null===(r=this.views[t])||void 0===r?void 0:r.id},isAutoCommitTerminal(this.getGraph(),t))return;const n=this.buildFormValue(),s=extractContextValue(this.context,!0);if(!Object.keys(n).length&&!Object.keys(s).length)return;const l=this.dataSignature(n,s);if(l===this.lastSentSignature||l===this.lastCompletedSubscribeSignature)return;const u=constructRequestPayload({contextValue:s,formValue:n,utmParams:UTMParamsExtractor.extractTrackingParams(this.context),referrer:window.location.href,triggeredBy:this.triggeredBy});u.ignoreTracking=!0,u.navigationData=this.latestForwardNavigationData,this.lastSentSignature=l,this.eventEmitter.emit(SysEventTypes.LEAD_PROGRESS,u)}catch(t){ErrorLogger.log(`NavigationLeadCollector.onNavigationEnd failed: ${(null==t?void 0:t.stack)||t}`)}}recordCommittedLead(){try{this.lastCompletedSubscribeSignature=this.dataSignature(this.buildFormValue(),extractContextValue(this.context,!0))}catch(t){ErrorLogger.log(`NavigationLeadCollector.recordCommittedLead failed: ${(null==t?void 0:t.stack)||t}`)}}dataSignature(t,e){return stableStringify({contextValue:e,formValue:t})}buildFormValue(){return this.form.getControlsAsArray().reduce((t,e)=>{const i=e.getValue();return hasMeaningfulValue(i)&&e.isValid()&&(t[e.getName()]=i),t},{})}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@claspo/renderer",
|
|
3
|
-
"version": "18.10.0-
|
|
3
|
+
"version": "18.10.0-grp1",
|
|
4
4
|
"scripts": {
|
|
5
5
|
"dev": " tsc --project tsconfig.json --watch",
|
|
6
6
|
"build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"node": ">=18.16.0"
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@claspo/common": "7.5.
|
|
18
|
+
"@claspo/common": "7.5.3-grp1",
|
|
19
19
|
"@testing-library/dom": "^10.4.0"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
@@ -4,20 +4,9 @@ export default class PrizePool {
|
|
|
4
4
|
configService: any;
|
|
5
5
|
prizeOption: any;
|
|
6
6
|
randomDistributor: any;
|
|
7
|
-
_loadPromise: Promise<void> | null;
|
|
8
|
-
_claimPromise: Promise<void> | null;
|
|
9
|
-
_reserved: boolean;
|
|
10
|
-
_reservedAt: number;
|
|
11
7
|
constructor(config: any, httpClient: any, configService: any);
|
|
12
8
|
load(): Promise<void>;
|
|
13
|
-
|
|
14
|
-
_claim(): Promise<void>;
|
|
15
|
-
_awaitReservationSettled(): Promise<void>;
|
|
16
|
-
_load(): Promise<void>;
|
|
17
|
-
_resolveReservation(reservation: any, options: any, prizePoolId: any): any;
|
|
18
|
-
_fetchReward(url: any, options: any, prizePoolId: any): Promise<any>;
|
|
19
|
-
_resolveReward(reward: any, options: any, prizePoolId: any): any;
|
|
20
|
-
_findPoolOption(rewardOrReservation: any, options: any): any;
|
|
9
|
+
_fetchReward(url: any, options: any): Promise<any>;
|
|
21
10
|
_mergeRewardIntoOption(reward: any, options: any): any;
|
|
22
11
|
_fetchPool(url: string, prizePoolId: string): Promise<any>;
|
|
23
12
|
_fetchJson(url: any, headers?: any): Promise<any>;
|
|
@@ -28,6 +17,7 @@ export default class PrizePool {
|
|
|
28
17
|
id: any;
|
|
29
18
|
label: any;
|
|
30
19
|
value: any;
|
|
20
|
+
navigateToViewId: any;
|
|
31
21
|
};
|
|
32
22
|
_calculatePrize(): any;
|
|
33
23
|
_mintsCodePerWinner(options: any): any;
|
package/prize-pool/PrizePool.js
CHANGED
|
@@ -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"
|
|
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,i,o){if(this.httpClient=i,this.configService=o,this.instanceModel=e||{},"FIXED"!==this.instanceModel.model){const e=this.configService.getConfig("prizePoolModels");if(e&&this.instanceModel.id){const i=e.find(e=>e.id===this.instanceModel.id);i&&(this.instanceModel=i)}}this.prizeOption=null,this.randomDistributor=new RandomDistributor}async load(){const{id:e,model:i,sourceType:o,options:t}=this.instanceModel;if(!(!t&&!!e&&"FIXED"!==i&&(!o||FETCHABLE_SOURCE_TYPES.includes(o))))return;const n=this.configService.getConfig("widgetId");try{const i=this.configService.getConfig("hostUrl"),t=`${i}forms/v2/prize/pool/${e}`,r=`${i}forms/v1/prizePool/${e}/reward?widgetId=${n}`;if(this._isPreview()){const i=await this._fetchPool(t,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(r,i.options))}const[s,a]=await Promise.all([this._fetchPool(t,e),this._fetchJson(r,{"cl-customer-id":this.configService.getConfig("clCustomerId")})]);this.instanceModel=Object.assign(Object.assign({},this.instanceModel),{sourceType:o||s.sourceType,options:s.options}),this.prizeOption=this._mergeRewardIntoOption(a,s.options)}catch(i){throw console.error(`PrizePool: failed to load pool or reward for widgetId "${n}" with poolId "${e}"`,i),i}}async _fetchReward(e,i){const o=await this._fetchJson(e,{"cl-customer-id":this.configService.getConfig("clCustomerId")});return this._mergeRewardIntoOption(o,i)}_mergeRewardIntoOption(e,i){return Object.assign(Object.assign({},i.find(i=>i.id===e.id)),e)}async _fetchPool(e,i){const o=await this._fetchJson(e);if(!1===(null==o?void 0:o.available))throw ErrorLogger.log(`PrizePool: the pool ${i} is not available and cannot be handed out with a reason "${o.unavailableReason}"`),new Error("PrizePool: the pool is not available and cannot be handed out");return o}async _fetchJson(e,i){const o=await this.httpClient.execute({url:e,headers:i});if(!o.ok)throw new Error(`PrizePool: request failed with status ${o.status} - ${e}`);return o.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 i,o;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!==(o=null===(i=e.config)||void 0===i?void 0:i.navigateToViewId)&&void 0!==o?o:null}}_calculatePrize(){const e=sum(this.instanceModel.options.map(e=>parseFloat(e.weight))),i=this.randomDistributor.calculateFromWeights(this.instanceModel.options,e);return i&&this._isCodeMintedPerWinner(i)?Object.assign(Object.assign({},i),{code:"CLXXXXXXXX"}):i}_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 i;return(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.codeType)===PrizeCodeType.UNIQUE}_mapLabelSuffix(e,i){return i===PrizeOptionValueType.DISCOUNT_PERCENTAGE?`${e}%`:e}}
|