@jsb188/mday 1.1.10 → 1.1.11

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 (119) hide show
  1. package/package.json +105 -54
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +35 -9
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +20 -4
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/integration.ts +8 -9
  13. package/src/constants/log.ts +7 -410
  14. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  15. package/src/constants/logTaxonomy.generated.ts +1103 -0
  16. package/src/constants/noteDoc.ts +77 -0
  17. package/src/constants/organization.ts +13 -15
  18. package/src/constants/pageRoute.ts +23 -0
  19. package/src/constants/schedule.ts +220 -0
  20. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  21. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  22. package/src/constants/sheet.ts +154 -6
  23. package/src/constants/sheetRegionSources.generated.ts +578 -0
  24. package/src/constants/square.ts +6 -6
  25. package/src/constants/storage.ts +56 -7
  26. package/src/constants/usage.ts +79 -0
  27. package/src/schemas/editLogEntry.ts +1010 -777
  28. package/src/schemas/fieldDocsQuery.ts +12 -0
  29. package/src/schemas/inboundContact.ts +60 -55
  30. package/src/schemas/logsQuery.ts +55 -49
  31. package/src/schemas/organization.ts +49 -46
  32. package/src/types/account.d.ts +4 -1
  33. package/src/types/agentDoc.d.ts +64 -0
  34. package/src/types/agentMemory.d.ts +74 -0
  35. package/src/types/campaign.d.ts +683 -0
  36. package/src/types/dataTable.d.ts +175 -256
  37. package/src/types/docAccess.d.ts +96 -0
  38. package/src/types/email.d.ts +83 -12
  39. package/src/types/fieldDoc.d.ts +273 -0
  40. package/src/types/inboundContact.d.ts +2 -1
  41. package/src/types/log.d.ts +209 -341
  42. package/src/types/noteDoc.d.ts +86 -0
  43. package/src/types/organization.d.ts +83 -40
  44. package/src/types/pageRoute.d.ts +48 -0
  45. package/src/types/schedule.d.ts +391 -0
  46. package/src/types/sheet.d.ts +862 -30
  47. package/src/types/storage.d.ts +206 -125
  48. package/src/types/usage.d.ts +106 -0
  49. package/src/types/workflow.d.ts +149 -18
  50. package/src/utils/agentDoc.ts +109 -0
  51. package/src/utils/aiChat.ts +26 -0
  52. package/src/utils/campaign.ts +741 -0
  53. package/src/utils/campaignFormEditor.ts +871 -0
  54. package/src/utils/dataTable.ts +425 -410
  55. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  56. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  57. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  58. package/src/utils/dataTableRowDocument.ts +508 -0
  59. package/src/utils/dataTableSource.ts +230 -0
  60. package/src/utils/docAccess.ts +383 -0
  61. package/src/utils/documentName.ts +53 -0
  62. package/src/utils/email.ts +112 -53
  63. package/src/utils/fieldDoc.ts +113 -0
  64. package/src/utils/log.ts +169 -176
  65. package/src/utils/logRegistryValue.ts +90 -0
  66. package/src/utils/logStoreRead.ts +266 -0
  67. package/src/utils/logTaxonomy.ts +76 -0
  68. package/src/utils/logTaxonomyDisplay.ts +439 -0
  69. package/src/utils/noteDoc.ts +827 -0
  70. package/src/utils/organization.ts +510 -91
  71. package/src/utils/pageRoute.ts +71 -0
  72. package/src/utils/schedule.ts +799 -0
  73. package/src/utils/scheduleEvaluation.ts +1994 -0
  74. package/src/utils/scheduleICS.ts +246 -0
  75. package/src/utils/scheduleRuleTemplates.ts +188 -0
  76. package/src/utils/sheet.ts +4842 -39
  77. package/src/utils/sheetAxisMove.ts +830 -0
  78. package/src/utils/sheetBootstrap.ts +1769 -0
  79. package/src/utils/sheetCommand.ts +423 -0
  80. package/src/utils/sheetExport.ts +238 -0
  81. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  82. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  83. package/src/utils/sheetJournal.ts +78 -0
  84. package/src/utils/sheetNumberFormat.ts +1211 -0
  85. package/src/utils/sheetRegion.ts +374 -0
  86. package/src/utils/sheetRegionFilter.ts +1259 -0
  87. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  88. package/src/utils/sheetSequence.ts +148 -0
  89. package/src/utils/sheetSnapshot.ts +992 -0
  90. package/src/utils/sheetStructureEdit.ts +1284 -0
  91. package/src/utils/square.ts +22 -12
  92. package/src/utils/storage.ts +152 -0
  93. package/src/utils/table-route.ts +127 -11
  94. package/src/utils/workflow.ts +191 -23
  95. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  96. package/tests/docAccess.test.ts +525 -0
  97. package/tests/editLogEntry.test.ts +112 -0
  98. package/tests/noteDoc.test.ts +669 -0
  99. package/tests/schedule.test.ts +693 -0
  100. package/tests/scheduleEvaluation.test.ts +1970 -0
  101. package/tests/scheduleICS.test.ts +208 -0
  102. package/tests/scheduleRuleTemplates.test.ts +176 -0
  103. package/tests/scheduleSweepInvariants.test.ts +428 -0
  104. package/tests/sheetAxisMove.test.ts +343 -0
  105. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  106. package/tests/sheetRegionFilter.test.ts +1135 -0
  107. package/tests/sheetSequence.test.ts +41 -0
  108. package/tests/sheetStructureEdit.test.ts +82 -0
  109. package/tsconfig.json +10 -10
  110. package/vitest.config.ts +8 -0
  111. package/src/constants/log-activityTexts.ts +0 -235
  112. package/src/constants/product.ts +0 -42
  113. package/src/constants/report.ts +0 -44
  114. package/src/schemas/productsQuery.ts +0 -53
  115. package/src/schemas/reportsQuery.ts +0 -20
  116. package/src/types/product.d.ts +0 -84
  117. package/src/types/report.d.ts +0 -290
  118. package/src/utils/product-calEvent.ts +0 -455
  119. package/src/utils/report.ts +0 -158
@@ -0,0 +1,741 @@
1
+ import { FIELD_DOC_REPLY_TO_AGENT_DOMAINS } from '@jsb188/app/constants/agent.ts';
2
+ import type { DraftSchema } from '@jsb188/app/utils/schema.ts';
3
+ import { isEmail } from '@jsb188/app/utils/string.ts';
4
+ import {
5
+ CAMPAIGN_CHOICE_ELEMENT_TYPES,
6
+ CAMPAIGN_DRAFT_KEY_PREFIX,
7
+ CAMPAIGN_ELEMENT_TYPES,
8
+ CAMPAIGN_ELEMENT_VISIBLE_WHEN_OPERATORS,
9
+ CAMPAIGN_FORM_BACKGROUND_FILL_STYLES,
10
+ CAMPAIGN_FORM_COLORS,
11
+ CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE,
12
+ CAMPAIGN_FORM_NEUTRAL_COLOR,
13
+ CAMPAIGN_INSTRUCTIONS_MAX_LENGTH,
14
+ } from '../constants/campaign.ts';
15
+ import { MAX_PUBLIC_FORM_GENERATION_FILES } from '../constants/storage.ts';
16
+ import type {
17
+ CampaignAnswerObj,
18
+ CampaignAnswersObj,
19
+ CampaignDraft,
20
+ CampaignElementData,
21
+ CampaignElementOptionObj,
22
+ CampaignElementSettingsGQL,
23
+ CampaignElementSettingsObj,
24
+ CampaignElementTypeEnum,
25
+ CampaignElementValidationObj,
26
+ CampaignElementVisibleWhenObj,
27
+ CampaignElementVisibleWhenOperatorEnum,
28
+ CampaignElementVisibleWhenValuesObj,
29
+ CampaignFormBackgroundFillStyleEnum,
30
+ CampaignKindEnum,
31
+ CampaignTemplateType,
32
+ EmailCampaignSettingsObj,
33
+ FormCampaignSettingsObj,
34
+ } from '../types/campaign.d.ts';
35
+
36
+ /*
37
+ * Narrow one untrusted JSONB value to a non-array object before reading fields.
38
+ */
39
+ function isCampaignObjectRecord(
40
+ value: unknown,
41
+ ): value is Record<string, unknown> {
42
+ return !!value && typeof value === 'object' && !Array.isArray(value);
43
+ }
44
+
45
+ /*
46
+ * Check whether one value fits GraphQL's signed 32-bit Int scalar.
47
+ */
48
+ function isCampaignGraphQLInt(value: unknown): value is number {
49
+ return (
50
+ Number.isInteger(value) &&
51
+ (value as number) >= -2147483648 &&
52
+ (value as number) <= 2147483647
53
+ );
54
+ }
55
+
56
+ /*
57
+ * Check whether one element collects an answer. "kind" is the structural role,
58
+ * so this is the only correct test - never infer it from "type" being set.
59
+ */
60
+
61
+ export function isCampaignQuestionElement(
62
+ element?: Pick<CampaignElementData, 'kind'> | null,
63
+ ): boolean {
64
+ return element?.kind === 'QUESTION';
65
+ }
66
+
67
+ /*
68
+ * Check whether one element's answer must be one of its declared options.
69
+ */
70
+
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
+ );
77
+ }
78
+
79
+ /*
80
+ * Check whether one element accepts more than one answer value.
81
+ */
82
+
83
+ export function isCampaignMultiValueElement(
84
+ element?: Pick<CampaignElementData, 'type'> | null,
85
+ ): boolean {
86
+ return element?.type === 'MULTI_CHOICE' || element?.type === 'FILE';
87
+ }
88
+
89
+ /*
90
+ * Check whether one value is a supported element answer type.
91
+ */
92
+
93
+ export function isCampaignElementType(
94
+ value?: string | null,
95
+ ): value is CampaignElementTypeEnum {
96
+ return CAMPAIGN_ELEMENT_TYPES.includes(value as CampaignElementTypeEnum);
97
+ }
98
+
99
+ /*
100
+ * Map one template route type to its campaign kind.
101
+ */
102
+
103
+ export function getCampaignKindFromTemplateType(
104
+ templateType?: string | null,
105
+ ): CampaignKindEnum | null {
106
+ switch (templateType as CampaignTemplateType) {
107
+ case 'forms':
108
+ return 'PUBLIC_FORM';
109
+ case 'emails':
110
+ return 'EMAIL';
111
+ default:
112
+ return null;
113
+ }
114
+ }
115
+
116
+ /*
117
+ * Check whether one value is a reply-to agent domain this app owns.
118
+ */
119
+
120
+ export function isCampaignReplyToAgentDomain(value?: string | null): boolean {
121
+ return FIELD_DOC_REPLY_TO_AGENT_DOMAINS.includes(
122
+ String(value || '')
123
+ .trim()
124
+ .toLowerCase() as (typeof FIELD_DOC_REPLY_TO_AGENT_DOMAINS)[number],
125
+ );
126
+ }
127
+
128
+ /*
129
+ * Check whether one value is usable as a template's secondary reply-to address.
130
+ * The database also rejects uppercase and comma-bearing values.
131
+ */
132
+
133
+ export function isCampaignSecondaryReplyToEmail(
134
+ value?: string | null,
135
+ ): boolean {
136
+ const normalizedValue = String(value || '').trim();
137
+
138
+ return (
139
+ !!normalizedValue &&
140
+ normalizedValue === normalizedValue.toLowerCase() &&
141
+ !normalizedValue.includes(',') &&
142
+ isEmail(normalizedValue)
143
+ );
144
+ }
145
+
146
+ /*
147
+ * Read one email settings object from campaign JSONB without trusting unknown
148
+ * stored values to have the expected scalar types.
149
+ */
150
+
151
+ export function getEmailCampaignSettings(
152
+ settings?: unknown,
153
+ ): EmailCampaignSettingsObj {
154
+ const values = isCampaignObjectRecord(settings) ? settings : {};
155
+
156
+ return {
157
+ subject: typeof values?.subject === 'string' ? values.subject : null,
158
+ 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,
168
+ };
169
+ }
170
+
171
+ /*
172
+ * Read one form settings object from campaign JSONB without trusting unknown
173
+ * stored values to have the expected scalar types.
174
+ */
175
+
176
+ export function getFormCampaignSettings(
177
+ settings?: unknown,
178
+ ): FormCampaignSettingsObj {
179
+ const values = isCampaignObjectRecord(settings) ? settings : {};
180
+
181
+ return {
182
+ color: typeof values?.color === 'string' ? values.color : undefined,
183
+ backgroundFillStyle:
184
+ typeof values?.backgroundFillStyle === 'string' &&
185
+ isCampaignFormBackgroundFillStyle(values.backgroundFillStyle)
186
+ ? values.backgroundFillStyle
187
+ : undefined,
188
+ confirmationMessage:
189
+ typeof values?.confirmationMessage === 'string'
190
+ ? values.confirmationMessage
191
+ : undefined,
192
+ };
193
+ }
194
+
195
+ /*
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.
198
+ */
199
+
200
+ export function getCampaignElementOptions(
201
+ element?: unknown,
202
+ ): CampaignElementOptionObj[] {
203
+ const options = isCampaignObjectRecord(element) ? element.options : null;
204
+
205
+ if (!Array.isArray(options)) {
206
+ return [];
207
+ }
208
+
209
+ 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') {
215
+ return [];
216
+ }
217
+
218
+ return [
219
+ {
220
+ value: option.value,
221
+ label: typeof option.label === 'string' ? option.label : option.value,
222
+ },
223
+ ];
224
+ });
225
+ }
226
+
227
+ /*
228
+ * Read one element validation object while dropping unknown or incorrectly
229
+ * typed JSONB values before they reach GraphQL or another editor save.
230
+ */
231
+
232
+ export function getCampaignElementValidation(
233
+ validation?: unknown,
234
+ ): CampaignElementValidationObj | null {
235
+ const values = isCampaignObjectRecord(validation) ? validation : {};
236
+ 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,
255
+ acceptedContentTypes: Array.isArray(values?.acceptedContentTypes)
256
+ ? values.acceptedContentTypes.filter(
257
+ (value): value is string => typeof value === 'string',
258
+ )
259
+ : undefined,
260
+ };
261
+
262
+ return Object.values(normalized).some((value) => value !== undefined)
263
+ ? normalized
264
+ : null;
265
+ }
266
+
267
+ /*
268
+ * Check whether one value is a supported conditional-visibility operator.
269
+ */
270
+
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
+ );
277
+ }
278
+
279
+ /*
280
+ * Normalize stored or mutation-input visibility into GraphQL's always-array
281
+ * values shape.
282
+ */
283
+
284
+ export function getCampaignElementVisibleWhenValues(
285
+ visibleWhen?: unknown,
286
+ ): CampaignElementVisibleWhenValuesObj | null {
287
+ const valuesObject = isCampaignObjectRecord(visibleWhen) ? visibleWhen : null;
288
+ const operator =
289
+ typeof valuesObject?.operator === 'string' &&
290
+ isCampaignElementVisibleWhenOperator(valuesObject.operator)
291
+ ? valuesObject.operator
292
+ : null;
293
+
294
+ if (typeof valuesObject?.elementKey !== 'string' || !operator) {
295
+ return null;
296
+ }
297
+
298
+ const rawValues =
299
+ 'values' in valuesObject ? valuesObject.values : valuesObject.value;
300
+ const values =
301
+ rawValues == null
302
+ ? []
303
+ : (Array.isArray(rawValues) ? rawValues : [rawValues]).filter(
304
+ (value): value is string => typeof value === 'string',
305
+ );
306
+
307
+ return {
308
+ elementKey: valuesObject.elementKey,
309
+ operator,
310
+ values,
311
+ };
312
+ }
313
+
314
+ /*
315
+ * Convert GraphQL's visibility values list into the JSONB storage shape used
316
+ * by campaign definitions and snapshots.
317
+ */
318
+
319
+ export function getCampaignElementVisibleWhenStorageValue(
320
+ visibleWhen?:
321
+ | CampaignElementVisibleWhenObj
322
+ | CampaignElementVisibleWhenValuesObj
323
+ | null,
324
+ ): CampaignElementVisibleWhenObj | null {
325
+ const normalized = getCampaignElementVisibleWhenValues(visibleWhen);
326
+
327
+ return normalized
328
+ ? {
329
+ elementKey: normalized.elementKey,
330
+ operator: normalized.operator,
331
+ value: normalized.values,
332
+ }
333
+ : null;
334
+ }
335
+
336
+ /*
337
+ * Resolve sparse element presentation settings to GraphQL's explicit boolean
338
+ * fields.
339
+ */
340
+
341
+ export function getCampaignElementSettings(
342
+ settings?: unknown,
343
+ ): CampaignElementSettingsGQL {
344
+ const values = isCampaignObjectRecord(settings) ? settings : {};
345
+
346
+ return {
347
+ numbered: values.numbered === true,
348
+ fullWidth: values.fullWidth === true,
349
+ };
350
+ }
351
+
352
+ /*
353
+ * Convert element presentation settings back to sparse JSONB, clearing the
354
+ * object when every flag is false.
355
+ */
356
+
357
+ export function getCampaignElementSettingsStorageValue(
358
+ settings?: unknown,
359
+ ): CampaignElementSettingsObj | null {
360
+ const values = isCampaignObjectRecord(settings) ? settings : {};
361
+ const normalized: CampaignElementSettingsObj = {
362
+ ...(values.numbered === true ? { numbered: true } : {}),
363
+ ...(values.fullWidth === true ? { fullWidth: true } : {}),
364
+ };
365
+
366
+ return Object.keys(normalized).length ? normalized : null;
367
+ }
368
+
369
+ /*
370
+ * Return one answer's values as an array, so single- and multi-value elements
371
+ * can be validated and rendered through one code path.
372
+ */
373
+
374
+ export function getCampaignAnswerValues(
375
+ answer?: CampaignAnswerObj | null,
376
+ ): string[] {
377
+ if (answer?.value == null) {
378
+ return [];
379
+ }
380
+
381
+ const values = Array.isArray(answer.value) ? answer.value : [answer.value];
382
+ return values.map((value) => String(value).trim()).filter(Boolean);
383
+ }
384
+
385
+ /*
386
+ * Check whether one answer holds nothing a respondent actually entered. FILE
387
+ * elements count their uploads rather than their (always empty) value.
388
+ */
389
+
390
+ export function isCampaignAnswerEmpty(
391
+ element: Pick<CampaignElementData, 'type'>,
392
+ answer?: CampaignAnswerObj | null,
393
+ ): boolean {
394
+ if (element.type === 'FILE') {
395
+ return !answer?.files?.length;
396
+ }
397
+ return !getCampaignAnswerValues(answer).length;
398
+ }
399
+
400
+ /*
401
+ * Decide whether one element is visible given the answers so far. An element
402
+ * with no condition is always visible; a condition naming an unknown element
403
+ * is treated as visible so a malformed rule can never hide a required
404
+ * question and deadlock the form.
405
+ */
406
+
407
+ export function isCampaignElementVisible(
408
+ element: Pick<CampaignElementData, 'visibleWhen'>,
409
+ answers: CampaignAnswersObj,
410
+ elementsByKey?: Map<string, CampaignElementData>,
411
+ ): boolean {
412
+ const condition = element.visibleWhen;
413
+ if (!condition?.elementKey) {
414
+ return true;
415
+ }
416
+
417
+ const target = elementsByKey?.get(condition.elementKey);
418
+ if (elementsByKey && !target) {
419
+ return true;
420
+ }
421
+
422
+ 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];
429
+
430
+ switch (condition.operator) {
431
+ case 'IS_ANSWERED':
432
+ return values.length > 0;
433
+ case 'NOT_EQUALS':
434
+ return !expected.some((value) => values.includes(value));
435
+ case 'INCLUDES':
436
+ return expected.some((value) => values.includes(value));
437
+ case 'EQUALS':
438
+ default:
439
+ return (
440
+ values.length === expected.length &&
441
+ expected.every((value) => values.includes(value))
442
+ );
443
+ }
444
+ }
445
+
446
+ /*
447
+ * Validate one respondent's answers against a template definition and return
448
+ * the element keys that failed, so the caller can reject the whole submission
449
+ * with a precise list. Shared by the public form UI and the server so both
450
+ * agree on what "valid" means.
451
+ *
452
+ * Hidden elements are skipped entirely: a required question behind an unmet
453
+ * condition must not block a submission.
454
+ */
455
+
456
+ export function getInvalidCampaignAnswerKeys(
457
+ elements: CampaignElementData[],
458
+ answers: CampaignAnswersObj,
459
+ options?: { requireAnswers?: boolean },
460
+ ): string[] {
461
+ const questions = elements.filter(isCampaignQuestionElement);
462
+ const elementsByKey = new Map(
463
+ elements.map((element) => [element.key, element]),
464
+ );
465
+ const invalidKeys = new Set<string>();
466
+
467
+ for (const element of questions) {
468
+ if (!isCampaignElementVisible(element, answers, elementsByKey)) {
469
+ continue;
470
+ }
471
+
472
+ const answer = answers[element.key];
473
+ const values = getCampaignAnswerValues(answer);
474
+ const isEmpty = isCampaignAnswerEmpty(element, answer);
475
+
476
+ if (isEmpty) {
477
+ // Drafts may be incomplete; only a submission enforces "required"
478
+ if (element.required && options?.requireAnswers) {
479
+ invalidKeys.add(element.key);
480
+ }
481
+ continue;
482
+ }
483
+
484
+ if (!isCampaignMultiValueElement(element) && values.length > 1) {
485
+ invalidKeys.add(element.key);
486
+ continue;
487
+ }
488
+
489
+ if (isCampaignChoiceElement(element)) {
490
+ const allowedValues = new Set(
491
+ getCampaignElementOptions(element).map((option) => option.value),
492
+ );
493
+ if (values.some((value) => !allowedValues.has(value))) {
494
+ invalidKeys.add(element.key);
495
+ }
496
+ continue;
497
+ }
498
+
499
+ if (!isCampaignAnswerValueValidForType(element, values)) {
500
+ invalidKeys.add(element.key);
501
+ }
502
+ }
503
+
504
+ // An answer naming an element the template does not have is always invalid
505
+ for (const answerKey of Object.keys(answers)) {
506
+ const element = elementsByKey.get(answerKey);
507
+ if (!element || !isCampaignQuestionElement(element)) {
508
+ invalidKeys.add(answerKey);
509
+ }
510
+ }
511
+
512
+ return [...invalidKeys];
513
+ }
514
+
515
+ /*
516
+ * Check one non-choice answer against its element's type and validation rules.
517
+ */
518
+
519
+ export function isCampaignAnswerValueValidForType(
520
+ element: Pick<CampaignElementData, 'type' | 'validation'>,
521
+ values: string[],
522
+ ): boolean {
523
+ const validation = element.validation || {};
524
+
525
+ return values.every((value) => {
526
+ switch (element.type) {
527
+ case 'NUMBER': {
528
+ const numberValue = Number(value);
529
+ if (!Number.isFinite(numberValue)) {
530
+ return false;
531
+ }
532
+ if (validation.min != null && numberValue < validation.min) {
533
+ return false;
534
+ }
535
+ return !(validation.max != null && numberValue > validation.max);
536
+ }
537
+ 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
+ );
542
+ case 'EMAIL':
543
+ return isEmail(value);
544
+ case 'PHONE':
545
+ return /^[+()\-.\s\d]{7,20}$/.test(value);
546
+ case 'SHORT_TEXT':
547
+ case 'LONG_TEXT': {
548
+ if (
549
+ validation.minLength != null &&
550
+ value.length < validation.minLength
551
+ ) {
552
+ return false;
553
+ }
554
+ if (
555
+ validation.maxLength != null &&
556
+ value.length > validation.maxLength
557
+ ) {
558
+ return false;
559
+ }
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
+ }
567
+ }
568
+ return true;
569
+ }
570
+ default:
571
+ return true;
572
+ }
573
+ });
574
+ }
575
+
576
+ /*
577
+ * Check whether one value is a supported form background fill style.
578
+ */
579
+
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
+ );
586
+ }
587
+
588
+ /*
589
+ * Resolve a form color into one generated CSS palette name.
590
+ */
591
+
592
+ export function normalizeCampaignFormColor(
593
+ color?: string | null,
594
+ ): string | null {
595
+ const normalizedColor = String(color || '')
596
+ .trim()
597
+ .toLowerCase();
598
+
599
+ if (!normalizedColor) {
600
+ return null;
601
+ }
602
+
603
+ if (normalizedColor === 'gray' || normalizedColor === 'grey') {
604
+ return CAMPAIGN_FORM_NEUTRAL_COLOR;
605
+ }
606
+
607
+ return CAMPAIGN_FORM_COLORS.includes(normalizedColor)
608
+ ? normalizedColor
609
+ : null;
610
+ }
611
+
612
+ /*
613
+ * Resolve the form theme color; GRAYSCALE always renders neutral.
614
+ */
615
+
616
+ export function getCampaignFormColor(
617
+ settings?: FormCampaignSettingsObj | null,
618
+ ): string | null {
619
+ if (getCampaignFormBackgroundFillStyle(settings) === 'GRAYSCALE') {
620
+ return CAMPAIGN_FORM_NEUTRAL_COLOR;
621
+ }
622
+
623
+ return normalizeCampaignFormColor(settings?.color);
624
+ }
625
+
626
+ /*
627
+ * Resolve the form background fill style, falling back to the default.
628
+ */
629
+
630
+ export function getCampaignFormBackgroundFillStyle(
631
+ settings?: FormCampaignSettingsObj | null,
632
+ ): CampaignFormBackgroundFillStyleEnum {
633
+ const style = String(settings?.backgroundFillStyle || '')
634
+ .trim()
635
+ .toUpperCase();
636
+
637
+ return isCampaignFormBackgroundFillStyle(style)
638
+ ? style
639
+ : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
640
+ }
641
+
642
+ /*
643
+ * Resolve one form's body background colour to a CSS custom property.
644
+ *
645
+ * GRAYSCALE ignores the chosen colour entirely; every other fill style maps to
646
+ * a shade of it. Unknown input falls back to the neutral palette rather than
647
+ * emitting an undefined variable.
648
+ */
649
+
650
+ export function getCampaignFormBackgroundColorValue(
651
+ color?: string | null,
652
+ backgroundFillStyle?: string | null,
653
+ ): string {
654
+ const style = String(backgroundFillStyle || '')
655
+ .trim()
656
+ .toUpperCase();
657
+ const fillStyle = isCampaignFormBackgroundFillStyle(style)
658
+ ? style
659
+ : CAMPAIGN_FORM_DEFAULT_BACKGROUND_FILL_STYLE;
660
+ const resolvedColor =
661
+ fillStyle === 'GRAYSCALE'
662
+ ? CAMPAIGN_FORM_NEUTRAL_COLOR
663
+ : normalizeCampaignFormColor(color) || CAMPAIGN_FORM_NEUTRAL_COLOR;
664
+
665
+ switch (fillStyle) {
666
+ case 'FADED':
667
+ return `var(--color-${resolvedColor}-alt-fade)`;
668
+ case 'LIGHT':
669
+ return `var(--color-${resolvedColor}-alt-light)`;
670
+ case 'GRAYSCALE':
671
+ case 'MEDIUM':
672
+ default:
673
+ return `var(--color-${resolvedColor}-alt-medium)`;
674
+ }
675
+ }
676
+
677
+ /*
678
+ * Resolve one typed form settings object to its background colour.
679
+ */
680
+ export function getCampaignFormBackgroundColorValueFromSettings(
681
+ settings?: FormCampaignSettingsObj | null,
682
+ ): string {
683
+ return getCampaignFormBackgroundColorValue(
684
+ settings?.color,
685
+ settings?.backgroundFillStyle,
686
+ );
687
+ }
688
+
689
+ /**
690
+ * Local draft shape for the create-campaign modal.
691
+ *
692
+ * Every persisted field is declared so a draft written by an older build is
693
+ * rejected rather than half-read; the file list is capped at the same limit the
694
+ * generation request enforces.
695
+ */
696
+
697
+ export const CAMPAIGN_DRAFT_SCHEMA: DraftSchema = {
698
+ files: {
699
+ type: 'array',
700
+ maxLength: MAX_PUBLIC_FORM_GENERATION_FILES,
701
+ of: {
702
+ contentType: 'string',
703
+ fileKey: 'string',
704
+ fileUri: 'string',
705
+ name: 'string',
706
+ storageId: 'string',
707
+ uploadedAt: 'number',
708
+ },
709
+ },
710
+ instructions: {
711
+ EMAIL: { type: 'string', maxLength: CAMPAIGN_INSTRUCTIONS_MAX_LENGTH },
712
+ PUBLIC_FORM: {
713
+ type: 'string',
714
+ maxLength: CAMPAIGN_INSTRUCTIONS_MAX_LENGTH,
715
+ },
716
+ },
717
+ };
718
+
719
+ /*
720
+ * Build the local draft key for one organization's create-campaign modal.
721
+ * Drafts hold organization content, so the key is scoped per organization.
722
+ */
723
+
724
+ export function getCampaignDraftKey(organizationId: string | number | bigint) {
725
+ return `${CAMPAIGN_DRAFT_KEY_PREFIX}:${organizationId}`;
726
+ }
727
+
728
+ /*
729
+ * Build the empty create-campaign draft. Returned fresh each call so callers
730
+ * can hold it in state without sharing one mutable object.
731
+ */
732
+
733
+ export function getEmptyCampaignDraft(): CampaignDraft {
734
+ return {
735
+ files: [],
736
+ instructions: {
737
+ EMAIL: '',
738
+ PUBLIC_FORM: '',
739
+ },
740
+ };
741
+ }