@jsb188/mday 1.1.10 → 1.1.11

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 (119) hide show
  1. package/package.json +105 -54
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +35 -9
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +20 -4
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/integration.ts +8 -9
  13. package/src/constants/log.ts +7 -410
  14. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  15. package/src/constants/logTaxonomy.generated.ts +1103 -0
  16. package/src/constants/noteDoc.ts +77 -0
  17. package/src/constants/organization.ts +13 -15
  18. package/src/constants/pageRoute.ts +23 -0
  19. package/src/constants/schedule.ts +220 -0
  20. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  21. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  22. package/src/constants/sheet.ts +154 -6
  23. package/src/constants/sheetRegionSources.generated.ts +578 -0
  24. package/src/constants/square.ts +6 -6
  25. package/src/constants/storage.ts +56 -7
  26. package/src/constants/usage.ts +79 -0
  27. package/src/schemas/editLogEntry.ts +1010 -777
  28. package/src/schemas/fieldDocsQuery.ts +12 -0
  29. package/src/schemas/inboundContact.ts +60 -55
  30. package/src/schemas/logsQuery.ts +55 -49
  31. package/src/schemas/organization.ts +49 -46
  32. package/src/types/account.d.ts +4 -1
  33. package/src/types/agentDoc.d.ts +64 -0
  34. package/src/types/agentMemory.d.ts +74 -0
  35. package/src/types/campaign.d.ts +683 -0
  36. package/src/types/dataTable.d.ts +175 -256
  37. package/src/types/docAccess.d.ts +96 -0
  38. package/src/types/email.d.ts +83 -12
  39. package/src/types/fieldDoc.d.ts +273 -0
  40. package/src/types/inboundContact.d.ts +2 -1
  41. package/src/types/log.d.ts +209 -341
  42. package/src/types/noteDoc.d.ts +86 -0
  43. package/src/types/organization.d.ts +83 -40
  44. package/src/types/pageRoute.d.ts +48 -0
  45. package/src/types/schedule.d.ts +391 -0
  46. package/src/types/sheet.d.ts +862 -30
  47. package/src/types/storage.d.ts +206 -125
  48. package/src/types/usage.d.ts +106 -0
  49. package/src/types/workflow.d.ts +149 -18
  50. package/src/utils/agentDoc.ts +109 -0
  51. package/src/utils/aiChat.ts +26 -0
  52. package/src/utils/campaign.ts +741 -0
  53. package/src/utils/campaignFormEditor.ts +871 -0
  54. package/src/utils/dataTable.ts +425 -410
  55. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  56. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  57. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  58. package/src/utils/dataTableRowDocument.ts +508 -0
  59. package/src/utils/dataTableSource.ts +230 -0
  60. package/src/utils/docAccess.ts +383 -0
  61. package/src/utils/documentName.ts +53 -0
  62. package/src/utils/email.ts +112 -53
  63. package/src/utils/fieldDoc.ts +113 -0
  64. package/src/utils/log.ts +169 -176
  65. package/src/utils/logRegistryValue.ts +90 -0
  66. package/src/utils/logStoreRead.ts +266 -0
  67. package/src/utils/logTaxonomy.ts +76 -0
  68. package/src/utils/logTaxonomyDisplay.ts +439 -0
  69. package/src/utils/noteDoc.ts +827 -0
  70. package/src/utils/organization.ts +510 -91
  71. package/src/utils/pageRoute.ts +71 -0
  72. package/src/utils/schedule.ts +799 -0
  73. package/src/utils/scheduleEvaluation.ts +1994 -0
  74. package/src/utils/scheduleICS.ts +246 -0
  75. package/src/utils/scheduleRuleTemplates.ts +188 -0
  76. package/src/utils/sheet.ts +4842 -39
  77. package/src/utils/sheetAxisMove.ts +830 -0
  78. package/src/utils/sheetBootstrap.ts +1769 -0
  79. package/src/utils/sheetCommand.ts +423 -0
  80. package/src/utils/sheetExport.ts +238 -0
  81. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  82. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  83. package/src/utils/sheetJournal.ts +78 -0
  84. package/src/utils/sheetNumberFormat.ts +1211 -0
  85. package/src/utils/sheetRegion.ts +374 -0
  86. package/src/utils/sheetRegionFilter.ts +1259 -0
  87. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  88. package/src/utils/sheetSequence.ts +148 -0
  89. package/src/utils/sheetSnapshot.ts +992 -0
  90. package/src/utils/sheetStructureEdit.ts +1284 -0
  91. package/src/utils/square.ts +22 -12
  92. package/src/utils/storage.ts +152 -0
  93. package/src/utils/table-route.ts +127 -11
  94. package/src/utils/workflow.ts +191 -23
  95. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  96. package/tests/docAccess.test.ts +525 -0
  97. package/tests/editLogEntry.test.ts +112 -0
  98. package/tests/noteDoc.test.ts +669 -0
  99. package/tests/schedule.test.ts +693 -0
  100. package/tests/scheduleEvaluation.test.ts +1970 -0
  101. package/tests/scheduleICS.test.ts +208 -0
  102. package/tests/scheduleRuleTemplates.test.ts +176 -0
  103. package/tests/scheduleSweepInvariants.test.ts +428 -0
  104. package/tests/sheetAxisMove.test.ts +343 -0
  105. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  106. package/tests/sheetRegionFilter.test.ts +1135 -0
  107. package/tests/sheetSequence.test.ts +41 -0
  108. package/tests/sheetStructureEdit.test.ts +82 -0
  109. package/tsconfig.json +10 -10
  110. package/vitest.config.ts +8 -0
  111. package/src/constants/log-activityTexts.ts +0 -235
  112. package/src/constants/product.ts +0 -42
  113. package/src/constants/report.ts +0 -44
  114. package/src/schemas/productsQuery.ts +0 -53
  115. package/src/schemas/reportsQuery.ts +0 -20
  116. package/src/types/product.d.ts +0 -84
  117. package/src/types/report.d.ts +0 -290
  118. package/src/utils/product-calEvent.ts +0 -455
  119. package/src/utils/report.ts +0 -158
@@ -1,660 +1,933 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import { getCalDate } from '@jsb188/app/utils/datetime.ts';
3
3
  import { formatCurrency } from '@jsb188/app/utils/number.ts';
4
- import { getObject } from '@jsb188/app/utils/object.ts';
5
4
  import { textWithBrackets } from '@jsb188/app/utils/string.ts';
6
5
  import { getTimeZoneCode } from '@jsb188/app/utils/timeZone.ts';
7
- import {
8
- ARABLE_ACTIVITIES_GROUPED,
9
- FARMERS_MARKET_ACTIVITIES_GROUPED,
10
- GROWER_NETWORK_ACTIVITIES_GROUPED,
11
- LIVESTOCK_ACTIVITIES_GROUPED
12
- } from '../constants/log.ts';
13
6
  import type {
14
- LogArableDetailsGQL,
15
- LogEntryGQL,
16
- LogFarmersMarketDetailsGQL,
17
- LogGrowerNetworkDetailsGQL,
18
- LogLivestockDetailsGQL,
19
- LogTypeEnum
7
+ LogEntryDetailsFieldInput,
8
+ LogEntryDetailsGQL,
9
+ LogEntryGQL,
10
+ LogTaxonomyGQL,
20
11
  } from '../types/log.d.ts';
21
- import { getLogCategoryColor, getLogTypeFromActivity } from '../utils/log.ts';
12
+ import { isAccountingLogActivity } from '../utils/log.ts';
13
+ import {
14
+ formatLogTaxonomyFieldLabel,
15
+ getLogEntryDetailsEnvelopeFieldLabel,
16
+ getLogEntryDetailsFieldLabel,
17
+ getLogEntryDetailsFieldValue,
18
+ getTaxonomyActivitiesGrouped,
19
+ getTaxonomyActivityLabel,
20
+ getTaxonomyFieldDefsForActivity,
21
+ getTaxonomyFieldRequirement,
22
+ getTaxonomyGroupKey,
23
+ getTaxonomyGroupLabel,
24
+ normalizeLogEntryDetailsDateTimeValue,
25
+ normalizeLogEntryDetailsDateValue,
26
+ } from '../utils/logTaxonomyDisplay.ts';
22
27
 
23
28
  /**
24
29
  * Get editable values based on activity & type (which is also used to display UI)
25
30
  */
26
31
 
27
- export const LOG_TYPENAME_TO_DETAILS_INPUT_NAME = {
28
- LogArable: 'arableDetails',
29
- LogFarmersMarket: 'farmersMarketDetails',
30
- LogGrowerNetwork: 'growerNetworkDetails',
31
- LogLivestock: 'livestockDetails',
32
+ export const LOG_DETAILS_INPUT_NAME_BY_TYPENAME = {
33
+ LogEntryDetails: 'details',
32
34
  };
33
35
 
34
36
  /**
35
37
  * Convert GQL data to GQL mutation input format
36
38
  */
37
39
 
38
- export function makeFormValuesFromData(logEntry: LogEntryGQL) {
39
- const formValues = {
40
- logEntryId: logEntry.id,
41
- organizationId: logEntry.organizationId,
42
- accountId: logEntry.accountId,
43
- date: logEntry.date,
44
- } as Record<string, any>;
45
-
46
- switch (logEntry.details?.__typename) {
47
- case 'LogArable': {
48
- const details = logEntry.details as LogArableDetailsGQL;
49
- formValues.arableDetails = {
50
- activity: details.activity,
51
- quantity: details.quantity,
52
- item: details.item,
53
- unit: details.unit,
54
- concentration: details.concentration,
55
- concentrationUnit: details.concentrationUnit,
56
- location: logEntry.location,
57
- referenceNumber: details.referenceNumber,
58
- otherParty: details.otherParty,
59
- values: details.values,
60
- voided: details.voided,
61
- notes: details.notes,
62
- };
63
- } break;
64
- case 'LogFarmersMarket': {
65
- const details = logEntry.details as LogFarmersMarketDetailsGQL;
66
- formValues.farmersMarketDetails = {
67
- activity: details.activity,
68
- referenceNumber: details.referenceNumber,
69
- voided: details.voided,
70
- values: details.values,
71
- notes: details.notes,
72
- };
73
- } break;
74
- case 'LogGrowerNetwork': {
75
- const details = logEntry.details as LogGrowerNetworkDetailsGQL;
76
- formValues.growerNetworkDetails = {
77
- activity: details.activity,
78
- childOrgId: logEntry.childOrgId,
79
- otherParty: details.otherParty,
80
- item: details.item,
81
- location: logEntry.location,
82
- notes: details.notes,
83
- };
84
- } break;
85
- case 'LogLivestock': {
86
- const details = logEntry.details as LogLivestockDetailsGQL;
87
- formValues.livestockDetails = {
88
- activity: details.activity,
89
- livestock: details.livestock,
90
- livestockIdentifiers: details.livestockIdentifiers,
91
- livestockGroup: details.livestockGroup,
92
- referenceNumber: details.referenceNumber,
93
- otherParty: details.otherParty,
94
- values: details.values,
95
- item: details.item,
96
- quantity: details.quantity,
97
- unit: details.unit,
98
- location: logEntry.location,
99
- price: details.price,
100
- tax: details.tax,
101
- notes: details.notes,
102
- };
103
- } break;
104
- default:
105
- // @ts-expect-error
106
- console.log(`${logEntry.details?.__typename} is not done yet.`);
107
- }
108
-
109
- // input LogArableInput {
110
- // activity: LogArableActivity
111
- // voided: Boolean
112
- // item: String
113
- // quantity: Float
114
- // unit: String
115
- // concentration: Float
116
- // concentrationUnit: String
117
- // price: Float
118
- // notes: String
119
- // }
120
-
121
- // input LogFarmersMarketInput {
122
- // activity: LogFarmersMarketActivity
123
- // childOrgId: GenericID
124
- // voided: Boolean
125
- // values: [LabelAndValueInput]
126
- // notes: String
127
- // }
128
-
129
- // input LogLivestockInput {
130
- // activity: LogLivestockType
131
- // livestock: String
132
- // livestockIdentifiers: [String]
133
- // item: String
134
- // quantity: Float
135
- // unit: String
136
- // price: Float
137
- // notes: String
138
- // }
139
-
140
-
141
- return formValues;
40
+ export function makeFormValuesFromData(
41
+ logEntry: LogEntryGQL,
42
+ taxonomy?: LogTaxonomyGQL | null,
43
+ timeZone?: string | null,
44
+ ) {
45
+ const formValues = {
46
+ logEntryId: logEntry.id,
47
+ organizationId: logEntry.organizationId,
48
+ accountId: logEntry.accountId,
49
+ date: logEntry.date,
50
+ } as Record<string, any>;
51
+
52
+ if (logEntry.details?.__typename === 'LogEntryDetails') {
53
+ // Registry-driven operations (Phase 8b): typed field-def values ride a
54
+ // flat map keyed by field-def key; every taxonomy def key is
55
+ // initialized so popover-driven inputs pass the form's hasObject guard
56
+ const details = logEntry.details as LogEntryDetailsGQL;
57
+ const fields: Record<string, any> = {};
58
+ const fieldUnits: Record<string, string | null> = {};
59
+ for (const def of taxonomy?.fieldDefs || []) {
60
+ fields[def.key] = null;
61
+ fieldUnits[def.key] = null;
62
+ }
63
+ for (const field of details.fields || []) {
64
+ fields[field.key] = getLogEntryDetailsFieldValue(field, timeZone);
65
+ fieldUnits[field.key] = field.unit;
66
+ }
67
+
68
+ formValues.details = {
69
+ activity: details.activity,
70
+ __groupKey: details.type,
71
+ __originalFields: { ...fields },
72
+ __originalFieldUnits: { ...fieldUnits },
73
+ item: details.item,
74
+ quantity: details.quantity,
75
+ unit: details.unit,
76
+ price: details.price,
77
+ values: details.values,
78
+ otherParty: details.otherParty,
79
+ referenceNumber: details.referenceNumber,
80
+ voided: details.voided,
81
+ fieldLocation: details.fieldLocation,
82
+ notes: details.notes,
83
+ fields,
84
+ fieldUnits,
85
+ };
86
+ }
87
+
88
+ return formValues;
142
89
  }
143
90
 
144
- /**
145
- * Convert HTML input values to GQL mutation input types
91
+ /*
92
+ * Clone the top-level mutation variables and each details envelope so
93
+ * normalization never mutates the React form state object.
94
+ */
95
+
96
+ function cloneFormValuesForMutation(formValues: Record<string, any>) {
97
+ return Object.fromEntries(
98
+ Object.entries(formValues).map(([key, value]) => {
99
+ if (
100
+ !value ||
101
+ typeof value !== 'object' ||
102
+ Array.isArray(value) ||
103
+ value instanceof Date
104
+ ) {
105
+ return [key, value];
106
+ }
107
+
108
+ return [key, { ...value }];
109
+ }),
110
+ );
111
+ }
112
+
113
+ /*
114
+ * Return a finite form number, using null for an empty or invalid input so a
115
+ * GraphQL Float never receives NaN.
146
116
  */
147
117
 
148
- export function formatFormValuesForMutation(formValues: Record<string, any>) {
149
- for (const key in formValues) {
150
- if (formValues[key] && typeof formValues[key] === 'object') {
118
+ function getFormNumberValue(value: unknown): number | null {
119
+ if (value === '' || value === null || value === undefined) {
120
+ return null;
121
+ }
151
122
 
152
- for (const subKey in formValues[key]) {
153
- if (['quantity','price','tax','concentration'].includes(subKey)) {
154
- formValues[key][subKey] = parseFloat(formValues[key][subKey]);
155
- }
156
- }
157
- }
158
- }
123
+ const numberValue = Number(value);
124
+ return Number.isFinite(numberValue) ? numberValue : null;
125
+ }
159
126
 
160
- return formValues;
127
+ /*
128
+ * Render numeric form values as strings so a valid zero is not replaced by the shared input's empty fallback.
129
+ */
130
+
131
+ function getLogEntryDetailsNumericInputValue(value: unknown): string {
132
+ return value === null || value === undefined || value === ''
133
+ ? ''
134
+ : String(value);
161
135
  }
162
136
 
163
- /**
164
- * Arable log metadata schema
137
+ /*
138
+ * Return whether one generic form scalar represents an intentionally empty
139
+ * optional field.
140
+ */
141
+
142
+ function isEmptyLogEntryDetailsFieldValue(value: unknown): boolean {
143
+ return (
144
+ value === undefined ||
145
+ value === null ||
146
+ (typeof value === 'string' && !value.trim())
147
+ );
148
+ }
149
+
150
+ /*
151
+ * Return whether a generic field value or quantity unit changed from the form's original snapshot.
152
+ */
153
+
154
+ function logEntryDetailsFieldValueChanged(
155
+ key: string,
156
+ fields: Record<string, any>,
157
+ fieldUnits: Record<string, any>,
158
+ originalFields: Record<string, any> | null,
159
+ originalFieldUnits: Record<string, any> | null,
160
+ ): boolean {
161
+ if (!originalFields || !originalFieldUnits) {
162
+ return true;
163
+ }
164
+ return (
165
+ !Object.is(fields[key], originalFields[key]) ||
166
+ !Object.is(fieldUnits[key], originalFieldUnits[key])
167
+ );
168
+ }
169
+
170
+ /*
171
+ * Convert one applicable field-def form value to the typed mutation shape.
172
+ * Optional empty fields become explicit clear operations.
173
+ */
174
+
175
+ function makeLogEntryDetailsFieldMutationInput(
176
+ def: LogTaxonomyGQL['fieldDefs'][number],
177
+ rawValue: unknown,
178
+ rawUnit: unknown,
179
+ timeZone?: string | null,
180
+ ): LogEntryDetailsFieldInput | null {
181
+ if (isEmptyLogEntryDetailsFieldValue(rawValue)) {
182
+ // The server rejects clears for required defs after merging against the
183
+ // locked current row; omitting the key would silently preserve it.
184
+ return { key: def.key, clear: true };
185
+ }
186
+
187
+ if (def.fieldType === 'BOOLEAN') {
188
+ return {
189
+ key: def.key,
190
+ booleanValue: rawValue === true || rawValue === 'true',
191
+ };
192
+ }
193
+
194
+ if (['NUMBER', 'MONEY'].includes(def.fieldType)) {
195
+ const numberValue = getFormNumberValue(rawValue);
196
+ return numberValue === null ? null : { key: def.key, numberValue };
197
+ }
198
+
199
+ if (def.fieldType === 'QUANTITY') {
200
+ const numberValue = getFormNumberValue(rawValue);
201
+ if (numberValue === null) {
202
+ return null;
203
+ }
204
+
205
+ return {
206
+ key: def.key,
207
+ numberValue,
208
+ unit: String(rawUnit || '').trim() || null,
209
+ };
210
+ }
211
+
212
+ if (def.fieldType === 'DATE') {
213
+ const dateValue = normalizeLogEntryDetailsDateValue(String(rawValue));
214
+ return dateValue ? { key: def.key, dateValue } : null;
215
+ }
216
+
217
+ if (def.fieldType === 'DATETIME') {
218
+ const datetimeValue = normalizeLogEntryDetailsDateTimeValue(
219
+ String(rawValue),
220
+ timeZone,
221
+ );
222
+ return datetimeValue ? { key: def.key, datetimeValue } : null;
223
+ }
224
+
225
+ return { key: def.key, textValue: String(rawValue) };
226
+ }
227
+
228
+ /*
229
+ * Build mutation variables without mutating the React form state object.
230
+ */
231
+
232
+ export function formatFormValuesForMutation(
233
+ formValues: Record<string, any>,
234
+ taxonomy?: LogTaxonomyGQL | null,
235
+ timeZone?: string | null,
236
+ ) {
237
+ const mutationValues = cloneFormValuesForMutation(formValues);
238
+
239
+ for (const key in mutationValues) {
240
+ const details = mutationValues[key];
241
+ if (details && typeof details === 'object' && !Array.isArray(details)) {
242
+ for (const subKey in details) {
243
+ if (['quantity', 'price', 'tax', 'concentration'].includes(subKey)) {
244
+ details[subKey] = getFormNumberValue(details[subKey]);
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ // Only fields applicable to the saved activity are sent. The server owns
251
+ // authoritative cleanup of stale fields from the previous activity scope.
252
+ const details = mutationValues.details;
253
+ if (details && typeof details === 'object') {
254
+ const {
255
+ fields = {},
256
+ fieldUnits = {},
257
+ __groupKey,
258
+ __originalFields = null,
259
+ __originalFieldUnits = null,
260
+ ...envelope
261
+ } = details;
262
+ const applicableDefs = getTaxonomyFieldDefsForActivity(
263
+ taxonomy,
264
+ envelope.activity,
265
+ __groupKey,
266
+ );
267
+ const fieldInputs = applicableDefs
268
+ .filter((def) =>
269
+ logEntryDetailsFieldValueChanged(
270
+ def.key,
271
+ fields as Record<string, any>,
272
+ fieldUnits as Record<string, any>,
273
+ __originalFields as Record<string, any> | null,
274
+ __originalFieldUnits as Record<string, any> | null,
275
+ ),
276
+ )
277
+ .map((def) =>
278
+ makeLogEntryDetailsFieldMutationInput(
279
+ def,
280
+ (fields as Record<string, any>)[def.key],
281
+ (fieldUnits as Record<string, any>)[def.key],
282
+ timeZone,
283
+ ),
284
+ )
285
+ .filter(Boolean) as LogEntryDetailsFieldInput[];
286
+
287
+ mutationValues.details = { ...envelope, fields: fieldInputs };
288
+ }
289
+
290
+ return mutationValues;
291
+ }
292
+
293
+ /*
294
+ * Build the companion unit editor for a QUANTITY field def. Registry enum
295
+ * units use a picker; defs without an enum keep the existing free-text input.
296
+ */
297
+
298
+ function makeLogEntryDetailsQuantityUnitSchemaItem(
299
+ def: LogTaxonomyGQL['fieldDefs'][number],
300
+ fieldUnitName: string,
301
+ currentUnit: string | null | undefined,
302
+ formId: string,
303
+ focusedName: string,
304
+ basePopOverProps: Record<string, any>,
305
+ ) {
306
+ if (!def.allowedUnits?.length) {
307
+ return {
308
+ __type: 'input',
309
+ label: i18n.t('form.unit'),
310
+ item: {
311
+ name: fieldUnitName,
312
+ maxLength: 40,
313
+ placeholder: '',
314
+ },
315
+ };
316
+ }
317
+
318
+ return {
319
+ __type: 'input_click',
320
+ forceClickId: `input_click_${fieldUnitName}`,
321
+ label: i18n.t('form.unit'),
322
+ item: {
323
+ focused: focusedName === `${formId}_field_${def.key}_unit`,
324
+ name: fieldUnitName,
325
+ placeholder: '',
326
+ getter: (value: string | null) => value || '',
327
+ popOverProps: {
328
+ id: `${formId}_field_${def.key}_unit`,
329
+ ...basePopOverProps,
330
+ iface: {
331
+ name: 'PO_LIST',
332
+ variables: {
333
+ designClassName: 'w_250',
334
+ className: 'max_h_40vh',
335
+ options: [
336
+ {
337
+ __type: 'LIST_ITEM' as const,
338
+ text: i18n.t('form.remove'),
339
+ selected: !currentUnit,
340
+ name: fieldUnitName,
341
+ value: null,
342
+ },
343
+ ...def.allowedUnits.map((unit) => ({
344
+ __type: 'LIST_ITEM' as const,
345
+ text: unit,
346
+ selected: currentUnit === unit,
347
+ name: fieldUnitName,
348
+ value: unit,
349
+ })),
350
+ ],
351
+ },
352
+ },
353
+ },
354
+ },
355
+ };
356
+ }
357
+
358
+ /*
359
+ * Build the shared itemized-values editor used by transaction-style logs.
165
360
  */
166
361
 
167
- export type ValidMetadataFieldName =
168
- | 'break'
169
- | 'activity'
170
- | 'childOrgName'
171
- | 'childOrgName*fill'
172
- | 'location'
173
- | 'location*fill'
174
- | 'fieldLocation'
175
-
176
- // ARABLE
177
- | 'water_testing'
178
- | 'concentration_unit'
179
- | 'water_quantity'
180
- | 'quantity'
181
- | 'water_unit'
182
- | 'unit'
183
- | 'price'
184
- | 'crop'
185
- | 'purchased_item'
186
- | 'location_water'
187
- | 'location_arable'
188
-
189
- // FARMERS_MARKET
190
- | 'receiptNumber'
191
- // | 'childOrgId' // Not editable
192
- | 'void'
193
- | 'marketCredits'
194
-
195
- // LIVESTOCK
196
- | 'livestock'
197
- | 'livestockIdentifiers'
198
- | 'livestockGroup'
199
- | 'otherParty'
200
- | 'invoiceNumber'
201
- | 'invoiceItems'
202
- | 'tax'
203
- | 'item_used'
204
- | 'location_livestock'
205
- | null; // Need this for eslint satisfcation, but null will never happen (because of a filter())
206
-
207
- function makeMetadataSchema(
208
- namespace: string,
209
- formValues: Record<string, any>,
210
- metadataParams: MakeMetadataSchemaParams,
211
- basePopOverProps: Record<string, any>,
212
- schemaFields: ValidMetadataFieldName[]
362
+ function makeLogEntryDetailsValuesSchemaItem(
363
+ namespace: string,
364
+ detailsFormValues: Record<string, any>,
365
+ formId: string,
366
+ focusedName: string,
367
+ basePopOverProps: Record<string, any>,
368
+ required: boolean,
213
369
  ) {
214
- const { scrollAreaDOMId, formId, timeZone, focusedName, isCreateNew } = metadataParams;
215
- const schemaItems = schemaFields.map((field: ValidMetadataFieldName) => {
216
- switch (field) {
217
- case 'activity':
218
- return {
219
- __type: 'input_click',
220
- forceClickId: `input_click_${namespace}.activity`,
221
- label: i18n.t('form.activity'),
222
- item: {
223
- // editable: false,
224
- // locked: () => true, // Conditional lock is possible
225
- focused: focusedName === (formId + '_activity'),
226
- name: `${namespace}.activity`,
227
- placeholder: isCreateNew ? i18n.t(`form.activity_ph`) : '',
228
- getter: (value: string) => value ? i18n.t(`log.activity.${value}`) : '',
229
- },
230
- };
231
- case 'water_testing':
232
- return {
233
- __type: 'input',
234
- label: i18n.t('form.concentration'),
235
- item: {
236
- name: `${namespace}.concentration`,
237
- type: 'number',
238
- step: 0.1,
239
- min: 0.1,
240
- max: 99999999.99, // database max is numeric(10, 2)
241
- placeholder: isCreateNew ? i18n.t('form.concentration_ph') : '',
242
- }
243
- };
244
- case 'concentration_unit':
245
- return {
246
- __type: 'input',
247
- label: i18n.t('form.concentration_unit'),
248
- item: {
249
- name: `${namespace}.concentrationUnit`,
250
- maxLength: 40,
251
- placeholder: isCreateNew ? i18n.t('form.concentration_unit_ph') : '',
252
- },
253
- };
254
- case 'water_quantity':
255
- return {
256
- __type: 'input',
257
- label: i18n.t('form.water_quantity'),
258
- item: {
259
- name: `${namespace}.quantity`,
260
- type: 'number',
261
- step: 0.1,
262
- min: 0.1,
263
- max: 99999999.99, // database max is numeric(10, 2)
264
- placeholder: isCreateNew ? i18n.t('form.quantity_ph') : '',
265
- }
266
- };
267
- case 'quantity':
268
- return {
269
- __type: 'input',
270
- label: i18n.t('form.quantity'),
271
- item: {
272
- name: `${namespace}.quantity`,
273
- type: 'number',
274
- step: 0.1,
275
- min: 0.1,
276
- max: 99999999.99, // database max is numeric(10, 2)
277
- placeholder: isCreateNew ? i18n.t('form.quantity_ph') : '',
278
- }
279
- };
280
- case 'water_unit':
281
- return {
282
- __type: 'input',
283
- label: i18n.t('form.water_unit'),
284
- item: {
285
- name: `${namespace}.unit`,
286
- maxLength: 40,
287
- placeholder: isCreateNew ? i18n.t('form.water_unit_ph') : '',
288
- }
289
- };
290
- case 'unit':
291
- return {
292
- __type: 'input',
293
- label: i18n.t('form.unit'),
294
- item: {
295
- name: `${namespace}.unit`,
296
- maxLength: 40,
297
- placeholder: isCreateNew ? i18n.t('log.unit_arable_ph') : '',
298
- }
299
- };
300
- case 'fieldLocation':
301
- return {
302
- __type: 'input',
303
- label: i18n.t('log.fieldLocation'),
304
- item: {
305
- name: `${namespace}.fieldLocation`,
306
- maxLength: 64,
307
- placeholder: '',
308
- }
309
- };
310
- case 'location_arable':
311
- return {
312
- __type: 'input',
313
- label: i18n.t('form.location'),
314
- item: {
315
- name: `${namespace}.location`,
316
- maxLength: 40,
317
- placeholder: isCreateNew ? i18n.t('log.location_arable_ph') : '',
318
- }
319
- };
320
- case 'location_water':
321
- return {
322
- __type: 'input',
323
- label: i18n.t('form.location'),
324
- item: {
325
- name: `${namespace}.location`,
326
- maxLength: 40,
327
- placeholder: isCreateNew ? i18n.t('log.location_water_ph') : '',
328
- }
329
- };
330
- case 'location_livestock':
331
- return {
332
- __type: 'input',
333
- label: i18n.t('form.location'),
334
- item: {
335
- name: `${namespace}.location`,
336
- maxLength: 100,
337
- placeholder: isCreateNew ? i18n.t('log.location_livestock_ph') : '',
338
- }
339
- };
340
- case 'price':
341
- return {
342
- __type: 'input',
343
- label: i18n.t('form.price'),
344
- item: {
345
- name: `${namespace}.price`,
346
- type: 'number',
347
- step: 0.1,
348
- min: 0.1,
349
- max: 99999999.99, // database max is numeric(10, 2)
350
- placeholder: isCreateNew ? i18n.t('form.price_ph') : '',
351
- },
352
- };
353
- case 'tax':
354
- return {
355
- __type: 'input',
356
- label: i18n.t('form.tax'),
357
- item: {
358
- name: `${namespace}.tax`,
359
- type: 'number',
360
- step: 0.1,
361
- min: 0.1,
362
- max: 99999999.99, // database max is numeric(10, 2)
363
- placeholder: isCreateNew ? i18n.t('form.tax_ph') : '',
364
- },
365
- };
366
- case 'crop':
367
- return {
368
- __type: 'input',
369
- label: i18n.t('form.crop'),
370
- item: {
371
- name: `${namespace}.item`,
372
- placeholder: isCreateNew ? i18n.t('log.crop_ph') : '',
373
- }
374
- };
375
- case 'purchased_item':
376
- return {
377
- __type: 'input',
378
- label: i18n.t('form.purchase_summary'),
379
- item: {
380
- name: `${namespace}.item`,
381
- placeholder: isCreateNew ? i18n.t('log.crop_ph') : '',
382
- }
383
- };
384
- case 'livestock':
385
- return {
386
- __type: 'input',
387
- label: i18n.t('log.livestock'),
388
- item: {
389
- name: `${namespace}.livestock`,
390
- placeholder: isCreateNew ? i18n.t('log.livestock_ph') : '',
391
- }
392
- };
393
- case 'livestockIdentifiers':
394
- return {
395
- __type: 'input',
396
- label: i18n.t('log.id_tags'),
397
- item: {
398
- name: `${namespace}.livestockIdentifiers`,
399
- placeholder: isCreateNew ? i18n.t('log.id_tags_ph') : '',
400
- getter: (value: string[]) => value ? value.join(',') : '',
401
- setter: (value: string) => value.split(',')
402
- }
403
- };
404
- case 'livestockGroup':
405
- return {
406
- __type: 'input',
407
- label: i18n.t('log.group'),
408
- item: {
409
- name: `${namespace}.livestockGroup`,
410
- placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
411
- }
412
- };
413
- case 'otherParty':
414
- return {
415
- __type: 'input',
416
- label: i18n.t('form.vendor'),
417
- item: {
418
- name: `${namespace}.otherParty`,
419
- }
420
- };
421
- case 'invoiceNumber':
422
- return {
423
- __type: 'input',
424
- label: i18n.t('log.invoice_number'),
425
- item: {
426
- // editable: false,
427
- locked: true,
428
- name: `${namespace}.referenceNumber`,
429
- }
430
- };
431
- case 'receiptNumber':
432
- return {
433
- __type: 'input',
434
- label: i18n.t('log.receipt_number'),
435
- item: {
436
- // editable: false,
437
- locked: true,
438
- name: `${namespace}.referenceNumber`,
439
- // placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
440
- // getter: (value: string[]) => value ? value.join(',') : '',
441
- // setter: (value: string) => value.split(',')
442
- }
443
- };
444
-
445
- // Not allowed to edit
446
- // case 'childOrgId':
447
- // return {
448
- // __type: 'input',
449
- // label: i18n.t('log.receipt_for'),
450
- // item: {
451
- // name: `${namespace}.childOrgId`,
452
- // // placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
453
- // // getter: (value: string[]) => value ? value.join(',') : '',
454
- // // setter: (value: string) => value.split(',')
455
- // }
456
- // };
457
- case 'void':
458
- return {
459
- __type: 'input_click',
460
- forceClickId: `input_click_${namespace}.voided`,
461
- label: i18n.t('form.void'),
462
- inputClassName: formValues[namespace]?.voided ? 'cl_red' : '',
463
- item: {
464
- // locked: () => true,
465
- focused: focusedName === (formId + '_void'),
466
- name: `${namespace}.voided`,
467
- placeholder: isCreateNew ? i18n.t(`form.void_ph`) : '',
468
- getter: (value: string) => i18n.t(value ? 'form.voided' : 'form.valid'),
469
- },
470
- popOverProps: {
471
- id: formId + '_void',
472
- ...basePopOverProps,
473
- iface: {
474
- name: 'PO_LIST',
475
- variables: {
476
- designClassName: 'w_250',
477
- className: 'max_h_40vh',
478
- options: [{
479
- __type: 'LIST_ITEM' as const,
480
- text: i18n.t('form.valid'),
481
- iconName: 'receipt-dollar',
482
- selected: !formValues[namespace]?.voided,
483
- name: `${namespace}.voided`,
484
- value: false,
485
- }, {
486
- __type: 'LIST_ITEM' as const,
487
- text: i18n.t('form.voided'),
488
- iconName: 'receipt-off',
489
- selected: formValues[namespace]?.voided === true,
490
- name: `${namespace}.voided`,
491
- value: true,
492
- }]
493
- }
494
- }
495
- }
496
- };
497
- case 'invoiceItems':
498
- return {
499
- __type: 'input_click',
500
- label: i18n.t('log.invoice_items'),
501
- forceClickId: `input_click_${namespace}.values`,
502
- item: {
503
- // locked: () => true,
504
- focused: focusedName === (formId + '_values'),
505
- name: `${namespace}.values`,
506
- placeholder: isCreateNew ? i18n.t(`log.invoice_items_ph`) : '',
507
- getter: (labelsAndValues: string[]) => {
508
- return labelsAndValues?.map((lv: any) => {
509
- return textWithBrackets(
510
- `${lv.quantity ? `${lv.quantity} ` : ''}${lv.unit ? `${lv.unit} ` : ''}${lv.label}`,
511
- formatCurrency(lv.value, false),
512
- );
513
- }).join(', ');
514
- },
515
- },
516
- popOverProps: {
517
- id: formId + '_invoiceItems',
518
- ...basePopOverProps,
519
- iface: {
520
- name: 'PO_LABELS_AND_VALUES',
521
- variables: {
522
- gridLayoutStyle: '70px 70px 1fr 85px',
523
- designClassName: 'w_400',
524
- className: 'max_h_40vh',
525
- // flipInputOrder: true,
526
- forceNumericValues: true,
527
- includeQuantity: true,
528
- includeUnit: true,
529
- name: `${namespace}.values`,
530
- labels: [i18n.t('form.quantity'), i18n.t('form.unit'), i18n.t('log.invoice_item'), `$ ${i18n.t('form.amount')}`],
531
- inputs: formValues[namespace]?.values || [],
532
- }
533
- }
534
- }
535
- };
536
- case 'marketCredits':
537
- return {
538
- __type: 'input_click',
539
- label: i18n.t('log.marketCredits'),
540
- forceClickId: `input_click_${namespace}.values`,
541
- item: {
542
- // locked: () => true,
543
- focused: focusedName === (formId + '_values'),
544
- name: `${namespace}.values`,
545
- placeholder: isCreateNew ? i18n.t(`log.marketCredits_ph`) : '',
546
- getter: (labelsAndValues: string[]) => {
547
- return labelsAndValues?.map((lv: any) => {
548
- return `${formatCurrency(lv.value, false)} ${lv.label}`;
549
- }).join(', ');
550
- },
551
- },
552
- popOverProps: {
553
- id: formId + '_marketCredits',
554
- ...basePopOverProps,
555
- iface: {
556
- name: 'PO_LABELS_AND_VALUES',
557
- variables: {
558
- gridLayoutStyle: '85px 1fr',
559
- designClassName: 'w_250',
560
- className: 'max_h_40vh',
561
- flipInputOrder: true,
562
- forceNumericValues: true,
563
- name: `${namespace}.values`,
564
- labels: [`$ ${i18n.t('form.amount')}`, i18n.t('log.name_of_credit')],
565
- inputs: formValues[namespace]?.values || [],
566
- }
567
- }
568
- }
569
- };
570
- default:
571
- console.warn(`Field ${field} is not defined in metadata schema.`);
572
- return null;
573
- }
574
- }).filter(Boolean);
575
-
576
- return schemaItems;
370
+ return {
371
+ __type: 'input_click',
372
+ label: formatLogTaxonomyFieldLabel(
373
+ i18n.t('log.invoice_items'),
374
+ required ? 'REQUIRED' : null,
375
+ ),
376
+ forceClickId: `input_click_${namespace}.values`,
377
+ item: {
378
+ focused: focusedName === `${formId}_values`,
379
+ name: `${namespace}.values`,
380
+ required,
381
+ placeholder: i18n.t('log.invoice_items_ph'),
382
+ getter: (labelsAndValues: any[]) =>
383
+ labelsAndValues
384
+ ?.map((entry) =>
385
+ textWithBrackets(
386
+ `${entry.quantity ? `${entry.quantity} ` : ''}${entry.unit ? `${entry.unit} ` : ''}${entry.label}`,
387
+ formatCurrency(entry.value, false),
388
+ ),
389
+ )
390
+ .join(', '),
391
+ },
392
+ popOverProps: {
393
+ id: `${formId}_values`,
394
+ ...basePopOverProps,
395
+ iface: {
396
+ name: 'PO_LABELS_AND_VALUES',
397
+ variables: {
398
+ gridLayoutStyle: '70px 70px 1fr 85px',
399
+ designClassName: 'w_400',
400
+ className: 'max_h_40vh',
401
+ forceNumericValues: true,
402
+ includeQuantity: true,
403
+ includeUnit: true,
404
+ name: `${namespace}.values`,
405
+ labels: [
406
+ i18n.t('form.quantity'),
407
+ i18n.t('form.unit'),
408
+ i18n.t('log.invoice_item'),
409
+ `$ ${i18n.t('form.amount')}`,
410
+ ],
411
+ inputs: detailsFormValues.values || [],
412
+ },
413
+ },
414
+ },
415
+ };
577
416
  }
578
417
 
579
418
  /**
580
- * Get schema fields from log type
419
+ * Editor schema for registry-driven operations (Phase 8b): the envelope
420
+ * (activity/item/quantity/unit/price/fieldLocation/void) plus one typed input per
421
+ * applicable registry field def. Labels fall back i18n -> registry text ->
422
+ * humanized key because registry keys are data, not compile-time enums.
581
423
  */
582
424
 
583
- export function getSchemaFieldsFromLog(__typename: string, logType: LogTypeEnum): ValidMetadataFieldName[] {
584
-
585
- let schemaFields: ValidMetadataFieldName[];
586
- switch (__typename) {
587
- case 'LogArable': {
588
- const isWaterTesting = logType === 'WATER';
589
- const isSale = ['SALES'].includes(logType!);
590
- const isPurchase = ['SEED'].includes(logType!);
591
- const isSaleOrPurchase = isSale || isPurchase;
592
-
593
- schemaFields = [
594
- 'activity',
595
- isWaterTesting ? 'water_testing' : null,
596
- isWaterTesting ? 'concentration_unit' : null, // unit will be ignored in view mode
597
- isWaterTesting ? null : isSaleOrPurchase ? 'purchased_item' : 'crop',
598
- isWaterTesting ? 'water_quantity' : isSaleOrPurchase ? null : 'quantity',
599
- isWaterTesting ? 'water_unit' : isSaleOrPurchase ? null : 'unit', // unit will be ignored in view mode
600
- isSaleOrPurchase ? 'otherParty' : null,
601
- isSaleOrPurchase ? 'invoiceNumber' : null,
602
- isSaleOrPurchase ? 'invoiceItems' : null,
603
- isSaleOrPurchase ? 'tax' : null,
604
- isSaleOrPurchase ? 'void' : null,
605
- isSaleOrPurchase ? null : isWaterTesting ? 'location_water' : 'location_arable',
606
- 'location',
607
- 'fieldLocation',
608
- ];
609
- } break;
610
- case 'LogFarmersMarket': {
611
- const isReceipt = ['MARKET_RECEIPT'].includes(logType);
612
-
613
- schemaFields = [
614
- 'activity',
615
- isReceipt ? 'receiptNumber' : null,
616
- // 'childOrgId', // not editable
617
- isReceipt ? 'void' : null,
618
- isReceipt ? 'marketCredits' : null,
619
- 'location*fill',
620
- 'fieldLocation',
621
- ];
622
- } break;
623
- case 'LogGrowerNetwork': {
624
- schemaFields = [
625
- 'activity',
626
- 'childOrgName*fill',
627
- // 'break',
628
- 'location*fill',
629
- 'fieldLocation'
630
- ];
631
- } break;
632
- case 'LogLivestock': {
633
- const isLivestock = ['LIVESTOCK_LIFE_CYCLE', 'LIVESTOCK_TRACKING', 'LIVESTOCK_HEALTHCARE'].includes(logType);
634
- const isSupplyPurchase = logType === 'SUPPLY_PURCHASE';
635
- const isLandManagement = logType === 'PASTURE_LAND_MANAGEMENT';
636
-
637
- schemaFields = [
638
- 'activity',
639
- isLivestock ? 'livestock' : null,
640
- isLivestock ? 'livestockIdentifiers' : null,
641
- isLivestock ? 'livestockGroup' : null,
642
- isSupplyPurchase ? 'otherParty' : null,
643
- isSupplyPurchase ? 'invoiceNumber' : null,
644
- isSupplyPurchase ? 'invoiceItems' : null,
645
- isSupplyPurchase ? 'tax' : null,
646
- isLandManagement ? 'item_used' : null,
647
- isLivestock || isSupplyPurchase ? null : 'quantity',
648
- isLivestock || isSupplyPurchase ? null : 'unit',
649
- !isSupplyPurchase ? 'location_livestock' : null,
650
- isLivestock ? 'price' : null,
651
- ];
652
- } break;
653
- default:
654
- schemaFields = [];
655
- }
656
-
657
- return schemaFields.filter(Boolean);
425
+ function makeLogEntryDetailsMetadataSchema(
426
+ namespace: string,
427
+ formValues: Record<string, any>,
428
+ metadataParams: MakeMetadataSchemaParams,
429
+ basePopOverProps: Record<string, any>,
430
+ ) {
431
+ const { taxonomy, formId, focusedName, isCreateNew } = metadataParams;
432
+ if (!taxonomy) {
433
+ return [];
434
+ }
435
+
436
+ const detailsFormValues = formValues[namespace] || {};
437
+ const activityKey = detailsFormValues.activity;
438
+ const groupKey = getTaxonomyGroupKey(
439
+ taxonomy,
440
+ activityKey,
441
+ detailsFormValues.__groupKey,
442
+ );
443
+ const activityGroups = getTaxonomyActivitiesGrouped(taxonomy);
444
+ const isAccountingActivity = isAccountingLogActivity(activityKey);
445
+
446
+ const schemaItems: any[] = [
447
+ {
448
+ __type: 'input_click',
449
+ forceClickId: `input_click_${namespace}.activity`,
450
+ label: i18n.t('form.activity'),
451
+ item: {
452
+ focused: focusedName === `${formId}_activity`,
453
+ name: `${namespace}.activity`,
454
+ placeholder: isCreateNew ? i18n.t('form.activity_ph') : '',
455
+ getter: (value: string) => getTaxonomyActivityLabel(taxonomy, value),
456
+ popOverProps: {
457
+ id: `${formId}_activity`,
458
+ ...basePopOverProps,
459
+ iface: {
460
+ name: 'PO_LIST',
461
+ variables: {
462
+ designClassName: 'w_250',
463
+ className: 'max_h_40vh',
464
+ options: activityGroups.reduce(
465
+ (options, [groupKey, activities], index) => {
466
+ const groupOptions: any[] = [
467
+ {
468
+ __type: 'LIST_SUBTITLE' as const,
469
+ text: getTaxonomyGroupLabel(taxonomy, groupKey),
470
+ className: 'mt_sm',
471
+ },
472
+ ...activities.map((activity) => ({
473
+ __type: 'LIST_ITEM' as const,
474
+ text: getTaxonomyActivityLabel(taxonomy, activity.key),
475
+ textClassName: 'ft_xs',
476
+ rightIconClassName: 'ft_xs mb_2',
477
+ name: `${namespace}.activity`,
478
+ value: activity.key,
479
+ selected: activityKey === activity.key,
480
+ })),
481
+ ];
482
+
483
+ if (index < activityGroups.length - 1) {
484
+ groupOptions.push({ __type: 'BREAK' as const });
485
+ }
486
+
487
+ return options.concat(groupOptions);
488
+ },
489
+ [] as any[],
490
+ ),
491
+ },
492
+ },
493
+ },
494
+ },
495
+ },
496
+ {
497
+ __type: 'input',
498
+ label: formatLogTaxonomyFieldLabel(
499
+ i18n.t('form.item'),
500
+ getTaxonomyFieldRequirement(taxonomy, activityKey, 'item', groupKey),
501
+ ),
502
+ item: {
503
+ name: `${namespace}.item`,
504
+ required:
505
+ getTaxonomyFieldRequirement(
506
+ taxonomy,
507
+ activityKey,
508
+ 'item',
509
+ groupKey,
510
+ ) === 'REQUIRED',
511
+ maxLength: 255,
512
+ placeholder: '',
513
+ },
514
+ },
515
+ {
516
+ __type: 'input',
517
+ label: formatLogTaxonomyFieldLabel(
518
+ getLogEntryDetailsEnvelopeFieldLabel('quantity', activityKey, groupKey),
519
+ getTaxonomyFieldRequirement(
520
+ taxonomy,
521
+ activityKey,
522
+ 'quantity',
523
+ groupKey,
524
+ ),
525
+ ),
526
+ item: {
527
+ name: `${namespace}.quantity`,
528
+ type: 'number',
529
+ getter: getLogEntryDetailsNumericInputValue,
530
+ required:
531
+ getTaxonomyFieldRequirement(
532
+ taxonomy,
533
+ activityKey,
534
+ 'quantity',
535
+ groupKey,
536
+ ) === 'REQUIRED',
537
+ step: 0.1,
538
+ max: 99999999.99, // database max is numeric(10, 2)
539
+ placeholder: isCreateNew ? i18n.t('form.quantity_ph') : '',
540
+ },
541
+ },
542
+ {
543
+ __type: 'input',
544
+ label: formatLogTaxonomyFieldLabel(
545
+ i18n.t('form.unit'),
546
+ getTaxonomyFieldRequirement(taxonomy, activityKey, 'unit', groupKey),
547
+ ),
548
+ item: {
549
+ name: `${namespace}.unit`,
550
+ required:
551
+ getTaxonomyFieldRequirement(
552
+ taxonomy,
553
+ activityKey,
554
+ 'unit',
555
+ groupKey,
556
+ ) === 'REQUIRED',
557
+ maxLength: 40,
558
+ placeholder: '',
559
+ },
560
+ },
561
+ {
562
+ __type: 'input',
563
+ label: formatLogTaxonomyFieldLabel(
564
+ i18n.t('form.price'),
565
+ getTaxonomyFieldRequirement(taxonomy, activityKey, 'price', groupKey),
566
+ ),
567
+ item: {
568
+ name: `${namespace}.price`,
569
+ type: 'number',
570
+ getter: getLogEntryDetailsNumericInputValue,
571
+ required:
572
+ getTaxonomyFieldRequirement(
573
+ taxonomy,
574
+ activityKey,
575
+ 'price',
576
+ groupKey,
577
+ ) === 'REQUIRED',
578
+ step: 0.01,
579
+ max: 99999999.99, // database max is numeric(10, 2)
580
+ placeholder: isCreateNew ? i18n.t('form.price_ph') : '',
581
+ },
582
+ },
583
+ {
584
+ __type: 'input',
585
+ label: formatLogTaxonomyFieldLabel(
586
+ i18n.t('form.vendor'),
587
+ getTaxonomyFieldRequirement(
588
+ taxonomy,
589
+ activityKey,
590
+ 'otherParty',
591
+ groupKey,
592
+ ),
593
+ ),
594
+ item: {
595
+ name: `${namespace}.otherParty`,
596
+ required:
597
+ getTaxonomyFieldRequirement(
598
+ taxonomy,
599
+ activityKey,
600
+ 'otherParty',
601
+ groupKey,
602
+ ) === 'REQUIRED',
603
+ maxLength: 255,
604
+ placeholder: '',
605
+ },
606
+ },
607
+ ];
608
+
609
+ // One typed input per applicable registry field def
610
+ for (const def of getTaxonomyFieldDefsForActivity(
611
+ taxonomy,
612
+ activityKey,
613
+ groupKey,
614
+ )) {
615
+ const fieldName = `${namespace}.fields.${def.key}`;
616
+ const fieldUnitName = `${namespace}.fieldUnits.${def.key}`;
617
+ const fieldLabel = getLogEntryDetailsFieldLabel(def.key);
618
+ const fieldRequirement = def.required
619
+ ? 'REQUIRED'
620
+ : getTaxonomyFieldRequirement(taxonomy, activityKey, def.key, groupKey);
621
+ const fieldIsRequired = fieldRequirement === 'REQUIRED';
622
+ const label = formatLogTaxonomyFieldLabel(fieldLabel, fieldRequirement);
623
+ const currentValue = detailsFormValues.fields?.[def.key];
624
+ const currentUnit = detailsFormValues.fieldUnits?.[def.key];
625
+
626
+ if (def.fieldType === 'SELECT' && def.options?.length) {
627
+ schemaItems.push({
628
+ __type: 'input_click',
629
+ forceClickId: `input_click_${fieldName}`,
630
+ label,
631
+ item: {
632
+ focused: focusedName === `${formId}_field_${def.key}`,
633
+ name: fieldName,
634
+ placeholder: '',
635
+ required: fieldIsRequired,
636
+ getter: (value: string) => value || '',
637
+ popOverProps: {
638
+ id: `${formId}_field_${def.key}`,
639
+ ...basePopOverProps,
640
+ iface: {
641
+ name: 'PO_LIST',
642
+ variables: {
643
+ designClassName: 'w_250',
644
+ className: 'max_h_40vh',
645
+ options: [
646
+ ...(!fieldIsRequired
647
+ ? [
648
+ {
649
+ __type: 'LIST_ITEM' as const,
650
+ text: i18n.t('form.remove'),
651
+ selected:
652
+ currentValue === null ||
653
+ currentValue === undefined ||
654
+ currentValue === '',
655
+ name: fieldName,
656
+ value: null,
657
+ },
658
+ ]
659
+ : []),
660
+ ...def.options.map((option) => ({
661
+ __type: 'LIST_ITEM' as const,
662
+ text: option,
663
+ selected: currentValue === option,
664
+ name: fieldName,
665
+ value: option,
666
+ })),
667
+ ],
668
+ },
669
+ },
670
+ },
671
+ },
672
+ });
673
+ } else if (def.fieldType === 'BOOLEAN') {
674
+ schemaItems.push({
675
+ __type: 'input_click',
676
+ forceClickId: `input_click_${fieldName}`,
677
+ label,
678
+ item: {
679
+ focused: focusedName === `${formId}_field_${def.key}`,
680
+ name: fieldName,
681
+ placeholder: '',
682
+ required: fieldIsRequired,
683
+ getter: (value: boolean | null) =>
684
+ typeof value === 'boolean'
685
+ ? i18n.t(value ? 'form.yes' : 'form.no')
686
+ : '',
687
+ popOverProps: {
688
+ id: `${formId}_field_${def.key}`,
689
+ ...basePopOverProps,
690
+ iface: {
691
+ name: 'PO_LIST',
692
+ variables: {
693
+ designClassName: 'w_250',
694
+ className: 'max_h_40vh',
695
+ options: [
696
+ ...(!fieldIsRequired
697
+ ? [
698
+ {
699
+ __type: 'LIST_ITEM' as const,
700
+ text: i18n.t('form.remove'),
701
+ selected:
702
+ currentValue === null ||
703
+ currentValue === undefined ||
704
+ currentValue === '',
705
+ name: fieldName,
706
+ value: null,
707
+ },
708
+ ]
709
+ : []),
710
+ {
711
+ __type: 'LIST_ITEM' as const,
712
+ text: i18n.t('form.yes'),
713
+ selected: currentValue === true,
714
+ name: fieldName,
715
+ value: true,
716
+ },
717
+ {
718
+ __type: 'LIST_ITEM' as const,
719
+ text: i18n.t('form.no'),
720
+ selected: currentValue === false,
721
+ name: fieldName,
722
+ value: false,
723
+ },
724
+ ],
725
+ },
726
+ },
727
+ },
728
+ },
729
+ });
730
+ } else if (def.fieldType === 'DATE' || def.fieldType === 'DATETIME') {
731
+ schemaItems.push({
732
+ __type: 'input',
733
+ label,
734
+ item: {
735
+ name: fieldName,
736
+ type: def.fieldType === 'DATE' ? 'date' : 'datetime-local',
737
+ required: fieldIsRequired,
738
+ step: def.fieldType === 'DATETIME' ? 60 : undefined,
739
+ placeholder: '',
740
+ },
741
+ });
742
+ } else if (def.fieldType === 'QUANTITY') {
743
+ schemaItems.push(
744
+ {
745
+ __type: 'input',
746
+ label,
747
+ item: {
748
+ name: fieldName,
749
+ type: 'number',
750
+ getter: getLogEntryDetailsNumericInputValue,
751
+ required: fieldIsRequired,
752
+ step: 0.1,
753
+ max: 99999999.99, // database max is numeric(10, 2)
754
+ placeholder: '',
755
+ },
756
+ },
757
+ makeLogEntryDetailsQuantityUnitSchemaItem(
758
+ def,
759
+ fieldUnitName,
760
+ currentUnit,
761
+ formId,
762
+ focusedName,
763
+ basePopOverProps,
764
+ ),
765
+ );
766
+ } else if (['NUMBER', 'MONEY'].includes(def.fieldType)) {
767
+ schemaItems.push({
768
+ __type: 'input',
769
+ label,
770
+ item: {
771
+ name: fieldName,
772
+ type: 'number',
773
+ getter: getLogEntryDetailsNumericInputValue,
774
+ required: fieldIsRequired,
775
+ step: def.fieldType === 'MONEY' ? 0.01 : 0.1,
776
+ max: 99999999.99, // database max is numeric(10, 2)
777
+ placeholder: '',
778
+ },
779
+ });
780
+ } else {
781
+ schemaItems.push({
782
+ __type: 'input',
783
+ label,
784
+ item: {
785
+ name: fieldName,
786
+ required: fieldIsRequired,
787
+ maxLength: 255,
788
+ placeholder: '',
789
+ },
790
+ });
791
+ }
792
+ }
793
+
794
+ const valuesRequirement = getTaxonomyFieldRequirement(
795
+ taxonomy,
796
+ activityKey,
797
+ 'values',
798
+ groupKey,
799
+ );
800
+ if (valuesRequirement || detailsFormValues.values?.length) {
801
+ schemaItems.push(
802
+ makeLogEntryDetailsValuesSchemaItem(
803
+ namespace,
804
+ detailsFormValues,
805
+ formId,
806
+ focusedName,
807
+ basePopOverProps,
808
+ valuesRequirement === 'REQUIRED',
809
+ ),
810
+ );
811
+ }
812
+
813
+ schemaItems.push(
814
+ {
815
+ __type: 'input',
816
+ label: formatLogTaxonomyFieldLabel(
817
+ i18n.t('log.receipt_number'),
818
+ getTaxonomyFieldRequirement(
819
+ taxonomy,
820
+ activityKey,
821
+ 'referenceNumber',
822
+ groupKey,
823
+ ),
824
+ ),
825
+ item: {
826
+ name: `${namespace}.referenceNumber`,
827
+ required:
828
+ getTaxonomyFieldRequirement(
829
+ taxonomy,
830
+ activityKey,
831
+ 'referenceNumber',
832
+ groupKey,
833
+ ) === 'REQUIRED',
834
+ maxLength: 120,
835
+ placeholder: '',
836
+ },
837
+ },
838
+ {
839
+ __type: 'input',
840
+ label: formatLogTaxonomyFieldLabel(
841
+ i18n.t('log.fieldLocation'),
842
+ getTaxonomyFieldRequirement(
843
+ taxonomy,
844
+ activityKey,
845
+ 'fieldLocation',
846
+ groupKey,
847
+ ),
848
+ ),
849
+ item: {
850
+ name: `${namespace}.fieldLocation`,
851
+ required:
852
+ getTaxonomyFieldRequirement(
853
+ taxonomy,
854
+ activityKey,
855
+ 'fieldLocation',
856
+ groupKey,
857
+ ) === 'REQUIRED',
858
+ maxLength: 255,
859
+ placeholder: '',
860
+ },
861
+ },
862
+ {
863
+ __type: 'input_click',
864
+ forceClickId: `input_click_${namespace}.voided`,
865
+ label: formatLogTaxonomyFieldLabel(
866
+ i18n.t('form.void'),
867
+ getTaxonomyFieldRequirement(taxonomy, activityKey, 'voided', groupKey),
868
+ ),
869
+ inputClassName: detailsFormValues.voided ? 'cl_red' : '',
870
+ item: {
871
+ focused: focusedName === `${formId}_void`,
872
+ name: `${namespace}.voided`,
873
+ required:
874
+ getTaxonomyFieldRequirement(
875
+ taxonomy,
876
+ activityKey,
877
+ 'voided',
878
+ groupKey,
879
+ ) === 'REQUIRED',
880
+ placeholder: isCreateNew ? i18n.t(`form.void_ph`) : '',
881
+ getter: (value: string) => i18n.t(value ? 'form.voided' : 'form.valid'),
882
+ },
883
+ popOverProps: {
884
+ id: `${formId}_void`,
885
+ ...basePopOverProps,
886
+ iface: {
887
+ name: 'PO_LIST',
888
+ variables: {
889
+ designClassName: 'w_250',
890
+ className: 'max_h_40vh',
891
+ options: [
892
+ {
893
+ __type: 'LIST_ITEM' as const,
894
+ text: i18n.t('form.valid'),
895
+ iconName: 'receipt-dollar',
896
+ selected: !detailsFormValues.voided,
897
+ name: `${namespace}.voided`,
898
+ value: false,
899
+ },
900
+ {
901
+ __type: 'LIST_ITEM' as const,
902
+ text: i18n.t('form.voided'),
903
+ iconName: 'receipt-off',
904
+ selected: detailsFormValues.voided === true,
905
+ name: `${namespace}.voided`,
906
+ value: true,
907
+ },
908
+ ],
909
+ },
910
+ },
911
+ },
912
+ },
913
+ );
914
+
915
+ if (!isAccountingActivity) {
916
+ // Operation-wide finance field definitions must not leak accounting
917
+ // inputs into non-financial activity editors.
918
+ const financialFieldNames = [
919
+ `${namespace}.price`,
920
+ `${namespace}.otherParty`,
921
+ `${namespace}.fields.tax`,
922
+ `${namespace}.referenceNumber`,
923
+ `${namespace}.voided`,
924
+ ];
925
+ return schemaItems.filter(
926
+ (schemaItem) => !financialFieldNames.includes(schemaItem?.item?.name),
927
+ );
928
+ }
929
+
930
+ return schemaItems;
658
931
  }
659
932
 
660
933
  /**
@@ -662,162 +935,122 @@ export function getSchemaFieldsFromLog(__typename: string, logType: LogTypeEnum)
662
935
  */
663
936
 
664
937
  interface MakeMetadataSchemaParams {
665
- __typename: string;
666
- scrollAreaDOMId: string;
667
- formId: string;
668
- timeZone: string | null | undefined;
669
- focusedName: string;
670
- isCreateNew: boolean;
938
+ __typename: string;
939
+ scrollAreaDOMId: string;
940
+ formId: string;
941
+ timeZone: string | null | undefined;
942
+ focusedName: string;
943
+ isCreateNew: boolean;
944
+ taxonomy?: LogTaxonomyGQL | null;
671
945
  }
672
946
 
947
+ /*
948
+ * Build the registry-driven generic log metadata editor schema.
949
+ */
950
+
673
951
  export function makeLogMetadataSchema(
674
- formValues: Record<string, any> = {},
675
- metadataParams: MakeMetadataSchemaParams,
952
+ formValues: Record<string, any> = {},
953
+ metadataParams: MakeMetadataSchemaParams,
676
954
  ) {
677
- const { __typename, scrollAreaDOMId, formId, timeZone, focusedName, isCreateNew } = metadataParams;
678
-
679
- let activitiesList: any[] = [];
680
- let schemaItems: any[] = [];
681
-
682
- const basePopOverProps = {
683
- scrollAreaDOMId,
684
- zClassName: 'z9',
685
- position: 'bottom_left',
686
- offsetX: 0,
687
- offsetY: 7,
688
- };
689
-
690
- const minDate = new Date();
691
- minDate.setFullYear(minDate.getFullYear() - 10);
692
-
693
- const maxDate = new Date();
694
- maxDate.setMonth(maxDate.getMonth() + 1);
695
-
696
- const namespace = {
697
- LogArable: 'arableDetails',
698
- LogFarmersMarket: 'farmersMarketDetails',
699
- LogGrowerNetwork: 'growerNetworkDetails',
700
- LogLivestock: 'livestockDetails',
701
- }[__typename] || '';
702
-
703
- const logActivity = formValues[namespace]?.activity;
704
- const logType = getLogTypeFromActivity(__typename, logActivity)!;
705
- const schemaFields = getSchemaFieldsFromLog(__typename, logType);
706
-
707
- switch (__typename) {
708
- case 'LogArable': {
709
- activitiesList = ARABLE_ACTIVITIES_GROUPED;
710
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
711
- } break;
712
- case 'LogFarmersMarket': {
713
- activitiesList = FARMERS_MARKET_ACTIVITIES_GROUPED;
714
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
715
- } break;
716
- case 'LogGrowerNetwork': {
717
- activitiesList = GROWER_NETWORK_ACTIVITIES_GROUPED;
718
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
719
- } break;
720
- case 'LogLivestock': {
721
- activitiesList = LIVESTOCK_ACTIVITIES_GROUPED;
722
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
723
- } break;
724
- default:
725
- }
726
-
727
- if (logType) {
728
- activitiesList = activitiesList.filter(([type]) => type === logType);
729
- }
730
-
731
- // Date, time, createdBy is common across all log types
732
-
733
- if (schemaItems.length) {
734
- const timeZoneCode = getTimeZoneCode(timeZone);
735
-
736
- schemaItems = schemaItems.concat([{
737
- __type: 'input_click',
738
- forceClickId: 'input_click_date',
739
- label: i18n.t('form.date'),
740
- item: {
741
- name: 'date',
742
- focused: focusedName === (formId + '_date'),
743
- getter: (value: string) => getCalDate(new Date(value), timeZone).calDate,
744
- },
745
- popOverProps: {
746
- id: formId + '_date',
747
- ...basePopOverProps,
748
- iface: {
749
- name: 'PO_LIST',
750
- variables: {
751
- designClassName: 'w_350',
752
- className: 'max_h_40vh',
753
- initialState: {
754
- date: formValues.date ? new Date(formValues.date) : new Date(),
755
- },
756
- options: [{
757
- __type: 'DATE_PICKER',
758
- name: 'date',
759
- minDate,
760
- maxDate,
761
- }]
762
- }
763
- }
764
- }
765
- }, {
766
- __type: 'input_time_from_date',
767
- label: i18n.t(timeZoneCode ? 'form.time_with_zone' : 'form.time', { timeZone: timeZoneCode }),
768
- scrollAreaDOMId,
769
- item: {
770
- name: 'date', // date value will be used to extract time
771
- type: 'time',
772
- timeZone,
773
- },
774
- }]);
775
- }
776
-
777
- if (schemaItems[0] && activitiesList.length) {
778
- // First item is always activity
779
- const activityValue = getObject(formValues, schemaItems[0].item.name);
780
- schemaItems[0].item.popOverProps = {
781
- id: formId + '_activity',
782
- ...basePopOverProps,
783
- iface: {
784
- name: 'PO_LIST',
785
- variables: {
786
- designClassName: 'w_250',
787
- className: 'max_h_40vh',
788
- options: activitiesList.reduce((acc, [type, activities], i) => {
789
- const colorIndicator = getLogCategoryColor(type);
790
- const isEnd = i === activitiesList.length - 1;
791
-
792
- const updatedList = acc.concat({
793
- __type: 'LIST_SUBTITLE' as const,
794
- colorIndicator,
795
- text: i18n.t(`log.type_short.${type}`),
796
- className: 'mt_sm',
797
- textClassName: `cl_${colorIndicator}`,
798
- }).concat(activities.map((activity: string) => ({
799
- __type: 'LIST_ITEM' as const,
800
- // colorIndicator,
801
- text: i18n.t(`log.activity.${activity}`),
802
- textClassName: 'ft_xs',
803
- rightIconClassName: 'ft_xs mb_2',
804
- name: schemaItems[0].item.name,
805
- value: activity,
806
- selected: activityValue === activity,
807
- })));
808
-
809
- if (!isEnd) {
810
- updatedList.push({
811
- __type: 'BREAK' as const,
812
- });
813
- }
814
-
815
- return updatedList;
816
- }, [])
817
- }
818
- }
819
- };
820
- }
821
-
822
- return schemaItems;
955
+ const { __typename, scrollAreaDOMId, formId, timeZone, focusedName } =
956
+ metadataParams;
957
+
958
+ const basePopOverProps = {
959
+ scrollAreaDOMId,
960
+ zClassName: 'z9',
961
+ position: 'bottom_left',
962
+ offsetX: 0,
963
+ offsetY: 7,
964
+ };
965
+
966
+ const minDate = new Date();
967
+ minDate.setFullYear(minDate.getFullYear() - 10);
968
+
969
+ const maxDate = new Date();
970
+ maxDate.setMonth(maxDate.getMonth() + 1);
971
+
972
+ if (__typename !== 'LogEntryDetails') {
973
+ return [];
974
+ }
975
+ const namespace = LOG_DETAILS_INPUT_NAME_BY_TYPENAME.LogEntryDetails;
976
+
977
+ const logActivity = formValues[namespace]?.activity;
978
+ let schemaItems = makeLogEntryDetailsMetadataSchema(
979
+ namespace,
980
+ formValues,
981
+ metadataParams,
982
+ basePopOverProps,
983
+ );
984
+
985
+ // Date, time, createdBy is common across all log types
986
+
987
+ if (schemaItems.length) {
988
+ const timeZoneCode = getTimeZoneCode(timeZone);
989
+
990
+ schemaItems = schemaItems.concat([
991
+ {
992
+ __type: 'input_click',
993
+ forceClickId: 'input_click_date',
994
+ label: formatLogTaxonomyFieldLabel(
995
+ i18n.t('form.date'),
996
+ getTaxonomyFieldRequirement(
997
+ metadataParams.taxonomy,
998
+ logActivity,
999
+ 'date',
1000
+ formValues[namespace]?.__groupKey,
1001
+ ),
1002
+ ),
1003
+ item: {
1004
+ name: 'date',
1005
+ focused: focusedName === formId + '_date',
1006
+ getter: (value: string) =>
1007
+ getCalDate(new Date(value), timeZone).calDate,
1008
+ },
1009
+ popOverProps: {
1010
+ id: formId + '_date',
1011
+ ...basePopOverProps,
1012
+ iface: {
1013
+ name: 'PO_LIST',
1014
+ variables: {
1015
+ designClassName: 'w_350',
1016
+ className: 'max_h_40vh',
1017
+ initialState: {
1018
+ date: formValues.date ? new Date(formValues.date) : new Date(),
1019
+ },
1020
+ options: [
1021
+ {
1022
+ __type: 'DATE_PICKER',
1023
+ name: 'date',
1024
+ minDate,
1025
+ maxDate,
1026
+ },
1027
+ ],
1028
+ },
1029
+ },
1030
+ },
1031
+ },
1032
+ {
1033
+ __type: 'input_time_from_date',
1034
+ label: formatLogTaxonomyFieldLabel(
1035
+ i18n.t(timeZoneCode ? 'form.time_with_zone' : 'form.time', {
1036
+ timeZone: timeZoneCode,
1037
+ }),
1038
+ getTaxonomyFieldRequirement(
1039
+ metadataParams.taxonomy,
1040
+ logActivity,
1041
+ 'time',
1042
+ formValues[namespace]?.__groupKey,
1043
+ ),
1044
+ ),
1045
+ scrollAreaDOMId,
1046
+ item: {
1047
+ name: 'date', // date value will be used to extract time
1048
+ type: 'time',
1049
+ timeZone,
1050
+ },
1051
+ },
1052
+ ]);
1053
+ }
1054
+
1055
+ return schemaItems;
823
1056
  }