@capillarytech/creatives-library 9.1.8-alpha.sprint-cap-214249.38 → 9.2.0

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.
Files changed (127) hide show
  1. package/constants/unified.js +4 -0
  2. package/index.js +13 -0
  3. package/package.json +1 -1
  4. package/services/getSchema.js +4 -1
  5. package/services/tests/getSchema.test.js +2 -2
  6. package/translations/en.json +1 -0
  7. package/translations/ja-JP.json +1 -0
  8. package/translations/zh.json +1 -0
  9. package/utils/common.js +6 -0
  10. package/utils/createMobilePushPayload.js +33 -47
  11. package/utils/tagValidations.js +35 -4
  12. package/utils/templateVarUtils.js +49 -0
  13. package/utils/tests/createMobilePushPayload.test.js +8 -102
  14. package/utils/tests/tagValidations.test.js +48 -0
  15. package/utils/tests/templateVarUtils.test.js +89 -0
  16. package/v2Components/CapMpushCTA/index.js +9 -10
  17. package/v2Components/CapMpushCTA/index.scss +3 -29
  18. package/v2Components/CapTagList/TagFallbackPanel.js +124 -0
  19. package/v2Components/CapTagList/constants.js +5 -0
  20. package/v2Components/CapTagList/index.js +46 -7
  21. package/v2Components/CapTagList/messages.js +44 -0
  22. package/v2Components/CapTagList/style.scss +113 -1
  23. package/v2Components/CapTagList/tests/TagFallback.test.js +222 -0
  24. package/v2Components/CapTagList/utils.js +17 -0
  25. package/v2Components/CommonTestAndPreview/UnifiedPreview/MobilePushPreviewContent.js +13 -26
  26. package/v2Components/CommonTestAndPreview/UnifiedPreview/_unifiedPreview.scss +1 -13
  27. package/v2Components/CommonTestAndPreview/constants.js +3 -2
  28. package/v2Components/CommonTestAndPreview/index.js +62 -62
  29. package/v2Components/CommonTestAndPreview/tests/UnifiedPreview/MobilePushPreviewContent.test.js +5 -79
  30. package/v2Components/CommonTestAndPreview/tests/index.test.js +0 -86
  31. package/v2Components/CommonTestAndPreview/tests/utils.test.js +102 -0
  32. package/v2Components/CommonTestAndPreview/utils.js +42 -3
  33. package/v2Components/FormBuilder/Classic.js +24 -14
  34. package/v2Components/FormBuilder/Functional/channels/mobilepush/config.js +1 -0
  35. package/v2Components/FormBuilder/Functional/channels/mobilepush/getEditorErrorDescriptor.js +1 -1
  36. package/v2Components/FormBuilder/Functional/channels/mobilepush/tests/validate.test.js +57 -0
  37. package/v2Components/FormBuilder/Functional/channels/mobilepush/validate.js +4 -4
  38. package/v2Components/FormBuilder/Functional/channels/sms/getEditorErrorDescriptor.js +3 -0
  39. package/v2Components/FormBuilder/Functional/channels/sms/tests/getEditorErrorDescriptor.test.js +5 -0
  40. package/v2Components/FormBuilder/Functional/channels/sms/tests/validate.test.js +6 -0
  41. package/v2Components/FormBuilder/Functional/channels/sms/validate.js +3 -1
  42. package/v2Components/FormBuilder/Functional/renderers/mpushRenderers.js +3 -0
  43. package/v2Components/FormBuilder/Functional/tests/manual.typingPerf.test.js +135 -0
  44. package/v2Components/FormBuilder/Functional/tests/mpush.crossFlowParity.test.js +1 -1
  45. package/v2Components/FormBuilder/Functional/tests/mpush.ctaFlows.parity.test.js +320 -0
  46. package/v2Components/FormBuilder/Functional/tests/mpush.editContainer.parity.test.js +148 -0
  47. package/v2Components/FormBuilder/Functional/tests/mpush.libraryValidity.parity.test.js +152 -0
  48. package/v2Components/FormBuilder/Functional/tests/mpush.shellEvents.test.js +1 -1
  49. package/v2Components/FormBuilder/Functional/tests/mpush.singlePlatform.test.js +1 -1
  50. package/v2Components/FormBuilder/Functional/tests/mpushRenderers.test.js +22 -0
  51. package/v2Components/FormBuilder/tests/mpush.characterization.test.js +2 -2
  52. package/v2Components/TemplatePreview/_templatePreview.scss +2 -12
  53. package/v2Components/TemplatePreview/index.js +17 -30
  54. package/v2Components/TemplatePreview/tests/index.test.js +0 -61
  55. package/v2Containers/Cap/index.js +3 -0
  56. package/v2Containers/Cap/messages.js +4 -0
  57. package/v2Containers/Cap/tests/__snapshots__/index.test.js.snap +1 -0
  58. package/v2Containers/CreativesContainer/SlideBoxContent.js +151 -70
  59. package/v2Containers/CreativesContainer/index.js +6 -3
  60. package/v2Containers/CreativesContainer/tests/SlideBoxContent.test.js +0 -29
  61. package/v2Containers/InApp/index.js +4 -1
  62. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/content.test.js.snap +3 -0
  63. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/index.test.js.snap +2 -0
  64. package/v2Containers/Line/Container/Text/index.js +3 -1
  65. package/v2Containers/Line/Container/Wrapper/tests/__snapshots__/index.test.js.snap +16 -0
  66. package/v2Containers/Line/Container/tests/__snapshots__/index.test.js.snap +18 -0
  67. package/v2Containers/MobilePush/Create/_mobilePushCreate.scss +70 -0
  68. package/v2Containers/MobilePush/Create/actions.js +52 -0
  69. package/v2Containers/MobilePush/Create/constants.js +26 -0
  70. package/v2Containers/MobilePush/Create/index.js +2149 -0
  71. package/v2Containers/MobilePush/Create/messages.js +349 -0
  72. package/v2Containers/MobilePush/Create/reducer.js +72 -0
  73. package/v2Containers/MobilePush/Create/sagas.js +79 -0
  74. package/v2Containers/MobilePush/Create/selectors.js +29 -0
  75. package/v2Containers/MobilePush/Create/test/contentValidity.test.js +154 -0
  76. package/v2Containers/MobilePush/Create/test/saga.test.js +19 -0
  77. package/v2Containers/MobilePush/Create/test/stayOpenOnSave.test.js +80 -0
  78. package/v2Containers/MobilePush/Edit/_mobilePushCreate.scss +65 -0
  79. package/v2Containers/MobilePush/Edit/actions.js +94 -0
  80. package/v2Containers/MobilePush/Edit/constants.js +37 -0
  81. package/v2Containers/MobilePush/Edit/index.js +2407 -0
  82. package/v2Containers/MobilePush/Edit/messages.js +341 -0
  83. package/v2Containers/MobilePush/Edit/reducer.js +113 -0
  84. package/v2Containers/MobilePush/Edit/sagas.js +113 -0
  85. package/v2Containers/MobilePush/Edit/selectors.js +33 -0
  86. package/v2Containers/MobilePush/Edit/test/contentValidity.test.js +149 -0
  87. package/v2Containers/MobilePush/Edit/test/saga.test.js +255 -0
  88. package/v2Containers/MobilePush/Edit/test/stayOpenOnSave.test.js +60 -0
  89. package/v2Containers/MobilePush/commonMethods.js +333 -0
  90. package/v2Containers/MobilePush/eventsMap.js +130 -0
  91. package/v2Containers/MobilePush/tests/commonMethods.test.js +401 -0
  92. package/v2Containers/MobilePushNew/components/CtaButtons.js +47 -52
  93. package/v2Containers/MobilePushNew/components/MediaUploaders.js +192 -207
  94. package/v2Containers/MobilePushNew/components/PlatformContentFields.js +121 -116
  95. package/v2Containers/MobilePushNew/components/tests/CtaButtons.test.js +208 -30
  96. package/v2Containers/MobilePushNew/components/tests/MediaUploaders.test.js +72 -316
  97. package/v2Containers/MobilePushNew/components/tests/PlatformContentFields.test.js +16 -45
  98. package/v2Containers/MobilePushNew/constants.js +0 -5
  99. package/v2Containers/MobilePushNew/hooks/tests/usePlatformSync.test.js +1 -63
  100. package/v2Containers/MobilePushNew/hooks/tests/useUpload.test.js +0 -52
  101. package/v2Containers/MobilePushNew/hooks/usePlatformSync.js +1 -38
  102. package/v2Containers/MobilePushNew/hooks/useUpload.js +39 -29
  103. package/v2Containers/MobilePushNew/index.js +192 -454
  104. package/v2Containers/MobilePushNew/index.scss +4 -188
  105. package/v2Containers/MobilePushNew/messages.js +6 -86
  106. package/v2Containers/MobilePushNew/tests/index.test.js +1 -450
  107. package/v2Containers/MobilePushNew/tests/utils.test.js +0 -25
  108. package/v2Containers/MobilePushNew/utils.js +0 -8
  109. package/v2Containers/MobilepushWrapper/_mobilepushWrapper.scss +22 -0
  110. package/v2Containers/MobilepushWrapper/index.js +178 -0
  111. package/v2Containers/MobilepushWrapper/messages.js +29 -0
  112. package/v2Containers/Rcs/index.js +8 -1
  113. package/v2Containers/Rcs/tests/__snapshots__/index.test.js.snap +59 -0
  114. package/v2Containers/SmsTrai/Create/tests/__snapshots__/index.test.js.snap +4 -0
  115. package/v2Containers/SmsTrai/Edit/index.js +17 -7
  116. package/v2Containers/SmsTrai/Edit/tests/__snapshots__/index.test.js.snap +42 -0
  117. package/v2Containers/Templates/_templates.scss +2 -10
  118. package/v2Containers/Templates/index.js +90 -84
  119. package/v2Containers/Templates/tests/index.test.js +0 -68
  120. package/v2Containers/Viber/index.js +3 -1
  121. package/v2Containers/WebPush/Create/utils/validation.js +6 -0
  122. package/v2Containers/WebPush/Create/utils/validation.test.js +50 -0
  123. package/v2Containers/Whatsapp/index.js +9 -5
  124. package/v2Containers/Whatsapp/tests/__snapshots__/index.test.js.snap +2 -2
  125. package/v2Containers/Zalo/index.js +4 -1
  126. package/v2Components/CapMpushCTA/tests/index.test.js +0 -89
  127. /package/{v2Components/FormBuilder/Functional/tests/fixtures/mpushInitialSchema.js → v2Containers/MobilePush/initialSchema.js} +0 -0
@@ -0,0 +1,2407 @@
1
+ /*
2
+ *
3
+ * Edit Mobile Push
4
+ *
5
+ */
6
+
7
+ import PropTypes from 'prop-types';
8
+
9
+ import React from 'react';
10
+ import {bindActionCreators} from "redux";
11
+ import { notification } from 'antd';
12
+ import { createStructuredSelector } from 'reselect';
13
+ import { intlShape, FormattedMessage } from 'react-intl';
14
+ import _, {get, findIndex, set, forEach, cloneDeep} from 'lodash';
15
+ import { CapSpin, CapSlideBox, CapHeader, CapTable, CapLink, CapRow, CapColumn, CapIcons, CapNotification} from '@capillarytech/cap-ui-library';
16
+ import styled from 'styled-components';
17
+ import {makeSelectEdit, makeSelectEditResponse, makeSelectTemplateDetailsResponse, makeSelectIosCta} from "./selectors";
18
+ import {makeSelectMetaEntities, setInjectedTags, isLoadingMetaEntities} from "../../Cap/selectors";
19
+ import {getMessageObject} from "../../../utils/messageUtils";
20
+ import FormBuilder from '../../../v2Components/FormBuilder';
21
+ import * as actions from "../../MobilePush/Edit/actions";
22
+ import * as templatesActions from "../../Templates/actions";
23
+ import {makeSelectTemplates} from "../../Templates/selectors";
24
+ import messages from './messages';
25
+ import './_mobilePushCreate.scss';
26
+ import {makeSelectCreate} from "../Create/selectors";
27
+ import withCreatives from '../../../hoc/withCreatives';
28
+ import { gtmPush } from '../../../utils/gtmTrackers';
29
+
30
+ import getEventsMap from '../eventsMap';
31
+ import {getPrimaryCtaFields, getSecondaryCtaFields, getLinkTypeFields, getContent, getMobilePushEmbeddedContentValidity} from '../commonMethods';
32
+ import { GA } from '@capillarytech/cap-ui-utils';
33
+ import { EDIT, TRACK_EDIT_MPUSH } from '../../App/constants';
34
+ import { MOBILE_PUSH } from '../../CreativesContainer/constants';
35
+ import { getCdnUrl } from '../../../utils/cdnTransformation';
36
+ import injectSaga from '../../../utils/injectSaga';
37
+ import injectReducer from '../../../utils/injectReducer';
38
+ import { v2MobilePushEditSagas } from './sagas';
39
+ import v2MobilePushEditReducer from './reducer';
40
+ import * as globalActions from '../../Cap/actions';
41
+ import { MAPP_SDK } from './constants';
42
+ import { checkForPersonalizationTokens, isEmbeddedEditOrPreview, validateMobilePushContent } from '../../../utils/commonUtils';
43
+ import formBuilderMessages from '../../../v2Components/FormBuilder/messages';
44
+ import { EMBEDDED } from '../../Whatsapp/constants';
45
+ import { OUTBOUND } from '../../../v2Components/FormBuilder/constants';
46
+ import TestAndPreviewSlidebox from '../../../v2Components/TestAndPreviewSlidebox';
47
+
48
+ const PrefixWrapper = styled.div`
49
+ margin-right: 16px;
50
+ `;
51
+
52
+ const safeParseDeeplinkConfig = (value) => {
53
+ if (!value || typeof value !== 'string') return [];
54
+ try {
55
+ const parsed = JSON.parse(value);
56
+ return Array.isArray(parsed) ? parsed : [];
57
+ } catch {
58
+ return [];
59
+ }
60
+ };
61
+
62
+ export class Edit extends React.Component { // eslint-disable-line react/prefer-stateless-function
63
+ constructor(props) {
64
+ super(props);
65
+ const eventsMap = getEventsMap(this);
66
+ this.state = {
67
+ formData: {},
68
+ tabCount: 1,
69
+ schema: {},
70
+ currentTab: 1,
71
+ editData: {},
72
+ errorData: [],
73
+ loading: false,
74
+ isFormValid: true,
75
+ injectedTags: {},
76
+ showModal: false,
77
+ eventsMap,
78
+ startValidation: false,
79
+ modalContent: {title: this.props.intl.formatMessage(messages.alertMessage), body: this.props.intl.formatMessage(messages.templateNotConfigured), type: 'confirm'},
80
+ };
81
+ this.getPrimaryCtaFields = getPrimaryCtaFields.bind(this);
82
+ this.getSecondaryCtaFields = getSecondaryCtaFields.bind(this);
83
+ this.getLinkTypeFields = getLinkTypeFields.bind(this);
84
+ // Guard: only one initial meta/TAG fetch (getTags can be invoked from multiple code paths)
85
+ this.hasFetchedInitialTagsRef = false;
86
+ // Guard: avoid duplicate fetch when multiple TagList instances trigger same context
87
+ this.lastFetchedTagContextRef = null;
88
+ // Tracks the last content-emptiness value reported to the parent so componentDidUpdate
89
+ // does not dispatch on every render. Intentionally undefined (not true) so the first
90
+ // render always reports the real validity rather than assuming the form starts invalid.
91
+ this._lastReportedMobilePushContentEmpty = undefined;
92
+ }
93
+ componentWillMount() {
94
+ this.props.actions.getWeCrmAccounts("mobilepush");
95
+ if (!this.props.Templates.selectedWeChatAccount && this.props.location.query.type !== 'embedded') {
96
+ const type = this.props.location.query.type;
97
+ const module = this.props.location.query.module ? this.props.location.query.module : 'default';
98
+ this.props.router.push({
99
+ pathname: `/mobilepush/`,
100
+ query: type === 'embedded' ? {type: 'embedded', module} : {module},
101
+ });
102
+ } else {
103
+ const query = {
104
+ layout: 'MOBILEPUSH',
105
+ type: 'LAYOUT',
106
+ version: "v2",
107
+ };
108
+ this.props.globalActions.fetchSchemaForEntity(query);
109
+ }
110
+ }
111
+ componentDidMount() {
112
+ window.addEventListener("message", this.handleFrameTasks);
113
+ if (!_.isEmpty(this.state.schema)) {
114
+ this.injectEvents(this.state.schema);
115
+ }
116
+ const templateId = get(this, "props.params.id");
117
+ const hasTemplateData = !_.isEmpty(this.props.templateData);
118
+ if (this.props.location?.query && (templateId || hasTemplateData)) {
119
+ if (templateId && templateId !== 'temp') {
120
+ this.props.actions.getTemplateDetails(templateId);
121
+ } else if (hasTemplateData) {
122
+ this.props.actions.setTemplateDetails(this.props.templateData);
123
+ }
124
+ }
125
+ const type = this.props.location.query.type;
126
+ if (type === 'embedded') {
127
+ const response = {
128
+ action: 'startTemplateCreation',
129
+ };
130
+ parent.postMessage(JSON.stringify(response), '*');
131
+ }
132
+ }
133
+ componentDidUpdate() {
134
+ // Reports live form validity so the host (CreativesContainer) can disable Done/Preview
135
+ // and Test as soon as the message content is cleared — mirrors Sms/Edit's own reporting.
136
+ if (typeof this.props.onContentValidityChange !== 'function') {
137
+ return;
138
+ }
139
+ const validity = getMobilePushEmbeddedContentValidity(this.state.formData);
140
+ const isContentEmpty = !!validity.isContentEmpty;
141
+ if (this._lastReportedMobilePushContentEmpty === isContentEmpty) return;
142
+ this._lastReportedMobilePushContentEmpty = isContentEmpty;
143
+ this.props.onContentValidityChange({ isContentEmpty });
144
+ }
145
+ componentWillReceiveProps(nextProps) {
146
+ if (nextProps.params?.id !== this.props.params?.id) {
147
+ this.hasFetchedInitialTagsRef = false;
148
+ this.lastFetchedTagContextRef = null;
149
+ }
150
+ // Library mode: on Done click (transition to isGetFormData), run extractTags only when no existing validation errors (braces, personalization, etc.)
151
+ if (nextProps.isGetFormData && !this.props.isGetFormData && !nextProps.isFullMode) {
152
+ // If form already has validation errors (braces, personalization tags, etc.), do not call extractTags; just fail
153
+ if (!this.state.isFormValid) {
154
+ nextProps.onValidationFail?.();
155
+ return;
156
+ }
157
+ if (nextProps.getLiquidTags && nextProps.showLiquidErrorInFooter) {
158
+ const formDataArr = [this.state.formData?.[0], this.state.formData?.[1]];
159
+ validateMobilePushContent(formDataArr, {
160
+ currentTab: this.state.currentTab,
161
+ getLiquidTags: nextProps.getLiquidTags,
162
+ formatMessage: this.props.intl.formatMessage,
163
+ messages: formBuilderMessages,
164
+ onError: (err) => {
165
+ const { standardErrors = [], liquidErrors = [] } = err;
166
+ // _validatePlatformSpecificContent passes { standardErrors: { ANDROID, IOS, generic }, liquidErrors: { ... } }; footer expects arrays
167
+ const toArray = (v) => (Array.isArray(v) ? v : (v && typeof v === 'object' ? [].concat(...Object.values(v)) : []));
168
+ const STANDARD_ERROR_MSG = toArray(standardErrors);
169
+ const LIQUID_ERROR_MSG = toArray(liquidErrors);
170
+ nextProps.showLiquidErrorInFooter(
171
+ { STANDARD_ERROR_MSG, LIQUID_ERROR_MSG },
172
+ this.state.currentTab
173
+ );
174
+ // Only treat as validation failure when there are actual errors; skip when helper called onError with empty reset payload
175
+ const hasErrors = STANDARD_ERROR_MSG.length > 0 || LIQUID_ERROR_MSG.length > 0;
176
+ if (hasErrors) {
177
+ nextProps.onValidationFail?.();
178
+ }
179
+ },
180
+ onSuccess: () => {
181
+ nextProps.getFormLibraryData(this.getFormData());
182
+ },
183
+ });
184
+ } else {
185
+ nextProps.getFormLibraryData(this.getFormData());
186
+ }
187
+ } else if (nextProps.isGetFormData && this.props.isGetFormData !== nextProps.isGetFormData && this.props.isFullMode && !this.props.Create.createTemplateInProgress) {
188
+ // Re-arm per Save click (saves only on startValidation false → true).
189
+ this.setState({ startValidation: false }, this.startValidation);
190
+ }
191
+ let selectedWeChatAccount = {};
192
+ const queryType = String(get(this.props, 'location.query.type', ''))?.toLowerCase();
193
+ const creativesMode = String(get(this.props, 'creativesMode', ''))?.toLowerCase();
194
+ const { Edit: EditProps, templateData, Templates, type } = this.props || {};
195
+ const { selectedWeChatAccount: editSelectedWeChatAccount, templateDetails } = EditProps || {};
196
+ const { id: selectedWeChatAccountId } = editSelectedWeChatAccount || {};
197
+ const { definition } = templateDetails || {};
198
+ const { accountId: templateAccountId } = definition || {};
199
+ const { Templates: nextTemplates, Edit: nextEdit } = nextProps || {};
200
+ if (isEmbeddedEditOrPreview(queryType, creativesMode)) {
201
+ selectedWeChatAccount = !_.isEmpty(editSelectedWeChatAccount)
202
+ ? editSelectedWeChatAccount
203
+ : nextTemplates?.selectedWeChatAccount;
204
+ } else if (!_.isEmpty(Templates?.selectedWeChatAccount)) {
205
+ selectedWeChatAccount = Templates?.selectedWeChatAccount;
206
+ }
207
+
208
+ if (queryType === EMBEDDED && !nextEdit?.fetchingWeCrmAccounts && !_.isEqual(EditProps?.weCrmAccounts, nextEdit?.weCrmAccounts) && (!selectedWeChatAccount || _.isEmpty(selectedWeChatAccount))) {
209
+ this.setMobilePushAccountOptions(nextEdit?.weCrmAccounts, templateData?.definition?.accountId);
210
+ }
211
+ // Check if the query type is 'embedded' and the creatives mode is either 'edit' or 'preview'.
212
+ // If the type is not 'outbound', ensure that the selected WeChat account ID is not equal to the account ID in the template details.
213
+ // If all conditions are met, set the mobile push account options using the provided weCrmAccounts and the account ID from templateData.
214
+ if (
215
+ isEmbeddedEditOrPreview(queryType, creativesMode) &&
216
+ type !== OUTBOUND.toLowerCase() &&
217
+ nextEdit?.weCrmAccounts &&
218
+ !EditProps?.fetchingWeCrmAccounts &&
219
+ templateData?.definition?.accountId &&
220
+ !_.isEqual(templateAccountId, templateData?.definition?.accountId)
221
+ ) {
222
+ this.setMobilePushAccountOptions(nextEdit?.weCrmAccounts, templateData?.definition?.accountId);
223
+ }
224
+ // If the type is 'outbound', ensure that the selected WeChat account ID is not equal to the account ID in the template details.
225
+ // If all conditions are met, set the mobile push account options using the provided weCrmAccounts and the template account ID.
226
+ if (
227
+ isEmbeddedEditOrPreview(queryType, creativesMode) &&
228
+ type === OUTBOUND.toLowerCase() &&
229
+ nextEdit?.weCrmAccounts &&
230
+ selectedWeChatAccountId &&
231
+ templateAccountId &&
232
+ !_.isEqual(selectedWeChatAccountId, templateAccountId)
233
+ ) {
234
+ this.setMobilePushAccountOptions(nextEdit?.weCrmAccounts, templateAccountId);
235
+ }
236
+ if (!_.isEmpty(nextTemplates?.selectedWeChatAccount) && !_.isEqual(editSelectedWeChatAccount, nextEdit?.selectedWeChatAccount) && (queryType === EMBEDDED) && this.props.location.query.module === "loyalty") {
237
+ const params = {
238
+ name: '',
239
+ sortBy: 'Most Recent',
240
+ accountId: nextTemplates?.selectedWeChatAccount?.id,
241
+ };
242
+ this.props.actions.getMobilepushTemplatesList('mobilepush', params);
243
+ }
244
+ if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && _.isEmpty(this.state.fullSchema)) {
245
+ const definition = cloneDeep(nextProps.metaEntities.layouts[0].definition);
246
+ const initialSchema = definition?.textSchema || definition?.imageSchema || {};
247
+ this.setState({fullSchema: definition, schema: initialSchema}, () => {
248
+ // Use this.props (latest) in callback to avoid race: templateDetails may have arrived by now
249
+ const latestSelectedAccount = this.getSelectedWeChatAccountFromProps(this.props);
250
+ this.handleEditSchemaOnPropsChange(this.props, latestSelectedAccount);
251
+ const templateId = get(this, "props.params.id");
252
+ if (this.props.location.query.module !== 'loyalty' && templateId && templateId !== 'temp') {
253
+ this.props.actions.getTemplateDetails(templateId);
254
+ }
255
+ if (queryType === EMBEDDED && templateId === 'temp' && _.isEmpty(this.state.formData)) { // when his.props.params.id is temp that means mobile push template content will be passed from post message from parent with startTemplateCreation action
256
+ const response = {
257
+ action: 'startTemplateCreation',
258
+ };
259
+ parent.postMessage(JSON.stringify(response), '*');
260
+ this.getTags();
261
+ }
262
+ });
263
+ if (queryType === EMBEDDED) {
264
+ this.showNext();
265
+ }
266
+ }
267
+ if (nextProps.metaEntities && nextProps.metaEntities.layouts && nextProps.metaEntities.layouts.length > 0 && nextProps.Edit.mobilepushTemplates && !_.isEqual(nextProps.Edit.mobilepushTemplates, this.props.Edit.mobilepushTemplates)) { //used inloyalty
268
+ if (nextProps.location.query.type === EMBEDDED && nextProps.location.query.module === 'loyalty') {
269
+ this.setTemplateOptions(nextProps.Edit.mobilepushTemplates);
270
+ }
271
+ }
272
+ this.handleEditSchemaOnPropsChange(nextProps, selectedWeChatAccount);
273
+ if (nextProps.Edit.uploadedAssetData) {
274
+ const formData = _.cloneDeep(this.state.formData);
275
+ formData[this.state.currentTab - 1].image = nextProps.Edit.uploadedAssetData.metaInfo.public_url;
276
+ this.setState({formData});
277
+ this.props.actions.clearAsset();
278
+ }
279
+ if (nextProps.iosCtasData && _.isEmpty(this.state.templateCta)) {
280
+ this.setState({showIosCtaTable: true});
281
+ }
282
+ if (nextProps.Edit.editTemplateError && !_.isEqual(nextProps.Edit.editTemplateError, this.props.Edit.editTemplateError)) {
283
+ const message = getMessageObject('error', (nextProps.Edit.editTemplateErrorMessage && nextProps.Edit.editTemplateErrorMessage !== '') ? nextProps.Edit.editTemplateErrorMessage : this.props.intl.formatMessage(messages.somethingWentWrong), true);
284
+ this.props.globalActions.addMessageToQueue(message);
285
+ if (this.props.isFullMode && this.props.onValidationFail) {
286
+ // Slidebox stays open: reset the host's Save trigger so the user can retry
287
+ this.props.onValidationFail();
288
+ }
289
+ }
290
+ }
291
+ componentWillUnmount() {
292
+ this.props.actions.clearData();
293
+ window.removeEventListener("message", this.handleFrameTasks);
294
+ }
295
+ onTemplateChange = (isEvent, formData) => {
296
+ _.forEach(this.props.Edit.mobilepushTemplates, (template) => {
297
+ if (template._id === formData['mobilepush-template']) {
298
+ this.setState({editData: {}, formData: {}}, () => {
299
+ this.props.actions.setSelectedTemplate(template);
300
+ });
301
+ }
302
+ });
303
+ };
304
+ onFormDataChange = (formData, tabCount, currentTab, inputField) => {
305
+ const newFormData = _.cloneDeep(formData);
306
+ const {templateCta} = this.state;
307
+
308
+ // Check for personalization tokens if restriction is enabled and notify parent
309
+ if (this.props.restrictPersonalization) {
310
+ const hasTokens = checkForPersonalizationTokens(newFormData);
311
+ if (this.props.onPersonalizationTokensChange) {
312
+ this.props.onPersonalizationTokensChange(hasTokens);
313
+ }
314
+ }
315
+
316
+ if (!_.isEmpty(templateCta) && this.state.currentTab === 2) {
317
+ newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-label`] = get(templateCta, 'name');
318
+ newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action`] = get(templateCta, 'ctaTemplateDetails[0].buttonText');
319
+ delete newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action2`];
320
+ if (get(templateCta, 'ctaTemplateDetails[1]')) {
321
+ newFormData[this.state.currentTab - 1][`secondary-cta-${this.state.currentTab - 1}-action2`] = get(templateCta, 'ctaTemplateDetails[1].buttonText');
322
+ }
323
+ }
324
+ const newAccount = newFormData["mobilepush-accounts"];
325
+ const currentAccount = this.state.formData["mobilepush-accounts"];
326
+ const isExplicitAccountChange = newAccount !== undefined && newAccount !== currentAccount;
327
+ if (isExplicitAccountChange) {
328
+ this.setMobilePushAccountOptions(this.props.Edit.weCrmAccounts, newFormData["mobilepush-accounts"]);
329
+ delete newFormData['mobilepush-template'];
330
+ delete newFormData['template-name'];
331
+ if (!_.isEmpty(newFormData[0])) {
332
+ delete newFormData[0];
333
+ }
334
+ if (!_.isEmpty(newFormData[1])) {
335
+ delete newFormData[1];
336
+ }
337
+ } else if (newAccount === undefined && currentAccount !== undefined) {
338
+ newFormData["mobilepush-accounts"] = currentAccount;
339
+ }
340
+ if (this.state.isSchemaChanged) {
341
+ this.setState({isSchemaChanged: false});
342
+ }
343
+ if (this.props.isFullMode && this.props.defaultData && _.isEmpty(formData['template-name'])) {
344
+ newFormData['template-name'] = _.get(this.props, "defaultData['template-name']");
345
+ }
346
+ if (inputField && inputField.id === "add-sec-cta") {
347
+ if (!newFormData[0]["add-sec-cta"]) {
348
+ newFormData[0]["add-sec-cta-2"] = false;
349
+ }
350
+ }
351
+ this.setState({formData: newFormData, tabCount}, () => {
352
+ this.props.showTemplateName({formData: this.state.formData, onFormDataChange: this.onFormDataChange});
353
+ });
354
+ if (currentTab) {
355
+ this.setState({currentTab});
356
+ }
357
+ };
358
+
359
+ getWeChatAccount = () => {
360
+ const { location, creativesMode, Edit: EditProps, Templates } = this.props || {};
361
+ const { query } = location || {};
362
+ const { selectedWeChatAccount: editSelectedWeChatAccount } = EditProps || {};
363
+ const { selectedWeChatAccount: templateSelectedWeChatAccount } = Templates || {};
364
+ const queryType = String(get(query, 'type', '')).toLowerCase();
365
+ const mode = String(creativesMode).toLowerCase();
366
+ let selectedWeChatAccount = {};
367
+ if (isEmbeddedEditOrPreview(queryType, mode)) {
368
+ selectedWeChatAccount = !_.isEmpty(editSelectedWeChatAccount)
369
+ ? editSelectedWeChatAccount
370
+ : (templateSelectedWeChatAccount || {});
371
+ } else if (!_.isEmpty(templateSelectedWeChatAccount)) {
372
+ selectedWeChatAccount = templateSelectedWeChatAccount;
373
+ }
374
+ return selectedWeChatAccount;
375
+ };
376
+
377
+ onLinkTypeChange = (eventTriggered, formData, field, currentTab, inputSchema) => {
378
+ const selectedWeChatAccount = this.getWeChatAccount();
379
+ const schema = inputSchema ? _.cloneDeep(inputSchema) : _.cloneDeep(this.state.schema);
380
+ const tabIndex = currentTab || this.state.currentTab;
381
+ const inputFields = get(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`);
382
+ const id = field.id;
383
+ const fieldIndex = findIndex(inputFields, {identifier: id});
384
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
385
+ const deepLinkOptions = _.map(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (link) => ({label: link.name, value: link.link, title: link.link }) );
386
+ // let inputId = deeplinkValue && deeplinkValue.toLowerCase() === "deeplink" ? `${id}-select` : `${id}-text`;
387
+ // if (field.id === "cta-deeplink-secondary-cta-1" && (tabIndex > 1 || this.state.currentTab > 1)) {
388
+ // inputId = `${inputId}${tabIndex || this.state.currentTab}`;
389
+ // }
390
+ const newInputFields = this.getLinkTypeFields({inputFieldsArgs: inputFields, fieldIndex, deepLinkOptions, formData, field, tab: currentTab});
391
+ set(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
392
+
393
+ if (currentTab) { // identifying where ist called from setEditData or by event handler
394
+ return schema;
395
+ }
396
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true});
397
+ this.injectEvents(schema);
398
+ return schema;
399
+ };
400
+
401
+ onTabChange = (data) => {
402
+ this.setState({currentTab: data});
403
+ };
404
+
405
+ onTagSelect = (data, currentTab, srcComp) => {
406
+ const editorId = srcComp.target;
407
+ this.insertAtCursor(document.getElementById(editorId), `{{${data}}}`, currentTab);
408
+ document.getElementById(editorId).focus();
409
+ };
410
+ onModalCancel = () => {
411
+ if (this.state.modalContent && this.state.modalContent.show) {
412
+ this.setState({modalContent: {...this.state.modalContent, show: false}});
413
+ }
414
+ };
415
+ onUpdateTemplateComplete = (response) => {
416
+ const obj = this.getTransformedData(this.state.formData);
417
+ const content = getContent(obj);
418
+ const {
419
+ definition: {
420
+ mode: definitionMode,
421
+ },
422
+ } = obj || {};
423
+ const label = this.props.location.pathname.indexOf('image') >= 0 ? 'image' : 'text';
424
+ const timeTaken = GA.timeTracker.stopTimer(TRACK_EDIT_MPUSH, {
425
+ category: 'Creatives',
426
+ action: TRACK_EDIT_MPUSH,
427
+ label,
428
+ });
429
+ try {
430
+ gtmPush('creativeDetails', {
431
+ id: response.templateId,
432
+ name: obj.name,
433
+ channel: MOBILE_PUSH,
434
+ timeTaken,
435
+ content,
436
+ mode: EDIT,
437
+ imageAdded: definitionMode === 'image',
438
+ });
439
+ } catch (e) {
440
+
441
+ }
442
+
443
+ const message = this.props.intl.formatMessage(messages['MOBILEPUSH Template Edited Successfully']);
444
+ CapNotification.success({message, key: 'editMpushSuccess'});
445
+ this.props.actions.clearEditResponse();
446
+ if (this.props.isFullMode) {
447
+ // Stay open with the form as is (editData keeps the _id, so later saves update again); host refreshes its list
448
+ this.props.getFormLibraryData({ validity: true, keepSlideBoxOpen: true });
449
+ } else {
450
+ this.resetSchema();
451
+ this.setState({
452
+ formData: {},
453
+ tabCount: 1,
454
+ currentTab: 1,
455
+ editData: {},
456
+ });
457
+ const module = this.props.location.query.module ? this.props.location.query.module : 'default';
458
+ const type = this.props.location.query.type;
459
+ this.props.router.push({
460
+ pathname: `/mobilepush/`,
461
+ query: type === 'embedded' ? {type: 'embedded', module} : {module},
462
+ });
463
+ }
464
+ }
465
+ setMobilePushAccountOptions = (accounts, newAccountId) => {
466
+ let accId = newAccountId || this.props.location.query.account_id;
467
+ if (this.props.type !== "loyalty" && this.props.location.query.module !== "dvs") {
468
+ accId = Number(accId);
469
+ }
470
+ const formData = _.cloneDeep(this.state.formData);
471
+ let selectedAccount = {};
472
+ if (accId) {
473
+ _.forEach(accounts, (account) => {
474
+ let acccountId = account.id;
475
+ if ((this.props.type === "loyalty" || this.props.location.query.module === "dvs") && typeof accId === 'string') {
476
+ acccountId = account.sourceAccountIdentifier;
477
+ }
478
+ if (acccountId === accId) {
479
+ this.props.templatesActions.setWeChatAccount(account);
480
+ selectedAccount = account;
481
+ formData['mobilepush-accounts'] = account.id;
482
+ if (this.props.location.query.account_id) {
483
+ formData['mobilepush-template'] = this.props.params.id;
484
+ }
485
+ }
486
+ });
487
+ } else {
488
+ selectedAccount = accounts?.length > 0 ? accounts[0] : {};
489
+ formData['mobilepush-accounts'] = selectedAccount?.id;
490
+ }
491
+ this.props.actions.setWeChatAccount(selectedAccount);
492
+ this.setState({formData, accountsOptions: accounts?.length > 0 ? accounts.map((acc) => ({key: acc.id, label: acc.name, value: acc.id})) : []});
493
+ };
494
+
495
+ createDefinition = (account) => ({
496
+ accountId: account?.id,
497
+ licenseCode: account?.sourceAccountIdentifier,
498
+ gatewayId: account?.configs?.gatewayId,
499
+ gatewayAccountId: account?.configs?.gatewayAccountId,
500
+ sourceType: account?.sourceTypeName,
501
+ });
502
+
503
+ getTransformedData = (formData) => {
504
+ const selectedWeChatAccount = this.getWeChatAccount();
505
+ const obj = _.cloneDeep(this.state.editData);
506
+ obj.versions = {
507
+ base: {},
508
+ };
509
+ obj.type = 'MOBILEPUSH';
510
+ obj.name = formData['template-name'];
511
+ const queryType = String(get(this.props, 'location.query.type', ''))?.toLowerCase();
512
+ const creativesMode = String(get(this.props, 'creativesMode', ''))?.toLowerCase();
513
+ if (isEmbeddedEditOrPreview(queryType, creativesMode)) {
514
+ if (get(this.props, 'Edit.selectedWeChatAccount.sourceTypeName') === MAPP_SDK) {
515
+ obj.definition = this.createDefinition(selectedWeChatAccount);
516
+ } else {
517
+ obj.definition = {
518
+ accountId: selectedWeChatAccount?.id,
519
+ licenseCode: selectedWeChatAccount?.sourceAccountIdentifier,
520
+ sourceType: selectedWeChatAccount?.sourceTypeName,
521
+ };
522
+ }
523
+ } else if (get(this.props, 'Templates.selectedWeChatAccount.sourceTypeName') === MAPP_SDK) {
524
+ obj.definition = this.createDefinition(selectedWeChatAccount);
525
+ } else {
526
+ obj.definition = {
527
+ accountId: selectedWeChatAccount?.id,
528
+ licenseCode: selectedWeChatAccount?.sourceAccountIdentifier,
529
+ sourceType: selectedWeChatAccount?.sourceTypeName,
530
+ };
531
+ }
532
+ if (this.props.location.query && this.props.location.query.module !== 'dvs') {
533
+ obj.definition.mode = get(this, 'props.Edit.templateDetails.mode', '') || get(this, 'props.Edit.templateDetails.definition.mode', '');
534
+ }
535
+ const android = {};
536
+ Object.keys(formData[0] || {}).forEach((data) => {
537
+ if (!!formData[0][data] && data !== "tabKey") {
538
+ android[data] = formData[0][data];
539
+ }
540
+ });
541
+ const ios = {};
542
+ Object.keys(formData[1] || {}).forEach((data) => {
543
+ if (!!formData[1][data] && data !== "tabKey") {
544
+ ios[data] = formData[1][data];
545
+ }
546
+ });
547
+ obj.versions.base = {};
548
+ delete android.base;
549
+ if (!_.isEmpty(android)) {
550
+ obj.versions.base.ANDROID = {
551
+ luid: "{{luid}}",
552
+ cuid: "{{cuid}}",
553
+ communicationId: "{{communicationId}}",
554
+ title: android['message-title'],
555
+ message: android['message-editor'],
556
+ expandableDetails: {
557
+ style: "BIG_TEXT",
558
+ message: android['message-editor'],
559
+ },
560
+ custom: _.map(android, (field, key) => {
561
+ if (key.indexOf('custom-value') > -1) {
562
+ return field !== "" ? {key: key.replace('custom-value-', "").replace('-cta-deeplink-select', '').replace('-cta-deeplink-secondary-cta-0-select', '').replace('-cta-deeplink-secondary-cta-1-select', ''), value: field} : undefined;
563
+ }
564
+ return undefined;
565
+ }).filter((custom) => custom),
566
+ };
567
+ }
568
+ if (android['cta-deeplink'] && android['cta-deeplink'] !== "") {
569
+ obj.versions.base.ANDROID.cta = {
570
+ type: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
571
+ actionLink: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? android['cta-deeplink-select'] : android['cta-deeplink-text'],
572
+ deepLinkName: android['cta-deeplink'] && android['cta-deeplink'].toLowerCase() === "deeplink" ? this.getLinkName(android['cta-deeplink-select']) : undefined,
573
+ };
574
+ if (this.props.location.query.type === 'embedded') {
575
+ delete obj.versions.base.ANDROID.cta.deepLinkName;
576
+ }
577
+ }
578
+ if (!_.isEmpty(ios)) {
579
+ obj.versions.base.IOS = {
580
+ luid: "{{luid}}",
581
+ cuid: "{{cuid}}",
582
+ communicationId: "{{communicationId}}",
583
+ title: ios['message-title2'],
584
+ message: ios['message-editor2'],
585
+ expandableDetails: {
586
+ style: "BIG_TEXT",
587
+ message: ios['message-editor2'],
588
+ ctas: [
589
+
590
+ ],
591
+ },
592
+ custom: _.map(ios, (field, key) => {
593
+ if (key.indexOf('custom-value') > -1) {
594
+ return field !== "" ? {key: key.replace('custom-value-', "").replace('-cta-deeplink2-select', '').replace('-cta-deeplink-secondary-cta-0-select', '').replace('-cta-deeplink-secondary-cta-1-select2', ''), value: field} : undefined;
595
+ }
596
+ return undefined;
597
+ }).filter((custom) => custom),
598
+ };
599
+ }
600
+ if (ios['cta-deeplink2'] && ios['cta-deeplink2'] !== "") {
601
+ obj.versions.base.IOS.cta = {
602
+ type: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
603
+ actionLink: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? ios['cta-deeplink2-select'] : ios['cta-deeplink2-text'],
604
+ deepLinkName: ios['cta-deeplink2'] && ios['cta-deeplink2'].toLowerCase() === "deeplink" ? this.getLinkName(ios['cta-deeplink2-select']) : undefined,
605
+ };
606
+ if (this.props.location.query.type === 'embedded') {
607
+ delete obj.versions.base.IOS.cta.deepLinkName;
608
+ }
609
+ }
610
+ const imageLink = android.image;
611
+ if (imageLink) {
612
+ obj.versions.base.ANDROID.expandableDetails.image = getCdnUrl({url: imageLink, channelName: 'MOBILE_PUSH'});
613
+ obj.versions.base.ANDROID.expandableDetails.style = "BIG_PICTURE";
614
+ }
615
+ if (obj.versions.base.ANDROID && obj.versions.base.ANDROID.cta) {
616
+ if (obj.versions.base.ANDROID.cta.type === "DEEP_LINK") {
617
+ const params = _.map(android, (field, key) => {
618
+ let actionLink;
619
+ if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-select') > -1) {
620
+ const param = key.replace('custom-value-', "").replace('-cta-deeplink-select', '');
621
+ actionLink = field !== "" ? `${param}=${field}` : undefined;
622
+ }
623
+ return actionLink;
624
+ }).filter((actionLink) => actionLink);
625
+ // Check if base URL already has query parameters
626
+ const baseUrl = obj?.versions?.base?.ANDROID?.cta?.actionLink;
627
+ if (params.length) {
628
+ // Only append parameters if the URL doesn't already have them
629
+ if (baseUrl?.indexOf('?') === -1) {
630
+ obj.versions.base.ANDROID.cta.actionLink = `${baseUrl}?${params.join('&')}`;
631
+ } else {
632
+ // URL already has parameters, don't append them again
633
+ obj.versions.base.ANDROID.cta.actionLink = baseUrl;
634
+ }
635
+ }
636
+ }
637
+ }
638
+ const secondaryCta1 = !!android["cta-deeplink-secondary-cta-0-select"] || !!android['secondary-cta-0-label'];
639
+ const secondaryCta2 = !!android['cta-deeplink-secondary-cta-1-select'] || !!android['secondary-cta-1-label'];
640
+ if (secondaryCta1 || secondaryCta2 ) {
641
+ obj.versions.base.ANDROID.expandableDetails.ctas = [];
642
+ if (secondaryCta1) {
643
+ const cta = {
644
+ actionText: android['secondary-cta-0-label'],
645
+ type: (android['cta-deeplink-secondary-cta-0'] || '').toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
646
+ actionLink: (android['cta-deeplink-secondary-cta-0'] || '').toLowerCase() === "deeplink" ? android['cta-deeplink-secondary-cta-0-select'] : android['cta-deeplink-secondary-cta-0-text'],
647
+ seccdeepLinkName: this.getLinkName(android['cta-deeplink-secondary-cta-0-select']),
648
+ };
649
+ if (this.props.location.query.type === 'embedded') {
650
+ delete cta.seccdeepLinkName;
651
+ }
652
+ obj.versions.base.ANDROID.expandableDetails.ctas.push(cta);
653
+ if (obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
654
+ const params = _.map(android, (field, key) => {
655
+ let actionLink;
656
+ if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-0-select') > -1) {
657
+ const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-0-select', '');
658
+ actionLink = field !== "" ? `${param}=${field}` : undefined;
659
+ }
660
+ return actionLink;
661
+ }).filter((actionLink) => actionLink);
662
+ if (params.length) {
663
+ obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
664
+ }
665
+ }
666
+ }
667
+ if (secondaryCta2) {
668
+ obj.versions.base.ANDROID.expandableDetails.ctas.push({
669
+ actionText: android['secondary-cta-1-label'],
670
+ type: (android['cta-deeplink-secondary-cta-1'] || '').toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL",
671
+ actionLink: (android['cta-deeplink-secondary-cta-1'] || '').toLowerCase() === "deeplink" ? android['cta-deeplink-secondary-cta-1-select'] : android['cta-deeplink-secondary-cta-1-text'],
672
+ seccdeepLinkName: this.getLinkName(android['cta-deeplink-secondary-cta-1-select']),
673
+ });
674
+ if (obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
675
+ const params = _.map(android, (field, key) => {
676
+ let actionLink;
677
+ if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-1-select') > -1) {
678
+ const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-1-select', '');
679
+ actionLink = field !== "" ? `${param}=${field}` : undefined;
680
+ }
681
+ return actionLink;
682
+ }).filter((actionLink) => actionLink);
683
+ if (params.length) {
684
+ obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.ANDROID.expandableDetails.ctas[obj.versions.base.ANDROID.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
685
+ }
686
+ }
687
+ }
688
+ }
689
+ const imageLinkIos = ios.image;
690
+ if (imageLinkIos) {
691
+ obj.versions.base.IOS.expandableDetails.image = getCdnUrl({url: imageLinkIos, channelName: 'MOBILE_PUSH'});
692
+ obj.versions.base.IOS.expandableDetails.style = "BIG_PICTURE";
693
+ }
694
+ if (obj.versions.base.IOS && obj.versions.base.IOS.cta) {
695
+ if (obj.versions.base.IOS.cta.type === "DEEP_LINK") {
696
+ const params = _.map(ios, (field, key) => {
697
+ let actionLink;
698
+ if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink2-select') > -1) {
699
+ const param = key.replace('custom-value-', "").replace('-cta-deeplink2-select', '');
700
+ actionLink = field !== "" ? `${param}=${field}` : undefined;
701
+ }
702
+ return actionLink;
703
+ }).filter((actionLink) => actionLink);
704
+ // Check if base URL already has query parameters
705
+ const baseUrl = obj?.versions?.base?.IOS?.cta?.actionLink;
706
+ if (params.length) {
707
+ // Only append parameters if the URL doesn't already have them
708
+ if (baseUrl?.indexOf('?') === -1) {
709
+ obj.versions.base.IOS.cta.actionLink = `${baseUrl}?${params.join('&')}`;
710
+ } else {
711
+ // URL already has parameters, don't append them again
712
+ obj.versions.base.IOS.cta.actionLink = baseUrl;
713
+ }
714
+ }
715
+ }
716
+ }
717
+ const secondaryCtaIos = !!ios['cta-deeplink-secondary-cta-1-select'] || !!ios['secondary-cta-1-label'];
718
+
719
+ if (secondaryCtaIos) {
720
+ obj.versions.base.IOS.expandableDetails.ctas = [];
721
+ const templateCtaId = get(this.state, "templateCta.ctaTemplateDetails[0].id");
722
+
723
+ const cta = {
724
+ actionText: ios['secondary-cta-1-label'],
725
+ actionLabel: ios['secondary-cta-1-action'],
726
+ actionLabel2: ios['secondary-cta-1-action2'],
727
+ type: ios['cta-deeplink-secondary-cta-1'] && (ios['cta-deeplink-secondary-cta-1'].toLowerCase() === "deeplink" ? "DEEP_LINK" : "EXTERNAL_URL"),
728
+ actionLink: ios['cta-deeplink-secondary-cta-1'] && (ios['cta-deeplink-secondary-cta-1'].toLowerCase() === "deeplink" ? ios['cta-deeplink-secondary-cta-1-select2'] : ios['cta-deeplink-secondary-cta-1-text']),
729
+ ioscdeepLinkName: this.getLinkName(ios['cta-deeplink-secondary-cta-1-select']),
730
+ templateCtaId,
731
+ };
732
+ if (this.props.location.query.type === 'embedded') {
733
+ delete cta.ioscdeepLinkName;
734
+ }
735
+ obj.versions.base.IOS.expandableDetails.ctas.push(cta);
736
+ obj.versions.base.IOS.expandableDetails.categoryId = get(this.state, "templateCta.id") || get(this.state.editData, 'versions.base.IOS.expandableDetails.categoryId');
737
+
738
+ if (obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].type === "DEEP_LINK") {
739
+ const params = _.map(ios, (field, key) => {
740
+ let actionLink;
741
+ if (key.indexOf('custom-value') > -1 && key.indexOf('cta-deeplink-secondary-cta-1-select') > -1) {
742
+ const param = key.replace('custom-value-', "").replace('-cta-deeplink-secondary-cta-1-select2', '');
743
+ actionLink = field !== "" ? `${param}=${field}` : undefined;
744
+ }
745
+ return actionLink;
746
+ }).filter((actionLink) => actionLink);
747
+ if (params.length) {
748
+ obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].actionLink = `${obj.versions.base.IOS.expandableDetails.ctas[obj.versions.base.IOS.expandableDetails.ctas.length - 1].actionLink}?${params.join('&')}`;
749
+ }
750
+ }
751
+ }
752
+ return obj;
753
+ };
754
+
755
+ getLinkName = (link) => {
756
+ const selectedWeChatAccount = this.getWeChatAccount();
757
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
758
+ const deepLinkOptions = _.filter(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (l) => l.link === link);
759
+ if (deepLinkOptions[0]) {
760
+ return deepLinkOptions[0].name;
761
+ }
762
+ return undefined;
763
+ };
764
+ // eslint-disable-next-line react/sort-comp
765
+ showError = () => {
766
+ const {intl} = this.props;
767
+ const {errorData, schema} = this.state;
768
+ const errorMessage = {key: 'validation-error', message: intl.formatMessage(messages.validationError)};
769
+ if (!_.isEmpty(this.state.formData) && !this.state.isFormValid) {
770
+ let tab = this.state.currentTab;
771
+ const isAndroidInvalid = Object.values(errorData?.[0] || {}).includes(true);
772
+ const isIosInvalid = Object.values(errorData?.[1] || {}).includes(true);
773
+ const isIosTabVisible = get(schema, 'containers[0].panes[1].isSupported', true) !== false;
774
+ if (isAndroidInvalid) {
775
+ tab = 1;
776
+ errorMessage.description = intl.formatMessage(messages.invalidAndroidMessage);
777
+ } else if (isIosInvalid && isIosTabVisible) {
778
+ tab = 2;
779
+ errorMessage.description = intl.formatMessage(messages.invalidIosMessage);
780
+ }
781
+
782
+ if (tab !== this.state.currentTab) {
783
+ CapNotification.error(errorMessage);
784
+ }
785
+ }
786
+ }
787
+ setFormValidity = (isFormValid, errorData) => {
788
+ const newState = {isFormValid, errorData};
789
+ this.setState(newState);
790
+ };
791
+
792
+ getMappedEvent = (id, event) => {
793
+ const map = this.state.eventsMap;
794
+ if (!map[id] || !map[id][event]) {
795
+
796
+ }
797
+ return map[id][event];
798
+ };
799
+
800
+ getCurrentWindow = (e) => {
801
+ const response = {
802
+ action: e.action,
803
+ value: 'edit',
804
+ direction: e.value,
805
+ };
806
+ parent.postMessage(JSON.stringify(response), '*');
807
+ };
808
+
809
+ /**
810
+ * Compute selectedWeChatAccount from props (used so we can call with latest props
811
+ * in setState callback to avoid stale closure and intermittent empty form).
812
+ */
813
+ getSelectedWeChatAccountFromProps = (props) => {
814
+ const queryType = String(get(props, 'location.query.type', ''))?.toLowerCase();
815
+ const creativesMode = String(get(props, 'creativesMode', ''))?.toLowerCase();
816
+ const { Edit: EditProps, Templates } = props || {};
817
+ const { selectedWeChatAccount: editSelectedWeChatAccount } = EditProps || {};
818
+ const { Templates: nextTemplates } = props || {};
819
+ if (isEmbeddedEditOrPreview(queryType, creativesMode)) {
820
+ return !_.isEmpty(editSelectedWeChatAccount)
821
+ ? editSelectedWeChatAccount
822
+ : nextTemplates?.selectedWeChatAccount;
823
+ }
824
+ if (!_.isEmpty(Templates?.selectedWeChatAccount)) {
825
+ return Templates?.selectedWeChatAccount;
826
+ }
827
+ return undefined;
828
+ };
829
+
830
+ getFormData = (e) => {
831
+ const response = {
832
+ action: "getFormData",
833
+ value: this.getTransformedData(this.state.formData),
834
+ validity: this.state.isFormValid,
835
+ };
836
+
837
+ this.setState({checkValidation: true}, this.showError);
838
+ if (e) {
839
+ e.source.postMessage(JSON.stringify(response), e.origin);
840
+ }
841
+ return response;
842
+ };
843
+
844
+
845
+ setEditState(data, schema) {
846
+ if (!data?.versions?.base || typeof data.versions.base !== 'object') return;
847
+ const tabCount = Object.keys(data.versions.base).length;
848
+ const formData = {};
849
+ if (this.props.location.query.type === 'embedded' && this.props.location.query.module === "loyalty") {
850
+ formData["mobilepush-accounts"] = this.state.formData["mobilepush-accounts"];
851
+ formData['mobilepush-template'] = this.state.formData['mobilepush-template'];
852
+ }
853
+ if (data.definition?.accountId) {
854
+ formData['mobilepush-accounts'] = data.definition.accountId;
855
+ }
856
+ formData['template-name'] = data.name;
857
+ const androidData = data.versions.base.ANDROID;
858
+ const iosData = data.versions.base.IOS;
859
+ const android = {};
860
+ android[`message-title`] = androidData ? androidData.title : '';
861
+ android['message-editor'] = androidData ? androidData.message : '';
862
+ if (data.mode === "image") {
863
+ android.image = "";
864
+ }
865
+ if (androidData) {
866
+ if (androidData.cta) {
867
+ android['add-pri-cta'] = true;
868
+ android['cta-deeplink'] = androidData.cta.type === "DEEP_LINK" ? "Deeplink" : "External Link";
869
+ if ( androidData.cta.type === "DEEP_LINK") {
870
+ android['cta-deeplink-select'] = androidData ? androidData.cta.actionLink : '';
871
+ } else {
872
+ android['cta-deeplink-text'] = androidData ? androidData.cta.actionLink : '';
873
+ }
874
+ }
875
+ if (androidData.expandableDetails && androidData.expandableDetails.image) {
876
+ android.image = androidData.expandableDetails.image;
877
+ }
878
+ if (androidData.expandableDetails && androidData.expandableDetails.ctas && androidData.expandableDetails.ctas.length) {
879
+ android['add-sec-cta'] = true;
880
+ android['cta-deeplink-secondary-cta-0'] = androidData.expandableDetails.ctas[0].type === "DEEP_LINK" ? "Deeplink" : "External Link";
881
+ if ( androidData.expandableDetails.ctas[0].type === "DEEP_LINK") {
882
+ android['cta-deeplink-secondary-cta-0-select'] = androidData.expandableDetails.ctas[0].actionLink;
883
+ } else {
884
+ android['cta-deeplink-secondary-cta-0-text'] = androidData.expandableDetails.ctas[0].actionLink;
885
+ }
886
+ android['secondary-cta-0-label'] = androidData.expandableDetails.ctas[0].actionText;
887
+ if (androidData.expandableDetails.ctas[0].type === "DEEP_LINK") {
888
+ const originalUrl = android['cta-deeplink-secondary-cta-0-select'];
889
+
890
+ // Check if URL contains custom parameters that need extraction
891
+ if (originalUrl?.includes('custom_param=')) {
892
+ const link = originalUrl.split('?')[0];
893
+ const params = originalUrl.split('?')[1] && originalUrl.split('?')[1].split('&');
894
+
895
+ // Only process and extract custom parameters
896
+ const customParams = params?.filter(param => param?.startsWith('custom_param='));
897
+
898
+ if (customParams?.length) {
899
+ android['cta-deeplink-secondary-cta-0-select'] = link;
900
+ _.forEach(customParams, (param) => {
901
+ android[`custom-value-${param.split('=')[0]}-cta-deeplink-secondary-cta-0-select`] = param.split('=')[1];
902
+ });
903
+ }
904
+ }
905
+ // If no custom parameters, keep original URL intact
906
+ // android['cta-deeplink-secondary-cta-0-select'] remains unchanged
907
+ }
908
+ if (androidData?.expandableDetails && androidData?.expandableDetails?.ctas && androidData?.expandableDetails?.ctas?.length > 1) {
909
+ android['add-sec-cta-2'] = true;
910
+ android['cta-deeplink-secondary-cta-1'] = androidData?.expandableDetails?.ctas[1]?.type === "DEEP_LINK" ? "Deeplink" : "External Link";
911
+ if (androidData?.expandableDetails?.ctas[1]?.type === "DEEP_LINK") {
912
+ android['cta-deeplink-secondary-cta-1-select'] = androidData?.expandableDetails?.ctas[1]?.actionLink;
913
+ } else {
914
+ android['cta-deeplink-secondary-cta-1-text'] = androidData?.expandableDetails?.ctas[1]?.actionLink;
915
+ }
916
+ android['secondary-cta-1-label'] = androidData?.expandableDetails?.ctas[1]?.actionText;
917
+ if (androidData?.expandableDetails?.ctas[1]?.type === "DEEP_LINK" && android['cta-deeplink-secondary-cta-1-select']) {
918
+ const originalUrl = android['cta-deeplink-secondary-cta-1-select'];
919
+
920
+ // Check if URL contains custom parameters that need extraction
921
+ if (originalUrl?.includes('custom_param=')) {
922
+ const link = originalUrl.split('?')[0];
923
+ const params = originalUrl.split('?')[1] && originalUrl.split('?')[1].split('&');
924
+
925
+ // Only process and extract custom parameters
926
+ const customParams = params?.filter(param => param?.startsWith('custom_param='));
927
+
928
+ if (customParams?.length) {
929
+ android['cta-deeplink-secondary-cta-1-select'] = link;
930
+ _.forEach(customParams, (param) => {
931
+ android[`custom-value-${param.split('=')[0]}-cta-deeplink-secondary-cta-1-select`] = param.split('=')[1];
932
+ });
933
+ }
934
+ }
935
+ // If no custom parameters, keep original URL intact
936
+ // android['cta-deeplink-secondary-cta-1-select'] remains unchanged
937
+ }
938
+ }
939
+ }
940
+ }
941
+ formData[0] = android;
942
+ const ios = {};
943
+ const templateCta = {};
944
+ ios[`message-title2`] = iosData ? iosData.title : '';
945
+ ios['message-editor2'] = iosData ? iosData.message : '';
946
+ if (data.mode === "image") {
947
+ ios.image = "";
948
+ }
949
+ if (iosData) {
950
+ if (iosData.cta) {
951
+ ios['add-pri-cta-ios'] = true;
952
+ ios['cta-deeplink2'] = iosData.cta.type === "DEEP_LINK" ? "Deeplink" : "External Link";
953
+ if (iosData.cta.type === "DEEP_LINK") {
954
+ ios['cta-deeplink2-select'] = iosData ? iosData.cta.actionLink : '';
955
+ } else {
956
+ ios['cta-deeplink2-text'] = iosData ? iosData.cta.actionLink : '';
957
+ }
958
+ }
959
+ if (iosData.expandableDetails && iosData.expandableDetails.image) {
960
+ ios.image = iosData.expandableDetails.image;
961
+ }
962
+ if (iosData.expandableDetails && iosData.expandableDetails.ctas && iosData.expandableDetails.ctas.length) {
963
+ ios['add-sec-cta-ios'] = true;
964
+ if (iosData.expandableDetails.ctas[0].type) {
965
+ ios['cta-deeplink-secondary-cta-1'] = iosData.expandableDetails.ctas[0].type === "DEEP_LINK" ? "Deeplink" : "External Link";
966
+ }
967
+ if (iosData.expandableDetails.ctas[0].type === "DEEP_LINK") {
968
+ ios['cta-deeplink-secondary-cta-1-select2'] = iosData.expandableDetails.ctas[0].actionLink;
969
+ } else {
970
+ ios['cta-deeplink-secondary-cta-1-text'] = iosData.expandableDetails.ctas[0].actionLink;
971
+ }
972
+ ios['secondary-cta-1-label'] = iosData.expandableDetails.ctas[0].actionText;
973
+ if (iosData.expandableDetails.ctas[0].type === "DEEP_LINK" && ios['cta-deeplink-secondary-cta-1-select2']) {
974
+ const originalUrl = ios['cta-deeplink-secondary-cta-1-select2'];
975
+
976
+ // Check if URL contains custom parameters that need extraction
977
+ if (originalUrl?.includes('custom_param=')) {
978
+ const link = originalUrl.split('?')[0];
979
+ const params = originalUrl.split('?')[1] && originalUrl.split('?')[1].split('&');
980
+
981
+ // Only process and extract custom parameters
982
+ const customParams = params?.filter(param => param?.startsWith('custom_param='));
983
+
984
+ if (customParams?.length) {
985
+ ios['cta-deeplink-secondary-cta-1-select2'] = link;
986
+ _.forEach(customParams, (param) => {
987
+ ios[`custom-value-${param.split('=')[0]}-cta-deeplink-secondary-cta-1-select2`] = param.split('=')[1];
988
+ });
989
+ }
990
+ }
991
+ // If no custom parameters, keep original URL intact
992
+ // ios['cta-deeplink-secondary-cta-1-select2'] remains unchanged
993
+ }
994
+ set(templateCta, "ctaTemplateDetails[0].buttonText", iosData.expandableDetails.ctas[0].actionLabel);
995
+ set(templateCta, "name", iosData.expandableDetails.ctas[0].actionText);
996
+ set(templateCta, "ctaTemplateDetails[0].id", iosData.expandableDetails.ctas[0].templateCtaId);
997
+ ios['secondary-cta-1-action'] = iosData.expandableDetails.ctas[0].actionLabel;
998
+ if (iosData.expandableDetails.ctas[0].actionLabel2) {
999
+ set(templateCta, "ctaTemplateDetails[1].buttonText", iosData.expandableDetails.ctas[0].actionLabel2);
1000
+ ios['secondary-cta-1-action2'] = iosData.expandableDetails.ctas[0].actionLabel2;
1001
+ }
1002
+ }
1003
+ }
1004
+ formData[1] = ios;
1005
+ formData.base = formData[0];
1006
+ formData[0].base = true;
1007
+ // formData[0].tabKey = '1';
1008
+ // formData[1].tabKey = '2';
1009
+ this.setState({templateCta}, () => {
1010
+ this.getSchemaForFormData(formData, schema);
1011
+ this.setState({tabCount, formData, editData: data}, () => {
1012
+ this.props.showTemplateName({formData, onFormDataChange: this.onFormDataChange});
1013
+ });
1014
+ });
1015
+ }
1016
+
1017
+ getSchemaForFormData = (formdata, inputSchema) => {
1018
+ let schema = inputSchema;
1019
+ const formData = _.cloneDeep(formdata);
1020
+ if (!_.isEmpty(formData[0])) {
1021
+ if (formData[0]['cta-deeplink']) {
1022
+ formData[0]['add-pri-cta'] = true;
1023
+ schema = this.addPrimaryCta(null, formData, {id: 'add-pri-cta'}, schema, 1);
1024
+ schema = this.onLinkTypeChange(true, formData, {id: 'cta-deeplink'}, 1, schema);
1025
+ schema = this.showCtaKeys(true, formData, {id: 'cta-deeplink-select'}, 1, schema);
1026
+ }
1027
+ if (formData[0]['cta-deeplink-secondary-cta-0']) {
1028
+ formData[0]['add-sec-cta'] = true;
1029
+ schema = this.addSecondoryCta(null, formData, {id: 'add-sec-cta'}, schema, 1);
1030
+ schema = this.onLinkTypeChange(true, formData, {id: 'cta-deeplink-secondary-cta-0'}, 1, schema);
1031
+ schema = this.showCtaKeys(true, formData, {id: 'cta-deeplink-secondary-cta-0-select'}, 1, schema);
1032
+ }
1033
+ if (formData[0]['cta-deeplink-secondary-cta-1']) {
1034
+ formData[0]['add-sec-cta-2'] = true;
1035
+ schema = this.addSecondoryCta(null, formData, {id: 'add-sec-cta-2'}, schema, 1);
1036
+ schema = this.onLinkTypeChange(true, formData, {id: 'cta-deeplink-secondary-cta-1'}, 1, schema);
1037
+ schema = this.showCtaKeys(true, formData, {id: 'cta-deeplink-secondary-cta-1-select'}, 1, schema);
1038
+ }
1039
+ }
1040
+ if (!_.isEmpty(formData[1])) {
1041
+ if (formData[1]['cta-deeplink2']) {
1042
+ formData[1]['add-pri-cta-ios'] = true;
1043
+ schema = this.addPrimaryCta(null, formData, {id: 'add-pri-cta-ios'}, schema, 2);
1044
+ schema = this.onLinkTypeChange(true, formData, {id: 'cta-deeplink2'}, 2, schema);
1045
+ schema = this.showCtaKeys(true, formData, {id: 'cta-deeplink2-select'}, 2, schema);
1046
+ }
1047
+ if (formData[1]['secondary-cta-1-action']) {
1048
+ formData[1]['add-sec-cta-ios'] = true;
1049
+
1050
+ schema = this.showSelectedIosCta(schema, {id: 'add-sec-cta-ios'}, 2, this.state.templateCta, formData[1]['cta-deeplink-secondary-cta-1']);
1051
+ schema = this.onLinkTypeChange(true, formData, {id: 'cta-deeplink-secondary-cta-1'}, 2, schema);
1052
+ schema = this.showCtaKeys(true, formData, {id: 'cta-deeplink-secondary-cta-1-select2'}, 2, schema);
1053
+ }
1054
+ }
1055
+ this.setState({schema, isSchemaChanged: true, formData});
1056
+ this.injectEvents(schema);
1057
+ };
1058
+ setTemplateOptions = (mobilepushTemplates) => {
1059
+ const templateOptions = [];
1060
+ let selectedTemplate = {};
1061
+ if (!_.isEmpty(mobilepushTemplates)) {
1062
+ _.forEach(mobilepushTemplates, (template) => {
1063
+ templateOptions.push({
1064
+ key: template._id,
1065
+ label: template.name,
1066
+ value: template._id,
1067
+ });
1068
+ if (this.state.formData['mobilepush-template'] && template._id === this.state.formData['mobilepush-template']) {
1069
+ selectedTemplate = template;
1070
+ }
1071
+ });
1072
+ }
1073
+ this.setState({templateOptions}, () => {
1074
+ if (!_.isEmpty(selectedTemplate)) {
1075
+ this.props.actions.setSelectedTemplate(selectedTemplate);
1076
+ }
1077
+ if (!_.isEmpty(this.state.schema)) {
1078
+ this.injectEvents(this.state.schema);
1079
+ }
1080
+ });
1081
+ };
1082
+ getTags = () => {
1083
+ if (this.hasFetchedInitialTagsRef) {
1084
+ return;
1085
+ }
1086
+ this.hasFetchedInitialTagsRef = true;
1087
+ const context = this.props.getDefaultTags
1088
+ || (this.props.location.query.type === 'embedded' ? this.props.location.query.module : 'default');
1089
+ this.lastFetchedTagContextRef = typeof context === 'string' ? context.toLowerCase() : context;
1090
+ const query = {
1091
+ layout: 'mobilepush',
1092
+ type: 'TAG',
1093
+ context: this.lastFetchedTagContextRef,
1094
+ embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
1095
+ };
1096
+ this.props.globalActions.fetchSchemaForEntity(query);
1097
+ }
1098
+ setModalContent = (type) => {
1099
+ if (type === 'ios') {
1100
+ const modalContent = {
1101
+ title: this.props.intl.formatMessage(messages.alertMessage),
1102
+ body: this.props.intl.formatMessage(messages.androidTemplateNotConfigured),
1103
+ type: 'confirm',
1104
+ id: 'ios',
1105
+ };
1106
+ this.setState({modalContent, showModal: true});
1107
+ } else if (type === 'android') {
1108
+ const modalContent = {
1109
+ title: this.props.intl.formatMessage(messages.alertMessage),
1110
+ body: this.props.intl.formatMessage(messages.iosTemplateNotConfigured),
1111
+ type: 'confirm',
1112
+ id: 'android',
1113
+ };
1114
+ this.setState({modalContent, showModal: true});
1115
+ }
1116
+ }
1117
+
1118
+ openNotificationWithIcon = (type, message) => {
1119
+ const dur = (type === 'error' || type === 'warning') ? null : 5;
1120
+ notification[type]({
1121
+ message: (`${type.toUpperCase()} ! ! ! `),
1122
+ description: message, //'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
1123
+ duration: dur,
1124
+ });
1125
+ }
1126
+
1127
+ handleCancelModal = () => {
1128
+ this.setState({showModal: false}, this.stopValidation);
1129
+ };
1130
+
1131
+ insertAtCursor = (field, myValue, currentTab) => {
1132
+ //IE support
1133
+ const myField = field;
1134
+ if (document.selection) {
1135
+ myField.focus();
1136
+ const sel = document.selection.createRange();
1137
+ sel.text = myValue;
1138
+ } else if (myField.selectionStart || myField.selectionStart === '0') { //MOZILLA and others
1139
+ const startPos = myField.selectionStart;
1140
+ const endPos = myField.selectionEnd;
1141
+ myField.value = myField.value.substring(0, startPos)
1142
+ + myValue
1143
+ + myField.value.substring(endPos, myField.value.length);
1144
+ myField.selectionStart = startPos + myValue.length;
1145
+ myField.selectionEnd = startPos + myValue.length;
1146
+ } else {
1147
+ myField.value += myValue;
1148
+ }
1149
+ const formData = _.cloneDeep(this.state.formData);
1150
+ formData[currentTab - 1][field.id] = myField.value;
1151
+ this.setState({formData});
1152
+ };
1153
+
1154
+ selectCtaIos = (selectedConfig) => {
1155
+ this.showSelectedIosCta(null, null, null, selectedConfig);
1156
+ };
1157
+
1158
+ uploadImage = (data) => {
1159
+ if (data.fileParams.error) {
1160
+ const message = getMessageObject('error', this.props.intl.formatMessage(messages['File size cannot be more than 5mb']), true);
1161
+ this.props.globalActions.addMessageToQueue(message);
1162
+ } else {
1163
+ const name = data.file.name.split('.');
1164
+ const newFile = new File([data.file], `${name[0]}${Date.now()}.${name[1]}`, {type: 'image'});
1165
+ this.props.actions.uploadAsset(newFile, data.type, data.fileParams);
1166
+ }
1167
+ };
1168
+
1169
+ copyIphoneContent = () => {
1170
+ const formData = _.cloneDeep(this.state.formData);
1171
+ if (!!formData[1]['message-title2'] && !!formData[1]['message-editor2']) {
1172
+ formData[0]['message-title'] = formData[1]['message-title2'];
1173
+ formData[0]['message-editor'] = formData[1]['message-editor2'];
1174
+ this.setState({formData});
1175
+ } else {
1176
+ this.openNotificationWithIcon('warning', this.props.intl.formatMessage(messages.cantCopyEmptyFieldValues));
1177
+ }
1178
+ };
1179
+ copyAndroidContent = () => {
1180
+ const formData = _.cloneDeep(this.state.formData);
1181
+ if (!!formData[0]['message-title'] && formData[0]['message-editor']) {
1182
+ formData[1]['message-title2'] = formData[0]['message-title'];
1183
+ formData[1]['message-editor2'] = formData[0]['message-editor'];
1184
+ this.setState({formData});
1185
+ } else {
1186
+ this.openNotificationWithIcon('warning', this.props.intl.formatMessage(messages.cantCopyEmptyFieldValues));
1187
+ }
1188
+ };
1189
+
1190
+ showSelectedIosCta = (inputSchema, field, tab, selectedConfig) => {
1191
+ const currentTab = tab || this.state.currentTab;
1192
+ const schema = inputSchema ? _.cloneDeep(inputSchema) : _.cloneDeep(this.state.schema);
1193
+ const selectedWeChatAccount = this.getWeChatAccount();
1194
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1195
+ const deepLinkOptions = _.map(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (link) => ({label: link.name, value: link.link, title: link.link }) );
1196
+
1197
+ const inputFields = get(schema, `containers[0].panes[${currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1198
+ forEach(inputFields, (inputField, fieldIndex) => {
1199
+ forEach(inputField.cols, (col) => {
1200
+ if (col.id === "add-sec-cta-ios") {
1201
+ const inputId = `secondary-cta-${currentTab - 1}`;
1202
+ inputFields.splice(fieldIndex + 1, 0, {
1203
+ rowClassName: 'mobile-push-row',
1204
+ cols: [
1205
+ {
1206
+ id: `${inputId}-action-display`,
1207
+ metaType: "label",
1208
+ value: <CapRow>
1209
+ <CapColumn span={18}>
1210
+ <CapHeader
1211
+ title={this.state.templateCta.name}
1212
+ description={get(this.state, "templateCta.ctaTemplateDetails[0].buttonText")}
1213
+ size={"label"}/>
1214
+ </CapColumn>
1215
+ <CapColumn span={6}>
1216
+ <CapLink title={this.props.intl.formatMessage(messages.change)} onClick={() => this.addSecondoryCtaIos(true, this.state.formData, {id: "add-sec-cta-ios"})}/>
1217
+ </CapColumn>
1218
+ </CapRow>,
1219
+ primitive: true,
1220
+ dynamicTab: false,
1221
+ type: "div",
1222
+ width: 18,
1223
+ offset: 1,
1224
+ },
1225
+ {
1226
+ id: `${inputId}-action`,
1227
+ metaType: "label",
1228
+ value: "",
1229
+ primitive: true,
1230
+ dynamicTab: false,
1231
+ type: "div",
1232
+ width: 8,
1233
+ offset: 0,
1234
+ style: {
1235
+ display: 'none',
1236
+ },
1237
+ },
1238
+ {
1239
+ id: `${inputId}-action2`,
1240
+ metaType: "label",
1241
+ value: "",
1242
+ primitive: true,
1243
+ dynamicTab: false,
1244
+ type: "div",
1245
+ width: 8,
1246
+ offset: 0,
1247
+ style: {display: 'none'},
1248
+ },
1249
+
1250
+ ],
1251
+ });
1252
+ const selectedConfigTemplateCtaId = get(selectedConfig, 'ctaTemplateDetails[0].id');
1253
+ // the option to select deeplink and externa link should not come for these ctas
1254
+ if (selectedConfigTemplateCtaId && (selectedConfigTemplateCtaId.id !== "3heicig" && selectedConfigTemplateCtaId.id !== "6eigf4f" && selectedConfigTemplateCtaId.id !== "c97d0ed")) {
1255
+ inputFields.splice(fieldIndex + 2, 0, {
1256
+ rowClassName: "mobile-push-row",
1257
+ identifier: `cta-deeplink-${inputId}`,
1258
+ cols: [
1259
+
1260
+ {
1261
+ id: `cta-deeplink-${inputId}`,
1262
+ type: "radioGroup", //Resembles component to be used
1263
+ metaType: "text",
1264
+ datatype: "string",
1265
+ options: ["Deeplink", "External Link"],
1266
+ inductiveText: [<FormattedMessage {...messages.aPageWithMobileApp}/>, <FormattedMessage {...messages.anExternalWebPage}/>],
1267
+ value: "Deeplink",
1268
+ required: true,
1269
+ width: 18,
1270
+ offset: 1,
1271
+ errorMessage: this.props.intl.formatMessage(messages.selectLinkType),
1272
+ fluid: true,
1273
+
1274
+ styling: "semantic",
1275
+ order: 1,
1276
+ supportedEvents: ["onChange"],
1277
+ customComponent: false,
1278
+ },
1279
+ ],
1280
+ });
1281
+ inputFields.splice(fieldIndex + 3, 0, {
1282
+ rowClassName: 'mobile-push-row',
1283
+ id: 'cta-deeplink-select-section',
1284
+ identifier: `cta-deeplink-${inputId}-select2`,
1285
+ cols: [
1286
+
1287
+ {
1288
+ id: `cta-deeplink-${inputId}-select2`,
1289
+ placeholder: this.props.intl.formatMessage(messages.selectDeeplink),
1290
+ type: "select", //Resembles component to be used
1291
+ options: deepLinkOptions,
1292
+ metaType: "text",
1293
+ datatype: "string",
1294
+ errorMessage: this.props.intl.formatMessage(messages.selectADeeplink),
1295
+ required: true,
1296
+ fluid: true,
1297
+ width: 18,
1298
+ offset: 1,
1299
+ style: {
1300
+ width: '100%',
1301
+ marginBottom: '16px',
1302
+ },
1303
+ styling: "semantic",
1304
+ order: 1,
1305
+ customComponent: false,
1306
+ supportedEvents: [
1307
+ 'onSelect',
1308
+ ],
1309
+ },
1310
+ ],
1311
+ });
1312
+ }
1313
+ }
1314
+ });
1315
+ });
1316
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true}, () => { this.injectEvents(schema); });
1317
+ return schema;
1318
+ };
1319
+
1320
+ deletePrimaryCTA = (event) => {
1321
+ const selectedWeChatAccount = this.getWeChatAccount();
1322
+ const id = event.currentTarget.id;
1323
+ const schema = _.cloneDeep(this.state.schema);
1324
+ // const eventsMap = _.cloneDeep(this.state.eventsMap);
1325
+ const selectedDeeplink = this.state.formData[this.state.currentTab - 1][`${id.replace('delete', 'select')}`];
1326
+ const formData = _.cloneDeep(this.state.formData);
1327
+ const self = this;
1328
+ _.forEach(schema.containers, (container) => {
1329
+ _.forEach(container.panes, (pane) => {
1330
+ _.forEach(pane.sections, (section) => {
1331
+ _.forEach(section.childSections, (childeSection) => {
1332
+ _.forEach(childeSection.childSections, (formChild) => {
1333
+ const child = formChild;
1334
+ if (child.type === 'multicols') {
1335
+ _.forEach(child.inputFields, (inputField, fieldIndex) => {
1336
+ if (inputField) {
1337
+ _.forEach(inputField.cols, (col) => {
1338
+ if (col.id === id) {
1339
+ child.inputFields.splice(fieldIndex, 1);
1340
+ if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-external-link") {
1341
+ child.inputFields.splice(fieldIndex, 1);
1342
+ delete formData[self.state.currentTab - 1][`${id.replace('delete', 'text')}`];
1343
+ delete formData[self.state.currentTab - 1][`${id.replace('-delete', '')}`];
1344
+ }
1345
+ if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-deeplink-select-section") {
1346
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1347
+ const configkeys = selectedWeChatAccount ? _.filter(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (dl) => dl.link === selectedDeeplink) : [];
1348
+ if (configkeys.length) {
1349
+ const options = configkeys[0].keys;
1350
+ _.forEach(options, (opt) => {
1351
+ delete formData[this.state.currentTab - 1][`custom-value-${opt}-${id.replace('delete', 'select')}`];
1352
+ });
1353
+ child.inputFields = child.inputFields.slice(0, fieldIndex).concat(child.inputFields.slice( fieldIndex + options.length + 1, child.inputFields.length));
1354
+ delete formData[self.state.currentTab - 1][`${id.replace('delete', 'select')}`];
1355
+ delete formData[self.state.currentTab - 1][`${id.replace('-delete', '')}`];
1356
+ } else {
1357
+ child.inputFields.splice(fieldIndex, 1);
1358
+ }
1359
+ }
1360
+ child.inputFields.splice(fieldIndex, 0, {
1361
+ cols: [
1362
+ {
1363
+ id: `${this.state.currentTab === 1 ? "add-pri-cta" : "add-pri-cta-ios"}`,
1364
+ metaType: "label",
1365
+ value: this.props.intl.formatMessage(messages.addPrimaryCTA),
1366
+ primitive: true,
1367
+ dynamicTab: false,
1368
+ type: "div",
1369
+ style: {
1370
+ backgroundColor: 'white',
1371
+ textAlign: 'left',
1372
+ color: '#2673D7',
1373
+ lineHeight: '24px',
1374
+ fontSize: '14px',
1375
+ fontWeight: '600',
1376
+ fontFamily: 'open-sans',
1377
+ fontStyle: 'normal',
1378
+ cursor: 'pointer',
1379
+ },
1380
+ offset: 0,
1381
+ onlyDisplay: true,
1382
+ colStyle: {
1383
+ flex: 1,
1384
+ },
1385
+ submitAction: "addPrimaryCta",
1386
+ supportedEvents: ["addPrimaryCta"],
1387
+ },
1388
+ ],
1389
+ });
1390
+ }
1391
+ });
1392
+ }
1393
+ });
1394
+ }
1395
+ });
1396
+ });
1397
+ });
1398
+ });
1399
+ });
1400
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, formData, isSchemaChanged: true});
1401
+ this.injectEvents(schema);
1402
+ };
1403
+
1404
+ deleteSecondaryCtaIos = (callback) => {
1405
+ const schema = cloneDeep(this.state.schema);
1406
+ const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1407
+ forEach(inputFields, (inputField, fieldIndex) => {
1408
+ if (inputField) {
1409
+ forEach(inputField.cols, (col) => {
1410
+ if (col.id === "add-sec-cta-ios") {
1411
+ inputFields.splice(fieldIndex + 1, inputFields.length);
1412
+ }
1413
+ });
1414
+ }
1415
+ });
1416
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true}, callback);
1417
+ this.injectEvents(schema);
1418
+ };
1419
+
1420
+ deleteSecondaryCTA = (event) => {
1421
+ const selectedWeChatAccount = this.getWeChatAccount();
1422
+ const id = event.currentTarget.id;
1423
+ if (id === "secondary-cta-0-delete") {
1424
+ const secCta2 = document.getElementById("secondary-cta-1-delete");
1425
+ if (secCta2) {
1426
+ const modalContent = {title: this.props.intl.formatMessage(messages.alertMessage), body: this.props.intl.formatMessage(messages.deleteSecondCTAFirst), type: 'info', show: true, onCancel: this.onModalCancel};
1427
+ this.setState({modalContent, showModal: true});
1428
+ return;
1429
+ }
1430
+ }
1431
+ const schema = _.cloneDeep(this.state.schema);
1432
+ // const eventsMap = _.cloneDeep(this.state.eventsMap);
1433
+ const selectedDeeplink = this.state.formData[this.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'select')}`];
1434
+ const formData = _.cloneDeep(this.state.formData);
1435
+ const self = this;
1436
+ const device = this.state.currentTab === 1 ? 'android' : 'ios';
1437
+ _.forEach(schema.containers, (container) => {
1438
+ _.forEach(container.panes, (pane) => {
1439
+ _.forEach(pane.sections, (section) => {
1440
+ _.forEach(section.childSections, (childeSection) => {
1441
+ _.forEach(childeSection.childSections, (formChild) => {
1442
+ const child = formChild;
1443
+ if (child.type === 'multicols') {
1444
+ _.forEach(child.inputFields, (inputField, fieldIndex) => {
1445
+ if (inputField) {
1446
+ _.forEach(inputField.cols, (col) => {
1447
+ if (col.id === id) {
1448
+ if (device === 'ios') {
1449
+ child.inputFields.splice(fieldIndex, 3);
1450
+ } else {
1451
+ child.inputFields.splice(fieldIndex, 2);
1452
+ }
1453
+ if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-external-link") {
1454
+ child.inputFields.splice(fieldIndex, 1);
1455
+ delete formData[self.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'text')}`];
1456
+ }
1457
+ if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].id === "cta-deeplink-select-section") {
1458
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1459
+ const configkeys = selectedWeChatAccount ? _.filter(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (dl) => dl.link === selectedDeeplink) : [];
1460
+
1461
+ if (configkeys.length) {
1462
+ const options = configkeys[0].keys;
1463
+ _.forEach(options, (opt) => {
1464
+ delete formData[this.state.currentTab - 1][`custom-value-${opt}-cta-deeplink-${id.replace('delete', 'select')}`];
1465
+ });
1466
+ child.inputFields = child.inputFields.slice(0, fieldIndex).concat(child.inputFields.slice( fieldIndex + options.length + 1, child.inputFields.length));
1467
+ delete formData[this.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'select')}`];
1468
+ } else {
1469
+ child.inputFields.splice(fieldIndex, 1);
1470
+ }
1471
+ }
1472
+ delete formData[this.state.currentTab - 1][`${id.replace('delete', 'label')}`];
1473
+ delete formData[this.state.currentTab - 1][`cta-deeplink-${id.replace('-delete', '')}`];
1474
+ if (device === 'ios') {
1475
+ child.inputFields[fieldIndex] = {
1476
+ cols: [
1477
+ {
1478
+ id: "add-sec-cta-ios",
1479
+ metaType: "label",
1480
+ value: this.props.intl.formatMessage(messages.addSecondaryCTA),
1481
+ primitive: true,
1482
+ dynamicTab: false,
1483
+ type: "div",
1484
+ style: {
1485
+ backgroundColor: 'white',
1486
+ textAlign: 'left',
1487
+ color: '#2673D7',
1488
+ lineHeight: '24px',
1489
+ fontSize: '14px',
1490
+ marginTop: '16px',
1491
+ fontWeight: '600',
1492
+ fontFamily: 'open-sans',
1493
+ fontStyle: 'normal',
1494
+ cursor: 'pointer',
1495
+ },
1496
+ offset: 0,
1497
+ onlyDisplay: true,
1498
+ colStyle: {
1499
+ flex: 1,
1500
+ },
1501
+ submitAction: "addSecondaryCtaIos",
1502
+ supportedEvents: ["addSecondaryCtaIos"],
1503
+ },
1504
+ ],
1505
+ };
1506
+ } else {
1507
+ if (child.inputFields[fieldIndex] && child.inputFields[fieldIndex].cols[0] && child.inputFields[fieldIndex].cols[0].id === "add-sec-cta") {
1508
+ child.inputFields[fieldIndex] = {
1509
+ cols: [
1510
+ {
1511
+ id: "add-sec-cta",
1512
+ metaType: "label",
1513
+ value: this.props.intl.formatMessage(messages.addSecondaryCTA),
1514
+ primitive: true,
1515
+ dynamicTab: false,
1516
+ type: "div",
1517
+ style: {
1518
+ backgroundColor: 'white',
1519
+ textAlign: 'left',
1520
+ color: '#2673D7',
1521
+ lineHeight: '24px',
1522
+ fontSize: '14px',
1523
+ marginTop: '16px',
1524
+ fontWeight: '600',
1525
+ fontFamily: 'open-sans',
1526
+ fontStyle: 'normal',
1527
+ cursor: 'pointer',
1528
+ },
1529
+ offset: 0,
1530
+ onlyDisplay: true,
1531
+ colStyle: {
1532
+ flex: 1,
1533
+ },
1534
+ submitAction: "addSecondaryCta",
1535
+ supportedEvents: ['addSecondaryCta'],
1536
+ fieldsLimit: 2,
1537
+ fieldsCount: 0,
1538
+ },
1539
+ ],
1540
+ };
1541
+ }
1542
+ if (id === "secondary-cta-1-delete" || child.inputFields[fieldIndex].cols[0].id === "cta-label" || child.inputFields[fieldIndex].cols[0].id === "secondary-cta-1-space") {
1543
+ let nextFieldIndex = fieldIndex;
1544
+ if (id === "secondary-cta-1-delete" || child.inputFields[fieldIndex].cols[0].id === "secondary-cta-1-space") {
1545
+ nextFieldIndex = child.inputFields.length;
1546
+ }
1547
+ child.inputFields[nextFieldIndex] = {
1548
+ cols: [
1549
+ {
1550
+ id: "add-sec-cta",
1551
+ metaType: "label",
1552
+ value: this.props.intl.formatMessage(messages.addAnotherCTA),
1553
+ primitive: true,
1554
+ dynamicTab: false,
1555
+ type: "div",
1556
+ style: {
1557
+ backgroundColor: 'white',
1558
+ textAlign: 'left',
1559
+ color: '#2673D7',
1560
+ lineHeight: '24px',
1561
+ fontSize: '14px',
1562
+ fontWeight: '600',
1563
+ fontFamily: 'open-sans',
1564
+ fontStyle: 'normal',
1565
+ cursor: 'pointer',
1566
+ },
1567
+ offset: 0,
1568
+ onlyDisplay: true,
1569
+ colStyle: {
1570
+ flex: 1,
1571
+ },
1572
+ submitAction: "addSecondaryCta",
1573
+ supportedEvents: ['addSecondaryCta'],
1574
+ fieldsLimit: 2,
1575
+ fieldsCount: 1,
1576
+ },
1577
+ ],
1578
+ };
1579
+ }
1580
+ }
1581
+ }
1582
+ });
1583
+ }
1584
+ });
1585
+ }
1586
+ });
1587
+ });
1588
+ });
1589
+ });
1590
+ });
1591
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, formData, isSchemaChanged: true});
1592
+ this.injectEvents(schema);
1593
+ };
1594
+
1595
+
1596
+ startTemplateCreation = (data) => {
1597
+ if (!this.state.isContentEditLoaded && this.state.fullSchema && this.props.Edit.weCrmAccounts) {
1598
+ const schema = JSON.stringify(data).indexOf("BIG_PICTURE") > -1 ? this.state.fullSchema.imageSchema : this.state.fullSchema.textSchema;
1599
+ this.setMobilePushAccountOptions(this.props.Edit.weCrmAccounts, data.content.accId);
1600
+ this.setState({schema, isContentEditLoaded: true, loadingContentEdit: true}, () => {
1601
+ this.injectEvents(this.state.schema);
1602
+ let editData = data.content;
1603
+ editData = editData.versions && editData.versions.base ? editData : {versions: {base: editData}};
1604
+ this.setEditState(editData, this.state.schema);
1605
+ });
1606
+ }
1607
+ if (data.tags) {
1608
+ this.props.globalActions.setInjectedTags(data.tags);
1609
+ }
1610
+ };
1611
+ discardValues = () => {
1612
+ this.resetSchema();
1613
+ this.setState({
1614
+ formData: {},
1615
+ tabCount: 1,
1616
+ currentTab: 1,
1617
+ editData: {},
1618
+ }, () => {
1619
+ const schema = this.props.Edit.templateDetails.mode === "image" ? this.state.fullSchema.imageSchema : this.state.fullSchema.textSchema;
1620
+ this.setEditState(this.props.Edit.templateDetails, schema);
1621
+ });
1622
+ };
1623
+ resetSchema = () => {
1624
+ this.setState({ schema: this.state.initialState ? this.state.initialState : this.state.schema});
1625
+ };
1626
+ showNext = () => {
1627
+ const response = {
1628
+ action: "showNext",
1629
+ value: true,
1630
+ };
1631
+ parent.postMessage(JSON.stringify(response), '*');
1632
+ };
1633
+ copyContent = () => {
1634
+
1635
+ };
1636
+ moveToTemplates = () => {
1637
+ const modalContent = {
1638
+ title: this.props.intl.formatMessage(messages.alertMessage),
1639
+ body: this.props.intl.formatMessage(messages.goBackTemporaryChangesLost),
1640
+ type: 'confirm',
1641
+ id: 'template-back-confirm-modal',
1642
+ show: true,
1643
+ };
1644
+ this.setState({modalContent, showModal: true});
1645
+ };
1646
+ injectSections = (sections) => {
1647
+ _.forEach(sections, (section) => {
1648
+ let temp = section;
1649
+ if (temp.type === 'col-label') {
1650
+ temp = this.injectColLabelSection(temp);
1651
+ } else if (section.type === 'multicols') {
1652
+ temp = this.injectMultiColSection(temp);
1653
+ } else if (section.type === 'parent') {
1654
+ temp = this.injectSections(temp.childSections);
1655
+ }
1656
+ });
1657
+ return sections;
1658
+ };
1659
+ injectMultiColSection = (section) => {
1660
+ const { formatMessage } = this.props.intl;
1661
+ _.forEach(section.inputFields, (inputField) => {
1662
+ _.forEach(inputField.cols, (col) => {
1663
+ const temp = col;
1664
+ if (temp.type === 'popover') {
1665
+ temp.content.sections = this.injectSections(temp.content.sections);
1666
+ temp.value.sections = this.injectSections(temp.value.sections);
1667
+ return true;
1668
+ }
1669
+
1670
+ if (messages?.[temp?.value]) {
1671
+ temp.value = formatMessage(messages[temp.value]);
1672
+ }
1673
+ if (messages?.[temp?.label]) {
1674
+ temp.label = formatMessage(messages[temp.label]);
1675
+ }
1676
+ if (messages?.[temp?.errorMessage]) {
1677
+ temp.errorMessage = formatMessage(messages[temp.errorMessage]);
1678
+ }
1679
+ if (messages?.[temp?.placeholder]) {
1680
+ temp.placeholder = formatMessage(messages[temp.placeholder]);
1681
+ }
1682
+ if (messages?.[temp?.hoverText]) {
1683
+ temp.hoverText = formatMessage(messages[temp.hoverText]);
1684
+ }
1685
+ if (messages?.[temp?.previewProps?.label]) {
1686
+ temp.previewProps.label = formatMessage(messages[temp.previewProps.label]);
1687
+ }
1688
+ if (messages?.[temp?.previewProps?.inductiveText]) {
1689
+ temp.previewProps.inductiveText = formatMessage(messages[temp.previewProps.inductiveText]);
1690
+ }
1691
+ if (messages?.[temp?.previewProps?.errorMessage]) {
1692
+ temp.previewProps.errorMessage = formatMessage(messages[temp.previewProps.errorMessage]);
1693
+ }
1694
+
1695
+ temp.injectedEvents = {};
1696
+ temp.className = temp.className ? temp.className : '';
1697
+
1698
+ // if (this.props.location.query.type === 'embedded' && (temp.type === "input" || temp.type === "textarea" || temp.type === "radioGroup") && this.props.location.query.module !== "dvs") {
1699
+ // temp.className = `${temp.className} disabled`;
1700
+ // temp.disabled = true;
1701
+ // }
1702
+ if (this.props.location.query.type === 'embedded' && temp.id === "mobilepush-template" ) {
1703
+ temp.options = this.state.templateOptions ? this.state.templateOptions : [];
1704
+ }
1705
+ if (this.props.location.query.type === 'embedded' && temp.id === "mobilepush-accounts" ) {
1706
+ temp.options = this.state.templateOptions ? this.state.accountsOptions : [];
1707
+ }
1708
+ if (temp.id === "mobile-push-preview") {
1709
+ const { location, creativesMode, Edit: EditProps, Templates } = this.props || {};
1710
+ const { query } = location || {};
1711
+ const { selectedWeChatAccount: editSelectedWeChatAccount } = EditProps || {};
1712
+ const { selectedWeChatAccount: templateSelectedWeChatAccount } = Templates || {};
1713
+ const queryType = String(get(query, 'type', ''))?.toLowerCase();
1714
+ const mode = String(creativesMode).toLowerCase();
1715
+ if (isEmbeddedEditOrPreview(queryType, mode) && !_.isEmpty(editSelectedWeChatAccount)) {
1716
+ temp.content.appName = editSelectedWeChatAccount?.name;
1717
+ } else if (!_.isEmpty(templateSelectedWeChatAccount)) {
1718
+ temp.content.appName = templateSelectedWeChatAccount?.name;
1719
+ }
1720
+ }
1721
+ _.forEach(col.supportedEvents, (event) => {
1722
+ temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
1723
+ });
1724
+ return true;
1725
+ });
1726
+ });
1727
+ _.forEach(section.actionFields, (actionField) => {
1728
+ _.forEach(actionField.cols, (col) => {
1729
+ const temp = col;
1730
+ // temp.disabled = this.props.location.query.type === 'embedded' && this.props.location.query.module !== "dvs";
1731
+ if (temp.type === 'popover') {
1732
+ temp.content.sections = this.injectSections(temp.content.sections);
1733
+ temp.value.sections = this.injectSections(temp.value.sections);
1734
+ return true;
1735
+ }
1736
+ temp.injectedEvents = {};
1737
+ _.forEach(col.supportedEvents, (event) => {
1738
+ temp.injectedEvents[event] = this.getMappedEvent(col.id, event);
1739
+ });
1740
+ return true;
1741
+ });
1742
+ });
1743
+ return section;
1744
+ };
1745
+
1746
+ saveFormData = (formData) => {
1747
+ // Check for personalization tokens if restriction is enabled
1748
+ if (this.props.restrictPersonalization) {
1749
+ const hasTokens = checkForPersonalizationTokens(formData);
1750
+ if (hasTokens) {
1751
+ const message = this.props.intl.formatMessage(messages.personalizationTokensErrorMessage);
1752
+ CapNotification.error({message, key: 'personalizationTokensError'});
1753
+ return;
1754
+ }
1755
+ }
1756
+
1757
+ const obj = this.getTransformedData(formData);
1758
+
1759
+ this.props.actions.editTemplate(obj, this.onUpdateTemplateComplete);
1760
+ };
1761
+
1762
+ handleFrameTasks = (e) => {
1763
+ //
1764
+ const type = e.data;
1765
+
1766
+ if (typeof type === 'object') {
1767
+ //
1768
+ const action = type.action;
1769
+ switch (action) {
1770
+ case "startTemplateCreation":
1771
+ this.startTemplateCreation(type.value);
1772
+ break;
1773
+ case "startLoading":
1774
+ this.startLoading(type.edit);
1775
+ break;
1776
+ case "getCurrentWindow":
1777
+ this.getCurrentWindow(type);
1778
+ break;
1779
+ default:
1780
+ break;
1781
+ }
1782
+ } else {
1783
+ switch (type) {
1784
+ case "getFormData":
1785
+ this.getFormData(e);
1786
+ break;
1787
+ case "startTemplateCreation":
1788
+
1789
+ //this.getFormData(e);
1790
+ break;
1791
+ case "moveToTemplates":
1792
+
1793
+ this.moveToTemplates();
1794
+ break;
1795
+ case "validateContent":
1796
+
1797
+ this.validateContent(e);
1798
+ break;
1799
+ default:
1800
+ break;
1801
+ }
1802
+ }
1803
+ };
1804
+
1805
+ cancelTemplate = () => {
1806
+ const type = this.props.location.query.type;
1807
+ const module = this.props.location.query.module ? this.props.location.query.module : 'default';
1808
+ this.props.router.push({
1809
+ pathname: `/mobilepush/`,
1810
+ query: type === 'embedded' ? {type: 'embedded', module} : {module},
1811
+ });
1812
+ };
1813
+
1814
+ showCtaKeys = (eventTriggered, formData, field, tabIndex, schemaInput) => {
1815
+ const selectedWeChatAccount = this.getWeChatAccount();
1816
+ const currentTab = tabIndex || this.state.currentTab;
1817
+ const schema = _.cloneDeep(schemaInput || this.state.schema);
1818
+ const eventsMap = _.cloneDeep(this.state.eventsMap);
1819
+ let inputFields = get(schema, `containers[0].panes[${currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1820
+ const {id} = field;
1821
+ const fieldIndex = findIndex(inputFields, {identifier: id});
1822
+ const formDataKey = id.replace("-show-keys", "");
1823
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1824
+ let keys = selectedWeChatAccount ? _.filter(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (dl) => dl.link === formData[currentTab - 1][formDataKey]) : [];
1825
+ if (keys[0]) {
1826
+ keys = keys[0].keys;
1827
+ }
1828
+ _.map(keys, (key, index) => {
1829
+ const row = {
1830
+ rowClassName: 'mobile-push-row',
1831
+ id: 'cta-deeplink-keys',
1832
+ cols: [
1833
+ {
1834
+ id: `custom-value-${key}-${id}`,
1835
+ label: key.replace('_', " "),
1836
+ type: "input", //Resembles component to be used
1837
+ metaType: "text",
1838
+ datatype: "string",
1839
+ required: true,
1840
+ width: 18,
1841
+ offset: 1,
1842
+ placeholder: `${this.props.intl.formatMessage(messages.pleaseInput)} ${key.replace('_', " ")}.`,
1843
+ fluid: true,
1844
+ styling: "semantic",
1845
+ order: 1,
1846
+ customComponent: false,
1847
+ errorMessage: this.props.intl.formatMessage(messages.valueCantEmpty),
1848
+ },
1849
+ ],
1850
+ };
1851
+ inputFields.splice(fieldIndex + index + 1, 0, row);
1852
+ });
1853
+ if (!tabIndex) { // removes the existing selected options keys so that newly selected options keys can be added.
1854
+ const configkeys = _.filter(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (dl) => dl.link === this.state.formData[currentTab - 1][field.id]);
1855
+ if (configkeys.length) {
1856
+ const options = configkeys[0].keys;
1857
+ inputFields = inputFields.slice(0, fieldIndex + 1).concat(inputFields.slice(fieldIndex + options.length + 1, inputFields.length));
1858
+ // delete formData[self.state.currentTab - 1][`cta-deeplink-${id.replace('delete', 'select')}`];
1859
+ // delete formData[self.state.currentTab - 1][`cta-deeplink-${id.replace('-delete', '')}`];
1860
+ }
1861
+ }
1862
+ if (tabIndex) {
1863
+ return schema;
1864
+ }
1865
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, eventsMap, isSchemaChanged: true});
1866
+ this.injectEvents(schema);
1867
+ return schema;
1868
+ };
1869
+ addPrimaryCta = (flag, formData, field, inputSchema, currentTab) => {
1870
+ const selectedWeChatAccount = this.getWeChatAccount();
1871
+ const id = field.id;
1872
+ const schema = inputSchema ? _.cloneDeep(inputSchema) : _.cloneDeep(this.state.schema);
1873
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1874
+ const deepLinkOptions = selectedWeChatAccount ? _.map(safeParseDeeplinkConfig(ck ? selectedWeChatAccount?.configs?.deeplink : '[]'), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
1875
+ // const eventsMap = _.cloneDeep(this.state.eventsMap);
1876
+ const tabIndex = currentTab || this.state.currentTab;
1877
+ const inputFields = get(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1878
+ const fieldIndex = findIndex(inputFields, {identifier: id});
1879
+ let newInputFields;
1880
+ if (formData[tabIndex - 1][id]) {
1881
+ newInputFields = this.getPrimaryCtaFields({inputFields, fieldIndex, deepLinkOptions, tab: currentTab});
1882
+ } else {
1883
+ const identifier = (tabIndex - 1) ? 'add-sec-cta-ios' : 'add-sec-cta';
1884
+ const indexOfNextField = findIndex(inputFields, {identifier});
1885
+ const deleteCount = indexOfNextField - fieldIndex;
1886
+ newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputFields.length)];
1887
+ }
1888
+ set(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
1889
+ if (inputSchema) {
1890
+ return schema;
1891
+ }
1892
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true}, () => {
1893
+ this.injectEvents(schema);
1894
+ });
1895
+ return schema;
1896
+ };
1897
+
1898
+ addSecondoryCta = (flag, formData, field, inputSchema, currentTab) => {
1899
+ const id = field.id;
1900
+ const tabIndex = currentTab || this.state.currentTab;
1901
+ const formDataCopy = cloneDeep(formData);
1902
+ const schema = inputSchema ? _.cloneDeep(inputSchema) : _.cloneDeep(this.state.schema);
1903
+ const selectedWeChatAccount = this.getWeChatAccount();
1904
+ const ck = selectedWeChatAccount?.configs ? !!selectedWeChatAccount.configs.deeplink : false;
1905
+ const deepLinkOptions = selectedWeChatAccount ? _.map(safeParseDeeplinkConfig(ck ? selectedWeChatAccount.configs.deeplink : '[]'), (link) => ({label: link.name, value: link.link, title: link.link }) ) : [];
1906
+ const inputFields = get(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1907
+ const fieldIndex = findIndex(inputFields, {identifier: id});
1908
+ let newInputFields;
1909
+ if (formData[tabIndex - 1][id]) {
1910
+ newInputFields = this.getSecondaryCtaFields({inputFields, fieldIndex, deepLinkOptions});
1911
+ } else {
1912
+ const identifier = id === "add-sec-cta" ? 'add-sec-cta-2' : null;
1913
+ const indexOfNextField = identifier ? findIndex(inputFields, {identifier}) : inputFields.length;
1914
+ const deleteCount = indexOfNextField - fieldIndex;
1915
+ newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputFields.length)];
1916
+ }
1917
+ if (id === "add-sec-cta") {
1918
+ //The following block of code enables and disables add secondary button based on the primary button
1919
+ const indexOfSecondary = findIndex(newInputFields, {identifier: 'add-sec-cta-2'});
1920
+ newInputFields[indexOfSecondary].cols[0].disabled = !formData[this.state.currentTab - 1][id];
1921
+ //Calling the following function to unset the data set under secondary button
1922
+ if (!formData[this.state.currentTab - 1][id]) {
1923
+ formDataCopy[this.state.currentTab - 1]['add-sec-cta-2'] = false;
1924
+ }
1925
+ set(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
1926
+ //Calling set state here to update the state and schema before manually triggering secondarycta update
1927
+ this.setState(
1928
+ {schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true},
1929
+ () => {
1930
+ this.injectEvents(schema);
1931
+ this.addSecondoryCta(true, formDataCopy, newInputFields[indexOfSecondary].cols[0]);
1932
+ });
1933
+ } else {
1934
+ set(schema, `containers[0].panes[${tabIndex - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
1935
+ if (inputSchema) {
1936
+ return schema;
1937
+ }
1938
+ this.setState({schema, initialState: this.state.initialState ? this.state.initialState : this.state.schema, isSchemaChanged: true});
1939
+ this.injectEvents(schema);
1940
+ }
1941
+ return schema;
1942
+ };
1943
+
1944
+ addSecondoryCtaIos = (flag, formData, schemaField) => {
1945
+ const id = schemaField.id;
1946
+ if (formData[this.state.currentTab - 1][id]) {
1947
+ const actionText = formData[this.state.currentTab - 1]['secondary-cta-1-action'];
1948
+ if (!this.props.iosCtasData) {
1949
+ if (!_.isEmpty(actionText)) {
1950
+ this.deleteSecondaryCtaIos();
1951
+ }
1952
+ const queryType = String(get(this.props, 'location.query.type', ''))?.toLowerCase();
1953
+ const creativesMode = String(get(this.props, 'creativesMode', ''))?.toLowerCase();
1954
+ if (isEmbeddedEditOrPreview(queryType, creativesMode)) {
1955
+ this.props.actions.getIosCtas(this.props.Edit.selectedWeChatAccount.sourceAccountIdentifier);
1956
+ } else {
1957
+ this.props.actions.getIosCtas(this.props.Templates.selectedWeChatAccount.sourceAccountIdentifier);
1958
+ }
1959
+ //TODO: need to get license code of accoutn and send as arg
1960
+ } else {
1961
+ this.deleteSecondaryCtaIos(() => { // oncick of change
1962
+ this.setState({showIosCtaTable: true});
1963
+ });
1964
+ }
1965
+ } else {
1966
+ const schema = cloneDeep(this.state.schema);
1967
+ const inputFields = get(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`);
1968
+ forEach(inputFields, (inputField, fieldIndex) => {
1969
+ forEach(inputField.cols, (col) => {
1970
+ if (col.id === id) {
1971
+ const indexOfNextField = inputFields.length;
1972
+ const deleteCount = indexOfNextField - fieldIndex;
1973
+ const newInputFields = [...inputFields.slice(0, fieldIndex + 1), ...inputFields.slice(fieldIndex + deleteCount, inputField.length)];
1974
+ set(schema, `containers[0].panes[${this.state.currentTab - 1}].sections[0].childSections[0].childSections[0].inputFields`, newInputFields);
1975
+ this.setState({schema});
1976
+ }
1977
+ });
1978
+ });
1979
+ }
1980
+ };
1981
+ handleClose = () => {
1982
+ const formData = cloneDeep(this.state.formData);
1983
+ formData[this.state.currentTab - 1]['add-sec-cta-ios'] = false;
1984
+ this.setState({showIosCtaTable: false, formData});
1985
+ }
1986
+
1987
+ // Get template content for TestAndPreviewSlidebox
1988
+ // MobilePush uses formData[0] for Android and formData[1] for iOS
1989
+ getTemplateContent = () => {
1990
+ if (!this.state.formData || this.state.formData.length < 2) {
1991
+ return {
1992
+ androidContent: {},
1993
+ iosContent: {},
1994
+ };
1995
+ }
1996
+
1997
+ const androidData = this.state.formData[0] || {};
1998
+ const iosData = this.state.formData[1] || {};
1999
+
2000
+ // Extract actions (buttons) - format similar to TemplatePreview
2001
+ const getActions = (data) => {
2002
+ const actions = [];
2003
+ // Primary CTA
2004
+ if (data['cta-deeplink-label']) {
2005
+ actions.push({
2006
+ label: data['cta-deeplink-label'],
2007
+ url: data['cta-deeplink-select'] || data['cta-deeplink-text'] || '',
2008
+ });
2009
+ }
2010
+ // Secondary CTA
2011
+ if (data['secondary-cta-0-label']) {
2012
+ actions.push({
2013
+ label: data['secondary-cta-0-label'],
2014
+ url: data[`cta-deeplink-secondary-cta-0-select`] || data[`cta-deeplink-secondary-cta-0-text`] || '',
2015
+ });
2016
+ }
2017
+ if (data['secondary-cta-1-label']) {
2018
+ actions.push({
2019
+ label: data['secondary-cta-1-label'],
2020
+ url: data[`cta-deeplink-secondary-cta-1-select`] || data[`cta-deeplink-secondary-cta-1-text`] || '',
2021
+ });
2022
+ }
2023
+ return actions;
2024
+ };
2025
+
2026
+ return {
2027
+ androidContent: {
2028
+ header: androidData['message-title'] || '',
2029
+ bodyText: androidData['message-editor'] || '',
2030
+ bodyImage: androidData.image || '',
2031
+ actions: getActions(androidData),
2032
+ carouselData: [], // MobilePush carousel support can be added later if needed
2033
+ },
2034
+ iosContent: {
2035
+ header: iosData['message-title2'] || '',
2036
+ bodyText: iosData['message-editor2'] || '',
2037
+ bodyImage: iosData['image-upload-ios'] || '',
2038
+ actions: getActions(iosData),
2039
+ carouselData: [], // MobilePush carousel support can be added later if needed
2040
+ },
2041
+ };
2042
+ }
2043
+
2044
+ handleTestAndPreview = () => {
2045
+ if (this.props.handleTestAndPreview) {
2046
+ this.props.handleTestAndPreview();
2047
+ }
2048
+ }
2049
+ injectContainer = (container) => {
2050
+ const temp = container;
2051
+ if (temp.type === 'tabs') {
2052
+ temp.injectedEvents = {};
2053
+ _.forEach(temp.supportedEvents, (event) => {
2054
+ temp.injectedEvents[event] = this.getMappedEvent(temp.id, event);
2055
+ });
2056
+ _.forEach(temp.panes, (pane) => {
2057
+ const tempPane = pane;
2058
+ tempPane.sectionsHeaders = this.injectSections(tempPane.sectionsHeaders);
2059
+ tempPane.sections = this.injectSections(tempPane.sections);
2060
+ });
2061
+ }
2062
+ return temp;
2063
+ };
2064
+
2065
+ injectEvents = (schema = {}) => {
2066
+ const temp = schema;
2067
+ if (this.injectSections && temp.standalone) {
2068
+ temp.standalone.sections = this.injectSections(temp.standalone.sections);
2069
+ }
2070
+ _.forEach(temp.containers, (container) => {
2071
+ let tempContainer = container;
2072
+ tempContainer = this.injectContainer(tempContainer);
2073
+ return tempContainer;
2074
+ });
2075
+
2076
+ this.setState({schema, loadingContentEdit: false}, () => {
2077
+ this.removeStandAlone();
2078
+ });
2079
+ return schema;
2080
+ };
2081
+ removeStandAlone = () => {
2082
+ const schema = _.cloneDeep(this.state.schema);
2083
+ const {isFullMode} = this.props;
2084
+ if (this.props.location.query.type === 'embedded' && this.props.location.query.module === 'loyalty') {
2085
+ if (schema.standalone.sections.length === 2) {
2086
+ schema.standalone.sections.splice(0, 1);
2087
+ }
2088
+ } else if ((this.props.location.query.type === 'embedded' && typeof this.props.location.query.module !== 'undefined') || isFullMode) {
2089
+ delete schema.standalone;
2090
+ } else {
2091
+ schema.standalone.sections.splice(1, 1);
2092
+ }
2093
+ this.setState({ schema });
2094
+ };
2095
+ handleOnTagsContextChange = (data) => {
2096
+ const context = (data || '').toLowerCase() === 'all' ? 'default' : (data || '').toLowerCase();
2097
+ if (this.lastFetchedTagContextRef === context) {
2098
+ return;
2099
+ }
2100
+ this.lastFetchedTagContextRef = context;
2101
+ const query = {
2102
+ layout: 'mobilepush',
2103
+ type: 'TAG',
2104
+ context,
2105
+ embedded: this.props.location.query.type === 'embedded' ? this.props.location.query.type : 'full',
2106
+ };
2107
+ this.props.globalActions.fetchSchemaForEntity(query);
2108
+ };
2109
+ startValidation = () => {
2110
+ this.setState({startValidation: true});
2111
+ }
2112
+ stopValidation = () => {
2113
+
2114
+ this.setState({startValidation: false}, () => {
2115
+ this.showError();
2116
+ this.props.onValidationFail();
2117
+ });
2118
+ }
2119
+
2120
+ handleEditSchemaOnPropsChange = (nextProps, selectedWeChatAccount) => {
2121
+ const templateDetails = nextProps.templateDetails || nextProps.templateData;
2122
+ const queryType = String(get(this.props, 'location.query.type', ''))?.toLowerCase();
2123
+ const isEmbeddedLibrary = queryType === EMBEDDED && !nextProps.isFullMode;
2124
+ const canSetAccountFromTemplate =
2125
+ (_.isEmpty(selectedWeChatAccount) || !selectedWeChatAccount?.configs) &&
2126
+ templateDetails?.definition?.accountId &&
2127
+ nextProps.Edit?.weCrmAccounts?.length > 0;
2128
+ const hasAccountOrEmbedded =
2129
+ !_.isEmpty(selectedWeChatAccount) ||
2130
+ isEmbeddedLibrary ||
2131
+ canSetAccountFromTemplate ||
2132
+ !nextProps.isFullMode ||
2133
+ queryType === EMBEDDED;
2134
+ const hasTemplateDetails = !_.isEmpty(templateDetails);
2135
+ const hasEditData = !_.isEmpty(this.state.editData);
2136
+ const hasFullSchema = !_.isEmpty(this.state.fullSchema);
2137
+ const locationCheck = (this.props.location.query.type !== 'embedded' || this.props.isFullMode === false || queryType === EMBEDDED);
2138
+ const canPopulateForm =
2139
+ hasTemplateDetails &&
2140
+ !hasEditData &&
2141
+ hasFullSchema &&
2142
+ locationCheck &&
2143
+ hasAccountOrEmbedded;
2144
+ if (canPopulateForm) {
2145
+ this.props = nextProps;
2146
+ if (canSetAccountFromTemplate) {
2147
+ this.setMobilePushAccountOptions(nextProps.Edit.weCrmAccounts, templateDetails.definition.accountId);
2148
+ }
2149
+ const mode = templateDetails.definition ? templateDetails.definition.mode : templateDetails.mode;
2150
+ const schema = mode === "text" ? this.state.fullSchema?.textSchema : this.state.fullSchema?.imageSchema;
2151
+ if (!schema) return;
2152
+ const configs = nextProps.Templates?.selectedWeChatAccount?.configs || {};
2153
+ const hasExplicitConfigs = !_.isEmpty(configs) && ('android' in configs || 'ios' in configs);
2154
+ const isAndroidSupported = hasExplicitConfigs ? configs.android === '1' : true;
2155
+ const isIosSupported = hasExplicitConfigs ? configs.ios === '1' : true;
2156
+ if (!isAndroidSupported) {
2157
+ const androidField = get(schema, "containers[0].panes[0]");
2158
+ if (androidField) {
2159
+ androidField.isSupported = false;
2160
+ this.setState({currentTab: 2});
2161
+ set(schema, "containers[0].panes[0]", androidField);
2162
+ }
2163
+ }
2164
+ if (!isIosSupported) {
2165
+ const iosField = get(schema, "containers[0].panes[1]");
2166
+ if (iosField) {
2167
+ iosField.isSupported = false;
2168
+ set(schema, "containers[0].panes[1]", iosField);
2169
+ }
2170
+ }
2171
+ const dataToUse = this.normalizeTemplateDataForEdit(templateDetails);
2172
+ if (dataToUse?.versions?.base) {
2173
+ this.setEditState(dataToUse, schema);
2174
+ this.getTags();
2175
+ } else {
2176
+ console.warn('[MobliPushEdit] Skipped setEditState - dataToUse.versions.base missing', { dataToUse });
2177
+ }
2178
+ }
2179
+ };
2180
+
2181
+ normalizeTemplateDataForEdit = (data) => {
2182
+ if (!data) return null;
2183
+ if (data.versions?.base) return data;
2184
+ if (data.content?.versions?.base) {
2185
+ return { ...data, versions: data.content.versions };
2186
+ }
2187
+ const baseContent = data.content || {};
2188
+ if (baseContent.ANDROID || baseContent.IOS) {
2189
+ return {
2190
+ ...data,
2191
+ versions: { base: baseContent },
2192
+ name: data.name || data.templateName || '',
2193
+ definition: data.definition || {},
2194
+ mode: data.mode || data.definition?.mode || 'text',
2195
+ };
2196
+ }
2197
+ return data;
2198
+ }
2199
+
2200
+ render() {
2201
+ const queryType = String(get(this.props, 'location.query.type', ''))?.toLowerCase();
2202
+ const isEmbeddedOrLibrary = queryType === 'embedded' || this.props.isFullMode === false;
2203
+ const hasFormContent = !_.isEmpty(this.state.formData) && !_.isEmpty(this.state.schema);
2204
+ const showFormBuilder = !this.props.isLoadingMetaEntities || hasFormContent;
2205
+ const schema = this.state.schema;
2206
+ const loadingContentEdit = this.state.loadingContentEdit || (this.props.location.query.module === 'dvs' && _.isEmpty(this.state.schema));
2207
+ const metaEntitiesBlockSpinner = hasFormContent;
2208
+ const spinning = get(this.props, "Edit.fetchingWeCrmAccounts") || (!metaEntitiesBlockSpinner && this.props.isLoadingMetaEntities) || loadingContentEdit || this.props.Edit.fetchingDefaultTemplates || this.props.Edit.assetUploading || this.state.loading || (this.props.Edit && (("getTemplateDetailsInProgress" in this.props.Edit && this.props.Edit.getTemplateDetailsInProgress) || ("editTemplateInProgress" in this.props.Edit && this.props.Edit.editTemplateInProgress)));
2209
+ let tags = this.props.metaEntities && this.props.metaEntities.tags ? this.props.metaEntities.tags.standard : [];
2210
+ if (this.props.supportedTags) {
2211
+ tags = this.props.supportedTags;
2212
+ }
2213
+ return (
2214
+ <div className="creatives-mobilepush-edit mobilepush-wrapper">
2215
+ <CapSpin spinning={spinning}>
2216
+ <CapRow>
2217
+ <CapColumn>
2218
+ {(() => {
2219
+ if (isEmbeddedOrLibrary && !showFormBuilder && hasFormContent) {
2220
+ console.warn('[MobliPushEdit] FormBuilder HIDDEN (isLoadingMetaEntities=true) but formData+schema exist');
2221
+ }
2222
+ return showFormBuilder && <FormBuilder
2223
+ channel={MOBILE_PUSH}
2224
+ schema={schema}
2225
+ showLiquidErrorInFooter={this.props.showLiquidErrorInFooter}
2226
+ onSubmit={this.saveFormData}
2227
+ onChange={this.onFormDataChange}
2228
+ formData={_.cloneDeep(this.state.formData)}
2229
+ currentTab={this.state.currentTab}
2230
+ parent={this}
2231
+ location={this.props.location}
2232
+ isEdit
2233
+ tabCount={2}
2234
+ iosCtasData={this.state.iosCtasData}
2235
+ tags={tags}
2236
+ injectedTags={this.props.injectedTags ? this.props.injectedTags : {}}
2237
+ onFormValidityChange={this.setFormValidity}
2238
+ usingTabContainer
2239
+ checkValidation={this.state.checkValidation}
2240
+ onContextChange={this.handleOnTagsContextChange}
2241
+ showModal={this.state.showModal}
2242
+ iframeParent={parent}
2243
+ router={this.props.router}
2244
+ isSchemaChanged={this.state.isSchemaChanged}
2245
+ handleCancelModal={this.handleCancelModal}
2246
+ modal={this.state.modalContent}
2247
+ setModalContent={this.setModalContent}
2248
+ startValidation={this.state.startValidation}
2249
+ stopValidation={this.stopValidation}
2250
+ selectedOfferDetails={this.props.selectedOfferDetails}
2251
+ onPreviewContentClicked={this.props.onPreviewContentClicked}
2252
+ onTestContentClicked={this.props.onTestContentClicked}
2253
+ templateData={this.props.templateData}
2254
+ hideTestAndPreviewBtn={this.props.hideTestAndPreviewBtn}
2255
+ isFullMode={this.props.isFullMode}
2256
+ eventContextTags={this.props?.eventContextTags}
2257
+ waitEventContextTags={this.props?.waitEventContextTags}
2258
+ restrictPersonalization={this.props.restrictPersonalization}
2259
+ />;
2260
+ })()}
2261
+ </CapColumn>
2262
+ {this.props.iosCtasData && this.state.showIosCtaTable &&
2263
+ <CapSlideBox
2264
+ size="size-l"
2265
+ header={<CapHeader
2266
+ title={<FormattedMessage {...messages.selectActionButton} />}
2267
+ prefix={
2268
+ <PrefixWrapper>
2269
+ <CapIcons.BackIcon onClick={this.handleClose} />
2270
+ </PrefixWrapper>
2271
+ }
2272
+
2273
+ />}
2274
+ content={<CapTable
2275
+ rowSelection={{
2276
+ type: 'radio',
2277
+ onSelect: (record) => {
2278
+ this.setState({templateCta: record, showIosCtaTable: false}, () => this.selectCtaIos(record));
2279
+ },
2280
+ }}
2281
+ dataSource={this.props.iosCtasData} columns={[
2282
+ {
2283
+ title: this.props.intl.formatMessage(messages.nameAndDescription),
2284
+ dataIndex: "name",
2285
+ key: "name",
2286
+ width: 200,
2287
+ render: (text, record) => (
2288
+ <div>
2289
+ <div>{record.name}</div>
2290
+ <div>{record.description}</div>
2291
+ </div>),
2292
+ },
2293
+ {
2294
+ title: this.props.intl.formatMessage(messages.button1),
2295
+ dataIndex: "description",
2296
+ key: "button1",
2297
+ width: 100,
2298
+ render: (text, record) => (
2299
+ <div>
2300
+ {record.ctaTemplateDetails[0] && record.ctaTemplateDetails[0].buttonText}
2301
+ </div>),
2302
+ },
2303
+ {
2304
+ title: this.props.intl.formatMessage(messages.button2),
2305
+ dataIndex: "description",
2306
+ key: "button2",
2307
+ width: 100,
2308
+ render: (text, record) => (
2309
+ <div>
2310
+ {record.ctaTemplateDetails[1] ? record.ctaTemplateDetails[1].buttonText : ''}
2311
+ </div>
2312
+ ),
2313
+ },
2314
+ ]}
2315
+ />}
2316
+ show={this.state.showIosCtaTable}
2317
+ handleClose={this.handleClose}
2318
+ />
2319
+ }
2320
+ </CapRow>
2321
+ </CapSpin>
2322
+ <TestAndPreviewSlidebox
2323
+ show={this.props.showTestAndPreviewSlidebox || false}
2324
+ onClose={this.props.handleCloseTestAndPreview}
2325
+ formData={this.state.formData} // Pass actual formData for payload building
2326
+ content={this.getTemplateContent()} // Also pass content for preview
2327
+ currentChannel={MOBILE_PUSH}
2328
+ accountId={this.props.Templates?.selectedWeChatAccount?.id || this.props.Edit?.selectedWeChatAccount?.id || null} // Pass selected account ID for test message payload
2329
+ />
2330
+ </div>
2331
+ );
2332
+ }
2333
+ }
2334
+
2335
+ Edit.propTypes = {
2336
+ actions: PropTypes.object.isRequired,
2337
+ Edit: PropTypes.object,
2338
+ params: PropTypes.object,
2339
+ router: PropTypes.object,
2340
+ location: PropTypes.object,
2341
+ globalActions: PropTypes.object,
2342
+ templatesActions: PropTypes.object,
2343
+ Templates: PropTypes.object,
2344
+ metaEntities: PropTypes.object,
2345
+ templateDetails: PropTypes.object,
2346
+ intl: intlShape.isRequired,
2347
+ supportedTags: PropTypes.array,
2348
+ getDefaultTags: PropTypes.string,
2349
+ templateData: PropTypes.object,
2350
+ isFullMode: PropTypes.bool,
2351
+ iosCtasData: PropTypes.array,
2352
+ isLoadingMetaEntities: PropTypes.bool,
2353
+ injectedTags: PropTypes.object,
2354
+ defaultData: PropTypes.object,
2355
+ showTemplateName: PropTypes.func,
2356
+ getFormLibraryData: PropTypes.func,
2357
+ isGetFormData: PropTypes.bool,
2358
+ Create: PropTypes.object,
2359
+ onValidationFail: PropTypes.func,
2360
+ onPreviewContentClicked: PropTypes.func,
2361
+ onTestContentClicked: PropTypes.func,
2362
+ onContentValidityChange: PropTypes.func,
2363
+ creativesMode: PropTypes.string,
2364
+ eventContextTags: PropTypes.array,
2365
+ waitEventContextTags: PropTypes.object,
2366
+ getLiquidTags: PropTypes.func,
2367
+ showLiquidErrorInFooter: PropTypes.func,
2368
+ showTestAndPreviewSlidebox: PropTypes.bool,
2369
+ handleTestAndPreview: PropTypes.func,
2370
+ handleCloseTestAndPreview: PropTypes.func,
2371
+ restrictPersonalization: PropTypes.bool,
2372
+ isAnonymousType: PropTypes.bool,
2373
+ onPersonalizationTokensChange: PropTypes.func,
2374
+ };
2375
+
2376
+ const mapStateToProps = createStructuredSelector({
2377
+ Edit: makeSelectEdit(),
2378
+ Create: makeSelectCreate(),
2379
+ editResponse: makeSelectEditResponse(),
2380
+ templateDetails: makeSelectTemplateDetailsResponse(),
2381
+ metaEntities: makeSelectMetaEntities(),
2382
+ Templates: makeSelectTemplates(),
2383
+ iosCtasData: makeSelectIosCta(),
2384
+ isLoadingMetaEntities: isLoadingMetaEntities(),
2385
+ injectedTags: setInjectedTags(),
2386
+ });
2387
+
2388
+ function mapDispatchToProps(dispatch) {
2389
+ return {
2390
+ actions: bindActionCreators(actions, dispatch),
2391
+ templatesActions: bindActionCreators(templatesActions, dispatch),
2392
+ globalActions: bindActionCreators(globalActions, dispatch),
2393
+ };
2394
+ }
2395
+
2396
+
2397
+ const withSaga = injectSaga({ key: 'mobileEdit', saga: v2MobilePushEditSagas });
2398
+ const withReducer = injectReducer({ key: 'mobileEdit', reducer: v2MobilePushEditReducer });
2399
+
2400
+ export default withCreatives({
2401
+ WrappedComponent: Edit,
2402
+ mapStateToProps,
2403
+ mapDispatchToProps,
2404
+ userAuth: false,
2405
+ sagas: [withSaga],
2406
+ reducers: [withReducer],
2407
+ });