@capillarytech/creatives-library 9.2.4 → 9.2.5-beta.sprint-cap-214027-tags-ux-changes.56

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 (89) hide show
  1. package/constants/unified.js +14 -0
  2. package/package.json +1 -1
  3. package/services/api.js +33 -9
  4. package/services/tests/api.test.js +40 -0
  5. package/translations/en.json +1 -0
  6. package/translations/ja-JP.json +1 -0
  7. package/translations/zh.json +1 -0
  8. package/utils/common.js +7 -0
  9. package/utils/mockGroupedTags.js +44 -0
  10. package/utils/tagValidations.js +37 -4
  11. package/utils/tests/mockGroupedTags.test.js +59 -0
  12. package/utils/tests/tagValidations.test.js +63 -0
  13. package/v2Components/CapTagList/TagFallbackPanel.js +126 -0
  14. package/v2Components/CapTagList/constants.js +46 -0
  15. package/v2Components/CapTagList/index.js +247 -65
  16. package/v2Components/CapTagList/messages.js +68 -0
  17. package/v2Components/CapTagList/style.scss +302 -1
  18. package/v2Components/CapTagList/tests/FallbackRequired.test.js +48 -0
  19. package/v2Components/CapTagList/tests/TagDescription.test.js +301 -0
  20. package/v2Components/CapTagList/tests/TagFallback.test.js +255 -0
  21. package/v2Components/CapTagList/utils.js +98 -0
  22. package/v2Components/ErrorInfoNote/ErrorInfoNote.test.js +53 -0
  23. package/v2Components/ErrorInfoNote/index.js +32 -11
  24. package/v2Components/ErrorInfoNote/messages.js +4 -0
  25. package/v2Components/ErrorInfoNote/style.scss +4 -0
  26. package/v2Components/ErrorInfoNote/utils.js +3 -0
  27. package/v2Components/FormBuilder/Classic.js +29 -16
  28. package/v2Components/FormBuilder/Functional/channels/mobilepush/config.js +1 -0
  29. package/v2Components/FormBuilder/Functional/channels/mobilepush/getEditorErrorDescriptor.js +1 -1
  30. package/v2Components/FormBuilder/Functional/channels/mobilepush/tests/validate.test.js +69 -0
  31. package/v2Components/FormBuilder/Functional/channels/mobilepush/validate.js +4 -4
  32. package/v2Components/FormBuilder/Functional/channels/sms/getEditorErrorDescriptor.js +3 -0
  33. package/v2Components/FormBuilder/Functional/channels/sms/tests/getEditorErrorDescriptor.test.js +17 -0
  34. package/v2Components/FormBuilder/Functional/channels/sms/tests/validate.test.js +18 -0
  35. package/v2Components/FormBuilder/Functional/channels/sms/validate.js +3 -1
  36. package/v2Components/FormBuilder/Functional/renderers/mpushRenderers.js +3 -0
  37. package/v2Components/FormBuilder/Functional/renderers/smsRenderers.js +5 -2
  38. package/v2Components/FormBuilder/Functional/tests/mpushRenderers.test.js +22 -0
  39. package/v2Components/FormBuilder/Functional/tests/smsRenderers.test.js +1 -1
  40. package/v2Components/HighlightedTextArea/MessageTextArea.js +16 -0
  41. package/v2Components/HighlightedTextArea/constants.js +27 -0
  42. package/v2Components/HighlightedTextArea/index.js +148 -0
  43. package/v2Components/HighlightedTextArea/messages.js +18 -0
  44. package/v2Components/HighlightedTextArea/smsCounter.js +11 -0
  45. package/v2Components/HighlightedTextArea/style.scss +110 -0
  46. package/v2Components/HighlightedTextArea/tests/HighlightedTextArea.test.js +97 -0
  47. package/v2Components/HighlightedTextArea/utils.js +17 -0
  48. package/v2Components/HtmlEditor/components/ValidationTabs/__tests__/ValidationTabs.test.js +42 -0
  49. package/v2Components/HtmlEditor/components/ValidationTabs/_validationTabs.scss +4 -0
  50. package/v2Components/HtmlEditor/components/ValidationTabs/index.js +17 -3
  51. package/v2Components/HtmlEditor/components/ValidationTabs/messages.js +4 -0
  52. package/v2Components/HtmlEditor/utils/__tests__/renderIssueMessage.test.js +32 -40
  53. package/v2Components/HtmlEditor/utils/renderIssueMessage.js +31 -24
  54. package/v2Components/HtmlEditor/utils/renderLegacyIssueMessage.js +56 -0
  55. package/v2Components/HtmlEditor/utils/validationConstants.js +2 -0
  56. package/v2Components/LiquidGenerator/constants.js +5 -0
  57. package/v2Components/LiquidGenerator/index.js +154 -0
  58. package/v2Components/LiquidGenerator/messages.js +50 -0
  59. package/v2Components/LiquidGenerator/style.scss +160 -0
  60. package/v2Components/LiquidGenerator/tests/LiquidGenerator.test.js +107 -0
  61. package/v2Components/LiquidGenerator/utils.js +42 -0
  62. package/v2Containers/Cap/messages.js +4 -0
  63. package/v2Containers/Cap/mockdata/groupedStandardTags.json +17386 -0
  64. package/v2Containers/Cap/tests/__snapshots__/index.test.js.snap +1 -0
  65. package/v2Containers/Facebook/Advertisement/index.js +2 -1
  66. package/v2Containers/InApp/index.js +4 -1
  67. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/content.test.js.snap +3 -0
  68. package/v2Containers/Line/Container/ImageCarousel/tests/__snapshots__/index.test.js.snap +2 -0
  69. package/v2Containers/Line/Container/Text/index.js +5 -2
  70. package/v2Containers/Line/Container/Wrapper/tests/__snapshots__/index.test.js.snap +177 -125
  71. package/v2Containers/Line/Container/tests/__snapshots__/index.test.js.snap +18 -0
  72. package/v2Containers/MobilePushNew/index.js +4 -1
  73. package/v2Containers/Rcs/index.js +10 -2
  74. package/v2Containers/Rcs/tests/__snapshots__/index.test.js.snap +1258 -1034
  75. package/v2Containers/Sms/Create/index.js +5 -1
  76. package/v2Containers/Sms/Edit/index.js +5 -1
  77. package/v2Containers/SmsTrai/Create/tests/__snapshots__/index.test.js.snap +4 -0
  78. package/v2Containers/SmsTrai/Edit/index.js +13 -5
  79. package/v2Containers/SmsTrai/Edit/tests/__snapshots__/index.test.js.snap +15 -0
  80. package/v2Containers/TagList/index.js +8 -0
  81. package/v2Containers/TagList/tests/TagList.test.js +16 -6
  82. package/v2Containers/Viber/index.js +5 -2
  83. package/v2Containers/WebPush/Create/tests/contentValidity.test.js +1 -0
  84. package/v2Containers/WebPush/Create/tests/stayOpenOnSave.test.js +1 -0
  85. package/v2Containers/WebPush/Create/utils/validation.js +6 -0
  86. package/v2Containers/WebPush/Create/utils/validation.test.js +50 -0
  87. package/v2Containers/Whatsapp/index.js +11 -6
  88. package/v2Containers/Whatsapp/tests/__snapshots__/index.test.js.snap +2 -2
  89. package/v2Containers/Zalo/index.js +4 -1
@@ -160,6 +160,9 @@ export const UNSUBSCRIBE_TAG = 'unsubscribe';
160
160
  export const UNSUBSCRIBE_TAG_REGEX = new RegExp(`\\{\\{\\s*${UNSUBSCRIBE_TAG}\\s*\\}\\}`);
161
161
  /** Matches {{ ... }} and captures the inner tag content (for scanning content for tags). */
162
162
  export const TAG_CONTENT_REGEX = /{{([^}]+)}}/g;
163
+ // `default:` filter inside a tag, and the same filter with a quoted value e.g. default: 'x'
164
+ export const DEFAULT_FILTER_REGEX = /^\s*default\s*:/;
165
+ export const QUOTED_DEFAULT_REGEX = /^\s*default\s*:\s*('[^']*'|"[^"]*")\s*$/;
163
166
  export const ENTRY_TRIGGER_TAG_REGEX = /\bentryTrigger\.\w+(?:\.\w+)?(?:\(\w+\))?/g;
164
167
  /** Strips characters not allowed in a downloaded file name, keeping alphanumerics, `-`, `_` and spaces. */
165
168
  export const SAFE_FILE_NAME_REGEX = /[^a-zA-Z0-9-_ ]/g;
@@ -239,3 +242,14 @@ export const HTTP_METHODS = Object.freeze({
239
242
  PATCH: 'PATCH',
240
243
  DELETE: 'DELETE',
241
244
  });
245
+
246
+ // Temporary org feature flag for the personalization tags revamp (CAP-214027); remove once the backend support is released.
247
+ export const ENABLE_TAGS_REVAMP = 'ENABLE_TAGS_REVAMP';
248
+ // Query parameter of the tags request: the API returns the revamped tag names and groups only when it is sent, so a
249
+ // host that was not upgraded (or an org without the flag) keeps getting the old tag list
250
+ export const TAGS_REVAMP_QUERY_PARAM = 'tagsRevamp';
251
+
252
+ // Development-only: local storage key that turns on the mock of the regrouped standard tags (see utils/mockGroupedTags.js)
253
+ export const MOCK_GROUPED_TAGS_STORAGE_KEY = 'MOCK_GROUPED_TAGS';
254
+ export const TIMELINE_CONTEXT = 'timeline';
255
+ export const OUTBOUND_CONTEXT = 'outbound';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capillarytech/creatives-library",
3
3
  "author": "meharaj",
4
- "version": "9.2.4",
4
+ "version": "9.2.5-beta.sprint-cap-214027-tags-ux-changes.56",
5
5
  "description": "Capillary creatives ui",
6
6
  "main": "./index.js",
7
7
  "module": "./index.es.js",
package/services/api.js CHANGED
@@ -13,7 +13,9 @@ import getSchema from './getSchema';
13
13
  import * as API from '../utils/ApiCaller';
14
14
  import { addBaseToTemplate, transformCustomFieldsData } from '../utils/commonUtils';
15
15
  import { EMAIL, SMS, TRANSACTION } from '../v2Containers/CreativesContainer/constants';
16
- import { HTTP_METHODS } from '../constants/unified';
16
+ import { HTTP_METHODS, TAGS_REVAMP_QUERY_PARAM } from '../constants/unified';
17
+ import { hasTagsRevampEnabled } from '../utils/common';
18
+ import { isMockGroupedTagsEnabled, getMockStandardTags, buildMockTagsResponse } from '../utils/mockGroupedTags';
17
19
  import { getMockValidateQueryResponse } from '../v2Containers/CustomTags/mockdata/customTags';
18
20
  let API_ENDPOINT = config.development.api_endpoint;
19
21
  let EXPORT_API_ENDPOINT = config.development.exports_api_endpoint;
@@ -469,6 +471,35 @@ export const getUserList = () => {
469
471
  return API.get(url);// request(url, getAPICallObject('GET'));
470
472
  };
471
473
 
474
+ const requestTagMeta = async (queryParams) => {
475
+ // the revamped tag names and groups are only requested by an upgraded UI with the flag on
476
+ const tagMetaQuery = queryParams.type === 'TAG' && hasTagsRevampEnabled()
477
+ ? { ...queryParams, [TAGS_REVAMP_QUERY_PARAM]: true }
478
+ : queryParams;
479
+ const url = `${API_ENDPOINT}/meta/${queryParams.type}?query=${JSON.stringify(tagMetaQuery)}`;
480
+ const useMockTags = queryParams.type === 'TAG' && isMockGroupedTagsEnabled();
481
+ let result;
482
+ try {
483
+ result = await request(url, getAPICallObject('GET'));// request(url, getAPICallObject('GET'));
484
+ } catch (error) {
485
+ if (!useMockTags) throw error;
486
+ }
487
+ if (useMockTags) {
488
+ // development only: the regrouped standard tags are not deployed yet (see utils/mockGroupedTags.js)
489
+ if (result?.response?.metaEntities) {
490
+ result.response.metaEntities.standard = await getMockStandardTags(queryParams);
491
+ } else {
492
+ result = await buildMockTagsResponse(queryParams);
493
+ }
494
+ }
495
+ const customFields = get(result, 'response.metaEntities.custom', {});
496
+ if (customFields && Object.keys(customFields)?.length > 0) {
497
+ const transformedData = transformCustomFieldsData(customFields);
498
+ result.response.metaEntities.custom = transformedData;
499
+ }
500
+ return result;
501
+ };
502
+
472
503
  export const fetchSchemaForEntity = async ({queryParams}) => {
473
504
  if (queryParams.version === "v2" && queryParams.type === "LAYOUT") {
474
505
  const schema = getSchema(queryParams.layout);
@@ -477,14 +508,7 @@ export const fetchSchemaForEntity = async ({queryParams}) => {
477
508
  console.error(err);
478
509
  });
479
510
  }
480
- const url = `${API_ENDPOINT}/meta/${queryParams.type}?query=${JSON.stringify(queryParams)}`;
481
- const result = await request(url, getAPICallObject('GET'));// request(url, getAPICallObject('GET'));
482
- const customFields = get(result, 'response.metaEntities.custom', {});
483
- if (customFields && Object.keys(customFields)?.length > 0) {
484
- const transformedData = transformCustomFieldsData(customFields);
485
- result.response.metaEntities.custom = transformedData;
486
- }
487
- return result;
511
+ return requestTagMeta(queryParams);
488
512
  };
489
513
 
490
514
  export const fetchWeCrmAccounts = (sourceName) => {
@@ -1,3 +1,4 @@
1
+ import { hasTagsRevampEnabled } from '../../utils/common';
1
2
  import {
2
3
  getSenderDetails,
3
4
  getDomainProperties,
@@ -52,6 +53,10 @@ jest.mock('@capillarytech/cap-ui-utils', () => {
52
53
  });
53
54
 
54
55
  jest.mock('../getSchema', () => jest.fn());
56
+ jest.mock('../../utils/common', () => ({
57
+ ...jest.requireActual('../../utils/common'),
58
+ hasTagsRevampEnabled: jest.fn(),
59
+ }));
55
60
 
56
61
  describe('getSenderDetails -- Test with valid responses', () => {
57
62
  it('Should return correct response', () =>
@@ -559,6 +564,41 @@ describe('fetchSchemaForEntity', () => {
559
564
  });
560
565
  });
561
566
 
567
+ describe('fetchSchemaForEntity - tags revamp request', () => {
568
+ const requestedQuery = () => JSON.parse(decodeURIComponent(global.fetch.mock.calls[0][0].split('?query=')[1].split('&time=')[0]));
569
+
570
+ beforeEach(() => {
571
+ global.fetch = jest.fn().mockResolvedValue({
572
+ status: 200,
573
+ ok: true,
574
+ json: () => Promise.resolve({ response: { metaEntities: { standard: [] } } }),
575
+ headers: { get: () => 'application/json' },
576
+ });
577
+ });
578
+
579
+ afterEach(() => {
580
+ jest.restoreAllMocks();
581
+ });
582
+
583
+ it('asks the API for the revamped tags when the flag is on', async () => {
584
+ hasTagsRevampEnabled.mockReturnValue(true);
585
+ await fetchSchemaForEntity({ queryParams: { type: 'TAG', layout: 'SMS', context: 'outbound' } }).catch(() => {});
586
+ expect(requestedQuery()).toEqual(expect.objectContaining({ type: 'TAG', tagsRevamp: true }));
587
+ });
588
+
589
+ it('does not ask for the revamped tags when the flag is off', async () => {
590
+ hasTagsRevampEnabled.mockReturnValue(false);
591
+ await fetchSchemaForEntity({ queryParams: { type: 'TAG', layout: 'SMS', context: 'outbound' } }).catch(() => {});
592
+ expect(requestedQuery().tagsRevamp).toBeUndefined();
593
+ });
594
+
595
+ it('does not add the parameter to requests for other types', async () => {
596
+ hasTagsRevampEnabled.mockReturnValue(true);
597
+ await fetchSchemaForEntity({ queryParams: { type: 'LAYOUT', layout: 'SMS' } }).catch(() => {});
598
+ expect(requestedQuery().tagsRevamp).toBeUndefined();
599
+ });
600
+ });
601
+
562
602
  describe('Email Template APIs', () => {
563
603
  beforeEach(() => {
564
604
  global.fetch = jest.fn();
@@ -317,6 +317,7 @@
317
317
  "creatives.componentsV2.TopBar.profile": "Profile",
318
318
  "creatives.componentsV2.TopBar.settings": "Settings",
319
319
  "creatives.componentsV2.unbalanacedCurlyBraces": "Invalid label, please close all curly braces",
320
+ "creatives.componentsV2.unquotedTagDefaultValue": "Invalid label, default value must be within quotes",
320
321
  "creatives.componentsv2.MobilePushPreviewV2.header": "This is the MobilePushPreviewV2 component !",
321
322
  "creatives.containers.Assets.Gallery.alphabetically": "Alphabetically",
322
323
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "Image deletion failed.",
@@ -316,6 +316,7 @@
316
316
  "creatives.componentsV2.TopBar.profile": "",
317
317
  "creatives.componentsV2.TopBar.settings": "",
318
318
  "creatives.componentsV2.unbalanacedCurlyBraces": "",
319
+ "creatives.componentsV2.unquotedTagDefaultValue": "",
319
320
  "creatives.componentsv2.MobilePushPreviewV2.header": "",
320
321
  "creatives.containers.Assets.Gallery.alphabetically": "",
321
322
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "",
@@ -316,6 +316,7 @@
316
316
  "creatives.componentsV2.TopBar.profile": "",
317
317
  "creatives.componentsV2.TopBar.settings": "",
318
318
  "creatives.componentsV2.unbalanacedCurlyBraces": "",
319
+ "creatives.componentsV2.unquotedTagDefaultValue": "",
319
320
  "creatives.componentsv2.MobilePushPreviewV2.header": "",
320
321
  "creatives.containers.Assets.Gallery.alphabetically": "",
321
322
  "creatives.containers.Assets.Gallery.assetDeleteFailed": "",
package/utils/common.js CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  ENABLE_NEW_FORMBUILDER_SMS,
29
29
  ENABLE_NEW_FORMBUILDER_MPUSH,
30
30
  SUPPORT_ENGAGEMENT_MODULE,
31
+ ENABLE_TAGS_REVAMP,
31
32
  } from '../constants/unified';
32
33
  import { apiMessageFormatHandler } from './commonUtils';
33
34
 
@@ -114,6 +115,12 @@ export const hasJPLocaleHideFeatureEnabled = Auth.hasFeatureAccess.bind(
114
115
  JP_LOCALE_HIDE_FEATURE,
115
116
  );
116
117
 
118
+ export const hasTagsRevampEnabled = Auth.hasFeatureAccess.bind(
119
+ null,
120
+ ENABLE_TAGS_REVAMP,
121
+ );
122
+
123
+
117
124
  export const hasWechatFeatureEnabled = Auth.hasFeatureAccess.bind(
118
125
  null,
119
126
  ENABLE_WECHAT,
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Development-only mock of the regrouped standard tags (CAP-214027).
3
+ *
4
+ * The grouping lives in the cc-crm-bootstrap seed, which cannot be deployed to the shared environments yet.
5
+ * On the local dev server the standard tags of GET /meta/TAG are replaced by the tags of
6
+ * groupedStandardTags.json (generated from the seed by docs/personalization-tags-revamp/tools/make_mock_tags.py).
7
+ * Custom, extended and loyalty tags stay real when the API answers. If the API does not answer, the mock alone
8
+ * is used. `localStorage.setItem('MOCK_GROUPED_TAGS', 'false')` turns the mock off.
9
+ */
10
+ import { MOCK_GROUPED_TAGS_STORAGE_KEY, TIMELINE_CONTEXT, OUTBOUND_CONTEXT } from '../constants/unified';
11
+
12
+ export const isMockGroupedTagsEnabled = () => {
13
+ if (process.env.NODE_ENV !== 'development') return false;
14
+ try {
15
+ return window.localStorage.getItem(MOCK_GROUPED_TAGS_STORAGE_KEY) !== 'false';
16
+ } catch (error) {
17
+ return true;
18
+ }
19
+ };
20
+
21
+ // Same filter the tag API applies: the tag must support the requested context and layout
22
+ export const filterTagsBySupportedModules = (tags = [], context = '', layout = '') => {
23
+ const requestedContext = context.toLowerCase() === TIMELINE_CONTEXT ? OUTBOUND_CONTEXT : context.toLowerCase();
24
+ const requestedLayout = layout.toLowerCase();
25
+ return tags.filter((tag) => tag?.definition?.supportedModules?.some((moduleInfo) => (
26
+ moduleInfo?.context?.toLowerCase() === requestedContext && moduleInfo?.layout?.toLowerCase() === requestedLayout
27
+ )));
28
+ };
29
+
30
+ export const getMockStandardTags = async ({ context, layout }) => {
31
+ // loaded on demand so that the mock never ends up in the main bundle
32
+ const { default: mockTags } = await import(/* webpackChunkName: "mock-grouped-tags" */ '../v2Containers/Cap/mockdata/groupedStandardTags.json');
33
+ return filterTagsBySupportedModules(mockTags, context, layout);
34
+ };
35
+
36
+ // What the tag API returns when only the standard tags are available
37
+ export const buildMockTagsResponse = async (queryParams) => ({
38
+ success: true,
39
+ response: {
40
+ metaEntities: {
41
+ standard: await getMockStandardTags(queryParams), custom: {}, extended: {}, loyaltyTags: {},
42
+ },
43
+ },
44
+ });
@@ -8,7 +8,16 @@
8
8
 
9
9
  import lodashForEach from 'lodash/forEach';
10
10
  import lodashCloneDeep from 'lodash/cloneDeep';
11
- import { ENTRY_TRIGGER_TAG_REGEX, SKIP_TAGS_REGEX_GROUPS, TAG_CONTENT_REGEX, UNSUBSCRIBE_TAG, UNSUBSCRIBE_TAG_REGEX } from '../constants/unified';
11
+ import {
12
+ ENTRY_TRIGGER_TAG_REGEX,
13
+ SKIP_TAGS_REGEX_GROUPS,
14
+ TAG_CONTENT_REGEX,
15
+ UNSUBSCRIBE_TAG,
16
+ UNSUBSCRIBE_TAG_REGEX,
17
+ DEFAULT_FILTER_REGEX,
18
+ QUOTED_DEFAULT_REGEX,
19
+ } from '../constants/unified';
20
+ import { hasTagsRevampEnabled } from './common';
12
21
 
13
22
  const DEFAULT = 'default';
14
23
  const SUBTAGS = 'subtags';
@@ -89,9 +98,9 @@ export const validateTagsCore = ({
89
98
  }
90
99
 
91
100
  response.isBraceError = !validateIfTagClosed(contentForBraceCheck);
92
- if (response.isBraceError) {
93
- response.valid = false;
94
- } else if (response?.missingTags?.length > 0) {
101
+ // the `default:` filter check belongs to the tags revamp (fallback), so it is skipped when the revamp is off
102
+ response.isDefaultQuoteError = hasTagsRevampEnabled() && !response.isBraceError && hasUnquotedTagDefault(contentForBraceCheck);
103
+ if (response.isBraceError || response.isDefaultQuoteError || response?.missingTags?.length > 0) {
95
104
  response.valid = false;
96
105
  }
97
106
  return response;
@@ -203,6 +212,30 @@ export const validateIfTagClosed = (value) => {
203
212
  return (l1 == l2 && l2 == l3 && l1 == l3);
204
213
  };
205
214
 
215
+ // Splits a tag body into filters on `|` outside quotes (Liquid has no escaped quotes).
216
+ const splitTagFilters = (body) => {
217
+ const filters = [''];
218
+ let quote = null;
219
+ [...body].forEach((char) => {
220
+ if (quote) {
221
+ if (char === quote) quote = null;
222
+ } else if (char === "'" || char === '"') {
223
+ quote = char;
224
+ } else if (char === '|') {
225
+ filters.push('');
226
+ return;
227
+ }
228
+ filters[filters.length - 1] += char;
229
+ });
230
+ return filters;
231
+ };
232
+
233
+ // `default:` inside a {{ }} tag must be followed by a quoted value, e.g. {{tag | default: 'x'}}
234
+ export const hasUnquotedTagDefault = (value = '') =>
235
+ (String(value).match(/{{.*?}}/g) || []).some((tag) => splitTagFilters(tag.slice(2, -2))
236
+ .slice(1)
237
+ .some((filter) => DEFAULT_FILTER_REGEX.test(filter) && !QUOTED_DEFAULT_REGEX.test(filter)));
238
+
206
239
  //replaces encoded string with their respective characters
207
240
  export const preprocessHtml = (content) => {
208
241
  const replacements = {
@@ -0,0 +1,59 @@
1
+ import { filterTagsBySupportedModules, isMockGroupedTagsEnabled, buildMockTagsResponse } from '../mockGroupedTags';
2
+ import mockTags from '../../v2Containers/Cap/mockdata/groupedStandardTags.json';
3
+
4
+ const tag = (value, modules) => ({ definition: { value, supportedModules: modules } });
5
+
6
+ describe('filterTagsBySupportedModules', () => {
7
+ const tags = [
8
+ tag('sms_outbound', [{ context: 'outbound', layout: 'sms' }]),
9
+ tag('email_outbound', [{ context: 'outbound', layout: 'email' }]),
10
+ tag('sms_journey', [{ context: 'journey', layout: 'sms' }]),
11
+ tag('no_modules'),
12
+ ];
13
+
14
+ it('keeps the tags that support both the context and the layout', () => {
15
+ expect(filterTagsBySupportedModules(tags, 'outbound', 'sms').map((t) => t.definition.value)).toEqual(['sms_outbound']);
16
+ });
17
+
18
+ it('is case insensitive and treats the timeline context as outbound', () => {
19
+ expect(filterTagsBySupportedModules(tags, 'Timeline', 'SMS').map((t) => t.definition.value)).toEqual(['sms_outbound']);
20
+ });
21
+ });
22
+
23
+ describe('isMockGroupedTagsEnabled', () => {
24
+ afterEach(() => window.localStorage.clear());
25
+
26
+ it('stays off outside the development build', () => {
27
+ // jest runs with NODE_ENV=test
28
+ expect(isMockGroupedTagsEnabled()).toBe(false);
29
+ });
30
+
31
+ it('is on in the development build unless the key is "false"', () => {
32
+ const original = process.env.NODE_ENV;
33
+ process.env.NODE_ENV = 'development';
34
+ try {
35
+ expect(isMockGroupedTagsEnabled()).toBe(true);
36
+ window.localStorage.setItem('MOCK_GROUPED_TAGS', 'false');
37
+ expect(isMockGroupedTagsEnabled()).toBe(false);
38
+ } finally {
39
+ process.env.NODE_ENV = original;
40
+ }
41
+ });
42
+ });
43
+
44
+ describe('groupedStandardTags mock', () => {
45
+ it('only holds active tag documents that carry a definition value', () => {
46
+ expect(mockTags.length).toBeGreaterThan(0);
47
+ expect(mockTags.every((doc) => doc.type === 'TAG' && doc.isActive && doc.definition?.value)).toBe(true);
48
+ });
49
+ });
50
+
51
+ describe('buildMockTagsResponse', () => {
52
+ it('answers like the tag API with only the standard tags filled', async () => {
53
+ const response = await buildMockTagsResponse({ context: 'outbound', layout: 'sms' });
54
+ expect(response.success).toBe(true);
55
+ const { standard, custom, extended, loyaltyTags } = response.response.metaEntities;
56
+ expect(standard.length).toBeGreaterThan(0);
57
+ expect([custom, extended, loyaltyTags]).toEqual([{}, {}, {}]);
58
+ });
59
+ });
@@ -1,4 +1,14 @@
1
1
  import '@testing-library/jest-dom';
2
+ import { hasTagsRevampEnabled } from '../common';
3
+
4
+ jest.mock('../common', () => ({
5
+ ...jest.requireActual('../common'),
6
+ hasTagsRevampEnabled: jest.fn(),
7
+ }));
8
+
9
+ beforeEach(() => {
10
+ hasTagsRevampEnabled.mockReturnValue(true);
11
+ });
2
12
  import {
3
13
  hasUnsubscribeTag,
4
14
  validateTagsCore,
@@ -11,6 +21,7 @@ import {
11
21
  skipTags,
12
22
  checkIfSupportedTag,
13
23
  transformInjectedTags,
24
+ hasUnquotedTagDefault,
14
25
  } from '../tagValidations';
15
26
  import { containsBase64Images } from '../content';
16
27
 
@@ -193,6 +204,58 @@ describe("check if curly brackets are balanced", () => {
193
204
  })
194
205
  })
195
206
 
207
+ describe('hasUnquotedTagDefault', () => {
208
+ it('allows tags without default and defaults within quotes', () => {
209
+ expect(hasUnquotedTagDefault('{{badge_description}}')).toBe(false);
210
+ expect(hasUnquotedTagDefault("{{badge_description | default: ''}}")).toBe(false);
211
+ expect(hasUnquotedTagDefault("{{badge_description | default: 'Rafeeq'}}")).toBe(false);
212
+ expect(hasUnquotedTagDefault('{{badge_description | default: "Rafeeq\'s"}}')).toBe(false);
213
+ expect(hasUnquotedTagDefault("Hi {{a|default:' '}} {{b}} plain text")).toBe(false);
214
+ });
215
+
216
+ it('flags default with missing or unquoted value', () => {
217
+ expect(hasUnquotedTagDefault('{{badge_description | default: }}')).toBe(true);
218
+ expect(hasUnquotedTagDefault('{{badge_description | default: Rafeeq}}')).toBe(true);
219
+ expect(hasUnquotedTagDefault("{{badge_description | default: 'Rafeeq}}")).toBe(true);
220
+ expect(hasUnquotedTagDefault("{{a}} {{b | default: 'x' y}}")).toBe(true);
221
+ });
222
+
223
+ it('ignores pipes inside quotes and allows chained filters', () => {
224
+ expect(hasUnquotedTagDefault("{{name | replace: '| default:', 'x'}}")).toBe(false);
225
+ expect(hasUnquotedTagDefault("{{name | default: 'a | default: b'}}")).toBe(false);
226
+ expect(hasUnquotedTagDefault("{{name | default: 'a|b'}}")).toBe(false);
227
+ expect(hasUnquotedTagDefault("{{name | default: 'x' | append: '!'}}")).toBe(false);
228
+ expect(hasUnquotedTagDefault("{{name | append: 'x' | default: 'y'}}")).toBe(false);
229
+ });
230
+
231
+ it('rejects backslash-escaped quotes since Liquid has no escapes', () => {
232
+ expect(hasUnquotedTagDefault("{{name | default: 'it\\'s'}}")).toBe(true);
233
+ });
234
+ });
235
+
236
+ describe('validateTagsCore default quote check', () => {
237
+ const run = (content) => validateTagsCore({
238
+ contentForBraceCheck: content, contentForUnsubscribeScan: content, tags: null, currentModule: 'default', isFullMode: true,
239
+ });
240
+
241
+ it('marks unquoted default as invalid with isDefaultQuoteError', () => {
242
+ expect(run('{{name | default: Rafeeq}}')).toEqual(expect.objectContaining({ valid: false, isBraceError: false, isDefaultQuoteError: true }));
243
+ });
244
+
245
+ it('skips the default quote check when the tags revamp is disabled', () => {
246
+ hasTagsRevampEnabled.mockReturnValueOnce(false);
247
+ expect(run('{{name | default: Rafeeq}}')).toEqual(expect.objectContaining({ valid: true, isDefaultQuoteError: false }));
248
+ });
249
+
250
+ it('keeps quoted default valid', () => {
251
+ expect(run("{{name | default: 'Rafeeq'}}")).toEqual(expect.objectContaining({ valid: true, isDefaultQuoteError: false }));
252
+ });
253
+
254
+ it('reports only brace error when braces are not closed', () => {
255
+ expect(run('{{name | default: Rafeeq}')).toEqual(expect.objectContaining({ isBraceError: true, isDefaultQuoteError: false }));
256
+ });
257
+ });
258
+
196
259
  describe("validateTags", () => {
197
260
  const tagsParam = [
198
261
  {
@@ -0,0 +1,126 @@
1
+ /**
2
+ * TagFallbackPanel
3
+ *
4
+ * Shown in the tag list after a tag is clicked, to choose what is sent when the tag has no value.
5
+ */
6
+ import PropTypes from 'prop-types';
7
+ import React from 'react';
8
+ import CapButton from '@capillarytech/cap-ui-library/CapButton';
9
+ import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
10
+ import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
11
+ import CapInput from '@capillarytech/cap-ui-library/CapInput';
12
+ import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
13
+ import CapRadio from '@capillarytech/cap-ui-library/CapRadio';
14
+ import CapRadioGroup from '@capillarytech/cap-ui-library/CapRadioGroup';
15
+ import CapRow from '@capillarytech/cap-ui-library/CapRow';
16
+ import { injectIntl, intlShape } from 'react-intl';
17
+ import messages from './messages';
18
+ import { FALLBACK_OPTIONS } from './constants';
19
+ import { buildTagWithFallback, isValidFallbackValue } from './utils';
20
+
21
+ export class TagFallbackPanel extends React.Component {
22
+ constructor(props) {
23
+ super(props);
24
+ this.state = {
25
+ option: FALLBACK_OPTIONS.NONE,
26
+ fallbackValue: '',
27
+ };
28
+ }
29
+
30
+ onOptionChange = (e) => {
31
+ this.setState({ option: e.target.value });
32
+ };
33
+
34
+ onFallbackValueChange = (e) => {
35
+ this.setState({ fallbackValue: e.target.value });
36
+ };
37
+
38
+ getTagValue = () => {
39
+ const { option, fallbackValue } = this.state;
40
+ return buildTagWithFallback(this.props.tagKey, option, fallbackValue);
41
+ };
42
+
43
+ copyTag = () => {
44
+ navigator?.clipboard?.writeText(`{{${this.getTagValue()}}}`);
45
+ };
46
+
47
+ onInsert = () => {
48
+ this.props.onInsert(this.getTagValue());
49
+ };
50
+
51
+ render() {
52
+ const {
53
+ intl: { formatMessage }, tagName, parentName, description, onBack,
54
+ } = this.props;
55
+ const { option, fallbackValue } = this.state;
56
+ const isCustomValue = option === FALLBACK_OPTIONS.CUSTOM_VALUE;
57
+ const isFallbackValueInvalid = isCustomValue && !isValidFallbackValue(fallbackValue);
58
+ const isInsertDisabled = isCustomValue && (!fallbackValue.trim() || isFallbackValueInvalid);
59
+
60
+ return (
61
+ <CapRow className="tag-fallback-panel">
62
+ <CapRow className="tag-fallback-header">
63
+ <CapRow type="flex" align="middle" noWrap className="tag-fallback-title-row">
64
+ <CapIcon
65
+ type="back"
66
+ size="m"
67
+ className="tag-fallback-back"
68
+ aria-label={formatMessage(messages.back)}
69
+ onClick={onBack}
70
+ />
71
+ <CapHeading type="h4" className="tag-fallback-tag-name">{tagName}</CapHeading>
72
+ </CapRow>
73
+ {parentName ? <CapLabel type="label2" className="tag-fallback-group-name">{parentName}</CapLabel> : null}
74
+ </CapRow>
75
+ <CapRow className="tag-fallback-body">
76
+ {description ? <CapLabel type="label2" className="tag-fallback-description">{description}</CapLabel> : null}
77
+ <CapHeading type="h4" className="tag-fallback-heading">{formatMessage(messages.fallbackBehaviour)}</CapHeading>
78
+ <CapLabel type="label2" className="tag-fallback-subtext">{formatMessage(messages.fallbackBehaviourDesc)}</CapLabel>
79
+ <CapRadioGroup className="tag-fallback-options" value={option} onChange={this.onOptionChange}>
80
+ <CapRadio value={FALLBACK_OPTIONS.NONE}>{formatMessage(messages.dontSendMessage)}</CapRadio>
81
+ <CapRadio value={FALLBACK_OPTIONS.NULL_VALUE}>{formatMessage(messages.sendWithNullValue)}</CapRadio>
82
+ <CapRadio value={FALLBACK_OPTIONS.CUSTOM_VALUE}>{formatMessage(messages.fallbackValue)}</CapRadio>
83
+ </CapRadioGroup>
84
+ {isCustomValue && (
85
+ <CapInput
86
+ className="tag-fallback-input"
87
+ value={fallbackValue}
88
+ onChange={this.onFallbackValueChange}
89
+ placeholder={formatMessage(messages.fallbackValuePlaceholder)}
90
+ errorMessage={isFallbackValueInvalid ? formatMessage(messages.fallbackValueInvalid) : ''}
91
+ size="default"
92
+ />
93
+ )}
94
+ <CapLabel type="label2" className="tag-fallback-preview-label">{formatMessage(messages.addsToMessageAs)}</CapLabel>
95
+ <CapRow type="flex" align="middle" noWrap className="tag-fallback-preview-row">
96
+ <CapLabel className="tag-fallback-preview">{`{{${this.getTagValue()}}}`}</CapLabel>
97
+ <CapIcon
98
+ type="copy"
99
+ size="m"
100
+ className="tag-fallback-copy"
101
+ aria-label={formatMessage(messages.copy)}
102
+ onClick={this.copyTag}
103
+ />
104
+ </CapRow>
105
+ </CapRow>
106
+ <CapRow type="flex" justify="end" className="tag-fallback-footer">
107
+ <CapButton type="primary" disabled={isInsertDisabled} onClick={this.onInsert}>
108
+ {formatMessage(messages.insertTag)}
109
+ </CapButton>
110
+ </CapRow>
111
+ </CapRow>
112
+ );
113
+ }
114
+ }
115
+
116
+ TagFallbackPanel.propTypes = {
117
+ intl: intlShape.isRequired,
118
+ tagKey: PropTypes.string.isRequired,
119
+ tagName: PropTypes.node,
120
+ parentName: PropTypes.node,
121
+ description: PropTypes.string,
122
+ onBack: PropTypes.func.isRequired,
123
+ onInsert: PropTypes.func.isRequired,
124
+ };
125
+
126
+ export default injectIntl(TagFallbackPanel);
@@ -0,0 +1,46 @@
1
+ export const FALLBACK_OPTIONS = {
2
+ NONE: 'NONE',
3
+ NULL_VALUE: 'NULL_VALUE',
4
+ CUSTOM_VALUE: 'CUSTOM_VALUE',
5
+ };
6
+
7
+ // Tag descriptions are shown in a tooltip next to the tag, using the cap-ui-library info icon.
8
+ export const TAG_DESCRIPTION_ICON_TYPE = 'info';
9
+
10
+ // Separates the groups in the path shown under a tag in the search results, e.g. "Customer › Customer properties".
11
+ export const TAG_PATH_SEPARATOR = ' › ';
12
+
13
+ // Group arrows of the tag tree with the tags revamp
14
+ export const TREE_SWITCHER_ICON_TYPES = { EXPANDED: 'chevron-down', COLLAPSED: 'chevron-right' };
15
+
16
+ // Tabs of the Personalization list with the tags revamp
17
+ export const LIST_TABS = { TAGS: 'tags', LIQUID: 'liquid' };
18
+ export const LIQUID_TAB_ICON_TYPE = 'aira-nav';
19
+
20
+ // Width (px) of the tag list when it opens in a modal (Bee editor): the revamped list is wider than CapModal's default 324
21
+ export const TAG_LIST_MODAL_WIDTH = 460;
22
+
23
+ // The description tooltip is rendered outside the Personalization popover, which is opened from a slide box
24
+ // (z-index 10002) and the test and preview panel (10003-10005), so the tooltip needs to be above those
25
+ export const DESCRIPTION_TOOLTIP_Z_INDEX = 10010;
26
+
27
+ // With the tags revamp the fallback options are offered only for the tags the "Personalization tags: Clean up" sheet marks
28
+ // "Fallback required? = Yes"; every other tag ("No", "?" or empty) is inserted straight away.
29
+ // Seed tags carry `definition.fallbackRequired`. Tags that come from intouch at request time carry no such field, so they
30
+ // are matched here: org extended and custom fields (all "Yes" in the sheet) by their token prefix, and the other
31
+ // runtime tags the sheet marks "Yes" by token.
32
+ export const FALLBACK_REQUIRED_RUNTIME_TOKEN_PATTERN = /^(extended_field|custom_field)/;
33
+ export const FALLBACK_REQUIRED_RUNTIME_TAG_KEYS = [
34
+ 'anniversary_date', 'badge_description', 'badge_expiry_date', 'badges_issue_expiry_date', 'base_currencycode',
35
+ 'card_expiry_date', 'card_issue_date', 'card_name', 'card_number', 'card_series', 'card_series_name', 'card_status',
36
+ 'cashier_id', 'current_slab', 'current_slab_expiry_date', 'customer_type', 'date_of_birth', 'downgrade_reason',
37
+ 'external_fact', 'fraud_status', 'gender', 'gift_voucher_expiry_date', 'last_transacted_store_mobile_number',
38
+ 'nationality', 'new_slab_expiry_date', 'new_slab_expiry_date_renewal', 'partner_reference_id', 'payment_mode',
39
+ 'preferred_language', 'preferred_store', 'promotion_expiry_date', 'recommended_products',
40
+ 'recommended_products_with_kpi', 'registered_date', 'registered_store', 'registered_till', 'reward_description',
41
+ 'reward_expiry_date', 'roomstay_marketcode', 'standard_description', 'standard_terms_and_conditions', 'store_city',
42
+ 'store_code', 'store_country', 'store_email', 'store_phone', 'store_state', 'store_zone', 'tax_code', 'tier_expiry',
43
+ 'tier_name', 'upgrade_criteria', 'user_group_primary_email', 'user_group_primary_first_name',
44
+ 'user_group_primary_last_name', 'user_group_primary_mobile_number', 'user_group_primary_name',
45
+ 'voucher_description', 'voucher_discount_value',
46
+ ];