@jsb188/mday 1.1.10 → 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 +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -1,66 +1,198 @@
1
- import type { InboundEmailBodyFormatEnum } from '../types/email.d.ts';
2
-
3
- type PostmarkAttachmentLike = {
4
- Name?: string | null;
5
- ContentType?: string | null;
6
- ContentLength?: number | null;
7
- };
1
+ import { convertHTMLToMarkdown } from '../../../@jsb188:react-web/utils/markdown.ts';
2
+ import { EMAIL_STATUS_GROUP_STATUSES } from '../constants/email.ts';
3
+ import type {
4
+ EmailDirectionEnum,
5
+ EmailStatusGroupEnum,
6
+ InboundEmailBodyFormatEnum,
7
+ OutboundEmailData,
8
+ OutboundEmailStatusEnum,
9
+ } from '../types/email.d.ts';
8
10
 
9
11
  type PostmarkInboundPayloadLike = {
12
+ HtmlBody?: string | null;
10
13
  TextBody?: string | null;
11
14
  StrippedTextReply?: string | null;
12
- HtmlBody?: string | null;
13
- Attachments?: PostmarkAttachmentLike[] | null;
14
15
  };
15
16
 
17
+ const INBOUND_EMAIL_PAYLOAD_OMIT_KEYS = [
18
+ 'HtmlBody',
19
+ 'Attachments',
20
+ // These keys are server-owned processing metadata, never provider input.
21
+ 'storedAttachments',
22
+ 'queuePublishedAt',
23
+ 'processingReadyAt',
24
+ 'processingQueueSuffix',
25
+ 'processingRetryNotBefore',
26
+ 'postmasterMutationCheckpoint',
27
+ 'postmasterTransientFailures',
28
+ ];
29
+ const INBOUND_EMAIL_DEFAULT_BODY_LENGTH = 12000;
30
+ const INBOUND_EMAIL_PREVIEW_LENGTH = 240;
31
+
32
+ /*
33
+ * Return the delivery status callers should present for one outbound row;
34
+ * Postmark spam complaints are stored alongside SENT but are terminal BLOCKED
35
+ * evidence for any future retry decision.
36
+ */
37
+ export function getOutboundEmailEffectiveDeliveryStatus(
38
+ value:
39
+ | OutboundEmailStatusEnum
40
+ | 'BLOCKED'
41
+ | Pick<OutboundEmailData, 'status' | 'spamComplaintAt'>,
42
+ ) {
43
+ return typeof value !== 'string' && value.spamComplaintAt
44
+ ? ('BLOCKED' as const)
45
+ : typeof value === 'string'
46
+ ? value
47
+ : value.status;
48
+ }
49
+
50
+ /*
51
+ * Classify one durable outbound-email row before a caller publishes a broker
52
+ * wake, so terminal or already accepted sends are never blindly requeued.
53
+ */
54
+ export function getOutboundEmailQueueDisposition(
55
+ value:
56
+ | OutboundEmailStatusEnum
57
+ | 'BLOCKED'
58
+ | Pick<OutboundEmailData, 'status' | 'spamComplaintAt'>,
59
+ ) {
60
+ const status = getOutboundEmailEffectiveDeliveryStatus(value);
61
+ switch (status) {
62
+ case 'QUEUED':
63
+ case 'ERRORED':
64
+ return 'QUEUE' as const;
65
+ case 'PROCESSING':
66
+ return 'PENDING' as const;
67
+ case 'SENT':
68
+ return 'ACCEPTED' as const;
69
+ case 'BOUNCED':
70
+ case 'DELIVERY_UNKNOWN':
71
+ case 'SUPPRESSED':
72
+ case 'BLOCKED':
73
+ return 'TERMINAL_FAILURE' as const;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Return a Postmark inbound payload safe to store on the email row.
79
+ */
80
+ export function getInboundEmailPayloadForStorage(payload?: object | null) {
81
+ const storagePayload: Record<string, unknown> = { ...(payload || {}) };
82
+ const hasTextBody =
83
+ typeof storagePayload.TextBody === 'string' && !!storagePayload.TextBody;
84
+ const hasStrippedTextReply =
85
+ typeof storagePayload.StrippedTextReply === 'string' &&
86
+ !!storagePayload.StrippedTextReply;
87
+ const htmlBodyMarkdown = getInboundEmailPayloadHtmlMarkdownText(
88
+ storagePayload as PostmarkInboundPayloadLike,
89
+ );
90
+
91
+ if (!hasTextBody && !hasStrippedTextReply && htmlBodyMarkdown) {
92
+ storagePayload.TextBody = htmlBodyMarkdown;
93
+ }
94
+
95
+ for (const key of INBOUND_EMAIL_PAYLOAD_OMIT_KEYS) {
96
+ delete storagePayload[key];
97
+ }
98
+
99
+ return storagePayload;
100
+ }
101
+
16
102
  /**
17
103
  * Limit optional Postmark text fields before displaying them.
18
104
  */
19
- export function limitInboundEmailTextValue(value: string | null | undefined, maxLength: number): string | null {
105
+ export function limitInboundEmailTextValue(
106
+ value: string | null | undefined,
107
+ maxLength: number,
108
+ ): string | null {
20
109
  return value ? value.substring(0, maxLength) : null;
21
110
  }
22
111
 
23
112
  /**
24
- * Strip HTML tags from an inbound email HTML body for plain-text display.
113
+ * Replace ASCII control characters in provider-owned email metadata.
25
114
  */
26
- export function stripInboundEmailHtmlBody(value: string | null | undefined): string | null {
27
- return value ? value.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim() : null;
115
+ export function replaceEmailControlCharacters(
116
+ value: string,
117
+ replacement: string,
118
+ ) {
119
+ return Array.from(value, (character) => {
120
+ const characterCode = character.charCodeAt(0);
121
+ return characterCode <= 31 || characterCode === 127
122
+ ? replacement
123
+ : character;
124
+ }).join('');
28
125
  }
29
126
 
30
127
  /**
31
- * Return the preferred raw text source from a saved inbound email payload.
128
+ * Return one limited Postmark text payload field.
32
129
  */
33
- export function getInboundEmailPayloadTextBody(
34
- payload?: PostmarkInboundPayloadLike | null,
35
- maxBodyLength = 12000,
36
- ): string | null {
37
- const textBody = limitInboundEmailTextValue(
38
- typeof payload?.TextBody === 'string' ? payload.TextBody : null,
39
- maxBodyLength,
130
+ function getInboundEmailPayloadTextValue(
131
+ payload: PostmarkInboundPayloadLike | null | undefined,
132
+ key: keyof PostmarkInboundPayloadLike,
133
+ maxLength: number,
134
+ ) {
135
+ return limitInboundEmailTextValue(
136
+ typeof payload?.[key] === 'string' ? payload[key] : null,
137
+ maxLength,
40
138
  );
41
-
42
- return textBody ||
43
- limitInboundEmailTextValue(
44
- typeof payload?.StrippedTextReply === 'string' ? payload.StrippedTextReply : null,
45
- maxBodyLength,
46
- );
47
139
  }
48
140
 
49
141
  /**
50
- * Return the fallback HTML-derived text from a saved inbound email payload.
142
+ * Return markdown converted from one HTML email body.
51
143
  */
52
- export function getInboundEmailPayloadHtmlText(
144
+ function getInboundEmailPayloadHtmlMarkdownText(
53
145
  payload?: PostmarkInboundPayloadLike | null,
54
- maxBodyLength = 12000,
55
- ): string | null {
146
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
147
+ ) {
56
148
  return limitInboundEmailTextValue(
57
149
  typeof payload?.HtmlBody === 'string'
58
- ? stripInboundEmailHtmlBody(payload.HtmlBody)
150
+ ? convertHTMLToMarkdown(payload.HtmlBody)
59
151
  : null,
60
152
  maxBodyLength,
61
153
  );
62
154
  }
63
155
 
156
+ /**
157
+ * Return the preferred raw text source from a saved inbound email payload.
158
+ */
159
+ export function getInboundEmailPayloadTextBody(
160
+ payload?: PostmarkInboundPayloadLike | null,
161
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
162
+ ): string | null {
163
+ return (
164
+ getInboundEmailPayloadTextValue(
165
+ payload,
166
+ 'StrippedTextReply',
167
+ maxBodyLength,
168
+ ) ||
169
+ getInboundEmailPayloadTextValue(payload, 'TextBody', maxBodyLength) ||
170
+ getInboundEmailPayloadHtmlMarkdownText(payload, maxBodyLength)
171
+ );
172
+ }
173
+
174
+ /**
175
+ * Return role-safe plain text for an inbound email agent message. Campaign
176
+ * replies never fall back to TextBody because it can contain the quoted
177
+ * organization-authored campaign that belongs in the assistant message.
178
+ */
179
+ export function getInboundEmailAgentBodyText(
180
+ payload: PostmarkInboundPayloadLike | null | undefined,
181
+ options: { campaignReply: boolean },
182
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
183
+ ): string {
184
+ const strippedReply =
185
+ typeof payload?.StrippedTextReply === 'string'
186
+ ? payload.StrippedTextReply.trim()
187
+ : '';
188
+ const textBody =
189
+ !options.campaignReply && typeof payload?.TextBody === 'string'
190
+ ? payload.TextBody.trim()
191
+ : '';
192
+
193
+ return (strippedReply || textBody).substring(0, maxBodyLength);
194
+ }
195
+
64
196
  /**
65
197
  * Return the display body format derived from a saved inbound email payload.
66
198
  */
@@ -71,10 +203,6 @@ export function getInboundEmailBodyFormat(
71
203
  return 'TEXT';
72
204
  }
73
205
 
74
- if (getInboundEmailPayloadHtmlText(payload)) {
75
- return 'HTML_TEXT';
76
- }
77
-
78
206
  return null;
79
207
  }
80
208
 
@@ -83,11 +211,9 @@ export function getInboundEmailBodyFormat(
83
211
  */
84
212
  export function getInboundEmailBodyText(
85
213
  payload?: PostmarkInboundPayloadLike | null,
86
- maxBodyLength = 12000,
214
+ maxBodyLength = INBOUND_EMAIL_DEFAULT_BODY_LENGTH,
87
215
  ): string {
88
- return getInboundEmailPayloadTextBody(payload, maxBodyLength) ||
89
- getInboundEmailPayloadHtmlText(payload, maxBodyLength) ||
90
- '';
216
+ return getInboundEmailPayloadTextBody(payload, maxBodyLength) || '';
91
217
  }
92
218
 
93
219
  /**
@@ -96,18 +222,158 @@ export function getInboundEmailBodyText(
96
222
  export function getInboundEmailPreviewText(
97
223
  payload?: PostmarkInboundPayloadLike | null,
98
224
  ): string {
99
- return getInboundEmailBodyText(payload, 240).replace(/\s+/g, ' ').trim();
225
+ return getInboundEmailBodyText(payload, INBOUND_EMAIL_PREVIEW_LENGTH)
226
+ .replace(/\s+/g, ' ')
227
+ .trim();
100
228
  }
101
229
 
102
230
  /**
103
- * Return safe attachment metadata from a saved inbound email payload.
104
- */
105
- export function getInboundEmailAttachments(payload?: PostmarkInboundPayloadLike | null) {
106
- return Array.isArray(payload?.Attachments)
107
- ? payload.Attachments.map((attachment) => ({
108
- name: attachment?.Name || null,
109
- contentType: attachment?.ContentType || null,
110
- contentLength: attachment?.ContentLength || null,
111
- }))
112
- : [];
231
+ * Return a compact preview text from an outbound email's plain-text body.
232
+ */
233
+ export function getOutboundEmailPreviewText(body?: string | null): string {
234
+ return (body || '')
235
+ .slice(0, INBOUND_EMAIL_PREVIEW_LENGTH * 4)
236
+ .replace(/\s+/g, ' ')
237
+ .trim()
238
+ .slice(0, INBOUND_EMAIL_PREVIEW_LENGTH);
239
+ }
240
+
241
+ /*
242
+ * Build the direction-scoped email message id. Inbound and outbound rows live in
243
+ * separate tables whose ids overlap, so the direction is part of the identity.
244
+ */
245
+ export function makeEmailMessageId(
246
+ direction: EmailDirectionEnum,
247
+ emailId: string,
248
+ ): string {
249
+ return `${direction === 'INBOUND' ? 'in' : 'out'}_${emailId}`;
250
+ }
251
+
252
+ /*
253
+ * Split an email message id into its direction and serialized table row id.
254
+ */
255
+ export function parseEmailMessageId(
256
+ emailMessageId: string | null | undefined,
257
+ ): { direction: EmailDirectionEnum; emailId: string } | null {
258
+ const match = /^(in|out)_(\d+)$/.exec(emailMessageId || '');
259
+ if (!match) {
260
+ return null;
261
+ }
262
+
263
+ return {
264
+ direction: match[1] === 'in' ? 'INBOUND' : 'OUTBOUND',
265
+ emailId: match[2],
266
+ };
267
+ }
268
+
269
+ /*
270
+ * Return the direction-neutral status group for one raw email status.
271
+ */
272
+ export function getEmailStatusGroup(
273
+ direction: EmailDirectionEnum,
274
+ status: string | null | undefined,
275
+ ): EmailStatusGroupEnum {
276
+ const groups = EMAIL_STATUS_GROUP_STATUSES[direction];
277
+ for (const group of Object.keys(groups) as EmailStatusGroupEnum[]) {
278
+ if ((groups[group] as readonly string[]).includes(status || '')) {
279
+ return group;
280
+ }
281
+ }
282
+
283
+ return 'PENDING';
284
+ }
285
+
286
+ /*
287
+ * Split an RFC-style address list while keeping commas inside quoted display
288
+ * names, angle brackets, and comments within their recipient entry.
289
+ */
290
+ function splitEmailAddressListEntries(value: string): string[] {
291
+ const entries: string[] = [];
292
+ let current = '';
293
+ let angleDepth = 0;
294
+ let commentDepth = 0;
295
+ let quoted = false;
296
+ let escaped = false;
297
+
298
+ for (const character of value) {
299
+ if (escaped) {
300
+ current += character;
301
+ escaped = false;
302
+ continue;
303
+ }
304
+ if (quoted && character === '\\') {
305
+ current += character;
306
+ escaped = true;
307
+ continue;
308
+ }
309
+ if (character === '"' && commentDepth === 0) {
310
+ quoted = !quoted;
311
+ current += character;
312
+ continue;
313
+ }
314
+ if (!quoted) {
315
+ if (character === '<') {
316
+ angleDepth += 1;
317
+ } else if (character === '>' && angleDepth > 0) {
318
+ angleDepth -= 1;
319
+ } else if (character === '(' && angleDepth === 0) {
320
+ commentDepth += 1;
321
+ } else if (character === ')' && commentDepth > 0) {
322
+ commentDepth -= 1;
323
+ } else if (character === ',' && angleDepth === 0 && commentDepth === 0) {
324
+ entries.push(current);
325
+ current = '';
326
+ continue;
327
+ }
328
+ }
329
+
330
+ current += character;
331
+ }
332
+ entries.push(current);
333
+ return entries.map((entry) => entry.trim());
334
+ }
335
+
336
+ /*
337
+ * Extract and normalize the mailbox from one RFC-style recipient entry.
338
+ */
339
+ function getEmailAddressListEntryMailbox(entry: string): string | null {
340
+ const matches =
341
+ entry.match(
342
+ /[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+/gi,
343
+ ) || [];
344
+ const mailboxes = [
345
+ ...new Set(matches.map((mailbox) => mailbox.trim().toLowerCase())),
346
+ ];
347
+ return mailboxes.length === 1 ? mailboxes[0] : null;
348
+ }
349
+
350
+ /*
351
+ * Parse normalized mailboxes and retain invalid recipient entries so callers
352
+ * that perform side effects can fail closed instead of silently dropping one.
353
+ */
354
+ export function parseEmailAddressList(value: string): {
355
+ mailboxes: string[];
356
+ invalidEntries: string[];
357
+ } {
358
+ const mailboxes: string[] = [];
359
+ const invalidEntries: string[] = [];
360
+
361
+ for (const entry of splitEmailAddressListEntries(value)) {
362
+ const mailbox = getEmailAddressListEntryMailbox(entry);
363
+ if (mailbox) {
364
+ mailboxes.push(mailbox);
365
+ } else {
366
+ invalidEntries.push(entry);
367
+ }
368
+ }
369
+
370
+ return { mailboxes, invalidEntries };
371
+ }
372
+
373
+ /*
374
+ * Extract normalized mailboxes from an RFC-style address list while keeping
375
+ * commas inside quoted display names, angle brackets, and comments intact.
376
+ */
377
+ export function getEmailAddressListMailboxes(value: string): string[] {
378
+ return parseEmailAddressList(value).mailboxes;
113
379
  }
@@ -0,0 +1,187 @@
1
+ import { deepStrictEqual, equal, throws } from 'node:assert/strict';
2
+ import { escapeCSVValue, isCSVFormulaLikeValue } from '@jsb188/app/utils/csv.ts';
3
+ import type { EmailCampaignReplyReportGQL } from '../types/emailReplyReport.d.ts';
4
+ import {
5
+ buildEmailCampaignReplyCSV,
6
+ type EmailCampaignReplyCSVLabels,
7
+ makeEmailCampaignReplyCSVFilename,
8
+ } from './emailReplyReport.ts';
9
+
10
+ const FILE_CONSTANTS = {
11
+ labels: {
12
+ email: 'Email',
13
+ name: 'Name',
14
+ replies: 'Replies',
15
+ lastReply: 'Last reply',
16
+ analysis: 'Analysis',
17
+ fieldUnit: (label: string) => `${label} unit`,
18
+ fieldStatus: (label: string) => `${label} status`,
19
+ answerStatus: {
20
+ ANSWERED: 'Answered',
21
+ UNCLEAR: 'Unclear',
22
+ WITHDRAWN: 'Withdrawn',
23
+ MISSING: 'Missing',
24
+ },
25
+ captureState: {
26
+ CAPTURED: 'Captured',
27
+ PROCESSING: 'Processing',
28
+ NOT_CAPTURED: 'Not captured',
29
+ },
30
+ notAnalyzed: 'Not analyzed yet',
31
+ withWarning: (label: string) => `${label} (later reply not captured)`,
32
+ yes: 'Yes',
33
+ no: 'No',
34
+ } satisfies EmailCampaignReplyCSVLabels,
35
+ };
36
+
37
+ /* Build a current snapshot with numeric zero, Boolean false, and untrusted text. */
38
+ function makeReport(): EmailCampaignReplyReportGQL {
39
+ return {
40
+ organizationId: 'organization',
41
+ campaignId: 'campaign',
42
+ campaignTitle: 'Reply report',
43
+ readAt: '2026-11-06T05:00:00.000Z',
44
+ availability: 'READY',
45
+ definitionReason: null,
46
+ limitReason: null,
47
+ instructions: null,
48
+ coverage: {
49
+ linkedReplyCount: 2,
50
+ spamReplyCount: 0,
51
+ nonRecipientReplyCount: 0,
52
+ replyCount: 2,
53
+ respondentCount: 2,
54
+ capturedReplyCount: 1,
55
+ capturedRespondentCount: 1,
56
+ processingReplyCount: 1,
57
+ notCapturedReplyCount: 0,
58
+ },
59
+ fields: (['NUMBER', 'BOOLEAN', 'TEXT'] as const).map((type, index) => ({
60
+ key: `f${index + 1}`,
61
+ label: index === 2 ? '=Question' : 'Answer',
62
+ type,
63
+ answeredCount: 1,
64
+ unclearCount: 0,
65
+ withdrawnCount: 0,
66
+ missingCount: 1,
67
+ unitGroupCount: 0,
68
+ omittedUnitGroups: 0,
69
+ numeric: [],
70
+ boolean: null,
71
+ })),
72
+ respondents: [
73
+ {
74
+ email: 'one@example.test',
75
+ displayName: '=HYPERLINK("evil")',
76
+ replyCount: 1,
77
+ lastReplyAt: '2026-11-06T05:00:00.000Z',
78
+ lastReplyEmailMessageId: 'source-one',
79
+ captureState: 'CAPTURED',
80
+ newerUncapturedReplyAt: '2026-11-06T06:00:00.000Z',
81
+ answers: ['f1', 'f2', 'f3'].map((fieldKey, index) => ({
82
+ fieldKey,
83
+ status: 'ANSWERED',
84
+ numberValue: index === 0 ? 0 : null,
85
+ booleanValue: index === 1 ? false : null,
86
+ textValue: index === 2 ? '"雪",\n=untrusted' : null,
87
+ unit: index === 0 ? 'people' : null,
88
+ receivedAt: '2026-11-06T05:00:00.000Z',
89
+ sourceEmailMessageId: `secret-${fieldKey}`,
90
+ hasNewerUncapturedReply: index === 0,
91
+ })),
92
+ },
93
+ {
94
+ email: 'two@example.test',
95
+ displayName: null,
96
+ replyCount: 1,
97
+ lastReplyAt: '2026-11-06T05:00:00.000Z',
98
+ lastReplyEmailMessageId: 'source-two',
99
+ captureState: 'PROCESSING',
100
+ newerUncapturedReplyAt: null,
101
+ answers: [],
102
+ },
103
+ ],
104
+ };
105
+ }
106
+
107
+ Deno.test('shared CSV escaping protects text and headers without changing signed numbers or phone-like values', () => {
108
+ for (const value of [
109
+ '=SUM(1,2)',
110
+ '@SUM(A1)',
111
+ '+cmd|evil',
112
+ '-cmd|evil',
113
+ '-1e-7+HYPERLINK("evil")',
114
+ '-1E9|cmd',
115
+ '\t=1',
116
+ '\r=1',
117
+ '\n=1',
118
+ ]) {
119
+ equal(isCSVFormulaLikeValue(value), true);
120
+ equal(escapeCSVValue(value).replace(/^"/, '').startsWith("'"), true);
121
+ }
122
+ for (const value of ['-12.50', '-1e-7', '-2E+21', '+1.25e3', '+14155550101', '0', 'plain text']) {
123
+ equal(escapeCSVValue(value), value);
124
+ }
125
+ equal(escapeCSVValue('"雪",\nvalue'), '"""雪"",\nvalue"');
126
+ deepStrictEqual([null, undefined, 0, false].map(escapeCSVValue), ['', '', '0', 'false']);
127
+ });
128
+
129
+ Deno.test('wide reply CSV preserves typed values, coverage warnings, text, and unique formula-safe headers', () => {
130
+ const report = makeReport();
131
+ const csv = buildEmailCampaignReplyCSV(report, {
132
+ labels: FILE_CONSTANTS.labels,
133
+ });
134
+ equal(
135
+ csv.split('\r\n')[0],
136
+ "Email,Name,Replies,Last reply,Analysis,Answer,Answer unit,Answer status,Answer (f2),Answer status (f2),'=Question,'=Question status",
137
+ );
138
+ equal(csv.includes(',0,people,Answered (later reply not captured),No,Answered,'), true);
139
+ equal(csv.includes('"\'=HYPERLINK(""evil"")"'), true);
140
+ equal(csv.includes('"""雪"",\n=untrusted"'), true);
141
+ equal(
142
+ csv.includes('two@example.test,,1,2026-11-06T05:00:00.000Z,Processing,,,Not analyzed yet,,Not analyzed yet,,Not analyzed yet'),
143
+ true,
144
+ );
145
+ equal(/secret-|source-one|source-two|organization/.test(csv), false);
146
+ });
147
+
148
+ Deno.test('CSV headers stay unique after formula neutralization and scientific numbers retain their value', () => {
149
+ const report = makeReport();
150
+ report.fields[0].label = '=Question';
151
+ report.fields[1].label = "'=Question";
152
+ report.fields[2].label = "'=Question (f2)";
153
+ report.respondents[0].answers[0].numberValue = -1e-7;
154
+ const csv = buildEmailCampaignReplyCSV(report, { labels: FILE_CONSTANTS.labels });
155
+ const headers = csv.split('\r\n')[0].split(',');
156
+ equal(new Set(headers).size, headers.length);
157
+ equal(csv.includes(',-1e-7,people,'), true);
158
+ });
159
+
160
+ Deno.test('CSV row selection uses the loaded snapshot and oversized reports cannot become partial files', () => {
161
+ const report = makeReport();
162
+ const selected = {
163
+ ...report.respondents[0],
164
+ displayName: 'Substituted stale value',
165
+ };
166
+ const csv = buildEmailCampaignReplyCSV(report, {
167
+ respondents: [selected, selected],
168
+ labels: FILE_CONSTANTS.labels,
169
+ });
170
+ equal(csv.includes('two@example.test'), false);
171
+ equal(csv.includes('Substituted stale value'), false);
172
+ equal(csv.match(/one@example.test/g)?.length, 1);
173
+ throws(
174
+ () =>
175
+ buildEmailCampaignReplyCSV(
176
+ { ...report, availability: 'TOO_LARGE' },
177
+ {
178
+ labels: FILE_CONSTANTS.labels,
179
+ },
180
+ ),
181
+ RangeError,
182
+ );
183
+ equal(
184
+ makeEmailCampaignReplyCSVFilename('A/B: replies', new Date('2026-11-06T05:00:00Z')),
185
+ 'A_B_ replies 2026-11-06T05-00-00-000Z.csv',
186
+ );
187
+ });