@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
@@ -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
+ }
@@ -0,0 +1,90 @@
1
+ /*
2
+ * Return whether a value is a canonical, real YYYY-MM-DD calendar date.
3
+ */
4
+
5
+ export function isCanonicalLogRegistryDate(value: unknown): value is string {
6
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
7
+ return false;
8
+ }
9
+
10
+ const [year, month, day] = value.split('-').map(Number);
11
+ const parsed = new Date(Date.UTC(year, month - 1, day));
12
+ return (
13
+ parsed.getUTCFullYear() === year &&
14
+ parsed.getUTCMonth() === month - 1 &&
15
+ parsed.getUTCDate() === day
16
+ );
17
+ }
18
+
19
+ /*
20
+ * Normalize a timezone-qualified datetime value to an ISO instant.
21
+ */
22
+
23
+ export function normalizeLogRegistryDateTime(value: unknown): string | null {
24
+ if (value instanceof Date) {
25
+ return Number.isFinite(value.getTime()) ? value.toISOString() : null;
26
+ }
27
+ if (typeof value !== 'string') {
28
+ return null;
29
+ }
30
+
31
+ const match = value.match(
32
+ /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{3})?(Z|[+-]\d{2}:\d{2})$/,
33
+ );
34
+ if (!match || !isCanonicalLogRegistryDate(match[1])) {
35
+ return null;
36
+ }
37
+
38
+ const hour = Number(match[2]);
39
+ const minute = Number(match[3]);
40
+ const second = Number(match[4]);
41
+ const timezone = match[5];
42
+ const offsetParts =
43
+ timezone === 'Z' ? null : timezone.slice(1).split(':').map(Number);
44
+ if (
45
+ hour > 23 ||
46
+ minute > 59 ||
47
+ second > 59 ||
48
+ (offsetParts && (offsetParts[0] > 23 || offsetParts[1] > 59))
49
+ ) {
50
+ return null;
51
+ }
52
+
53
+ const parsed = new Date(value);
54
+ return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : null;
55
+ }
56
+
57
+ /*
58
+ * Return whether a direct registry field value matches its declared scalar
59
+ * type and, for SELECT fields, its configured option set.
60
+ */
61
+
62
+ export function isValidLogRegistryScalarValue(
63
+ fieldType: string,
64
+ value: unknown,
65
+ options?: string[] | null,
66
+ ): boolean {
67
+ if (fieldType === 'BOOLEAN') {
68
+ return typeof value === 'boolean';
69
+ }
70
+ if (['NUMBER', 'QUANTITY', 'MONEY'].includes(fieldType)) {
71
+ return typeof value === 'number' && Number.isFinite(value);
72
+ }
73
+ if (fieldType === 'DATE') {
74
+ return isCanonicalLogRegistryDate(value);
75
+ }
76
+ if (fieldType === 'DATETIME') {
77
+ return normalizeLogRegistryDateTime(value) !== null;
78
+ }
79
+ if (fieldType === 'SELECT') {
80
+ return (
81
+ typeof value === 'string' &&
82
+ !!value.trim() &&
83
+ !!options?.includes(value.trim())
84
+ );
85
+ }
86
+ if (fieldType === 'TEXT') {
87
+ return typeof value === 'string' && !!value.trim();
88
+ }
89
+ return false;
90
+ }
@@ -0,0 +1,262 @@
1
+ import type { LogTranslationBundle } from '../types/log.d.ts';
2
+ import type { OrganizationOperationEnum } from '../types/organization.d.ts';
3
+
4
+ /**
5
+ * Pure reconstruction of a generic log `details` object from log-store rows.
6
+ * The output satisfies the shared LogEntryData contract: `id`/`logId` remain
7
+ * client-cache invariants, arrays remain arrays, and money values are decimal
8
+ * dollars (the store keeps BIGINT cents).
9
+ *
10
+ * Inverse of the server-side materializer (server logOps-store.ts): scalar
11
+ * item facts come back from the ordinal-0 item row, values[] from the rows
12
+ * with ordinal 1 and up, field-def-keyed scalars from log_values, and
13
+ * otherParty from an EXTERNAL counterparty. Item rows are read by ordinal
14
+ * alone: every row is an ITEM (a legacy MARKET_CREDIT row still reads as an
15
+ * ordinary line).
16
+ */
17
+
18
+ export interface LogStoreValueInput {
19
+ fieldDefKey: string;
20
+ fieldType?: string | null;
21
+ textValue?: string | null;
22
+ numberValue?: number | null;
23
+ booleanValue?: boolean | null;
24
+ dateValue?: string | null;
25
+ datetimeValue?: string | Date | null;
26
+ unit?: string | null;
27
+ }
28
+
29
+ export interface LogStoreItemInput {
30
+ ordinal: number;
31
+ label: string;
32
+ quantity?: number | null;
33
+ unit?: string | null;
34
+ amountCents?: number | bigint | null;
35
+ }
36
+
37
+ export interface LogStoreDetailsInput {
38
+ operation: OrganizationOperationEnum;
39
+ // GraphQL details.id and WS fragment dataIds derive from this identity.
40
+ detailsRowId: number | bigint | string;
41
+ logId: number | bigint | string;
42
+ activityKey: string;
43
+ logTypeKey?: string | null;
44
+ notes?: string | null;
45
+ translation?: LogTranslationBundle | null;
46
+ voided?: boolean | null;
47
+ referenceNumber?: string | null;
48
+ fieldLocation?: string | null;
49
+ counterparty?: { kind: string; name: string } | null;
50
+ values: LogStoreValueInput[];
51
+ items: LogStoreItemInput[];
52
+ }
53
+
54
+ /*
55
+ * Convert BIGINT cents back to decimal dollars
56
+ */
57
+
58
+ function centsToDollars(
59
+ cents: number | bigint | null | undefined,
60
+ ): number | undefined {
61
+ if (cents === null || cents === undefined) {
62
+ return undefined;
63
+ }
64
+ return Number(cents) / 100;
65
+ }
66
+
67
+ /*
68
+ * Return one finite numeric value from an untrusted reconstructed store
69
+ * boundary so GraphQL floats and arithmetic never receive invalid numbers.
70
+ */
71
+
72
+ function toFiniteNumber(value: any): number | undefined {
73
+ if (value === null || value === undefined) {
74
+ return undefined;
75
+ }
76
+ const parsed = Number(value);
77
+ return Number.isFinite(parsed) ? parsed : undefined;
78
+ }
79
+
80
+ /*
81
+ * Return a GraphQL-safe ISO datetime value from a trusted log-store mirror.
82
+ */
83
+
84
+ function getLogStoreDateTimeValue(
85
+ value: string | Date | null | undefined,
86
+ ): string | undefined {
87
+ if (value instanceof Date) {
88
+ return Number.isFinite(value.getTime()) ? value.toISOString() : undefined;
89
+ }
90
+
91
+ return typeof value === 'string' && value ? value : undefined;
92
+ }
93
+
94
+ /*
95
+ * Build the metadata object from store rows; returns null when empty.
96
+ */
97
+
98
+ function buildMetadataFromStore(
99
+ input: LogStoreDetailsInput,
100
+ ): Record<string, any> | null {
101
+ const metadata: Record<string, any> = {};
102
+
103
+ const scalarItem = input.items.find((item) => item.ordinal === 0);
104
+ if (scalarItem) {
105
+ if (scalarItem.label) {
106
+ metadata.item = scalarItem.label;
107
+ }
108
+ const quantity = toFiniteNumber(scalarItem.quantity);
109
+ if (quantity !== undefined) {
110
+ metadata.quantity = quantity;
111
+ }
112
+ if (scalarItem.unit != null) {
113
+ metadata.unit = scalarItem.unit;
114
+ }
115
+ const price = centsToDollars(scalarItem.amountCents);
116
+ if (price !== undefined) {
117
+ metadata.price = price;
118
+ }
119
+ }
120
+
121
+ const valueLines = input.items
122
+ .filter((item) => item.ordinal >= 1)
123
+ .sort((a, b) => a.ordinal - b.ordinal)
124
+ .map((item) => {
125
+ const line: Record<string, any> = { label: item.label };
126
+ const amount = centsToDollars(item.amountCents);
127
+ if (amount !== undefined) {
128
+ line.value = amount;
129
+ }
130
+ const quantity = toFiniteNumber(item.quantity);
131
+ if (quantity !== undefined) {
132
+ line.quantity = quantity;
133
+ }
134
+ if (item.unit != null) {
135
+ line.unit = item.unit;
136
+ }
137
+ return line;
138
+ });
139
+ if (valueLines.length) {
140
+ metadata.values = valueLines;
141
+ }
142
+
143
+ for (const value of input.values) {
144
+ if (value.fieldDefKey === 'concentration' && value.numberValue != null) {
145
+ metadata.concentration = toFiniteNumber(value.numberValue);
146
+ if (value.unit != null) {
147
+ metadata.concentrationUnit = value.unit;
148
+ }
149
+ } else if (value.fieldDefKey === 'tax' && value.numberValue != null) {
150
+ metadata.tax = (toFiniteNumber(value.numberValue) ?? 0) / 100;
151
+ } else if (value.fieldDefKey === 'flagColor' && value.textValue != null) {
152
+ metadata.flagColor = value.textValue;
153
+ } else if (value.fieldDefKey === 'quantity' && value.numberValue != null) {
154
+ // Label-less measurement (no scalar ITEM row); the item-row values
155
+ // win if both somehow exist
156
+ if (metadata.quantity === undefined) {
157
+ metadata.quantity = toFiniteNumber(value.numberValue);
158
+ if (value.unit != null && metadata.unit === undefined) {
159
+ metadata.unit = value.unit;
160
+ }
161
+ }
162
+ } else if (value.fieldDefKey === 'unit' && value.textValue != null) {
163
+ // Unit-only annotation (no scalar ITEM row, no numeric quantity);
164
+ // an item-row or quantity-value unit wins if both somehow exist
165
+ if (metadata.unit === undefined) {
166
+ metadata.unit = value.textValue;
167
+ }
168
+ } else if (value.fieldDefKey === 'otherParty' && value.textValue != null) {
169
+ metadata.otherParty = value.textValue;
170
+ } else if (value.fieldDefKey === 'location' && value.textValue != null) {
171
+ metadata.location = value.textValue;
172
+ } else {
173
+ // Any field-def value maps straight onto metadata under its own key.
174
+ // MONEY values store BIGINT cents — read back as decimal dollars
175
+ const genericNumber =
176
+ value.fieldType === 'MONEY'
177
+ ? centsToDollars(value.numberValue)
178
+ : toFiniteNumber(value.numberValue);
179
+ const genericValue =
180
+ value.textValue ??
181
+ genericNumber ??
182
+ value.booleanValue ??
183
+ value.dateValue ??
184
+ getLogStoreDateTimeValue(value.datetimeValue);
185
+ if (
186
+ genericValue !== undefined &&
187
+ genericValue !== null &&
188
+ metadata[value.fieldDefKey] === undefined
189
+ ) {
190
+ metadata[value.fieldDefKey] = genericValue;
191
+ if (value.unit != null) {
192
+ metadata[`${value.fieldDefKey}Unit`] = value.unit;
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ // Legacy fallback for rows materialized before the otherParty value
199
+ // existed: an EXTERNAL counterparty carries the (canonicalized) text
200
+ if (
201
+ metadata.otherParty === undefined &&
202
+ input.counterparty?.kind === 'EXTERNAL'
203
+ ) {
204
+ metadata.otherParty = input.counterparty.name;
205
+ }
206
+ if (typeof input.voided === 'boolean') {
207
+ metadata.voided = input.voided;
208
+ }
209
+ if (input.referenceNumber != null) {
210
+ metadata.referenceNumber = input.referenceNumber;
211
+ }
212
+ if (input.fieldLocation != null) {
213
+ metadata.fieldLocation = input.fieldLocation;
214
+ }
215
+
216
+ return Object.keys(metadata).length ? metadata : null;
217
+ }
218
+
219
+ /*
220
+ * Normalize one store value into the client-facing generic-field contract.
221
+ */
222
+
223
+ function mapStoreValueToLogEntryDetailsField(
224
+ value: LogStoreValueInput,
225
+ ): Record<string, any> {
226
+ return {
227
+ key: value.fieldDefKey,
228
+ fieldType: value.fieldType ?? null,
229
+ textValue: value.textValue ?? null,
230
+ numberValue:
231
+ value.fieldType === 'MONEY'
232
+ ? (centsToDollars(value.numberValue) ?? null)
233
+ : (toFiniteNumber(value.numberValue) ?? null),
234
+ booleanValue: value.booleanValue ?? null,
235
+ dateValue: value.dateValue ?? null,
236
+ datetimeValue: getLogStoreDateTimeValue(value.datetimeValue) ?? null,
237
+ unit: value.unit ?? null,
238
+ };
239
+ }
240
+
241
+ /*
242
+ * Reconstruct the generic details object for one log from store rows.
243
+ */
244
+
245
+ export function buildLogDetailsFromStore(
246
+ input: LogStoreDetailsInput,
247
+ ): Record<string, any> | null {
248
+ const details: Record<string, any> = {
249
+ __table: 'log_entry_details',
250
+ fields: input.values.map(mapStoreValueToLogEntryDetailsField),
251
+ logType: input.logTypeKey ?? null,
252
+ id: input.detailsRowId,
253
+ logId: input.logId,
254
+ activity: input.activityKey,
255
+ // The store keeps NULL for an empty note; clients expect a string.
256
+ notes: input.notes ?? '',
257
+ translation: input.translation ?? null,
258
+ metadata: buildMetadataFromStore(input),
259
+ };
260
+
261
+ return details;
262
+ }
@@ -0,0 +1,17 @@
1
+ export interface LogFieldScope {
2
+ groupKey?: string | null;
3
+ activityKey?: string | null;
4
+ config?: { includedActivityKeys?: string[]; excludedActivityKeys?: string[] } | null;
5
+ }
6
+
7
+ /*
8
+ * Match a field's activity/group scope and explicit activity exclusions.
9
+ */
10
+ export function isLogFieldApplicableToActivity(scope: LogFieldScope, activityKey?: string | null, groupKey?: string | null): boolean {
11
+ return (
12
+ (!scope.activityKey || scope.activityKey === activityKey) &&
13
+ (!scope.groupKey || scope.groupKey === groupKey) &&
14
+ (!scope.config?.includedActivityKeys || (!!activityKey && scope.config.includedActivityKeys.includes(activityKey))) &&
15
+ !(activityKey && scope.config?.excludedActivityKeys?.includes(activityKey))
16
+ );
17
+ }