@jsb188/mday 1.1.2

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 (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -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 +22 -0
  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 +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,357 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { normalizeLogLanguage } from '@jsb188/app/utils/language.ts';
3
+ import { formatCurrency, formatDecimal } from '@jsb188/app/utils/number.ts';
4
+ import { joinReadable, textWithBrackets, ucFirst } from '@jsb188/app/utils/string.ts';
5
+ import {
6
+ APP_INTERACTIONS_LOG_GROUP,
7
+ LOG_ACTIVITIES_BY_OPERATION,
8
+ LOG_TYPES_BY_OPERATION,
9
+ PURCHASE_ACTIVITIES,
10
+ SALE_ACTIVITIES,
11
+ } from '../constants/log.ts';
12
+ import type {
13
+ LogContentName,
14
+ LogDisplayText,
15
+ LogEntryDetailsFieldGQL,
16
+ LogTranslationBundle,
17
+ LogTranslationBundleGQL,
18
+ LogTranslationLocaleText,
19
+ LogTranslationSourceTexts,
20
+ LogTypeEnum,
21
+ } from '../types/log.d.ts';
22
+ import type { OrganizationOperationEnum } from '../types/organization.d.ts';
23
+ import { getLogEntryDetailsFieldUnitByKey, getLogEntryDetailsFieldValueByKey, humanizeRegistryKey } from './logTaxonomyDisplay.ts';
24
+
25
+ const FILE_CONSTANTS = {
26
+ accountingActivities: new Set([...PURCHASE_ACTIVITIES, ...SALE_ACTIVITIES] as string[]),
27
+ nonTranslatableFieldKeys: new Set(['flagColor', 'location', 'otherParty', 'unit']),
28
+ };
29
+
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;
41
+ };
42
+
43
+ /*
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.
198
+ */
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');
216
+ }
217
+
218
+ /*
219
+ * Flatten every original log text field into deterministic embedding and
220
+ * search input while omitting null and empty values.
221
+ */
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');
235
+ }
236
+
237
+ /*
238
+ * Return whether one log activity uses the shared accounting metadata fields.
239
+ */
240
+ export function isAccountingLogActivity(activity?: string | null) {
241
+ return FILE_CONSTANTS.accountingActivities.has(activity || '');
242
+ }
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
+
252
+ /**
253
+ * Get content type for log by activity
254
+ */
255
+
256
+ export function getLogContentName(activity: string): LogContentName {
257
+ if (activity === 'MARKET_CREDIT_RECEIPT') {
258
+ return 'receipt';
259
+ }
260
+
261
+ return isAccountingLogActivity(activity) ? 'invoice' : 'log';
262
+ }
263
+
264
+ /**
265
+ * Get all log types for the given organization operation
266
+ * @param operation - The operation of the organization
267
+ * @returns Array of log types for the operation
268
+ */
269
+
270
+ export function getLogTypesForOperation(operation: OrganizationOperationEnum): LogTypeEnum[] {
271
+ const logTypes = (LOG_TYPES_BY_OPERATION[operation] || []) as LogTypeEnum[];
272
+ return logTypes;
273
+ }
274
+
275
+ /**
276
+ * Get log type from activity; bassed on organization's industry-based operation
277
+ * @param operation - The operation of the organization
278
+ * @param activity - The activity of the log entry
279
+ * @returns The log type or null if not found
280
+ */
281
+
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));
284
+
285
+ return (logGroup?.[0] as LogTypeEnum) || null;
286
+ }
287
+
288
+ /**
289
+ * For UI visualization, use this function to get the shortest activity text
290
+ * @param activity - The activity of the log entry
291
+ * @returns i18n text for activity
292
+ */
293
+
294
+ export function getActivityText(activity: any, tryShortForm?: boolean): string {
295
+ if (tryShortForm && i18n.has(`log.activity_short.${activity}`)) {
296
+ return i18n.t(`log.activity_short.${activity}`);
297
+ }
298
+ return i18n.has(`log.activity.${activity}`) ? i18n.t(`log.activity.${activity}`) : humanizeRegistryKey(activity);
299
+ }
300
+
301
+ /**
302
+ * Get the title for a generic log entry.
303
+ * @param details - The generic details interface for the log entry
304
+ * @param isServer - True if used in server
305
+ * @param logType - Optional group-key override for partial or form details
306
+ * @param iface - In unique cases (such as client-side form), you can use this for interface name
307
+ * @return The title for the log entry
308
+ */
309
+
310
+ export function getLogEntryTitle(d: any, isServer?: boolean, logType_?: string | null, iface?: string): string {
311
+ const { __typename, __table, type, logType: storedLogType } = d;
312
+ const logType = logType_ || type || storedLogType;
313
+ const md = isServer ? d.metadata || {} : d;
314
+
315
+ switch (iface || __typename || __table) {
316
+ case 'log_entry_details':
317
+ case 'LogEntryDetails': {
318
+ const quantityText = joinReadable([formatDecimal(md.quantity, true, true), md.unit], ' ', ' ');
319
+
320
+ let titleItem = ucFirst(md.item);
321
+ let logSpecificText = '';
322
+
323
+ if (logType === 'WATER') {
324
+ const concentration = getLogEntryDetailsFieldValueByKey(md, 'concentration');
325
+ logSpecificText = joinReadable(
326
+ [
327
+ concentration === null ? null : String(concentration),
328
+ concentration === null ? null : getLogEntryDetailsFieldUnitByKey(md, 'concentration'),
329
+ ],
330
+ ' ',
331
+ ' ',
332
+ );
333
+ } else if (['SEED', 'SALES'].includes(logType)) {
334
+ if (!titleItem) {
335
+ titleItem = i18n.t('log.unknown_crop');
336
+ }
337
+ const totalPrice = (md?.values || []).reduce((sum: number, item: any) => sum + Number(item.value || 0), 0);
338
+ logSpecificText = formatCurrency(totalPrice, false);
339
+ }
340
+
341
+ // console.log(md);
342
+ // console.log('titleItem', titleItem);
343
+
344
+ const priceText = md.price ? formatCurrency(md.price, 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)}`;
350
+ }
351
+
352
+ return textWithBrackets(titleItem, [logSpecificText || priceText + (priceText && quantityText ? ',' : ''), quantityText]);
353
+ }
354
+ default:
355
+ }
356
+ return '..';
357
+ }
@@ -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
+ }
@@ -0,0 +1,87 @@
1
+ import { LOG_DISPLAY_REGISTRY } from '../constants/logDisplay/index.ts';
2
+ import type {
3
+ LogDisplayContext,
4
+ LogDisplayFieldKey,
5
+ LogDisplayInput,
6
+ LogDisplayRegistry,
7
+ LogEntryDisplay,
8
+ ResolvedLogDisplayDefinition,
9
+ } from '../types/logDisplay.types.ts';
10
+ import {
11
+ formatLogDisplayValue,
12
+ getLogDisplayContext,
13
+ getLogDisplayFieldLabel,
14
+ getLogDisplayValues,
15
+ mergeLogDisplayDefinition,
16
+ orderLogDisplayFields,
17
+ } from './logDisplay.helpers.ts';
18
+
19
+ export { getLogDisplayFieldLabel } from './logDisplay.helpers.ts';
20
+
21
+ /*
22
+ * Resolve generic -> explicitly shared -> operation -> group -> activity.
23
+ * Shared profiles are deliberately non-recursive and never match by activity
24
+ * name alone. Inputs are not mutated, so resolutions cannot leak across orgs.
25
+ */
26
+
27
+ export function resolveLogDisplayDefinition(
28
+ context: LogDisplayContext,
29
+ registry: LogDisplayRegistry = LOG_DISPLAY_REGISTRY,
30
+ ): ResolvedLogDisplayDefinition {
31
+ const scope = getLogDisplayContext(context);
32
+ const operation = scope.operation ? registry.operations[scope.operation] : undefined;
33
+ const layers = [
34
+ operation?.defaults,
35
+ scope.groupKey ? operation?.groups?.[scope.groupKey] : undefined,
36
+ scope.activityKey ? operation?.activities?.[scope.activityKey] : undefined,
37
+ ];
38
+ const resolved: ResolvedLogDisplayDefinition = { layout: 'metadata', order: ['*'], fields: {} };
39
+ mergeLogDisplayDefinition(resolved, registry.defaults);
40
+ const appliedProfiles = new Set<string>();
41
+ for (const layer of layers) {
42
+ for (const name of layer?.profiles || []) {
43
+ if (appliedProfiles.has(name)) continue;
44
+ const profile = registry.shared[name];
45
+ if (!profile) throw new Error(`Unknown log display profile: ${name}`);
46
+ mergeLogDisplayDefinition(resolved, profile);
47
+ appliedProfiles.add(name);
48
+ }
49
+ }
50
+ for (const layer of layers) mergeLogDisplayDefinition(resolved, layer);
51
+ return resolved;
52
+ }
53
+
54
+ /*
55
+ * Prepare renderer-independent rows from saved data and a resolved profile.
56
+ * Saved custom fields survive taxonomy changes; absent fields appear only when
57
+ * explicitly configured to show a placeholder. Visibility never validates data.
58
+ */
59
+
60
+ export function buildLogEntryDisplay(input: LogDisplayInput, registry: LogDisplayRegistry = LOG_DISPLAY_REGISTRY): LogEntryDisplay {
61
+ const context = getLogDisplayContext({
62
+ operation: input.operation,
63
+ taxonomy: input.taxonomy,
64
+ groupKey: input.logEntry.details.type,
65
+ activityKey: input.logEntry.details.activity,
66
+ });
67
+ const definition = resolveLogDisplayDefinition(context, registry);
68
+ const values = getLogDisplayValues(input, context);
69
+ const keys = [...new Set([...values.keys(), ...(Object.keys(definition.fields) as LogDisplayFieldKey[])])];
70
+ const rows = orderLogDisplayFields(keys, definition.order).flatMap((key) => {
71
+ const field = definition.fields[key] || {};
72
+ if (field.hidden) return [];
73
+ const source = values.get(key);
74
+ const empty = source?.raw === null || source?.raw === undefined || source.raw === '';
75
+ if (empty && field.empty !== 'show' && !(source?.field && field.empty !== 'hide')) return [];
76
+ return [
77
+ {
78
+ key,
79
+ label: getLogDisplayFieldLabel(key, field),
80
+ value: formatLogDisplayValue(source, field, values),
81
+ span: field.span || ('half' as const),
82
+ ...(key === 'logType' && context.groupKey ? { badgeGroupKey: context.groupKey } : {}),
83
+ },
84
+ ];
85
+ });
86
+ return { layout: definition.layout, rows };
87
+ }