@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
package/src/utils/log.ts CHANGED
@@ -1,85 +1,237 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { normalizeLogLanguage } from '@jsb188/app/utils/language.ts';
2
3
  import { formatCurrency, formatDecimal } from '@jsb188/app/utils/number.ts';
4
+ import { joinReadable, textWithBrackets, ucFirst } from '@jsb188/app/utils/string.ts';
3
5
  import {
4
- joinReadable,
5
- textWithBrackets,
6
- ucFirst,
7
- } from '@jsb188/app/utils/string.ts';
8
- import {
6
+ APP_INTERACTIONS_LOG_GROUP,
9
7
  LOG_ACTIVITIES_BY_OPERATION,
10
8
  LOG_TYPES_BY_OPERATION,
11
9
  PURCHASE_ACTIVITIES,
12
10
  SALE_ACTIVITIES,
13
11
  } from '../constants/log.ts';
14
- import { LOG_ACTIVITY_GROUP_COLORS } from '../constants/logActivityGroupColors.generated.ts';
15
12
  import type {
16
13
  LogContentName,
17
- LogEntryData,
14
+ LogDisplayText,
15
+ LogEntryDetailsFieldGQL,
16
+ LogTranslationBundle,
17
+ LogTranslationBundleGQL,
18
+ LogTranslationLocaleText,
19
+ LogTranslationSourceTexts,
18
20
  LogTypeEnum,
19
21
  } from '../types/log.d.ts';
20
22
  import type { OrganizationOperationEnum } from '../types/organization.d.ts';
21
- import type { SheetCustomRegionSourceColumnFormulaValueSourceEnum } from '../types/sheet.d.ts';
22
- import {
23
- getLogEntryDetailsFieldUnitByKey,
24
- getLogEntryDetailsFieldValueByKey,
25
- humanizeRegistryKey,
26
- } from './logTaxonomyDisplay.ts';
23
+ import { getLogEntryDetailsFieldUnitByKey, getLogEntryDetailsFieldValueByKey, humanizeRegistryKey } from './logTaxonomyDisplay.ts';
27
24
 
28
25
  const FILE_CONSTANTS = {
29
- accountingActivities: new Set([
30
- ...PURCHASE_ACTIVITIES,
31
- ...SALE_ACTIVITIES,
32
- ] as string[]),
26
+ accountingActivities: new Set([...PURCHASE_ACTIVITIES, ...SALE_ACTIVITIES] as string[]),
27
+ nonTranslatableFieldKeys: new Set(['flagColor', 'location', 'otherParty', 'unit']),
33
28
  };
34
29
 
35
- type LogRegionSourceFormulaValueSource = {
36
- accountId?: string | number | bigint | null;
37
- childOrgId?: string | number | bigint | null;
38
- id?: string | number | bigint | null;
39
- inboundContactId?: string | number | bigint | null;
40
- fieldDocId?: string | number | bigint | null;
41
- fieldDocSubmissionId?: string | number | bigint | null;
42
- siteId?: string | number | bigint | null;
30
+ type LogTextSource = {
31
+ summary?: string | null;
32
+ translation?: LogTranslationBundle | LogTranslationBundleGQL | null;
33
+ details?: {
34
+ item?: string | null;
35
+ notes?: string | null;
36
+ translation?: LogTranslationBundle | LogTranslationBundleGQL | null;
37
+ values?: Array<Record<string, any>> | null;
38
+ fields?: Array<Partial<LogEntryDetailsFieldGQL> & { fieldDefKey?: string | null }> | null;
39
+ metadata?: Record<string, any> | null;
40
+ } | null;
43
41
  };
44
42
 
45
43
  /*
46
- * Return the related record id backing one Logs custom source display column.
44
+ * Read the original translatable details from either server-native metadata or
45
+ * the flattened GraphQL details representation.
46
+ */
47
+ function getOriginalLogTextParts(log: LogTextSource) {
48
+ const details = log.details || {};
49
+ const metadata = details.metadata || {};
50
+
51
+ return {
52
+ summary: typeof log.summary === 'string' ? log.summary : null,
53
+ notes: typeof details.notes === 'string' ? details.notes : null,
54
+ item: typeof details.item === 'string' ? details.item : typeof metadata.item === 'string' ? metadata.item : null,
55
+ values: Array.isArray(details.values) ? details.values : Array.isArray(metadata.values) ? metadata.values : null,
56
+ fields: Array.isArray(details.fields) ? details.fields : null,
57
+ };
58
+ }
59
+
60
+ /*
61
+ * Return the persisted translation bundle from either the widened log row or
62
+ * its reconstructed server details.
63
+ */
64
+ function getLogTranslationBundle(log: LogTextSource) {
65
+ if (log.translation !== undefined) {
66
+ return log.translation;
67
+ }
68
+
69
+ return log.details?.translation ?? null;
70
+ }
71
+
72
+ /*
73
+ * Resolve one locale entry from the JSONB record or its GraphQL list shape.
74
+ */
75
+ function getLogLocaleTranslation(
76
+ translation: LogTranslationBundle | LogTranslationBundleGQL | null,
77
+ language: string,
78
+ ): LogTranslationLocaleText | null {
79
+ if (!translation?.texts) {
80
+ return null;
81
+ }
82
+
83
+ if (Array.isArray(translation.texts)) {
84
+ return translation.texts.find((text) => text.language === language) || null;
85
+ }
86
+
87
+ return translation.texts[language] || null;
88
+ }
89
+
90
+ /*
91
+ * Normalize one translated string while retaining valid empty strings.
92
+ */
93
+ function getTranslatedText(value: unknown, fallback: string | null) {
94
+ return typeof value === 'string' ? value : fallback;
95
+ }
96
+
97
+ /*
98
+ * Clone original item lines and replace only labels translated for their
99
+ * stable source ordinal.
100
+ */
101
+ function getTranslatedLogValues(values: Array<Record<string, any>> | null, translation: LogTranslationLocaleText | null) {
102
+ if (!values) {
103
+ return null;
104
+ }
105
+
106
+ const labelsByOrdinal = new Map(
107
+ (translation?.values || [])
108
+ .filter((value) => Number.isInteger(value.ordinal) && typeof value.label === 'string')
109
+ .map((value) => [value.ordinal, value.label]),
110
+ );
111
+
112
+ return values.map((value, ordinal) => ({
113
+ ...value,
114
+ label: labelsByOrdinal.has(ordinal) ? labelsByOrdinal.get(ordinal) : value.label,
115
+ }));
116
+ }
117
+
118
+ /*
119
+ * Clone original custom fields and replace only keyed text values present in
120
+ * the selected locale.
121
+ */
122
+ function getTranslatedLogFields(
123
+ fields: Array<Partial<LogEntryDetailsFieldGQL> & { fieldDefKey?: string | null }> | null,
124
+ translation: LogTranslationLocaleText | null,
125
+ ) {
126
+ if (!fields) {
127
+ return null;
128
+ }
129
+
130
+ const textByKey = new Map(
131
+ (translation?.fields || [])
132
+ .filter((field) => typeof field.key === 'string' && typeof field.textValue === 'string')
133
+ .map((field) => [field.key, field.textValue]),
134
+ );
135
+
136
+ return fields.map((field) => {
137
+ const key = field.key || field.fieldDefKey || '';
138
+
139
+ return {
140
+ ...field,
141
+ textValue: textByKey.has(key) ? textByKey.get(key)! : (field.textValue ?? null),
142
+ } as LogEntryDetailsFieldGQL;
143
+ });
144
+ }
145
+
146
+ /*
147
+ * Build the stable source payload shared by language detection, translation,
148
+ * and source hashing.
149
+ */
150
+ export function getLogTranslationSourceTexts(log: LogTextSource): LogTranslationSourceTexts {
151
+ const source = getOriginalLogTextParts(log);
152
+ const values = (source.values || []).flatMap((value, ordinal) =>
153
+ typeof value.label === 'string' ? [{ ordinal, label: value.label }] : [],
154
+ );
155
+ const fields = (source.fields || [])
156
+ .flatMap((field) => {
157
+ const key = field.key || field.fieldDefKey;
158
+
159
+ return typeof key === 'string' &&
160
+ field.fieldType === 'TEXT' &&
161
+ !FILE_CONSTANTS.nonTranslatableFieldKeys.has(key) &&
162
+ typeof field.textValue === 'string'
163
+ ? [{ key, textValue: field.textValue }]
164
+ : [];
165
+ })
166
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
167
+
168
+ return {
169
+ summary: source.summary,
170
+ notes: source.notes,
171
+ item: source.item,
172
+ values,
173
+ fields,
174
+ };
175
+ }
176
+
177
+ /*
178
+ * Select display-ready log text for one locale without mutating source data.
179
+ */
180
+ export function getLogDisplayText(log: LogTextSource, displayLanguage?: string | null): LogDisplayText {
181
+ const source = getOriginalLogTextParts(log);
182
+ const translationBundle = getLogTranslationBundle(log);
183
+ const normalizedLanguage = normalizeLogLanguage(displayLanguage) || displayLanguage?.trim().toLowerCase() || null;
184
+ const localeTranslation = normalizedLanguage ? getLogLocaleTranslation(translationBundle, normalizedLanguage) : null;
185
+
186
+ return {
187
+ summary: getTranslatedText(localeTranslation?.summary, source.summary) || '',
188
+ notes: getTranslatedText(localeTranslation?.notes, source.notes),
189
+ item: getTranslatedText(localeTranslation?.item, source.item),
190
+ values: getTranslatedLogValues(source.values, localeTranslation) as LogDisplayText['values'],
191
+ fields: getTranslatedLogFields(source.fields, localeTranslation),
192
+ };
193
+ }
194
+
195
+ /*
196
+ * Flatten every display-language text field into deterministic embedding and
197
+ * search input while omitting null and empty values.
47
198
  */
48
- export function getLogRegionSourceCellRelatedId(
49
- log: LogRegionSourceFormulaValueSource | null | undefined,
50
- formulaValueSource?:
51
- | SheetCustomRegionSourceColumnFormulaValueSourceEnum
52
- | string
53
- | null,
54
- ): string | number | bigint | null {
55
- const relatedId = {
56
- LOG_ACCOUNT_ID: log?.accountId,
57
- LOG_CHILD_ORGANIZATION_ID: log?.childOrgId,
58
- LOG_ID: log?.id,
59
- LOG_INBOUND_CONTACT_ID: log?.inboundContactId,
60
- LOG_REPORT_ID: log?.fieldDocId,
61
- LOG_REPORT_SUBMISSION_ID: log?.fieldDocSubmissionId,
62
- LOG_SITE_ID: log?.siteId,
63
- }[String(formulaValueSource || '')];
64
-
65
- return relatedId !== null && relatedId !== undefined ? relatedId : null;
199
+ export function getTextFormatDisplayLog(log: LogTextSource, displayLanguage?: string | null) {
200
+ const displayText = getLogDisplayText(log, displayLanguage);
201
+ const sourceTexts = getLogTranslationSourceTexts({
202
+ summary: displayText.summary,
203
+ details: displayText,
204
+ });
205
+
206
+ return [
207
+ sourceTexts.summary,
208
+ sourceTexts.item,
209
+ sourceTexts.notes,
210
+ ...sourceTexts.values.map((value) => value.label),
211
+ ...sourceTexts.fields.map((field) => field.textValue),
212
+ ]
213
+ .filter((value): value is string => typeof value === 'string' && !!value.trim())
214
+ .map((value) => value.trim())
215
+ .join('\n');
66
216
  }
67
217
 
68
218
  /*
69
- * Return the formula comparison value backing one Logs custom source display column.
219
+ * Flatten every original log text field into deterministic embedding and
220
+ * search input while omitting null and empty values.
70
221
  */
71
- export function getLogRegionSourceCellFormulaValue(
72
- log: LogRegionSourceFormulaValueSource | null | undefined,
73
- formulaValueSource?:
74
- | SheetCustomRegionSourceColumnFormulaValueSourceEnum
75
- | string
76
- | null,
77
- ): string | null {
78
- const formulaValue = getLogRegionSourceCellRelatedId(log, formulaValueSource);
79
-
80
- return formulaValue !== null && formulaValue !== undefined
81
- ? String(formulaValue)
82
- : null;
222
+ export function getTextFormatOriginalLog(log: LogTextSource) {
223
+ const sourceTexts = getLogTranslationSourceTexts(log);
224
+
225
+ return [
226
+ sourceTexts.summary,
227
+ sourceTexts.item,
228
+ sourceTexts.notes,
229
+ ...sourceTexts.values.map((value) => value.label),
230
+ ...sourceTexts.fields.map((field) => field.textValue),
231
+ ]
232
+ .filter((value): value is string => typeof value === 'string' && !!value.trim())
233
+ .map((value) => value.trim())
234
+ .join('\n');
83
235
  }
84
236
 
85
237
  /*
@@ -89,6 +241,14 @@ export function isAccountingLogActivity(activity?: string | null) {
89
241
  return FILE_CONSTANTS.accountingActivities.has(activity || '');
90
242
  }
91
243
 
244
+ /*
245
+ * Return whether a hydrated log belongs to the system-only app interactions
246
+ * group.
247
+ */
248
+ export function isAppInteractionLog(log: { details?: { logType?: string | null } | null } | null | undefined): boolean {
249
+ return log?.details?.logType === APP_INTERACTIONS_LOG_GROUP;
250
+ }
251
+
92
252
  /**
93
253
  * Get content type for log by activity
94
254
  */
@@ -101,31 +261,13 @@ export function getLogContentName(activity: string): LogContentName {
101
261
  return isAccountingLogActivity(activity) ? 'invoice' : 'log';
102
262
  }
103
263
 
104
- /**
105
- * Map log type to a color
106
- * @param type - The type of the log entry
107
- * @returns The color associated with the journal type
108
- */
109
-
110
- export function getLogCategoryColor(
111
- type: LogTypeEnum | 'DELETED' | string | null | undefined,
112
- ) {
113
- if (type === 'DELETED') {
114
- return 'medium';
115
- }
116
-
117
- return type ? LOG_ACTIVITY_GROUP_COLORS[type] || 'zinc' : 'zinc';
118
- }
119
-
120
264
  /**
121
265
  * Get all log types for the given organization operation
122
266
  * @param operation - The operation of the organization
123
267
  * @returns Array of log types for the operation
124
268
  */
125
269
 
126
- export function getLogTypesForOperation(
127
- operation: OrganizationOperationEnum,
128
- ): LogTypeEnum[] {
270
+ export function getLogTypesForOperation(operation: OrganizationOperationEnum): LogTypeEnum[] {
129
271
  const logTypes = (LOG_TYPES_BY_OPERATION[operation] || []) as LogTypeEnum[];
130
272
  return logTypes;
131
273
  }
@@ -137,13 +279,8 @@ export function getLogTypesForOperation(
137
279
  * @returns The log type or null if not found
138
280
  */
139
281
 
140
- export function getLogTypeFromActivity(
141
- operation: OrganizationOperationEnum | string,
142
- activity: any,
143
- ): LogTypeEnum | null {
144
- const logGroup = (LOG_ACTIVITIES_BY_OPERATION[operation] || []).find(
145
- (group: any) => group[1].includes(activity),
146
- );
282
+ export function getLogTypeFromActivity(operation: OrganizationOperationEnum | string, activity: any): LogTypeEnum | null {
283
+ const logGroup = (LOG_ACTIVITIES_BY_OPERATION[operation] || []).find((group: any) => group[1].includes(activity));
147
284
 
148
285
  return (logGroup?.[0] as LogTypeEnum) || null;
149
286
  }
@@ -158,9 +295,7 @@ export function getActivityText(activity: any, tryShortForm?: boolean): string {
158
295
  if (tryShortForm && i18n.has(`log.activity_short.${activity}`)) {
159
296
  return i18n.t(`log.activity_short.${activity}`);
160
297
  }
161
- return i18n.has(`log.activity.${activity}`)
162
- ? i18n.t(`log.activity.${activity}`)
163
- : humanizeRegistryKey(activity);
298
+ return i18n.has(`log.activity.${activity}`) ? i18n.t(`log.activity.${activity}`) : humanizeRegistryKey(activity);
164
299
  }
165
300
 
166
301
  /**
@@ -172,12 +307,7 @@ export function getActivityText(activity: any, tryShortForm?: boolean): string {
172
307
  * @return The title for the log entry
173
308
  */
174
309
 
175
- export function getLogEntryTitle(
176
- d: any,
177
- isServer?: boolean,
178
- logType_?: string | null,
179
- iface?: string,
180
- ): string {
310
+ export function getLogEntryTitle(d: any, isServer?: boolean, logType_?: string | null, iface?: string): string {
181
311
  const { __typename, __table, type, logType: storedLogType } = d;
182
312
  const logType = logType_ || type || storedLogType;
183
313
  const md = isServer ? d.metadata || {} : d;
@@ -185,26 +315,17 @@ export function getLogEntryTitle(
185
315
  switch (iface || __typename || __table) {
186
316
  case 'log_entry_details':
187
317
  case 'LogEntryDetails': {
188
- const quantityText = joinReadable(
189
- [formatDecimal(md.quantity, true, true), md.unit],
190
- ' ',
191
- ' ',
192
- );
318
+ const quantityText = joinReadable([formatDecimal(md.quantity, true, true), md.unit], ' ', ' ');
193
319
 
194
320
  let titleItem = ucFirst(md.item);
195
321
  let logSpecificText = '';
196
322
 
197
323
  if (logType === 'WATER') {
198
- const concentration = getLogEntryDetailsFieldValueByKey(
199
- md,
200
- 'concentration',
201
- );
324
+ const concentration = getLogEntryDetailsFieldValueByKey(md, 'concentration');
202
325
  logSpecificText = joinReadable(
203
326
  [
204
327
  concentration === null ? null : String(concentration),
205
- concentration === null
206
- ? null
207
- : getLogEntryDetailsFieldUnitByKey(md, 'concentration'),
328
+ concentration === null ? null : getLogEntryDetailsFieldUnitByKey(md, 'concentration'),
208
329
  ],
209
330
  ' ',
210
331
  ' ',
@@ -213,10 +334,7 @@ export function getLogEntryTitle(
213
334
  if (!titleItem) {
214
335
  titleItem = i18n.t('log.unknown_crop');
215
336
  }
216
- const totalPrice = (md?.values || []).reduce(
217
- (sum: number, item: any) => sum + Number(item.value || 0),
218
- 0,
219
- );
337
+ const totalPrice = (md?.values || []).reduce((sum: number, item: any) => sum + Number(item.value || 0), 0);
220
338
  logSpecificText = formatCurrency(totalPrice, false);
221
339
  }
222
340
 
@@ -224,43 +342,16 @@ export function getLogEntryTitle(
224
342
  // console.log('titleItem', titleItem);
225
343
 
226
344
  const priceText = md.price ? formatCurrency(md.price, false) : '';
227
- if (
228
- logType === 'MARKET_RECEIPT' &&
229
- Array.isArray(md.values) &&
230
- md.values.length
231
- ) {
232
- const creditsText = md.values
233
- .map(
234
- (item: any) => `${formatCurrency(item.value, false)} ${item.label}`,
235
- )
236
- .join(', ');
237
- const totalAmount = md.values.reduce(
238
- (sum: number, item: any) => sum + Number(item.value || 0),
239
- 0,
240
- );
241
- const voidText =
242
- isServer && md.voided ? i18n.t('form.void').toUpperCase() : '';
243
- return `${voidText ? `(${voidText}) ` : ''}${creditsText} = ${i18n.t('form.total')}: ${formatCurrency(totalAmount, false)}`;
345
+ if (logType === 'MARKET_RECEIPT' && Array.isArray(md.values) && md.values.length) {
346
+ const creditsText = md.values.map((item: any) => `${formatCurrency(item.value, false)} ${item.label}`).join(', ');
347
+ const totalAmount = md.values.reduce((sum: number, item: any) => sum + Number(item.value || 0), 0);
348
+ const voidText = isServer && md.voided ? i18n.t('c.void').toUpperCase() : '';
349
+ return `${voidText ? `(${voidText}) ` : ''}${creditsText} = ${i18n.t('c.total')}: ${formatCurrency(totalAmount, false)}`;
244
350
  }
245
351
 
246
- return textWithBrackets(titleItem, [
247
- logSpecificText || priceText + (priceText && quantityText ? ',' : ''),
248
- quantityText,
249
- ]);
352
+ return textWithBrackets(titleItem, [logSpecificText || priceText + (priceText && quantityText ? ',' : ''), quantityText]);
250
353
  }
251
354
  default:
252
355
  }
253
356
  return '..';
254
357
  }
255
-
256
- /**
257
- * Get the text format for this log
258
- * @param log - Log entry object from database
259
- * @return Log in text format
260
- */
261
-
262
- export function getTextFormatLog(log: LogEntryData) {
263
- const { notes } = log.details;
264
- const title = getLogEntryTitle(log.details || {}, true);
265
- return (title + '\n\n' + (notes + '')).trim();
266
- }
@@ -0,0 +1,177 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { formatDisplayDate } from '@jsb188/app/utils/datetime.ts';
3
+ import { formatCurrency } from '@jsb188/app/utils/number.ts';
4
+ import { joinReadable, ucFirst } from '@jsb188/app/utils/string.ts';
5
+ import type { LogEntryDetailsFieldGQL } from '../types/log.d.ts';
6
+ import type {
7
+ LogDisplayContext,
8
+ LogDisplayDefinition,
9
+ LogDisplayFieldDefinition,
10
+ LogDisplayFieldKey,
11
+ LogDisplayInput,
12
+ ResolvedLogDisplayDefinition,
13
+ } from '../types/logDisplay.types.ts';
14
+ import {
15
+ formatLogEntryDetailsFieldValue,
16
+ formatLogTemperatureValue,
17
+ getLogEntryDetailsFieldLabel,
18
+ getLogEntryDetailsFieldValue,
19
+ getTaxonomyActivityLabel,
20
+ getTaxonomyGroupLabel,
21
+ } from './logTaxonomyDisplay.ts';
22
+
23
+ export interface LogDisplayValue {
24
+ raw: string | number | boolean | null;
25
+ text: string;
26
+ field?: LogEntryDetailsFieldGQL;
27
+ }
28
+
29
+ /*
30
+ * Resolve operation context without using another operation's taxonomy. Prefer
31
+ * the saved group for historical logs, then the current activity's group.
32
+ */
33
+
34
+ export function getLogDisplayContext(context: LogDisplayContext): LogDisplayContext {
35
+ const operation = context.operation ?? context.taxonomy?.operation ?? null;
36
+ const taxonomy = context.taxonomy?.operation === operation ? context.taxonomy : null;
37
+ const groupKey = context.groupKey ?? taxonomy?.activities.find((activity) => activity.key === context.activityKey)?.groupKey;
38
+ return { ...context, operation, taxonomy, groupKey };
39
+ }
40
+
41
+ /*
42
+ * Merge one presentation layer. Undefined inherits, nullable field settings
43
+ * reset, explicit false overrides true, and order replaces instead of appending.
44
+ */
45
+
46
+ export function mergeLogDisplayDefinition(target: ResolvedLogDisplayDefinition, layer?: LogDisplayDefinition): void {
47
+ if (!layer) return;
48
+ if (layer.layout !== undefined) target.layout = layer.layout;
49
+ if (layer.order !== undefined) target.order = [...layer.order];
50
+ if (!layer.fields) return;
51
+ for (const [key, override] of Object.entries(layer.fields)) {
52
+ if (!override) continue;
53
+ const fieldKey = key as LogDisplayFieldKey;
54
+ const defined = Object.fromEntries(Object.entries(override).filter(([, value]) => value !== undefined));
55
+ target.fields[fieldKey] = { ...target.fields[fieldKey], ...defined };
56
+ }
57
+ }
58
+
59
+ /*
60
+ * Order rows once, expanding the wildcard without duplicating explicitly placed
61
+ * fields. Unlisted saved fields remain visible even if the wildcard is omitted.
62
+ */
63
+
64
+ export function orderLogDisplayFields(keys: LogDisplayFieldKey[], order: ResolvedLogDisplayDefinition['order']): LogDisplayFieldKey[] {
65
+ const available = new Set(keys);
66
+ const explicit = new Set(order.filter((key) => key !== '*'));
67
+ const remaining = keys.filter((key) => !explicit.has(key));
68
+ const result: LogDisplayFieldKey[] = [];
69
+ const added = new Set<LogDisplayFieldKey>();
70
+ for (const key of [...order.flatMap((entry) => (entry === '*' ? remaining : [entry])), ...remaining]) {
71
+ if (available.has(key) && !added.has(key)) {
72
+ result.push(key);
73
+ added.add(key);
74
+ }
75
+ }
76
+ return result;
77
+ }
78
+
79
+ /*
80
+ * Resolve translated field labels independently of the renderer. A null label
81
+ * override restores the generic label rather than changing the stored key.
82
+ */
83
+
84
+ export function getLogDisplayFieldLabel(key: LogDisplayFieldKey, definition?: LogDisplayFieldDefinition): string {
85
+ if (definition?.labelKey) return i18n.t(definition.labelKey);
86
+ if (key === 'activity') return i18n.t('c.activity');
87
+ return getLogEntryDetailsFieldLabel(key.startsWith('field:') ? key.slice(6) : key);
88
+ }
89
+
90
+ /*
91
+ * Read the built-in envelope once. Registry fields are added separately with
92
+ * field: identities so a custom item/location cannot overwrite the envelope.
93
+ */
94
+
95
+ export function getLogDisplayValues(input: LogDisplayInput, context: LogDisplayContext): Map<LogDisplayFieldKey, LogDisplayValue> {
96
+ const { logEntry: log, timeZone } = input;
97
+ const details = log.details;
98
+ const groupKey = context.groupKey;
99
+ const groupLabel = getTaxonomyGroupLabel(context.taxonomy, groupKey, context.operation, false);
100
+ const location = joinReadable([log.location, details.fieldLocation], ' – ', ' – ');
101
+ const interactionType =
102
+ groupKey === 'APP_INTERACTIONS'
103
+ ? details.activity === 'CAMPAIGN_FORM_SUBMISSION'
104
+ ? 'CAMPAIGN_FORM'
105
+ : details.activity === 'CAMPAIGN_EMAIL'
106
+ ? 'CAMPAIGN_EMAIL'
107
+ : null
108
+ : null;
109
+ const valuesText = (details.values || [])
110
+ .map((entry) =>
111
+ joinReadable(
112
+ [
113
+ entry.quantity == null ? null : String(entry.quantity),
114
+ entry.unit,
115
+ entry.label,
116
+ entry.value == null ? null : formatCurrency(Number(entry.value), false),
117
+ ],
118
+ ' ',
119
+ ' ',
120
+ ),
121
+ )
122
+ .join(', ');
123
+ const values = new Map<LogDisplayFieldKey, LogDisplayValue>([
124
+ ['date', { raw: log.date, text: formatDisplayDate(log.date, timeZone) }],
125
+ ['logType', { raw: groupKey ?? null, text: groupLabel }],
126
+ ['activity', { raw: details.activity, text: getTaxonomyActivityLabel(context.taxonomy, details.activity) }],
127
+ ['interactionType', { raw: interactionType, text: interactionType ? i18n.t(`agent_note.source_type.${interactionType}`) : '' }],
128
+ ['childOrgName', { raw: log.childOrgName, text: log.childOrgName || '' }],
129
+ ['item', { raw: details.item, text: details.item == null ? '' : ucFirst(details.item) }],
130
+ [
131
+ 'quantity',
132
+ {
133
+ raw: details.quantity,
134
+ text: details.quantity == null ? '' : joinReadable([String(details.quantity), details.unit], ' ', ' '),
135
+ },
136
+ ],
137
+ ['price', { raw: details.price, text: details.price == null ? '' : formatCurrency(details.price, false) }],
138
+ ['values', { raw: valuesText, text: valuesText }],
139
+ ['otherParty', { raw: details.otherParty, text: details.otherParty || '' }],
140
+ ['referenceNumber', { raw: details.referenceNumber, text: details.referenceNumber || '' }],
141
+ ['voided', { raw: details.voided, text: details.voided == null ? '' : i18n.t(details.voided ? 'c.voided' : 'c.valid') }],
142
+ ['location', { raw: location, text: location }],
143
+ ]);
144
+ if (!details.fields?.length) return values;
145
+ const ordinals = new Map(context.taxonomy?.fieldDefs.map((field) => [field.key, field.ordinal ?? Number.MAX_SAFE_INTEGER]));
146
+ const fields = [...details.fields].sort(
147
+ (a, b) => (ordinals.get(a.key) ?? Number.MAX_SAFE_INTEGER) - (ordinals.get(b.key) ?? Number.MAX_SAFE_INTEGER),
148
+ );
149
+ for (const field of fields) {
150
+ if (!field.key) continue;
151
+ values.set(`field:${field.key}`, {
152
+ raw: getLogEntryDetailsFieldValue(field, timeZone),
153
+ text: formatLogEntryDetailsFieldValue(field, timeZone),
154
+ field,
155
+ });
156
+ }
157
+ return values;
158
+ }
159
+
160
+ /*
161
+ * Apply an optional named formatter to a value; field-type formatting remains
162
+ * the default. Unknown units remain visible rather than silently disappearing.
163
+ */
164
+
165
+ export function formatLogDisplayValue(
166
+ value: LogDisplayValue | undefined,
167
+ definition: LogDisplayFieldDefinition,
168
+ values: Map<LogDisplayFieldKey, LogDisplayValue>,
169
+ ): string {
170
+ if (value?.raw === null || value?.raw === undefined || value.raw === '') return '';
171
+ if (!definition.formatter || definition.formatter === 'auto') return value.text;
172
+ const number = typeof value.raw === 'boolean' ? NaN : Number(value.raw);
173
+ if (!Number.isFinite(number)) return value.text;
174
+ if (definition.formatter === 'currency') return formatCurrency(number, false);
175
+ const unit = definition.unitField ? values.get(definition.unitField)?.raw : value.field?.unit;
176
+ return formatLogTemperatureValue(number, unit == null ? null : String(unit));
177
+ }