@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,871 +0,0 @@
1
- import { CAMPAIGN_CHOICE_ELEMENT_TYPES } from '../constants/campaign.ts';
2
- import type {
3
- CampaignDefinitionSectionGQL,
4
- CampaignDefinitionSnapshotGQL,
5
- CampaignElementGQL,
6
- CampaignElementKindEnum,
7
- CampaignElementOptionObj,
8
- CampaignElementSettingsObj,
9
- CampaignElementTypeEnum,
10
- CampaignElementValidationObj,
11
- CampaignElementVisibleWhenObj,
12
- CampaignElementVisibleWhenValuesObj,
13
- CampaignGQL,
14
- CampaignSectionInputObj,
15
- CampaignTemplateGQL,
16
- } from '../types/campaign.d.ts';
17
- import {
18
- getCampaignElementSettingsStorageValue,
19
- getCampaignElementValidation,
20
- getCampaignElementVisibleWhenValues,
21
- } from './campaign.ts';
22
-
23
- /**
24
- * Client editing model for one campaign definition.
25
- *
26
- * This is a port of the field-doc form editor onto the campaign element model.
27
- * The draft shape and every tree operation are unchanged; only the two ends
28
- * differ - what is read out of a fetched template, and what is sent back on
29
- * save. A campaign element carries two axes rather than the field doc's kind
30
- * plus answer mode: "kind" is its structural role and "type" is how a QUESTION
31
- * is answered, set if and only if kind is QUESTION.
32
- */
33
-
34
- // A child element is never a SECTION; sections are the draft's own level
35
- export type CampaignFormEditorElementKind = Exclude<
36
- CampaignElementKindEnum,
37
- 'SECTION'
38
- >;
39
-
40
- export type CampaignFormEditorDropPosition = 'AFTER' | 'BEFORE';
41
-
42
- export const CAMPAIGN_FORM_EDITOR_TITLE_DESCRIPTION_ANCHOR_ID =
43
- 'campaign_form_title_description';
44
-
45
- export interface CampaignFormEditorDraftElement {
46
- clientId: string;
47
- description: string;
48
- id?: string | null;
49
- key: string;
50
- kind: CampaignFormEditorElementKind;
51
- label: string;
52
- options: CampaignElementOptionObj[];
53
- placeholder: string;
54
- required: boolean;
55
- settings: CampaignElementSettingsObj | null;
56
- type: CampaignElementTypeEnum | null;
57
- validation: CampaignElementValidationObj | null;
58
- visibleWhen: CampaignElementVisibleWhenValuesObj | null;
59
- }
60
-
61
- /*
62
- * Return the stable DOM anchor ID for one editable campaign-form question.
63
- */
64
- export function getCampaignFormEditorQuestionAnchorId(elementClientId: string) {
65
- return `campaign_form_question_${elementClientId}`;
66
- }
67
-
68
- export interface CampaignFormEditorDraftSection {
69
- clientId: string;
70
- description: string;
71
- elements: CampaignFormEditorDraftElement[];
72
- id?: string | null;
73
- key: string;
74
- label: string;
75
- settings: CampaignElementSettingsObj | null;
76
- }
77
-
78
- export type CampaignFormEditorSourceType = 'CAMPAIGN' | 'TEMPLATE';
79
-
80
- export interface CampaignFormEditorSource {
81
- description: string;
82
- generating: boolean;
83
- generatingMessage?: string | null;
84
- id: string;
85
- kind: CampaignGQL['kind'] | CampaignTemplateGQL['kind'];
86
- sections: CampaignFormEditorDraftSection[];
87
- title: string;
88
- type: CampaignFormEditorSourceType;
89
- updatedAt: string;
90
- }
91
-
92
- type CampaignFormEditorSourceInput =
93
- | {
94
- data: CampaignGQL;
95
- type: 'CAMPAIGN';
96
- }
97
- | {
98
- data: CampaignTemplateGQL;
99
- type: 'TEMPLATE';
100
- };
101
-
102
- interface CampaignFormEditorElementSource {
103
- clientId?: string | null;
104
- description?: string | null;
105
- id?: string | null;
106
- key: string;
107
- kind: CampaignElementKindEnum;
108
- label?: string | null;
109
- options?: unknown;
110
- placeholder?: string | null;
111
- required?: boolean | null;
112
- settings?: CampaignElementSettingsObj | null;
113
- type?: CampaignElementTypeEnum | null;
114
- validation?: CampaignElementValidationObj | null;
115
- visibleWhen?:
116
- | CampaignElementVisibleWhenObj
117
- | CampaignElementVisibleWhenValuesObj
118
- | null;
119
- }
120
-
121
- /*
122
- * Create one edit-session identifier that is never persisted to the server.
123
- */
124
- function createCampaignFormEditorClientId(prefix: string) {
125
- const randomId =
126
- globalThis.crypto?.randomUUID?.() ||
127
- `${Date.now()}_${Math.random().toString(36).slice(2)}`;
128
-
129
- return `${prefix}_${randomId}`;
130
- }
131
-
132
- /*
133
- * Create one stable answer key for a new section or child element.
134
- */
135
- function createCampaignFormEditorKey(prefix: string) {
136
- const randomId =
137
- globalThis.crypto?.randomUUID?.().replaceAll('-', '') ||
138
- `${Date.now()}${Math.random().toString(36).slice(2)}`;
139
-
140
- return `${prefix}_${randomId}`;
141
- }
142
-
143
- /*
144
- * Create one unsaved choice whose stable value will be derived on first save.
145
- */
146
- function createCampaignFormEditorDraftOption(): CampaignElementOptionObj {
147
- return {
148
- label: '',
149
- value: '',
150
- };
151
- }
152
-
153
- /**
154
- * Return whether one element type takes a fixed list of choices.
155
- */
156
- export function isCampaignFormEditorChoiceType(
157
- type?: CampaignElementTypeEnum | null,
158
- ): boolean {
159
- return !!type && CAMPAIGN_CHOICE_ELEMENT_TYPES.includes(type);
160
- }
161
-
162
- /*
163
- * Normalize stored choices into the stable value-and-label shape the editor
164
- * carries. Legacy string choices are promoted without changing their value.
165
- */
166
- function getCampaignFormEditorOptions(
167
- options: unknown,
168
- ): CampaignElementOptionObj[] {
169
- if (!Array.isArray(options)) {
170
- return [];
171
- }
172
-
173
- return options.flatMap((option) => {
174
- if (typeof option === 'string') {
175
- return option ? [{ label: option, value: option }] : [];
176
- }
177
-
178
- if (!option || typeof option !== 'object') {
179
- return [];
180
- }
181
-
182
- const optionValue = String(
183
- (option as CampaignElementOptionObj).value || '',
184
- );
185
- const optionLabel = String(
186
- (option as CampaignElementOptionObj).label || optionValue,
187
- );
188
-
189
- return optionLabel
190
- ? [{ label: optionLabel, value: optionValue || optionLabel }]
191
- : [];
192
- });
193
- }
194
-
195
- /*
196
- * Convert one fetched campaign element into mutable client draft data.
197
- *
198
- * An element's stored type is carried through untouched rather than being
199
- * re-derived, so a generated question the editor has no dedicated control for
200
- * still round-trips instead of silently degrading to text on the next save.
201
- */
202
- function getCampaignFormEditorDraftElement(
203
- element: CampaignFormEditorElementSource,
204
- ): CampaignFormEditorDraftElement {
205
- const kind: CampaignFormEditorElementKind =
206
- element.kind === 'QUESTION' ? 'QUESTION' : 'CONTENT';
207
- const answerable = kind === 'QUESTION';
208
-
209
- return {
210
- clientId:
211
- element.clientId ||
212
- element.id ||
213
- createCampaignFormEditorClientId('element'),
214
- description: element.description || '',
215
- id: element.id || null,
216
- key: element.key,
217
- kind,
218
- label: element.label || '',
219
- options: answerable ? getCampaignFormEditorOptions(element.options) : [],
220
- placeholder: element.placeholder || '',
221
- required: answerable && !!element.required,
222
- settings: getCampaignElementSettingsStorageValue(element.settings),
223
- type: answerable ? element.type || 'SHORT_TEXT' : null,
224
- validation: getCampaignElementValidation(element.validation),
225
- visibleWhen: getCampaignElementVisibleWhenValues(element.visibleWhen),
226
- };
227
- }
228
-
229
- /**
230
- * Convert one fetched template's flat element list into draft sections.
231
- *
232
- * Campaign elements arrive flat with a parentId rather than nested, so the
233
- * sections are picked out first and their children matched against them.
234
- */
235
- export function getCampaignFormEditorDraftSections(
236
- elements?: CampaignElementGQL[] | null,
237
- ): CampaignFormEditorDraftSection[] {
238
- const allElements = elements || [];
239
-
240
- return allElements
241
- .filter((element) => element.kind === 'SECTION')
242
- .slice()
243
- .sort((first, second) => (first.order || 0) - (second.order || 0))
244
- .map((section) => ({
245
- clientId: section.id || createCampaignFormEditorClientId('section'),
246
- description: section.description || '',
247
- elements: allElements
248
- .filter(
249
- (element) =>
250
- element.parentId && String(element.parentId) === String(section.id),
251
- )
252
- .slice()
253
- .sort((first, second) => (first.order || 0) - (second.order || 0))
254
- .map(getCampaignFormEditorDraftElement),
255
- id: section.id || null,
256
- key: section.key,
257
- label: section.label || '',
258
- settings: getCampaignElementSettingsStorageValue(section.settings),
259
- }));
260
- }
261
-
262
- /*
263
- * Convert one nested snapshot section into the editor's section shape.
264
- */
265
- function getCampaignFormEditorCampaignSection(
266
- section: CampaignDefinitionSectionGQL,
267
- ): CampaignFormEditorDraftSection {
268
- const sectionKey = String(
269
- section?.key || createCampaignFormEditorKey('section'),
270
- );
271
-
272
- return {
273
- clientId: sectionKey,
274
- description: String(section?.description || ''),
275
- elements: Array.isArray(section?.elements)
276
- ? section.elements.map((element) => {
277
- const elementKey = String(
278
- element?.key || createCampaignFormEditorKey('question'),
279
- );
280
-
281
- return getCampaignFormEditorDraftElement({
282
- clientId: elementKey,
283
- description: element?.description,
284
- key: elementKey,
285
- kind: element?.kind,
286
- label: element?.label,
287
- options: element?.options,
288
- placeholder: element?.placeholder,
289
- required: element?.required,
290
- settings: element?.settings,
291
- type: element?.type,
292
- validation: element?.validation,
293
- visibleWhen: element?.visibleWhen,
294
- });
295
- })
296
- : [],
297
- id: null,
298
- key: sectionKey,
299
- label: String(section?.label || ''),
300
- settings: getCampaignElementSettingsStorageValue(section?.settings),
301
- };
302
- }
303
-
304
- /*
305
- * Convert one campaign-owned nested definition snapshot into editor sections.
306
- */
307
- function getCampaignFormEditorCampaignSections(
308
- definitionSnapshot?: CampaignDefinitionSnapshotGQL | null,
309
- ): CampaignFormEditorDraftSection[] | null {
310
- if (!Array.isArray(definitionSnapshot?.sections)) {
311
- return null;
312
- }
313
-
314
- return definitionSnapshot.sections.map(getCampaignFormEditorCampaignSection);
315
- }
316
-
317
- /*
318
- * Map a template or published campaign into the editor's shared source shape.
319
- */
320
- export function getCampaignFormEditorSource(
321
- input: CampaignFormEditorSourceInput,
322
- ): CampaignFormEditorSource | null {
323
- if (input.type === 'CAMPAIGN') {
324
- const sections = getCampaignFormEditorCampaignSections(
325
- input.data.definitionSnapshot,
326
- );
327
-
328
- if (!sections) {
329
- return null;
330
- }
331
-
332
- return {
333
- description: input.data.description || '',
334
- generating: false,
335
- id: String(input.data.id),
336
- kind: input.data.kind,
337
- sections,
338
- title: input.data.title || '',
339
- type: input.type,
340
- updatedAt: input.data.updatedAt,
341
- };
342
- }
343
-
344
- return {
345
- description: input.data.description || '',
346
- generating: input.data.status === 'GENERATING',
347
- generatingMessage:
348
- input.data.status === 'GENERATING'
349
- ? input.data.generationProgress?.message
350
- : null,
351
- id: String(input.data.id),
352
- kind: input.data.kind,
353
- sections: getCampaignFormEditorDraftSections(input.data.elements),
354
- title: input.data.title || '',
355
- type: input.type,
356
- updatedAt: input.data.updatedAt,
357
- };
358
- }
359
-
360
- /*
361
- * Create a blank section ready to be inserted into the form draft.
362
- */
363
- export function createCampaignFormEditorDraftSection(): CampaignFormEditorDraftSection {
364
- return {
365
- clientId: createCampaignFormEditorClientId('section'),
366
- description: '',
367
- elements: [],
368
- id: null,
369
- key: createCampaignFormEditorKey('section'),
370
- label: '',
371
- settings: null,
372
- };
373
- }
374
-
375
- /*
376
- * Create a blank child element ready to be inserted into a section.
377
- */
378
- export function createCampaignFormEditorDraftElement(
379
- kind: CampaignFormEditorElementKind = 'QUESTION',
380
- ): CampaignFormEditorDraftElement {
381
- return {
382
- clientId: createCampaignFormEditorClientId('element'),
383
- description: '',
384
- id: null,
385
- key: createCampaignFormEditorKey('question'),
386
- kind,
387
- label: '',
388
- options: [],
389
- placeholder: '',
390
- required: false,
391
- settings: null,
392
- // A CONTENT element must never carry a type; the database rejects it
393
- type: kind === 'QUESTION' ? 'SHORT_TEXT' : null,
394
- validation: null,
395
- visibleWhen: null,
396
- };
397
- }
398
-
399
- /**
400
- * Return a section list with one section's editable fields changed.
401
- */
402
- export function updateCampaignFormEditorSection(
403
- sections: CampaignFormEditorDraftSection[],
404
- sectionClientId: string,
405
- changes: Partial<
406
- Omit<CampaignFormEditorDraftSection, 'clientId' | 'elements'>
407
- >,
408
- ) {
409
- return sections.map((section) =>
410
- section.clientId === sectionClientId ? { ...section, ...changes } : section,
411
- );
412
- }
413
-
414
- /**
415
- * Return a section list with one child element's editable fields changed.
416
- */
417
- export function updateCampaignFormEditorElement(
418
- sections: CampaignFormEditorDraftSection[],
419
- sectionClientId: string,
420
- elementClientId: string,
421
- changes: Partial<Omit<CampaignFormEditorDraftElement, 'clientId'>>,
422
- ) {
423
- return sections.map((section) => {
424
- if (section.clientId !== sectionClientId) {
425
- return section;
426
- }
427
-
428
- return {
429
- ...section,
430
- elements: section.elements.map((element) =>
431
- element.clientId === elementClientId
432
- ? { ...element, ...changes }
433
- : element,
434
- ),
435
- };
436
- });
437
- }
438
-
439
- /**
440
- * Return a section list with one blank section appended.
441
- */
442
- export function addCampaignFormEditorSection(
443
- sections: CampaignFormEditorDraftSection[],
444
- ) {
445
- return [...sections, createCampaignFormEditorDraftSection()];
446
- }
447
-
448
- /**
449
- * Return a section list without one selected section.
450
- */
451
- export function removeCampaignFormEditorSection(
452
- sections: CampaignFormEditorDraftSection[],
453
- sectionClientId: string,
454
- ) {
455
- return sections.filter((section) => section.clientId !== sectionClientId);
456
- }
457
-
458
- /**
459
- * Return a section list with one blank element appended to a selected section.
460
- */
461
- export function addCampaignFormEditorElement(
462
- sections: CampaignFormEditorDraftSection[],
463
- sectionClientId: string,
464
- kind: CampaignFormEditorElementKind = 'QUESTION',
465
- ) {
466
- return sections.map((section) =>
467
- section.clientId === sectionClientId
468
- ? {
469
- ...section,
470
- elements: [
471
- ...section.elements,
472
- createCampaignFormEditorDraftElement(kind),
473
- ],
474
- }
475
- : section,
476
- );
477
- }
478
-
479
- /**
480
- * Return a section list without one selected child element.
481
- */
482
- export function removeCampaignFormEditorElement(
483
- sections: CampaignFormEditorDraftSection[],
484
- sectionClientId: string,
485
- elementClientId: string,
486
- ) {
487
- return sections.map((section) =>
488
- section.clientId === sectionClientId
489
- ? {
490
- ...section,
491
- elements: section.elements.filter(
492
- (element) => element.clientId !== elementClientId,
493
- ),
494
- }
495
- : section,
496
- );
497
- }
498
-
499
- /*
500
- * Move one array item immediately before or after a selected target.
501
- */
502
- function moveCampaignFormEditorItem<T extends { clientId: string }>(
503
- items: T[],
504
- sourceClientId: string,
505
- targetClientId: string,
506
- position: CampaignFormEditorDropPosition,
507
- ) {
508
- const sourceIndex = items.findIndex(
509
- (item) => item.clientId === sourceClientId,
510
- );
511
- const targetIndex = items.findIndex(
512
- (item) => item.clientId === targetClientId,
513
- );
514
-
515
- if (sourceIndex < 0 || targetIndex < 0 || sourceClientId === targetClientId) {
516
- return items;
517
- }
518
-
519
- const nextItems = [...items];
520
- const [movedItem] = nextItems.splice(sourceIndex, 1);
521
- const adjustedTargetIndex = nextItems.findIndex(
522
- (item) => item.clientId === targetClientId,
523
- );
524
- const insertIndex =
525
- position === 'AFTER' ? adjustedTargetIndex + 1 : adjustedTargetIndex;
526
-
527
- nextItems.splice(insertIndex, 0, movedItem);
528
-
529
- return nextItems;
530
- }
531
-
532
- /**
533
- * Move one section before or after another section.
534
- */
535
- export function moveCampaignFormEditorSection(
536
- sections: CampaignFormEditorDraftSection[],
537
- sourceSectionClientId: string,
538
- targetSectionClientId: string,
539
- position: CampaignFormEditorDropPosition = 'BEFORE',
540
- ) {
541
- return moveCampaignFormEditorItem(
542
- sections,
543
- sourceSectionClientId,
544
- targetSectionClientId,
545
- position,
546
- );
547
- }
548
-
549
- /**
550
- * Move one section up or down by a single step.
551
- */
552
- export function moveCampaignFormEditorSectionByOffset(
553
- sections: CampaignFormEditorDraftSection[],
554
- sectionClientId: string,
555
- offset: number,
556
- ) {
557
- const sectionIndex = sections.findIndex(
558
- (section) => section.clientId === sectionClientId,
559
- );
560
- const targetIndex = sectionIndex + offset;
561
-
562
- if (sectionIndex < 0 || targetIndex < 0 || targetIndex >= sections.length) {
563
- return sections;
564
- }
565
-
566
- const nextSections = [...sections];
567
- const [movedSection] = nextSections.splice(sectionIndex, 1);
568
- nextSections.splice(targetIndex, 0, movedSection);
569
-
570
- return nextSections;
571
- }
572
-
573
- /**
574
- * Move one child element within or across sections.
575
- *
576
- * A null target element appends to the end of the target section, which is what
577
- * the section-level drop zone means.
578
- */
579
- export function moveCampaignFormEditorElement(
580
- sections: CampaignFormEditorDraftSection[],
581
- elementClientId: string,
582
- targetSectionClientId: string,
583
- targetElementClientId?: string | null,
584
- position: CampaignFormEditorDropPosition = 'BEFORE',
585
- ) {
586
- const sourceSection = sections.find((section) =>
587
- section.elements.some((element) => element.clientId === elementClientId),
588
- );
589
-
590
- if (!sourceSection) {
591
- return sections;
592
- }
593
-
594
- const sourceElement = sourceSection.elements.find(
595
- (element) => element.clientId === elementClientId,
596
- );
597
-
598
- if (!sourceElement) {
599
- return sections;
600
- }
601
-
602
- // Reordering inside one section is a plain move; no element leaves its parent
603
- if (
604
- sourceSection.clientId === targetSectionClientId &&
605
- targetElementClientId
606
- ) {
607
- return sections.map((section) =>
608
- section.clientId === targetSectionClientId
609
- ? {
610
- ...section,
611
- elements: moveCampaignFormEditorItem(
612
- section.elements,
613
- elementClientId,
614
- targetElementClientId,
615
- position,
616
- ),
617
- }
618
- : section,
619
- );
620
- }
621
-
622
- return sections.map((section) => {
623
- if (section.clientId === sourceSection.clientId) {
624
- return {
625
- ...section,
626
- elements: section.elements.filter(
627
- (element) => element.clientId !== elementClientId,
628
- ),
629
- };
630
- }
631
-
632
- if (section.clientId === targetSectionClientId) {
633
- if (!targetElementClientId) {
634
- return { ...section, elements: [...section.elements, sourceElement] };
635
- }
636
-
637
- const targetIndex = section.elements.findIndex(
638
- (element) => element.clientId === targetElementClientId,
639
- );
640
-
641
- if (targetIndex < 0) {
642
- return { ...section, elements: [...section.elements, sourceElement] };
643
- }
644
-
645
- const nextElements = [...section.elements];
646
- nextElements.splice(
647
- position === 'AFTER' ? targetIndex + 1 : targetIndex,
648
- 0,
649
- sourceElement,
650
- );
651
-
652
- return { ...section, elements: nextElements };
653
- }
654
-
655
- return section;
656
- });
657
- }
658
-
659
- /**
660
- * Move one child element up or down by a single step, crossing into the
661
- * neighbouring section when it is already at an edge.
662
- */
663
- export function moveCampaignFormEditorElementByOffset(
664
- sections: CampaignFormEditorDraftSection[],
665
- sectionClientId: string,
666
- elementClientId: string,
667
- offset: number,
668
- ) {
669
- const sectionIndex = sections.findIndex(
670
- (section) => section.clientId === sectionClientId,
671
- );
672
-
673
- if (sectionIndex < 0) {
674
- return sections;
675
- }
676
-
677
- const section = sections[sectionIndex];
678
- const elementIndex = section.elements.findIndex(
679
- (element) => element.clientId === elementClientId,
680
- );
681
-
682
- if (elementIndex < 0) {
683
- return sections;
684
- }
685
-
686
- const targetIndex = elementIndex + offset;
687
-
688
- if (targetIndex >= 0 && targetIndex < section.elements.length) {
689
- const nextElements = [...section.elements];
690
- const [movedElement] = nextElements.splice(elementIndex, 1);
691
- nextElements.splice(targetIndex, 0, movedElement);
692
-
693
- return sections.map((item, index) =>
694
- index === sectionIndex ? { ...item, elements: nextElements } : item,
695
- );
696
- }
697
-
698
- const neighbourIndex = sectionIndex + (offset < 0 ? -1 : 1);
699
-
700
- if (neighbourIndex < 0 || neighbourIndex >= sections.length) {
701
- return sections;
702
- }
703
-
704
- const [movedElement] = [section.elements[elementIndex]];
705
-
706
- return sections.map((item, index) => {
707
- if (index === sectionIndex) {
708
- return {
709
- ...item,
710
- elements: item.elements.filter(
711
- (element) => element.clientId !== elementClientId,
712
- ),
713
- };
714
- }
715
-
716
- if (index === neighbourIndex) {
717
- return {
718
- ...item,
719
- elements:
720
- offset < 0
721
- ? [...item.elements, movedElement]
722
- : [movedElement, ...item.elements],
723
- };
724
- }
725
-
726
- return item;
727
- });
728
- }
729
-
730
- /**
731
- * Return the element changes needed when its answer type changes.
732
- *
733
- * Entering a choice type seeds one blank option so the author has a row to type
734
- * into; leaving one clears the choices the new type cannot hold.
735
- */
736
- export function getCampaignFormEditorTypeChanges(
737
- element: CampaignFormEditorDraftElement,
738
- type: CampaignElementTypeEnum,
739
- ): Partial<CampaignFormEditorDraftElement> {
740
- if (!isCampaignFormEditorChoiceType(type)) {
741
- return { options: [], type };
742
- }
743
-
744
- return {
745
- options: element.options.length
746
- ? element.options
747
- : [createCampaignFormEditorDraftOption()],
748
- type,
749
- };
750
- }
751
-
752
- /**
753
- * Return normalized field changes when a form element changes kind.
754
- */
755
- export function getCampaignFormEditorKindChanges(
756
- kind: CampaignFormEditorElementKind,
757
- ): Partial<CampaignFormEditorDraftElement> {
758
- if (kind !== 'QUESTION') {
759
- return {
760
- kind,
761
- options: [],
762
- placeholder: '',
763
- required: false,
764
- type: null,
765
- };
766
- }
767
-
768
- return { kind, type: 'SHORT_TEXT' };
769
- }
770
-
771
- /**
772
- * Return whether the current draft contains all values required for saving.
773
- *
774
- * Mirrors the server's own rules so the editor can disable Save rather than
775
- * letting a write fail: every question labelled, and every choice question
776
- * carrying at least two distinct, non-empty choices.
777
- */
778
- export function isCampaignFormEditorDraftValid(
779
- sections: CampaignFormEditorDraftSection[],
780
- ) {
781
- const questions = sections.flatMap((section) =>
782
- section.elements.filter((element) => element.kind === 'QUESTION'),
783
- );
784
-
785
- if (!questions.length) {
786
- return false;
787
- }
788
-
789
- return sections.every((section) =>
790
- section.elements.every((element) => {
791
- if (element.kind === 'QUESTION' && !element.label.trim()) {
792
- return false;
793
- }
794
-
795
- const normalizedOptions = new Set<string>();
796
- for (const option of element.options) {
797
- const normalizedOption = option.label.trim();
798
- if (!normalizedOption || normalizedOptions.has(normalizedOption)) {
799
- return false;
800
- }
801
- normalizedOptions.add(normalizedOption);
802
- }
803
-
804
- if (
805
- isCampaignFormEditorChoiceType(element.type) &&
806
- normalizedOptions.size < 2
807
- ) {
808
- return false;
809
- }
810
-
811
- return true;
812
- }),
813
- );
814
- }
815
-
816
- /**
817
- * Convert the client draft into the ordered GraphQL mutation input.
818
- *
819
- * Order is positional rather than an explicit field: the server renumbers from
820
- * array position, so the draft never has to keep an order counter in sync.
821
- */
822
- export function getCampaignFormEditorSectionInputs(
823
- sections: CampaignFormEditorDraftSection[],
824
- ): CampaignSectionInputObj[] {
825
- return sections.map((section) => ({
826
- description: section.description.trim() || null,
827
- elements: section.elements.map((element) => {
828
- const answerable = element.kind === 'QUESTION';
829
-
830
- return {
831
- description: element.description.trim() || null,
832
- key: element.key,
833
- kind: element.kind,
834
- label: element.label.trim() || null,
835
- options:
836
- answerable && isCampaignFormEditorChoiceType(element.type)
837
- ? element.options
838
- .map((option) => ({
839
- label: option.label.trim(),
840
- value: option.value.trim() || option.label.trim(),
841
- }))
842
- .filter((option) => option.label)
843
- : null,
844
- placeholder: answerable ? element.placeholder.trim() || null : null,
845
- required: answerable && element.required,
846
- settings: element.settings,
847
- type: answerable ? element.type : null,
848
- validation: answerable ? element.validation : null,
849
- visibleWhen: element.visibleWhen,
850
- };
851
- }),
852
- key: section.key,
853
- label: section.label.trim() || null,
854
- settings: section.settings,
855
- }));
856
- }
857
-
858
- /**
859
- * Build the stable comparison value used to detect unsaved editor changes.
860
- */
861
- export function getCampaignFormEditorDraftKey(
862
- title: string,
863
- description: string,
864
- sections: CampaignFormEditorDraftSection[],
865
- ) {
866
- return JSON.stringify({
867
- description,
868
- sections: getCampaignFormEditorSectionInputs(sections),
869
- title,
870
- });
871
- }