@jsb188/mday 1.1.11 → 1.1.12

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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,4 +1,11 @@
1
- import { FIELD_DOC_REPLY_TO_AGENT_DOMAINS } from '@jsb188/app/constants/agent.ts';
1
+ import {
2
+ CAMPAIGN_REPLY_TO_AGENT_DOMAINS,
3
+ DISABLED_INBOXES,
4
+ DO_NOT_REPLY_EMAIL_DOMAINS,
5
+ DOMAIN_TO_INBOX,
6
+ EMAIL_BASE_DOMAINS,
7
+ OPERATION_INBOX_DOMAINS,
8
+ } from '@jsb188/app/constants/agent.ts';
2
9
  import type { DraftSchema } from '@jsb188/app/utils/schema.ts';
3
10
  import { isEmail } from '@jsb188/app/utils/string.ts';
4
11
  import {
@@ -6,16 +13,24 @@ import {
6
13
  CAMPAIGN_DRAFT_KEY_PREFIX,
7
14
  CAMPAIGN_ELEMENT_TYPES,
8
15
  CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS,
16
+ CAMPAIGN_EMAIL_TEXT_LIMITS,
9
17
  CAMPAIGN_FORM_BACKGROUND_FILL_STYLES,
10
18
  CAMPAIGN_FORM_COLORS,
11
19
  CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE,
12
20
  CAMPAIGN_FORM_NEUTRAL_COLOR,
13
21
  CAMPAIGN_INSTRUCTIONS_MAX_LENGTH,
22
+ CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH,
23
+ CAMPAIGN_PUBLISH_STATUS_ENUMS,
24
+ CAMPAIGN_RESPONSE_TEXT_ANSWERS_MAX_LENGTH,
25
+ CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH,
26
+ CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS,
14
27
  } from '../constants/campaign.ts';
15
28
  import { MAX_PUBLIC_FORM_GENERATION_FILES } from '../constants/storage.ts';
16
29
  import type {
17
30
  CampaignAnswerObj,
18
31
  CampaignAnswersObj,
32
+ CampaignDefinitionSnapshotElementObj,
33
+ CampaignDefinitionSnapshotObj,
19
34
  CampaignDraft,
20
35
  CampaignElementData,
21
36
  CampaignElementOptionObj,
@@ -28,17 +43,46 @@ import type {
28
43
  CampaignElementVisibleWhenValuesObj,
29
44
  CampaignFormBackgroundFillStyleEnum,
30
45
  CampaignKindEnum,
46
+ CampaignPublishStatusEnum,
47
+ CampaignStatusEnum,
31
48
  CampaignTemplateType,
32
49
  EmailCampaignSettingsObj,
33
50
  FormCampaignSettingsObj,
34
51
  } from '../types/campaign.d.ts';
52
+ import {
53
+ getCampaignEmailBlockStorageSettings,
54
+ getCampaignEmailDesignSettings,
55
+ getCampaignEmailRowStorageSettings,
56
+ } from './campaignEmail.ts';
57
+ import { getCampaignFormWithoutAIQuestions, isCampaignAIQuestion } from './campaignAI.ts';
58
+
59
+ export type CampaignFormPublicationErrorCode =
60
+ | 'EMPTY_CHOICE_OPTION'
61
+ | 'EMPTY_QUESTION_LABEL'
62
+ | 'EMPTY_SECTION'
63
+ | 'INSUFFICIENT_CHOICE_OPTIONS'
64
+ | 'INVALID_QUESTION_VALIDATION'
65
+ | 'NO_QUESTIONS'
66
+ | 'RESERVED_QUESTION_KEY'
67
+ | 'UNSUPPORTED_FILE_QUESTION';
68
+
69
+ export interface CampaignFormPublicationError {
70
+ code: CampaignFormPublicationErrorCode;
71
+ elementKey?: string;
72
+ sectionKey?: string;
73
+ }
74
+
75
+ /*
76
+ * Return whether one lifecycle state can be the source of a publish command.
77
+ */
78
+ export function isCampaignPublishStatus(status: CampaignStatusEnum): status is CampaignPublishStatusEnum {
79
+ return CAMPAIGN_PUBLISH_STATUS_ENUMS.some((publishStatus) => publishStatus === status);
80
+ }
35
81
 
36
82
  /*
37
83
  * Narrow one untrusted JSONB value to a non-array object before reading fields.
38
84
  */
39
- function isCampaignObjectRecord(
40
- value: unknown,
41
- ): value is Record<string, unknown> {
85
+ function isCampaignObjectRecord(value: unknown): value is Record<string, unknown> {
42
86
  return !!value && typeof value === 'object' && !Array.isArray(value);
43
87
  }
44
88
 
@@ -46,11 +90,7 @@ function isCampaignObjectRecord(
46
90
  * Check whether one value fits GraphQL's signed 32-bit Int scalar.
47
91
  */
48
92
  function isCampaignGraphQLInt(value: unknown): value is number {
49
- return (
50
- Number.isInteger(value) &&
51
- (value as number) >= -2147483648 &&
52
- (value as number) <= 2147483647
53
- );
93
+ return Number.isInteger(value) && (value as number) >= -2147483648 && (value as number) <= 2147483647;
54
94
  }
55
95
 
56
96
  /*
@@ -58,31 +98,32 @@ function isCampaignGraphQLInt(value: unknown): value is number {
58
98
  * so this is the only correct test - never infer it from "type" being set.
59
99
  */
60
100
 
61
- export function isCampaignQuestionElement(
62
- element?: Pick<CampaignElementData, 'kind'> | null,
63
- ): boolean {
101
+ export function isCampaignQuestionElement(element?: Pick<CampaignElementData, 'kind'> | null): boolean {
64
102
  return element?.kind === 'QUESTION';
65
103
  }
66
104
 
105
+ /*
106
+ * Return whether one key is reserved for a fixed Web form results Sheet column.
107
+ */
108
+ export function isCampaignWebFormResultFixedColumnKey(key?: string | null): boolean {
109
+ return CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS.includes(
110
+ String(key || '') as (typeof CAMPAIGN_WEB_FORM_RESULT_FIXED_COLUMN_KEYS)[number],
111
+ );
112
+ }
113
+
67
114
  /*
68
115
  * Check whether one element's answer must be one of its declared options.
69
116
  */
70
117
 
71
- export function isCampaignChoiceElement(
72
- element?: Pick<CampaignElementData, 'type'> | null,
73
- ): boolean {
74
- return (
75
- !!element?.type && CAMPAIGN_CHOICE_ELEMENT_TYPES.includes(element.type)
76
- );
118
+ export function isCampaignChoiceElement(element?: Pick<CampaignElementData, 'type'> | null): boolean {
119
+ return !!element?.type && CAMPAIGN_CHOICE_ELEMENT_TYPES.includes(element.type);
77
120
  }
78
121
 
79
122
  /*
80
123
  * Check whether one element accepts more than one answer value.
81
124
  */
82
125
 
83
- export function isCampaignMultiValueElement(
84
- element?: Pick<CampaignElementData, 'type'> | null,
85
- ): boolean {
126
+ export function isCampaignMultiValueElement(element?: Pick<CampaignElementData, 'type'> | null): boolean {
86
127
  return element?.type === 'MULTI_CHOICE' || element?.type === 'FILE';
87
128
  }
88
129
 
@@ -90,19 +131,247 @@ export function isCampaignMultiValueElement(
90
131
  * Check whether one value is a supported element answer type.
91
132
  */
92
133
 
93
- export function isCampaignElementType(
94
- value?: string | null,
95
- ): value is CampaignElementTypeEnum {
134
+ export function isCampaignElementType(value?: string | null): value is CampaignElementTypeEnum {
96
135
  return CAMPAIGN_ELEMENT_TYPES.includes(value as CampaignElementTypeEnum);
97
136
  }
98
137
 
138
+ /*
139
+ * Remove unusable and duplicated choice rows while preserving the first
140
+ * canonical value-label pair for publication.
141
+ */
142
+ export function getCampaignPublishableOptions(options?: unknown): CampaignElementOptionObj[] {
143
+ if (!Array.isArray(options)) {
144
+ return [];
145
+ }
146
+
147
+ const labels = new Set<string>();
148
+ const values = new Set<string>();
149
+ const publishableOptions: CampaignElementOptionObj[] = [];
150
+
151
+ for (const option of options) {
152
+ if (!isCampaignObjectRecord(option) || typeof option.label !== 'string' || typeof option.value !== 'string') {
153
+ continue;
154
+ }
155
+
156
+ const label = option.label.trim();
157
+ const value = option.value.trim();
158
+ if (!label || !value || labels.has(label) || values.has(value)) {
159
+ continue;
160
+ }
161
+
162
+ labels.add(label);
163
+ values.add(value);
164
+ publishableOptions.push({ label, value });
165
+ }
166
+
167
+ return publishableOptions;
168
+ }
169
+
170
+ /*
171
+ * Clear one publication condition when option cleanup removed a value it
172
+ * depended on. Drafts retain the original condition until publication.
173
+ */
174
+ function getCampaignPublicationVisibleWhen(
175
+ element: CampaignDefinitionSnapshotElementObj,
176
+ elementsByKey: ReadonlyMap<string, CampaignDefinitionSnapshotElementObj>,
177
+ ): CampaignElementVisibleWhenObj | null {
178
+ const condition = getCampaignElementVisibleWhenValues(element.visibleWhen);
179
+ if (!condition) {
180
+ return null;
181
+ }
182
+
183
+ const referencedElement = elementsByKey.get(condition.elementKey);
184
+ if (
185
+ condition.elementKey === element.key ||
186
+ !referencedElement ||
187
+ referencedElement.kind !== 'QUESTION' ||
188
+ referencedElement.type === 'FILE'
189
+ ) {
190
+ return null;
191
+ }
192
+
193
+ if (
194
+ isCampaignChoiceElement(referencedElement) &&
195
+ condition.values.some((value) => !referencedElement.options?.some((option) => option.value === value))
196
+ ) {
197
+ return null;
198
+ }
199
+
200
+ return {
201
+ elementKey: condition.elementKey,
202
+ operator: condition.operator,
203
+ value: condition.values,
204
+ };
205
+ }
206
+
207
+ /*
208
+ * Build the respondent-facing definition at the publication boundary. Drafts
209
+ * may save invalid option rows; publishing is where blank and duplicated rows
210
+ * are deleted, and the remaining definition is validated before use.
211
+ */
212
+ export function getCampaignFormPublicationSnapshot(snapshot: CampaignDefinitionSnapshotObj): CampaignDefinitionSnapshotObj {
213
+ const sections = getCampaignFormWithoutAIQuestions(snapshot).sections.map((section) => ({
214
+ ...section,
215
+ elements: (section.elements || []).map((element) =>
216
+ isCampaignChoiceElement(element)
217
+ ? {
218
+ ...element,
219
+ options: getCampaignPublishableOptions(element.options),
220
+ }
221
+ : element,
222
+ ),
223
+ }));
224
+ const elementsByKey = new Map<string, CampaignDefinitionSnapshotElementObj>();
225
+ for (const section of sections) {
226
+ elementsByKey.set(section.key, section);
227
+ for (const element of section.elements) {
228
+ elementsByKey.set(element.key, element);
229
+ }
230
+ }
231
+
232
+ return {
233
+ ...snapshot,
234
+ sections: sections.map((section) => ({
235
+ ...section,
236
+ visibleWhen: getCampaignPublicationVisibleWhen(section, elementsByKey),
237
+ elements: section.elements.map((element) => ({
238
+ ...element,
239
+ visibleWhen: getCampaignPublicationVisibleWhen(element, elementsByKey),
240
+ })),
241
+ })),
242
+ };
243
+ }
244
+
245
+ /*
246
+ * Return one choice question's respondent-facing publication errors.
247
+ */
248
+ function getCampaignChoicePublicationErrors(element: CampaignDefinitionSnapshotElementObj): CampaignFormPublicationError[] {
249
+ if (!isCampaignChoiceElement(element)) {
250
+ return [];
251
+ }
252
+
253
+ const options = element.options || [];
254
+ const labels = new Set<string>();
255
+ const values = new Set<string>();
256
+ const invalidOption = options.some((option) => {
257
+ const label = option.label.trim();
258
+ const value = option.value.trim();
259
+ const invalid = !label || !value || labels.has(label) || values.has(value);
260
+ labels.add(label);
261
+ values.add(value);
262
+ return invalid;
263
+ });
264
+ const errors: CampaignFormPublicationError[] = [];
265
+
266
+ if (options.length < 2) {
267
+ errors.push({
268
+ code: 'INSUFFICIENT_CHOICE_OPTIONS',
269
+ elementKey: element.key,
270
+ });
271
+ }
272
+ if (invalidOption) {
273
+ errors.push({ code: 'EMPTY_CHOICE_OPTION', elementKey: element.key });
274
+ }
275
+
276
+ return errors;
277
+ }
278
+
279
+ /*
280
+ * Reject validation ranges that make a published question impossible to
281
+ * answer. Drafts may temporarily contain these values, but respondents must
282
+ * never receive a form whose minimum exceeds its maximum.
283
+ */
284
+ function isCampaignQuestionValidationInvalid(element: CampaignDefinitionSnapshotElementObj): boolean {
285
+ const validation = getCampaignElementValidation(element.validation);
286
+ if (!validation) {
287
+ return false;
288
+ }
289
+
290
+ if (element.type === 'SHORT_TEXT' || element.type === 'LONG_TEXT') {
291
+ const hardMaxLength = element.type === 'SHORT_TEXT' ? CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH : CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH;
292
+ return (
293
+ (validation.minLength != null && validation.minLength < 0) ||
294
+ (validation.maxLength != null && validation.maxLength < 1) ||
295
+ (validation.maxLength != null && validation.maxLength > hardMaxLength) ||
296
+ (validation.minLength != null && validation.minLength > hardMaxLength) ||
297
+ (validation.minLength != null && validation.maxLength != null && validation.minLength > validation.maxLength)
298
+ );
299
+ }
300
+
301
+ return element.type === 'NUMBER' && validation.min != null && validation.max != null && validation.min > validation.max;
302
+ }
303
+
304
+ /*
305
+ * Return every semantic issue that prevents one structurally safe form from being published.
306
+ */
307
+ export function getCampaignFormPublicationErrors(snapshot: CampaignDefinitionSnapshotObj): CampaignFormPublicationError[] {
308
+ const errors: CampaignFormPublicationError[] = [];
309
+ let questionCount = 0;
310
+
311
+ for (const [sectionIndex, section] of (snapshot.sections || []).entries()) {
312
+ const isImplicitFirstSection =
313
+ sectionIndex === 0 &&
314
+ !section.label?.trim() &&
315
+ !section.description?.trim() &&
316
+ !section.storageRels?.length &&
317
+ !section.settings;
318
+ if (!isImplicitFirstSection && !section.label?.trim()) {
319
+ errors.push({ code: 'EMPTY_SECTION', sectionKey: section.key });
320
+ }
321
+
322
+ for (const element of section.elements || []) {
323
+ if (element.kind !== 'QUESTION' || isCampaignAIQuestion(element)) {
324
+ continue;
325
+ }
326
+
327
+ questionCount += 1;
328
+ if (isCampaignWebFormResultFixedColumnKey(element.key)) {
329
+ errors.push({
330
+ code: 'RESERVED_QUESTION_KEY',
331
+ elementKey: element.key,
332
+ });
333
+ }
334
+ if (!element.label?.trim()) {
335
+ errors.push({
336
+ code: 'EMPTY_QUESTION_LABEL',
337
+ elementKey: element.key,
338
+ });
339
+ }
340
+ if (element.type === 'FILE') {
341
+ errors.push({
342
+ code: 'UNSUPPORTED_FILE_QUESTION',
343
+ elementKey: element.key,
344
+ });
345
+ }
346
+ if (isCampaignQuestionValidationInvalid(element)) {
347
+ errors.push({
348
+ code: 'INVALID_QUESTION_VALIDATION',
349
+ elementKey: element.key,
350
+ });
351
+ }
352
+ errors.push(...getCampaignChoicePublicationErrors(element));
353
+ }
354
+ }
355
+
356
+ if (!questionCount) {
357
+ errors.push({ code: 'NO_QUESTIONS' });
358
+ }
359
+
360
+ return errors;
361
+ }
362
+
363
+ /*
364
+ * Return whether one structurally safe form is complete enough for respondents.
365
+ */
366
+ export function isCampaignFormPublishable(snapshot: CampaignDefinitionSnapshotObj): boolean {
367
+ return getCampaignFormPublicationErrors(snapshot).length === 0;
368
+ }
369
+
99
370
  /*
100
371
  * Map one template route type to its campaign kind.
101
372
  */
102
373
 
103
- export function getCampaignKindFromTemplateType(
104
- templateType?: string | null,
105
- ): CampaignKindEnum | null {
374
+ export function getCampaignKindFromTemplateType(templateType?: string | null): CampaignKindEnum | null {
106
375
  switch (templateType as CampaignTemplateType) {
107
376
  case 'forms':
108
377
  return 'PUBLIC_FORM';
@@ -118,53 +387,155 @@ export function getCampaignKindFromTemplateType(
118
387
  */
119
388
 
120
389
  export function isCampaignReplyToAgentDomain(value?: string | null): boolean {
121
- return FIELD_DOC_REPLY_TO_AGENT_DOMAINS.includes(
390
+ return CAMPAIGN_REPLY_TO_AGENT_DOMAINS.includes(
122
391
  String(value || '')
123
392
  .trim()
124
- .toLowerCase() as (typeof FIELD_DOC_REPLY_TO_AGENT_DOMAINS)[number],
393
+ .toLowerCase(),
125
394
  );
126
395
  }
127
396
 
397
+ /*
398
+ * Return the app inbox domains available to one organization's operation.
399
+ */
400
+ export function getCampaignReplyToDomains(operation?: string | null): string[] {
401
+ const operationDomains = (OPERATION_INBOX_DOMAINS as Record<string, string[]>)[operation || ''] || OPERATION_INBOX_DOMAINS.DEFAULT;
402
+
403
+ return [...new Set([...operationDomains, ...DO_NOT_REPLY_EMAIL_DOMAINS])];
404
+ }
405
+
406
+ /*
407
+ * Check whether one app inbox domain can receive mail today. Domains of disabled inboxes are listed as campaign From
408
+ * options but cannot be chosen until their inbox launches.
409
+ */
410
+ export function isCampaignReplyToDomainEnabled(domain?: string | null): boolean {
411
+ if (!isCampaignReplyToAgentDomain(domain)) return false;
412
+ const inbox = (DOMAIN_TO_INBOX as Record<string, string | undefined>)[
413
+ String(domain || '')
414
+ .trim()
415
+ .toLowerCase()
416
+ ];
417
+ return !inbox || !DISABLED_INBOXES.includes(inbox as (typeof DISABLED_INBOXES)[number]);
418
+ }
419
+
420
+ /*
421
+ * Return the app inbox domains one organization's operation can choose as a campaign From address today.
422
+ */
423
+ export function getEnabledCampaignReplyToDomains(operation?: string | null): string[] {
424
+ return getCampaignReplyToDomains(operation).filter(isCampaignReplyToDomainEnabled);
425
+ }
426
+
427
+ /*
428
+ * Build the Reply-To mailbox list shared by campaign sends and test emails.
429
+ * The manual address is additional when an agent inbox is configured; it must never replace that inbox.
430
+ * Replacing it sends replies only to the human mailbox, bypassing Postmark ingestion and AI order processing.
431
+ * Preserve the full agent address, including any recipient-specific token used to link replies to the sent campaign.
432
+ * Non-agent addresses (such as do-not-reply) use only the manual address when one is set.
433
+ */
434
+ export function getCampaignEmailReplyToAddress(fromInboxEmail: string, replyToEmail?: string | null): string {
435
+ const manualReplyTo = replyToEmail?.trim();
436
+ if (!manualReplyTo) return fromInboxEmail;
437
+ const inboxDomain = fromInboxEmail.trim().toLowerCase().split('@').at(-1) || '';
438
+ return Object.hasOwn(DOMAIN_TO_INBOX, inboxDomain) ? `${fromInboxEmail}, ${manualReplyTo}` : manualReplyTo;
439
+ }
440
+
441
+ /*
442
+ * Reserve platform inbox subdomains from manual reply addresses, including unsupported inboxes.
443
+ */
444
+ export function isCampaignAppReplyToEmail(value?: string | null): boolean {
445
+ const domain =
446
+ String(value || '')
447
+ .trim()
448
+ .toLowerCase()
449
+ .split('@')
450
+ .at(-1) || '';
451
+ return EMAIL_BASE_DOMAINS.some((baseDomain) => domain.endsWith(`.${baseDomain}`));
452
+ }
453
+
128
454
  /*
129
455
  * Check whether one value is usable as a template's secondary reply-to address.
130
456
  * The database also rejects uppercase and comma-bearing values.
131
457
  */
132
458
 
133
- export function isCampaignSecondaryReplyToEmail(
134
- value?: string | null,
135
- ): boolean {
459
+ export function isCampaignSecondaryReplyToEmail(value?: string | null): boolean {
136
460
  const normalizedValue = String(value || '').trim();
137
461
 
138
462
  return (
139
463
  !!normalizedValue &&
464
+ normalizedValue.length <= CAMPAIGN_EMAIL_TEXT_LIMITS.secondaryReplyToEmail &&
140
465
  normalizedValue === normalizedValue.toLowerCase() &&
141
466
  !normalizedValue.includes(',') &&
142
467
  isEmail(normalizedValue)
143
468
  );
144
469
  }
145
470
 
471
+ /*
472
+ * Normalize one list of campaign-skipped address ids from JSONB or client input:
473
+ * database ids travel as digit strings so BIGINT identities survive JSON, and
474
+ * the result is deduplicated and sorted so equal sets always serialize equally.
475
+ */
476
+
477
+ export function getCampaignAudienceExclusionIds(value: unknown): string[] {
478
+ if (!Array.isArray(value)) {
479
+ return [];
480
+ }
481
+
482
+ const ids = new Set<string>();
483
+ for (const item of value) {
484
+ const id = typeof item === 'bigint' ? item.toString() : String(item ?? '');
485
+ if (/^\d+$/.test(id)) {
486
+ ids.add(id);
487
+ }
488
+ }
489
+
490
+ return [...ids].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
491
+ }
492
+
146
493
  /*
147
494
  * Read one email settings object from campaign JSONB without trusting unknown
148
495
  * stored values to have the expected scalar types.
149
496
  */
150
497
 
151
- export function getEmailCampaignSettings(
152
- settings?: unknown,
153
- ): EmailCampaignSettingsObj {
498
+ export function getEmailCampaignSettings(settings?: unknown): EmailCampaignSettingsObj {
154
499
  const values = isCampaignObjectRecord(settings) ? settings : {};
155
500
 
156
501
  return {
157
502
  subject: typeof values?.subject === 'string' ? values.subject : null,
503
+ preheader: typeof values?.preheader === 'string' ? values.preheader : null,
158
504
  body: typeof values?.body === 'string' ? values.body : null,
159
- bodyHTML: typeof values?.bodyHTML === 'string' ? values.bodyHTML : null,
160
- replyToAgentDomain:
161
- typeof values?.replyToAgentDomain === 'string'
162
- ? values.replyToAgentDomain
163
- : '',
164
- secondaryReplyToEmail:
165
- typeof values?.secondaryReplyToEmail === 'string'
166
- ? values.secondaryReplyToEmail
167
- : null,
505
+ aiAgentDomain: typeof values?.aiAgentDomain === 'string' ? values.aiAgentDomain : '',
506
+ secondaryReplyToEmail: typeof values?.secondaryReplyToEmail === 'string' ? values.secondaryReplyToEmail : null,
507
+ sendAt: typeof values?.sendAt === 'string' ? values.sendAt : null,
508
+ design: getCampaignEmailDesignSettings(values?.design),
509
+ trackOpens: values?.trackOpens !== false,
510
+ excludedEmailAddressIds: getCampaignAudienceExclusionIds(values?.excludedEmailAddressIds),
511
+ ...(Array.isArray(values.excludedEmails)
512
+ ? { excludedEmails: values.excludedEmails.filter((email): email is string => typeof email === 'string') }
513
+ : {}),
514
+ ...(Array.isArray(values.excludedOrganizationIds)
515
+ ? { excludedOrganizationIds: getCampaignAudienceExclusionIds(values.excludedOrganizationIds) }
516
+ : {}),
517
+ ...(values.networkPermissionPolicy === 'RELATIONSHIP' ? { networkPermissionPolicy: 'RELATIONSHIP' as const } : {}),
518
+ ...(isCampaignObjectRecord(values.emailReplyReport) &&
519
+ values.emailReplyReport.version === 1 &&
520
+ Array.isArray(values.emailReplyReport.fields)
521
+ ? { emailReplyReport: values.emailReplyReport as unknown as NonNullable<EmailCampaignSettingsObj['emailReplyReport']> }
522
+ : {}),
523
+ ...(isCampaignObjectRecord(values.emailListRecipientSummary)
524
+ ? { emailListRecipientSummary: values.emailListRecipientSummary }
525
+ : {}),
526
+ ...(isCampaignObjectRecord(values.networkRecipientSummary) ? { networkRecipientSummary: values.networkRecipientSummary } : {}),
527
+ ...(isCampaignObjectRecord(values.emailListSendInfo) &&
528
+ typeof values.emailListSendInfo.senderAddress === 'string' &&
529
+ typeof values.emailListSendInfo.replyAddress === 'string' &&
530
+ typeof values.emailListSendInfo.timeZone === 'string'
531
+ ? {
532
+ emailListSendInfo: {
533
+ senderAddress: values.emailListSendInfo.senderAddress,
534
+ replyAddress: values.emailListSendInfo.replyAddress,
535
+ timeZone: values.emailListSendInfo.timeZone,
536
+ },
537
+ }
538
+ : {}),
168
539
  };
169
540
  }
170
541
 
@@ -173,33 +544,26 @@ export function getEmailCampaignSettings(
173
544
  * stored values to have the expected scalar types.
174
545
  */
175
546
 
176
- export function getFormCampaignSettings(
177
- settings?: unknown,
178
- ): FormCampaignSettingsObj {
547
+ export function getFormCampaignSettings(settings?: unknown): FormCampaignSettingsObj {
179
548
  const values = isCampaignObjectRecord(settings) ? settings : {};
180
549
 
181
550
  return {
182
551
  color: typeof values?.color === 'string' ? values.color : undefined,
183
552
  backgroundFillStyle:
184
- typeof values?.backgroundFillStyle === 'string' &&
185
- isCampaignFormBackgroundFillStyle(values.backgroundFillStyle)
553
+ typeof values?.backgroundFillStyle === 'string' && isCampaignFormBackgroundFillStyle(values.backgroundFillStyle)
186
554
  ? values.backgroundFillStyle
187
555
  : undefined,
188
- confirmationMessage:
189
- typeof values?.confirmationMessage === 'string'
190
- ? values.confirmationMessage
191
- : undefined,
556
+ confirmationMessage: typeof values?.confirmationMessage === 'string' ? values.confirmationMessage : undefined,
192
557
  };
193
558
  }
194
559
 
195
560
  /*
196
- * Return one element's declared options as a stable list, tolerating rows that
197
- * predate the {value,label} shape by promoting a bare string to both fields.
561
+ * Return one element's declared options in the canonical value-and-label
562
+ * shape. Invalid persisted JSON is ignored instead of being promoted into a
563
+ * second legacy contract.
198
564
  */
199
565
 
200
- export function getCampaignElementOptions(
201
- element?: unknown,
202
- ): CampaignElementOptionObj[] {
566
+ export function getCampaignElementOptions(element?: unknown): CampaignElementOptionObj[] {
203
567
  const options = isCampaignObjectRecord(element) ? element.options : null;
204
568
 
205
569
  if (!Array.isArray(options)) {
@@ -207,20 +571,14 @@ export function getCampaignElementOptions(
207
571
  }
208
572
 
209
573
  return options.flatMap((option) => {
210
- if (typeof option === 'string') {
211
- return [{ value: option, label: option }];
212
- }
213
-
214
- if (!isCampaignObjectRecord(option) || typeof option.value !== 'string') {
574
+ if (!isCampaignObjectRecord(option) || typeof option.value !== 'string' || typeof option.label !== 'string') {
215
575
  return [];
216
576
  }
217
577
 
218
- return [
219
- {
220
- value: option.value,
221
- label: typeof option.label === 'string' ? option.label : option.value,
222
- },
223
- ];
578
+ const value = option.value.trim();
579
+ const label = option.label.trim();
580
+
581
+ return value ? [{ value, label }] : [];
224
582
  });
225
583
  }
226
584
 
@@ -229,51 +587,28 @@ export function getCampaignElementOptions(
229
587
  * typed JSONB values before they reach GraphQL or another editor save.
230
588
  */
231
589
 
232
- export function getCampaignElementValidation(
233
- validation?: unknown,
234
- ): CampaignElementValidationObj | null {
590
+ export function getCampaignElementValidation(validation?: unknown): CampaignElementValidationObj | null {
235
591
  const values = isCampaignObjectRecord(validation) ? validation : {};
236
592
  const normalized: CampaignElementValidationObj = {
237
- minLength: isCampaignGraphQLInt(values?.minLength)
238
- ? values.minLength
239
- : undefined,
240
- maxLength: isCampaignGraphQLInt(values?.maxLength)
241
- ? values.maxLength
242
- : undefined,
243
- min:
244
- typeof values?.min === 'number' && Number.isFinite(values.min)
245
- ? values.min
246
- : undefined,
247
- max:
248
- typeof values?.max === 'number' && Number.isFinite(values.max)
249
- ? values.max
250
- : undefined,
251
- pattern: typeof values?.pattern === 'string' ? values.pattern : undefined,
252
- maxFiles: isCampaignGraphQLInt(values?.maxFiles)
253
- ? values.maxFiles
254
- : undefined,
593
+ minLength: isCampaignGraphQLInt(values?.minLength) ? values.minLength : undefined,
594
+ maxLength: isCampaignGraphQLInt(values?.maxLength) ? values.maxLength : undefined,
595
+ min: typeof values?.min === 'number' && Number.isFinite(values.min) ? values.min : undefined,
596
+ max: typeof values?.max === 'number' && Number.isFinite(values.max) ? values.max : undefined,
597
+ maxFiles: isCampaignGraphQLInt(values?.maxFiles) ? values.maxFiles : undefined,
255
598
  acceptedContentTypes: Array.isArray(values?.acceptedContentTypes)
256
- ? values.acceptedContentTypes.filter(
257
- (value): value is string => typeof value === 'string',
258
- )
599
+ ? values.acceptedContentTypes.filter((value): value is string => typeof value === 'string')
259
600
  : undefined,
260
601
  };
261
602
 
262
- return Object.values(normalized).some((value) => value !== undefined)
263
- ? normalized
264
- : null;
603
+ return Object.values(normalized).some((value) => value !== undefined) ? normalized : null;
265
604
  }
266
605
 
267
606
  /*
268
607
  * Check whether one value is a supported conditional-visibility operator.
269
608
  */
270
609
 
271
- export function isCampaignElementVisibleWhenOperator(
272
- value?: string | null,
273
- ): value is CampaignElementVisibleWhenOperatorEnum {
274
- return CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS.includes(
275
- value as CampaignElementVisibleWhenOperatorEnum,
276
- );
610
+ export function isCampaignElementVisibleWhenOperator(value?: string | null): value is CampaignElementVisibleWhenOperatorEnum {
611
+ return CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS.includes(value as CampaignElementVisibleWhenOperatorEnum);
277
612
  }
278
613
 
279
614
  /*
@@ -281,13 +616,10 @@ export function isCampaignElementVisibleWhenOperator(
281
616
  * values shape.
282
617
  */
283
618
 
284
- export function getCampaignElementVisibleWhenValues(
285
- visibleWhen?: unknown,
286
- ): CampaignElementVisibleWhenValuesObj | null {
619
+ export function getCampaignElementVisibleWhenValues(visibleWhen?: unknown): CampaignElementVisibleWhenValuesObj | null {
287
620
  const valuesObject = isCampaignObjectRecord(visibleWhen) ? visibleWhen : null;
288
621
  const operator =
289
- typeof valuesObject?.operator === 'string' &&
290
- isCampaignElementVisibleWhenOperator(valuesObject.operator)
622
+ typeof valuesObject?.operator === 'string' && isCampaignElementVisibleWhenOperator(valuesObject.operator)
291
623
  ? valuesObject.operator
292
624
  : null;
293
625
 
@@ -295,14 +627,11 @@ export function getCampaignElementVisibleWhenValues(
295
627
  return null;
296
628
  }
297
629
 
298
- const rawValues =
299
- 'values' in valuesObject ? valuesObject.values : valuesObject.value;
630
+ const rawValues = 'values' in valuesObject ? valuesObject.values : valuesObject.value;
300
631
  const values =
301
632
  rawValues == null
302
633
  ? []
303
- : (Array.isArray(rawValues) ? rawValues : [rawValues]).filter(
304
- (value): value is string => typeof value === 'string',
305
- );
634
+ : (Array.isArray(rawValues) ? rawValues : [rawValues]).filter((value): value is string => typeof value === 'string');
306
635
 
307
636
  return {
308
637
  elementKey: valuesObject.elementKey,
@@ -317,10 +646,7 @@ export function getCampaignElementVisibleWhenValues(
317
646
  */
318
647
 
319
648
  export function getCampaignElementVisibleWhenStorageValue(
320
- visibleWhen?:
321
- | CampaignElementVisibleWhenObj
322
- | CampaignElementVisibleWhenValuesObj
323
- | null,
649
+ visibleWhen?: CampaignElementVisibleWhenObj | CampaignElementVisibleWhenValuesObj | null,
324
650
  ): CampaignElementVisibleWhenObj | null {
325
651
  const normalized = getCampaignElementVisibleWhenValues(visibleWhen);
326
652
 
@@ -338,14 +664,16 @@ export function getCampaignElementVisibleWhenStorageValue(
338
664
  * fields.
339
665
  */
340
666
 
341
- export function getCampaignElementSettings(
342
- settings?: unknown,
343
- ): CampaignElementSettingsGQL {
667
+ export function getCampaignElementSettings(settings?: unknown): CampaignElementSettingsGQL {
344
668
  const values = isCampaignObjectRecord(settings) ? settings : {};
669
+ const emailRow = getCampaignEmailRowStorageSettings(values.emailRow);
670
+ const emailBlock = getCampaignEmailBlockStorageSettings(values.emailBlock);
345
671
 
346
672
  return {
347
673
  numbered: values.numbered === true,
348
674
  fullWidth: values.fullWidth === true,
675
+ ...(emailRow ? { emailRow } : {}),
676
+ ...(emailBlock ? { emailBlock } : {}),
349
677
  };
350
678
  }
351
679
 
@@ -354,13 +682,15 @@ export function getCampaignElementSettings(
354
682
  * object when every flag is false.
355
683
  */
356
684
 
357
- export function getCampaignElementSettingsStorageValue(
358
- settings?: unknown,
359
- ): CampaignElementSettingsObj | null {
685
+ export function getCampaignElementSettingsStorageValue(settings?: unknown): CampaignElementSettingsObj | null {
360
686
  const values = isCampaignObjectRecord(settings) ? settings : {};
687
+ const emailRow = getCampaignEmailRowStorageSettings(values.emailRow);
688
+ const emailBlock = getCampaignEmailBlockStorageSettings(values.emailBlock);
361
689
  const normalized: CampaignElementSettingsObj = {
362
690
  ...(values.numbered === true ? { numbered: true } : {}),
363
691
  ...(values.fullWidth === true ? { fullWidth: true } : {}),
692
+ ...(emailRow ? { emailRow } : {}),
693
+ ...(emailBlock ? { emailBlock } : {}),
364
694
  };
365
695
 
366
696
  return Object.keys(normalized).length ? normalized : null;
@@ -371,9 +701,7 @@ export function getCampaignElementSettingsStorageValue(
371
701
  * can be validated and rendered through one code path.
372
702
  */
373
703
 
374
- export function getCampaignAnswerValues(
375
- answer?: CampaignAnswerObj | null,
376
- ): string[] {
704
+ export function getCampaignAnswerValues(answer?: CampaignAnswerObj | null): string[] {
377
705
  if (answer?.value == null) {
378
706
  return [];
379
707
  }
@@ -382,17 +710,31 @@ export function getCampaignAnswerValues(
382
710
  return values.map((value) => String(value).trim()).filter(Boolean);
383
711
  }
384
712
 
713
+ /*
714
+ * Return answer display values using submission-time choice labels first and
715
+ * current element labels only as a fallback for legacy responses.
716
+ */
717
+
718
+ export function getCampaignAnswerDisplayValues(answer?: CampaignAnswerObj | null, element?: unknown): string[] {
719
+ const labelsByValue = new Map(getCampaignElementOptions(element).map((option) => [option.value, option.label]));
720
+
721
+ for (const option of answer?.selectedOptions || []) {
722
+ if (option && typeof option.value === 'string' && typeof option.label === 'string' && option.value.trim()) {
723
+ labelsByValue.set(option.value, option.label);
724
+ }
725
+ }
726
+
727
+ return getCampaignAnswerValues(answer).map((value) => labelsByValue.get(value) ?? value);
728
+ }
729
+
385
730
  /*
386
731
  * Check whether one answer holds nothing a respondent actually entered. FILE
387
- * elements count their uploads rather than their (always empty) value.
732
+ * questions remain empty until an ownership-checked upload transport exists.
388
733
  */
389
734
 
390
- export function isCampaignAnswerEmpty(
391
- element: Pick<CampaignElementData, 'type'>,
392
- answer?: CampaignAnswerObj | null,
393
- ): boolean {
735
+ export function isCampaignAnswerEmpty(element: Pick<CampaignElementData, 'type'>, answer?: CampaignAnswerObj | null): boolean {
394
736
  if (element.type === 'FILE') {
395
- return !answer?.files?.length;
737
+ return true;
396
738
  }
397
739
  return !getCampaignAnswerValues(answer).length;
398
740
  }
@@ -407,7 +749,7 @@ export function isCampaignAnswerEmpty(
407
749
  export function isCampaignElementVisible(
408
750
  element: Pick<CampaignElementData, 'visibleWhen'>,
409
751
  answers: CampaignAnswersObj,
410
- elementsByKey?: Map<string, CampaignElementData>,
752
+ elementsByKey?: ReadonlyMap<string, unknown>,
411
753
  ): boolean {
412
754
  const condition = element.visibleWhen;
413
755
  if (!condition?.elementKey) {
@@ -420,12 +762,7 @@ export function isCampaignElementVisible(
420
762
  }
421
763
 
422
764
  const values = getCampaignAnswerValues(answers[condition.elementKey]);
423
- const expected =
424
- condition.value == null
425
- ? []
426
- : Array.isArray(condition.value)
427
- ? condition.value
428
- : [condition.value];
765
+ const expected = condition.value == null ? [] : Array.isArray(condition.value) ? condition.value : [condition.value];
429
766
 
430
767
  switch (condition.operator) {
431
768
  case 'IS_ANSWERED':
@@ -435,12 +772,96 @@ export function isCampaignElementVisible(
435
772
  case 'INCLUDES':
436
773
  return expected.some((value) => values.includes(value));
437
774
  case 'EQUALS':
775
+ return values.length === expected.length && expected.every((value) => values.includes(value));
438
776
  default:
439
- return (
440
- values.length === expected.length &&
441
- expected.every((value) => values.includes(value))
442
- );
777
+ return true;
778
+ }
779
+ }
780
+
781
+ export interface CampaignVisibilityElementObj {
782
+ key: string;
783
+ parentKey?: string | null;
784
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
785
+ }
786
+
787
+ /*
788
+ * Flatten sections and their children into one visibility graph. A child
789
+ * carries its containing section as an upstream dependency in addition to its
790
+ * own visibleWhen condition.
791
+ */
792
+
793
+ export function getCampaignDefinitionVisibilityElements(
794
+ sections: Array<{
795
+ key: string;
796
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
797
+ elements?: Array<{
798
+ key: string;
799
+ visibleWhen?: CampaignElementVisibleWhenObj | null;
800
+ }> | null;
801
+ }>,
802
+ ): CampaignVisibilityElementObj[] {
803
+ return sections.flatMap((section) => [
804
+ {
805
+ key: section.key,
806
+ visibleWhen: section.visibleWhen || null,
807
+ },
808
+ ...(section.elements || []).map((element) => ({
809
+ key: element.key,
810
+ parentKey: section.key,
811
+ visibleWhen: element.visibleWhen || null,
812
+ })),
813
+ ]);
814
+ }
815
+
816
+ /*
817
+ * Return the element keys whose own condition and every upstream dependency
818
+ * are visible. Recomputing from the complete definition keeps chained
819
+ * conditions correct even when an earlier answer hides several descendants.
820
+ */
821
+
822
+ export function getVisibleCampaignElementKeys(elements: CampaignVisibilityElementObj[], answers: CampaignAnswersObj): Set<string> {
823
+ const elementsByKey = new Map(elements.map((element) => [element.key, element]));
824
+ const visibleKeys = new Set(elementsByKey.keys());
825
+ let changed = true;
826
+
827
+ while (changed) {
828
+ changed = false;
829
+
830
+ for (const element of elements) {
831
+ if (!visibleKeys.has(element.key)) {
832
+ continue;
833
+ }
834
+
835
+ const dependencyKey = element.visibleWhen?.elementKey;
836
+ const parentIsHidden = !!element.parentKey && elementsByKey.has(element.parentKey) && !visibleKeys.has(element.parentKey);
837
+ const dependencyIsHidden = !!dependencyKey && elementsByKey.has(dependencyKey) && !visibleKeys.has(dependencyKey);
838
+ if (parentIsHidden || dependencyIsHidden || !isCampaignElementVisible(element, answers, elementsByKey)) {
839
+ visibleKeys.delete(element.key);
840
+ changed = true;
841
+ }
842
+ }
843
+ }
844
+
845
+ return visibleKeys;
846
+ }
847
+
848
+ /*
849
+ * Remove answers for questions a respondent can no longer see. The returned
850
+ * map has no object prototype so legacy reserved element keys remain ordinary
851
+ * serializable data until those publications are retired.
852
+ */
853
+
854
+ export function getVisibleCampaignAnswers(elements: CampaignVisibilityElementObj[], answers: CampaignAnswersObj): CampaignAnswersObj {
855
+ const visibleKeys = getVisibleCampaignElementKeys(elements, answers);
856
+ const visibleAnswers = Object.create(null) as CampaignAnswersObj;
857
+
858
+ for (const [elementKey, answer] of Object.entries(answers)) {
859
+ if (visibleKeys.has(elementKey)) {
860
+ visibleAnswers[elementKey] = answer;
861
+ }
443
862
  }
863
+
864
+ return visibleAnswers;
444
865
  }
445
866
 
446
867
  /*
@@ -456,22 +877,30 @@ export function isCampaignElementVisible(
456
877
  export function getInvalidCampaignAnswerKeys(
457
878
  elements: CampaignElementData[],
458
879
  answers: CampaignAnswersObj,
459
- options?: { requireAnswers?: boolean },
880
+ options?: {
881
+ requireAnswers?: boolean;
882
+ visibilityElements?: CampaignVisibilityElementObj[];
883
+ },
460
884
  ): string[] {
461
- const questions = elements.filter(isCampaignQuestionElement);
462
- const elementsByKey = new Map(
463
- elements.map((element) => [element.key, element]),
464
- );
885
+ const questions = elements.filter((element) => isCampaignQuestionElement(element) && !isCampaignAIQuestion(element));
886
+ const elementsByKey = new Map(elements.map((element) => [element.key, element]));
887
+ const visibleKeys = getVisibleCampaignElementKeys(options?.visibilityElements || elements, answers);
465
888
  const invalidKeys = new Set<string>();
889
+ const textAnswerKeys: string[] = [];
890
+ let totalTextAnswerLength = 0;
466
891
 
467
892
  for (const element of questions) {
468
- if (!isCampaignElementVisible(element, answers, elementsByKey)) {
893
+ if (!visibleKeys.has(element.key)) {
469
894
  continue;
470
895
  }
471
896
 
472
897
  const answer = answers[element.key];
473
898
  const values = getCampaignAnswerValues(answer);
474
899
  const isEmpty = isCampaignAnswerEmpty(element, answer);
900
+ if ((element.type === 'SHORT_TEXT' || element.type === 'LONG_TEXT') && values.length) {
901
+ textAnswerKeys.push(element.key);
902
+ totalTextAnswerLength += values.reduce((total, value) => total + value.length, 0);
903
+ }
475
904
 
476
905
  if (isEmpty) {
477
906
  // Drafts may be incomplete; only a submission enforces "required"
@@ -487,9 +916,7 @@ export function getInvalidCampaignAnswerKeys(
487
916
  }
488
917
 
489
918
  if (isCampaignChoiceElement(element)) {
490
- const allowedValues = new Set(
491
- getCampaignElementOptions(element).map((option) => option.value),
492
- );
919
+ const allowedValues = new Set(getCampaignElementOptions(element).map((option) => option.value));
493
920
  if (values.some((value) => !allowedValues.has(value))) {
494
921
  invalidKeys.add(element.key);
495
922
  }
@@ -500,6 +927,11 @@ export function getInvalidCampaignAnswerKeys(
500
927
  invalidKeys.add(element.key);
501
928
  }
502
929
  }
930
+ if (totalTextAnswerLength > CAMPAIGN_RESPONSE_TEXT_ANSWERS_MAX_LENGTH) {
931
+ for (const elementKey of textAnswerKeys) {
932
+ invalidKeys.add(elementKey);
933
+ }
934
+ }
503
935
 
504
936
  // An answer naming an element the template does not have is always invalid
505
937
  for (const answerKey of Object.keys(answers)) {
@@ -512,6 +944,24 @@ export function getInvalidCampaignAnswerKeys(
512
944
  return [...invalidKeys];
513
945
  }
514
946
 
947
+ /*
948
+ * Check one ISO-looking date by round-tripping its UTC calendar components.
949
+ */
950
+
951
+ function isStrictCampaignDate(value: string): boolean {
952
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
953
+ if (!match) {
954
+ return false;
955
+ }
956
+
957
+ const year = Number(match[1]);
958
+ const month = Number(match[2]);
959
+ const day = Number(match[3]);
960
+ const date = new Date(Date.UTC(year, month - 1, day));
961
+
962
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
963
+ }
964
+
515
965
  /*
516
966
  * Check one non-choice answer against its element's type and validation rules.
517
967
  */
@@ -521,6 +971,7 @@ export function isCampaignAnswerValueValidForType(
521
971
  values: string[],
522
972
  ): boolean {
523
973
  const validation = element.validation || {};
974
+ const textMaxLength = getCampaignTextAnswerMaxLength(element);
524
975
 
525
976
  return values.every((value) => {
526
977
  switch (element.type) {
@@ -535,35 +986,21 @@ export function isCampaignAnswerValueValidForType(
535
986
  return !(validation.max != null && numberValue > validation.max);
536
987
  }
537
988
  case 'DATE':
538
- // YYYY-MM-DD, and a real calendar date
539
- return (
540
- /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value))
541
- );
989
+ return isStrictCampaignDate(value);
542
990
  case 'EMAIL':
543
991
  return isEmail(value);
544
992
  case 'PHONE':
545
993
  return /^[+()\-.\s\d]{7,20}$/.test(value);
546
994
  case 'SHORT_TEXT':
547
995
  case 'LONG_TEXT': {
548
- if (
549
- validation.minLength != null &&
550
- value.length < validation.minLength
551
- ) {
996
+ if (textMaxLength !== null && value.length > textMaxLength) {
552
997
  return false;
553
998
  }
554
- if (
555
- validation.maxLength != null &&
556
- value.length > validation.maxLength
557
- ) {
999
+ if (validation.minLength != null && value.length < validation.minLength) {
558
1000
  return false;
559
1001
  }
560
- if (validation.pattern) {
561
- try {
562
- return new RegExp(validation.pattern).test(value);
563
- } catch {
564
- // A malformed stored pattern must not reject real answers
565
- return true;
566
- }
1002
+ if (validation.maxLength != null && value.length > validation.maxLength) {
1003
+ return false;
567
1004
  }
568
1005
  return true;
569
1006
  }
@@ -573,25 +1010,40 @@ export function isCampaignAnswerValueValidForType(
573
1010
  });
574
1011
  }
575
1012
 
1013
+ /*
1014
+ * Return the hard public-form text cap, narrowed further by a valid
1015
+ * author-configured maximum when one exists.
1016
+ */
1017
+ export function getCampaignTextAnswerMaxLength(element: Pick<CampaignElementData, 'type' | 'validation'>): number | null {
1018
+ const hardMaxLength =
1019
+ element.type === 'SHORT_TEXT'
1020
+ ? CAMPAIGN_SHORT_TEXT_ANSWER_MAX_LENGTH
1021
+ : element.type === 'LONG_TEXT'
1022
+ ? CAMPAIGN_LONG_TEXT_ANSWER_MAX_LENGTH
1023
+ : null;
1024
+ if (hardMaxLength === null) {
1025
+ return null;
1026
+ }
1027
+
1028
+ const configuredMaxLength = element.validation?.maxLength;
1029
+ return typeof configuredMaxLength === 'number' && Number.isSafeInteger(configuredMaxLength) && configuredMaxLength > 0
1030
+ ? Math.min(configuredMaxLength, hardMaxLength)
1031
+ : hardMaxLength;
1032
+ }
1033
+
576
1034
  /*
577
1035
  * Check whether one value is a supported form background fill style.
578
1036
  */
579
1037
 
580
- export function isCampaignFormBackgroundFillStyle(
581
- value?: string | null,
582
- ): value is CampaignFormBackgroundFillStyleEnum {
583
- return CAMPAIGN_FORM_BACKGROUND_FILL_STYLES.includes(
584
- value as CampaignFormBackgroundFillStyleEnum,
585
- );
1038
+ export function isCampaignFormBackgroundFillStyle(value?: string | null): value is CampaignFormBackgroundFillStyleEnum {
1039
+ return CAMPAIGN_FORM_BACKGROUND_FILL_STYLES.includes(value as CampaignFormBackgroundFillStyleEnum);
586
1040
  }
587
1041
 
588
1042
  /*
589
1043
  * Resolve a form color into one generated CSS palette name.
590
1044
  */
591
1045
 
592
- export function normalizeCampaignFormColor(
593
- color?: string | null,
594
- ): string | null {
1046
+ export function normalizeCampaignFormColor(color?: string | null): string | null {
595
1047
  const normalizedColor = String(color || '')
596
1048
  .trim()
597
1049
  .toLowerCase();
@@ -604,18 +1056,14 @@ export function normalizeCampaignFormColor(
604
1056
  return CAMPAIGN_FORM_NEUTRAL_COLOR;
605
1057
  }
606
1058
 
607
- return CAMPAIGN_FORM_COLORS.includes(normalizedColor)
608
- ? normalizedColor
609
- : null;
1059
+ return CAMPAIGN_FORM_COLORS.includes(normalizedColor) ? normalizedColor : null;
610
1060
  }
611
1061
 
612
1062
  /*
613
1063
  * Resolve the form theme color; GRAYSCALE always renders neutral.
614
1064
  */
615
1065
 
616
- export function getCampaignFormColor(
617
- settings?: FormCampaignSettingsObj | null,
618
- ): string | null {
1066
+ export function getCampaignFormColor(settings?: FormCampaignSettingsObj | null): string | null {
619
1067
  if (getCampaignFormBackgroundFillStyle(settings) === 'GRAYSCALE') {
620
1068
  return CAMPAIGN_FORM_NEUTRAL_COLOR;
621
1069
  }
@@ -627,16 +1075,12 @@ export function getCampaignFormColor(
627
1075
  * Resolve the form background fill style, falling back to the default.
628
1076
  */
629
1077
 
630
- export function getCampaignFormBackgroundFillStyle(
631
- settings?: FormCampaignSettingsObj | null,
632
- ): CampaignFormBackgroundFillStyleEnum {
1078
+ export function getCampaignFormBackgroundFillStyle(settings?: FormCampaignSettingsObj | null): CampaignFormBackgroundFillStyleEnum {
633
1079
  const style = String(settings?.backgroundFillStyle || '')
634
1080
  .trim()
635
1081
  .toUpperCase();
636
1082
 
637
- return isCampaignFormBackgroundFillStyle(style)
638
- ? style
639
- : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
1083
+ return isCampaignFormBackgroundFillStyle(style) ? style : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
640
1084
  }
641
1085
 
642
1086
  /*
@@ -647,20 +1091,13 @@ export function getCampaignFormBackgroundFillStyle(
647
1091
  * emitting an undefined variable.
648
1092
  */
649
1093
 
650
- export function getCampaignFormBackgroundColorValue(
651
- color?: string | null,
652
- backgroundFillStyle?: string | null,
653
- ): string {
1094
+ export function getCampaignFormBackgroundColorValue(color?: string | null, backgroundFillStyle?: string | null): string {
654
1095
  const style = String(backgroundFillStyle || '')
655
1096
  .trim()
656
1097
  .toUpperCase();
657
- const fillStyle = isCampaignFormBackgroundFillStyle(style)
658
- ? style
659
- : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
1098
+ const fillStyle = isCampaignFormBackgroundFillStyle(style) ? style : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
660
1099
  const resolvedColor =
661
- fillStyle === 'GRAYSCALE'
662
- ? CAMPAIGN_FORM_NEUTRAL_COLOR
663
- : normalizeCampaignFormColor(color) || CAMPAIGN_FORM_NEUTRAL_COLOR;
1100
+ fillStyle === 'GRAYSCALE' ? CAMPAIGN_FORM_NEUTRAL_COLOR : normalizeCampaignFormColor(color) || CAMPAIGN_FORM_NEUTRAL_COLOR;
664
1101
 
665
1102
  switch (fillStyle) {
666
1103
  case 'FADED':
@@ -669,21 +1106,17 @@ export function getCampaignFormBackgroundColorValue(
669
1106
  return `var(--color-${resolvedColor}-alt-light)`;
670
1107
  case 'GRAYSCALE':
671
1108
  case 'MEDIUM':
672
- default:
673
1109
  return `var(--color-${resolvedColor}-alt-medium)`;
674
1110
  }
1111
+
1112
+ return `var(--color-${resolvedColor}-alt-medium)`;
675
1113
  }
676
1114
 
677
1115
  /*
678
1116
  * Resolve one typed form settings object to its background colour.
679
1117
  */
680
- export function getCampaignFormBackgroundColorValueFromSettings(
681
- settings?: FormCampaignSettingsObj | null,
682
- ): string {
683
- return getCampaignFormBackgroundColorValue(
684
- settings?.color,
685
- settings?.backgroundFillStyle,
686
- );
1118
+ export function getCampaignFormBackgroundColorValueFromSettings(settings?: FormCampaignSettingsObj | null): string {
1119
+ return getCampaignFormBackgroundColorValue(settings?.color, settings?.backgroundFillStyle);
687
1120
  }
688
1121
 
689
1122
  /**