@jsb188/mday 1.1.8 → 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 (123) hide show
  1. package/package.json +105 -35
  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 +48 -0
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +44 -0
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/inboundContact.ts +8 -0
  13. package/src/constants/integration.ts +13 -0
  14. package/src/constants/log.ts +7 -366
  15. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  16. package/src/constants/logTaxonomy.generated.ts +1103 -0
  17. package/src/constants/noteDoc.ts +77 -0
  18. package/src/constants/organization.ts +18 -11
  19. package/src/constants/pageRoute.ts +23 -0
  20. package/src/constants/schedule.ts +220 -0
  21. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  22. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  23. package/src/constants/sheet.ts +168 -0
  24. package/src/constants/sheetRegionSources.generated.ts +578 -0
  25. package/src/constants/square.ts +16 -0
  26. package/src/constants/storage.ts +61 -0
  27. package/src/constants/usage.ts +79 -0
  28. package/src/schemas/editLogEntry.ts +1017 -738
  29. package/src/schemas/fieldDocsQuery.ts +12 -0
  30. package/src/schemas/inboundContact.ts +77 -0
  31. package/src/schemas/logsQuery.ts +57 -316
  32. package/src/schemas/organization.ts +53 -213
  33. package/src/types/account.d.ts +81 -0
  34. package/src/types/agentDoc.d.ts +64 -0
  35. package/src/types/agentMemory.d.ts +74 -0
  36. package/src/types/campaign.d.ts +683 -0
  37. package/src/types/dataTable.d.ts +366 -0
  38. package/src/types/docAccess.d.ts +96 -0
  39. package/src/types/email.d.ts +142 -0
  40. package/src/types/fieldDoc.d.ts +273 -0
  41. package/src/types/inboundContact.d.ts +57 -0
  42. package/src/types/integration.d.ts +42 -0
  43. package/src/types/log.d.ts +169 -190
  44. package/src/types/noteDoc.d.ts +86 -0
  45. package/src/types/organization.d.ts +175 -76
  46. package/src/types/pageRoute.d.ts +48 -0
  47. package/src/types/schedule.d.ts +391 -0
  48. package/src/types/sheet.d.ts +1130 -0
  49. package/src/types/storage.d.ts +242 -0
  50. package/src/types/usage.d.ts +106 -0
  51. package/src/types/workflow.d.ts +305 -0
  52. package/src/utils/agentDoc.ts +109 -0
  53. package/src/utils/aiChat.ts +26 -0
  54. package/src/utils/campaign.ts +741 -0
  55. package/src/utils/campaignFormEditor.ts +871 -0
  56. package/src/utils/dataTable.ts +849 -0
  57. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  58. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  59. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  60. package/src/utils/dataTableRowDocument.ts +508 -0
  61. package/src/utils/dataTableSource.ts +230 -0
  62. package/src/utils/docAccess.ts +383 -0
  63. package/src/utils/documentName.ts +53 -0
  64. package/src/utils/email.ts +172 -0
  65. package/src/utils/fieldDoc.ts +113 -0
  66. package/src/utils/log.ts +173 -778
  67. package/src/utils/logRegistryValue.ts +90 -0
  68. package/src/utils/logStoreRead.ts +266 -0
  69. package/src/utils/logTaxonomy.ts +76 -0
  70. package/src/utils/logTaxonomyDisplay.ts +439 -0
  71. package/src/utils/noteDoc.ts +827 -0
  72. package/src/utils/organization.ts +683 -81
  73. package/src/utils/pageRoute.ts +71 -0
  74. package/src/utils/schedule.ts +799 -0
  75. package/src/utils/scheduleEvaluation.ts +1994 -0
  76. package/src/utils/scheduleICS.ts +246 -0
  77. package/src/utils/scheduleRuleTemplates.ts +188 -0
  78. package/src/utils/sheet.ts +4973 -0
  79. package/src/utils/sheetAxisMove.ts +830 -0
  80. package/src/utils/sheetBootstrap.ts +1769 -0
  81. package/src/utils/sheetCommand.ts +423 -0
  82. package/src/utils/sheetExport.ts +238 -0
  83. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  84. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  85. package/src/utils/sheetJournal.ts +78 -0
  86. package/src/utils/sheetNumberFormat.ts +1211 -0
  87. package/src/utils/sheetRegion.ts +374 -0
  88. package/src/utils/sheetRegionFilter.ts +1259 -0
  89. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  90. package/src/utils/sheetSequence.ts +148 -0
  91. package/src/utils/sheetSnapshot.ts +992 -0
  92. package/src/utils/sheetStructureEdit.ts +1284 -0
  93. package/src/utils/square.ts +32 -0
  94. package/src/utils/storage.ts +152 -0
  95. package/src/utils/table-route.ts +262 -0
  96. package/src/utils/workflow.ts +380 -0
  97. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  98. package/tests/docAccess.test.ts +525 -0
  99. package/tests/editLogEntry.test.ts +112 -0
  100. package/tests/noteDoc.test.ts +669 -0
  101. package/tests/schedule.test.ts +693 -0
  102. package/tests/scheduleEvaluation.test.ts +1970 -0
  103. package/tests/scheduleICS.test.ts +208 -0
  104. package/tests/scheduleRuleTemplates.test.ts +176 -0
  105. package/tests/scheduleSweepInvariants.test.ts +428 -0
  106. package/tests/sheetAxisMove.test.ts +343 -0
  107. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  108. package/tests/sheetRegionFilter.test.ts +1135 -0
  109. package/tests/sheetSequence.test.ts +41 -0
  110. package/tests/sheetStructureEdit.test.ts +82 -0
  111. package/tsconfig.json +12 -0
  112. package/vitest.config.ts +8 -0
  113. package/src/constants/log-activityTexts.ts +0 -209
  114. package/src/constants/product.ts +0 -66
  115. package/src/constants/report.ts +0 -25
  116. package/src/schemas/childOrganizationsQuery.ts +0 -44
  117. package/src/schemas/productsQuery.ts +0 -145
  118. package/src/schemas/reportsQuery.ts +0 -107
  119. package/src/types/action.d.ts +0 -42
  120. package/src/types/product.d.ts +0 -173
  121. package/src/types/report.d.ts +0 -203
  122. package/src/utils/product-calEvent.ts +0 -508
  123. package/src/utils/route-helpers.ts +0 -583
@@ -1,617 +1,933 @@
1
- import i18n from '@jsb188/app/i18n';
2
- import { getCalDate } from '@jsb188/app/utils/datetime';
3
- import { formatCurrency } from '@jsb188/app/utils/number';
4
- import { getObject } from '@jsb188/app/utils/object';
5
- import { textWithBrackets } from '@jsb188/app/utils/string';
6
- import { getTimeZoneCode } from '@jsb188/app/utils/timeZone';
7
- import { ARABLE_ACTIVITIES_GROUPED, FARMERS_MARKET_ACTIVITIES_GROUPED, LIVESTOCK_ACTIVITIES_GROUPED } from '../constants/log';
8
- import type { LogArableMetadataGQL, LogEntryGQL, LogFarmersMarketMetadataGQL, LogLivestockMetadataGQL, LogTypeEnum } from '../types/log.d';
9
- import { getLogCategoryColor, getLogTypeFromActivity } from '../utils/log';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { getCalDate } from '@jsb188/app/utils/datetime.ts';
3
+ import { formatCurrency } from '@jsb188/app/utils/number.ts';
4
+ import { textWithBrackets } from '@jsb188/app/utils/string.ts';
5
+ import { getTimeZoneCode } from '@jsb188/app/utils/timeZone.ts';
6
+ import type {
7
+ LogEntryDetailsFieldInput,
8
+ LogEntryDetailsGQL,
9
+ LogEntryGQL,
10
+ LogTaxonomyGQL,
11
+ } from '../types/log.d.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';
10
27
 
11
28
  /**
12
29
  * Get editable values based on activity & type (which is also used to display UI)
13
30
  */
14
31
 
15
- export const LOG_TYPENAME_TO_DETAILS_INPUT_NAME = {
16
- LogArable: 'arableDetails',
17
- LogFarmersMarket: 'farmersMarketDetails',
18
- LogLivestock: 'livestockDetails',
32
+ export const LOG_DETAILS_INPUT_NAME_BY_TYPENAME = {
33
+ LogEntryDetails: 'details',
19
34
  };
20
35
 
21
36
  /**
22
37
  * Convert GQL data to GQL mutation input format
23
38
  */
24
39
 
25
- export function makeFormValuesFromData(logEntry: LogEntryGQL) {
26
- const formValues = {
27
- logEntryId: logEntry.id,
28
- organizationId: logEntry.organizationId,
29
- accountId: logEntry.accountId,
30
- date: logEntry.date,
31
- } as Record<string, any>;
32
-
33
- switch (logEntry.details?.__typename) {
34
- case 'LogArable': {
35
- const details = logEntry.details as LogArableMetadataGQL;
36
- formValues.arableDetails = {
37
- activity: details.activity,
38
- quantity: details.quantity,
39
- item: details.item,
40
- unit: details.unit,
41
- concentration: details.concentration,
42
- concentrationUnit: details.concentrationUnit,
43
- location: details.location,
44
- fieldLocation: details.fieldLocation,
45
- referenceNumber: details.referenceNumber,
46
- otherParty: details.otherParty,
47
- values: details.values,
48
- notes: details.notes,
49
- };
50
- } break;
51
- case 'LogFarmersMarket': {
52
- const details = logEntry.details as LogFarmersMarketMetadataGQL;
53
- formValues.farmersMarketDetails = {
54
- activity: details.activity,
55
- referenceNumber: details.referenceNumber,
56
- voided: details.voided,
57
- values: details.values,
58
- notes: details.notes,
59
- };
60
- } break;
61
- case 'LogLivestock': {
62
- const details = logEntry.details as LogLivestockMetadataGQL;
63
- formValues.livestockDetails = {
64
- activity: details.activity,
65
- livestock: details.livestock,
66
- livestockIdentifiers: details.livestockIdentifiers,
67
- livestockGroup: details.livestockGroup,
68
- referenceNumber: details.referenceNumber,
69
- otherParty: details.otherParty,
70
- values: details.values,
71
- item: details.item,
72
- quantity: details.quantity,
73
- unit: details.unit,
74
- location: details.location,
75
- fieldLocation: details.fieldLocation,
76
- price: details.price,
77
- tax: details.tax,
78
- notes: details.notes,
79
- };
80
- } break;
81
- default:
82
- console.log(`${logEntry.details?.__typename} is not done yet.`);
83
- }
84
-
85
- // input LogArableInput {
86
- // activity: LogArableActivity
87
- // item: String
88
- // quantity: Float
89
- // unit: String
90
- // concentration: Float
91
- // concentrationUnit: String
92
- // price: Float
93
- // notes: String
94
- // }
95
-
96
- // input LogFarmersMarketInput {
97
- // activity: LogFarmersMarketActivity
98
- // childOrgId: GenericID
99
- // voided: Boolean
100
- // values: [LabelAndValueInput]
101
- // notes: String
102
- // }
103
-
104
- // input LogLivestockInput {
105
- // activity: LogLivestockType
106
- // livestock: String
107
- // livestockIdentifiers: [String]
108
- // item: String
109
- // quantity: Float
110
- // unit: String
111
- // price: Float
112
- // notes: String
113
- // }
114
-
115
-
116
- 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;
117
89
  }
118
90
 
119
- /**
120
- * 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.
121
116
  */
122
117
 
123
- export function formatFormValuesForMutation(formValues: Record<string, any>) {
124
- for (const key in formValues) {
125
- 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
+ }
126
122
 
127
- for (const subKey in formValues[key]) {
128
- if (['quantity','price','tax','concentration'].includes(subKey)) {
129
- formValues[key][subKey] = parseFloat(formValues[key][subKey]);
130
- }
131
- }
132
- }
133
- }
123
+ const numberValue = Number(value);
124
+ return Number.isFinite(numberValue) ? numberValue : null;
125
+ }
134
126
 
135
- 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);
136
135
  }
137
136
 
138
- /**
139
- * 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.
140
360
  */
141
361
 
142
- export type ValidMetadataFieldName =
143
- | 'activity'
144
-
145
- // ARABLE
146
- | 'water_testing'
147
- | 'concentration_unit'
148
- | 'water_quantity'
149
- | 'quantity'
150
- | 'water_unit'
151
- | 'unit'
152
- | 'price'
153
- | 'crop'
154
- | 'purchased_item'
155
- | 'fieldLocation'
156
- | 'location_water'
157
- | 'location_arable'
158
-
159
- // FARMERS_MARKET
160
- | 'receiptNumber'
161
- // | 'childOrgId' // Not editable
162
- | 'void'
163
- | 'marketCredits'
164
-
165
- // LIVESTOCK
166
- | 'livestock'
167
- | 'livestockIdentifiers'
168
- | 'livestockGroup'
169
- | 'otherParty'
170
- | 'invoiceNumber'
171
- | 'invoiceItems'
172
- | 'tax'
173
- | 'item_used'
174
- | 'location_livestock'
175
- | null; // Need this for eslint satisfcation, but null will never happen (because of a filter())
176
-
177
- function makeMetadataSchema(
178
- namespace: string,
179
- formValues: Record<string, any>,
180
- metadataParams: MakeMetadataSchemaParams,
181
- basePopOverProps: Record<string, any>,
182
- 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,
183
369
  ) {
184
- const { scrollAreaDOMId, formId, timeZone, focusedName, isCreateNew } = metadataParams;
185
- const schemaItems = schemaFields.map((field: ValidMetadataFieldName) => {
186
- switch (field) {
187
- case 'activity':
188
- return {
189
- __type: 'input_click',
190
- forceClickId: `input_click_${namespace}.activity`,
191
- label: i18n.t('form.activity'),
192
- item: {
193
- // editable: false,
194
- locked: () => true, // Conditional lock is possible
195
- focused: focusedName === (formId + '_activity'),
196
- name: `${namespace}.activity`,
197
- placeholder: isCreateNew ? i18n.t(`form.activity_ph`) : '',
198
- getter: (value: string) => value ? i18n.t(`log.activity.${value}`) : '',
199
- },
200
- };
201
- case 'water_testing':
202
- return {
203
- __type: 'input',
204
- label: i18n.t('form.concentration'),
205
- item: {
206
- name: `${namespace}.concentration`,
207
- type: 'number',
208
- step: 0.1,
209
- min: 0.1,
210
- max: 99999999.99, // database max is numeric(10, 2)
211
- placeholder: isCreateNew ? i18n.t('form.concentration_ph') : '',
212
- }
213
- };
214
- case 'concentration_unit':
215
- return {
216
- __type: 'input',
217
- label: i18n.t('form.concentration_unit'),
218
- item: {
219
- name: `${namespace}.concentrationUnit`,
220
- maxLength: 40,
221
- placeholder: isCreateNew ? i18n.t('form.concentration_unit_ph') : '',
222
- },
223
- };
224
- case 'water_quantity':
225
- return {
226
- __type: 'input',
227
- label: i18n.t('form.water_quantity'),
228
- item: {
229
- name: `${namespace}.quantity`,
230
- type: 'number',
231
- step: 0.1,
232
- min: 0.1,
233
- max: 99999999.99, // database max is numeric(10, 2)
234
- placeholder: isCreateNew ? i18n.t('form.quantity_ph') : '',
235
- }
236
- };
237
- case 'quantity':
238
- return {
239
- __type: 'input',
240
- label: i18n.t('form.quantity'),
241
- item: {
242
- name: `${namespace}.quantity`,
243
- type: 'number',
244
- step: 0.1,
245
- min: 0.1,
246
- max: 99999999.99, // database max is numeric(10, 2)
247
- placeholder: isCreateNew ? i18n.t('form.quantity_ph') : '',
248
- }
249
- };
250
- case 'water_unit':
251
- return {
252
- __type: 'input',
253
- label: i18n.t('form.water_unit'),
254
- item: {
255
- name: `${namespace}.unit`,
256
- maxLength: 40,
257
- placeholder: isCreateNew ? i18n.t('form.water_unit_ph') : '',
258
- }
259
- };
260
- case 'unit':
261
- return {
262
- __type: 'input',
263
- label: i18n.t('form.unit'),
264
- item: {
265
- name: `${namespace}.unit`,
266
- maxLength: 40,
267
- placeholder: isCreateNew ? i18n.t('log.unit_arable_ph') : '',
268
- }
269
- };
270
- case 'location_arable':
271
- return {
272
- __type: 'input',
273
- label: i18n.t('form.location'),
274
- item: {
275
- name: `${namespace}.location`,
276
- maxLength: 40,
277
- placeholder: isCreateNew ? i18n.t('log.location_arable_ph') : '',
278
- }
279
- };
280
- case 'location_water':
281
- return {
282
- __type: 'input',
283
- label: i18n.t('form.location'),
284
- item: {
285
- name: `${namespace}.location`,
286
- maxLength: 40,
287
- placeholder: isCreateNew ? i18n.t('log.location_water_ph') : '',
288
- }
289
- };
290
- case 'location_livestock':
291
- return {
292
- __type: 'input',
293
- label: i18n.t('form.location'),
294
- item: {
295
- name: `${namespace}.location`,
296
- maxLength: 100,
297
- placeholder: isCreateNew ? i18n.t('log.location_livestock_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: 100,
307
- placeholder: isCreateNew ? i18n.t('log.fieldLocation_ph') : '',
308
- }
309
- };
310
- case 'price':
311
- return {
312
- __type: 'input',
313
- label: i18n.t('form.price'),
314
- item: {
315
- name: `${namespace}.price`,
316
- type: 'number',
317
- step: 0.1,
318
- min: 0.1,
319
- max: 99999999.99, // database max is numeric(10, 2)
320
- placeholder: isCreateNew ? i18n.t('form.price_ph') : '',
321
- },
322
- };
323
- case 'tax':
324
- return {
325
- __type: 'input',
326
- label: i18n.t('form.tax'),
327
- item: {
328
- name: `${namespace}.tax`,
329
- type: 'number',
330
- step: 0.1,
331
- min: 0.1,
332
- max: 99999999.99, // database max is numeric(10, 2)
333
- placeholder: isCreateNew ? i18n.t('form.tax_ph') : '',
334
- },
335
- };
336
- case 'crop':
337
- return {
338
- __type: 'input',
339
- label: i18n.t('form.crop'),
340
- item: {
341
- name: `${namespace}.item`,
342
- placeholder: isCreateNew ? i18n.t('log.crop_ph') : '',
343
- }
344
- };
345
- case 'purchased_item':
346
- return {
347
- __type: 'input',
348
- label: i18n.t('form.purchase_summary'),
349
- item: {
350
- name: `${namespace}.item`,
351
- placeholder: isCreateNew ? i18n.t('log.crop_ph') : '',
352
- }
353
- };
354
- case 'livestock':
355
- return {
356
- __type: 'input',
357
- label: i18n.t('log.livestock'),
358
- item: {
359
- name: `${namespace}.livestock`,
360
- placeholder: isCreateNew ? i18n.t('log.livestock_ph') : '',
361
- }
362
- };
363
- case 'livestockIdentifiers':
364
- return {
365
- __type: 'input',
366
- label: i18n.t('log.id_tags'),
367
- item: {
368
- name: `${namespace}.livestockIdentifiers`,
369
- placeholder: isCreateNew ? i18n.t('log.id_tags_ph') : '',
370
- getter: (value: string[]) => value ? value.join(',') : '',
371
- setter: (value: string) => value.split(',')
372
- }
373
- };
374
- case 'livestockGroup':
375
- return {
376
- __type: 'input',
377
- label: i18n.t('log.group'),
378
- item: {
379
- name: `${namespace}.livestockGroup`,
380
- placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
381
- }
382
- };
383
- case 'otherParty':
384
- return {
385
- __type: 'input',
386
- label: i18n.t('form.vendor'),
387
- item: {
388
- name: `${namespace}.otherParty`,
389
- }
390
- };
391
- case 'invoiceNumber':
392
- return {
393
- __type: 'input',
394
- label: i18n.t('log.invoice_number'),
395
- item: {
396
- // editable: false,
397
- locked: true,
398
- name: `${namespace}.referenceNumber`,
399
- }
400
- };
401
- case 'receiptNumber':
402
- return {
403
- __type: 'input',
404
- label: i18n.t('log.receipt_number'),
405
- item: {
406
- // editable: false,
407
- locked: true,
408
- name: `${namespace}.referenceNumber`,
409
- // placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
410
- // getter: (value: string[]) => value ? value.join(',') : '',
411
- // setter: (value: string) => value.split(',')
412
- }
413
- };
414
-
415
- // Not allowed to edit
416
- // case 'childOrgId':
417
- // return {
418
- // __type: 'input',
419
- // label: i18n.t('log.receipt_for'),
420
- // item: {
421
- // name: `${namespace}.childOrgId`,
422
- // // placeholder: isCreateNew ? i18n.t('log.group_ph') : '',
423
- // // getter: (value: string[]) => value ? value.join(',') : '',
424
- // // setter: (value: string) => value.split(',')
425
- // }
426
- // };
427
- case 'void':
428
- return {
429
- __type: 'input_click',
430
- forceClickId: `input_click_${namespace}.voided`,
431
- label: i18n.t('form.void'),
432
- inputClassName: formValues[namespace]?.voided ? 'cl_red' : '',
433
- item: {
434
- // locked: () => true,
435
- focused: focusedName === (formId + '_void'),
436
- name: `${namespace}.voided`,
437
- placeholder: isCreateNew ? i18n.t(`form.void_ph`) : '',
438
- getter: (value: string) => i18n.t(value ? 'log.receipt_is_void' : 'log.receipt_is_not_void'),
439
- },
440
- popOverProps: {
441
- id: formId + '_void',
442
- ...basePopOverProps,
443
- iface: {
444
- name: 'PO_LIST',
445
- variables: {
446
- designClassName: 'w_250',
447
- className: 'max_h_40vh',
448
- options: [{
449
- __type: 'LIST_ITEM' as const,
450
- text: i18n.t('log.receipt_is_not_void'),
451
- iconName: 'receipt-dollar',
452
- selected: !formValues[namespace]?.voided,
453
- name: `${namespace}.voided`,
454
- value: false,
455
- }, {
456
- __type: 'LIST_ITEM' as const,
457
- text: i18n.t('log.receipt_is_void'),
458
- iconName: 'receipt-off',
459
- selected: formValues[namespace]?.voided === true,
460
- name: `${namespace}.voided`,
461
- value: true,
462
- }]
463
- }
464
- }
465
- }
466
- };
467
- case 'invoiceItems':
468
- return {
469
- __type: 'input_click',
470
- label: i18n.t('log.invoice_items'),
471
- forceClickId: `input_click_${namespace}.values`,
472
- item: {
473
- // locked: () => true,
474
- focused: focusedName === (formId + '_values'),
475
- name: `${namespace}.values`,
476
- placeholder: isCreateNew ? i18n.t(`log.invoice_items_ph`) : '',
477
- getter: (labelsAndValues: string[]) => {
478
- return labelsAndValues?.map((lv: any) => {
479
- return textWithBrackets(
480
- `${lv.quantity ? `${lv.quantity} ` : ''}${lv.label}`,
481
- formatCurrency(lv.value, false),
482
- );
483
- }).join(', ');
484
- },
485
- },
486
- popOverProps: {
487
- id: formId + '_invoiceItems',
488
- ...basePopOverProps,
489
- iface: {
490
- name: 'PO_LABELS_AND_VALUES',
491
- variables: {
492
- gridLayoutStyle: '70px 1fr 85px',
493
- designClassName: 'w_400',
494
- className: 'max_h_40vh',
495
- // flipInputOrder: true,
496
- forceNumericValues: true,
497
- includeQuantity: true,
498
- name: `${namespace}.values`,
499
- labels: [i18n.t('form.quantity'), i18n.t('log.invoice_item'), `$ ${i18n.t('form.amount')}`],
500
- inputs: formValues[namespace]?.values || [],
501
- }
502
- }
503
- }
504
- };
505
- case 'marketCredits':
506
- return {
507
- __type: 'input_click',
508
- label: i18n.t('log.marketCredits'),
509
- forceClickId: `input_click_${namespace}.values`,
510
- item: {
511
- // locked: () => true,
512
- focused: focusedName === (formId + '_values'),
513
- name: `${namespace}.values`,
514
- placeholder: isCreateNew ? i18n.t(`log.marketCredits_ph`) : '',
515
- getter: (labelsAndValues: string[]) => {
516
- return labelsAndValues?.map((lv: any) => {
517
- return `${formatCurrency(lv.value, false)} ${lv.label}`;
518
- }).join(', ');
519
- },
520
- },
521
- popOverProps: {
522
- id: formId + '_marketCredits',
523
- ...basePopOverProps,
524
- iface: {
525
- name: 'PO_LABELS_AND_VALUES',
526
- variables: {
527
- gridLayoutStyle: '85px 1fr',
528
- designClassName: 'w_250',
529
- className: 'max_h_40vh',
530
- flipInputOrder: true,
531
- forceNumericValues: true,
532
- name: `${namespace}.values`,
533
- labels: [`$ ${i18n.t('form.amount')}`, i18n.t('log.name_of_credit')],
534
- inputs: formValues[namespace]?.values || [],
535
- }
536
- }
537
- }
538
- };
539
- default:
540
- console.warn(`Field ${field} is not defined in metadata schema.`);
541
- return null;
542
- }
543
- }).filter(Boolean);
544
-
545
- 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
+ };
546
416
  }
547
417
 
548
418
  /**
549
- * 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.
550
423
  */
551
424
 
552
- export function getSchemaFieldsFromLog(__typename: string, logType: LogTypeEnum): ValidMetadataFieldName[] {
553
-
554
- let schemaFields: ValidMetadataFieldName[];
555
- switch (__typename) {
556
- case 'LogArable': {
557
- const isWaterTesting = logType === 'WATER';
558
- const isSale = ['SALES'].includes(logType!);
559
- const isPurchase = ['SEED'].includes(logType!);
560
- const isSaleOrPurchase = isSale || isPurchase;
561
-
562
- schemaFields = [
563
- 'activity',
564
- isWaterTesting ? 'water_testing' : null,
565
- isWaterTesting ? 'concentration_unit' : null,
566
- isWaterTesting ? 'water_quantity' : isSaleOrPurchase ? null : 'quantity',
567
- isWaterTesting ? 'water_unit' : isSaleOrPurchase ? null : 'unit',
568
- isWaterTesting ? null : isSaleOrPurchase ? 'purchased_item' : 'crop',
569
- isSaleOrPurchase ? 'otherParty' : null,
570
- isSaleOrPurchase ? 'invoiceNumber' : null,
571
- isSaleOrPurchase ? 'invoiceItems' : null,
572
- isSaleOrPurchase ? 'tax' : null,
573
- isSaleOrPurchase ? null : isWaterTesting ? 'location_water' : 'location_arable',
574
- isSaleOrPurchase ? null : 'fieldLocation',
575
- ];
576
- } break;
577
- case 'LogFarmersMarket': {
578
- const isReceipt = ['MARKET_RECEIPTS'].includes(logType);
579
-
580
- schemaFields = [
581
- 'activity',
582
- isReceipt ? 'receiptNumber' : null,
583
- // 'childOrgId', // not editable
584
- isReceipt ? 'void' : null,
585
- isReceipt ? 'marketCredits' : null,
586
- ];
587
- } break;
588
- case 'LogLivestock': {
589
- const isLivestock = ['LIVESTOCK_LIFE_CYCLE', 'LIVESTOCK_TRACKING', 'LIVESTOCK_HEALTHCARE'].includes(logType);
590
- const isSupplyPurchase = logType === 'SUPPLY_PURCHASE';
591
- const isLandManagement = logType === 'PASTURE_LAND_MANAGEMENT';
592
-
593
- schemaFields = [
594
- 'activity',
595
- isLivestock ? 'livestock' : null,
596
- isLivestock ? 'livestockIdentifiers' : null,
597
- isLivestock ? 'livestockGroup' : null,
598
- isSupplyPurchase ? 'otherParty' : null,
599
- isSupplyPurchase ? 'invoiceNumber' : null,
600
- isSupplyPurchase ? 'invoiceItems' : null,
601
- isSupplyPurchase ? 'tax' : null,
602
- isLandManagement ? 'item_used' : null,
603
- isLivestock || isSupplyPurchase ? null : 'quantity',
604
- isLivestock || isSupplyPurchase ? null : 'unit',
605
- !isSupplyPurchase ? 'location_livestock' : null,
606
- isLivestock ? 'price' : null,
607
- isLivestock ? null : 'fieldLocation',
608
- ];
609
- } break;
610
- default:
611
- schemaFields = [];
612
- }
613
-
614
- 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;
615
931
  }
616
932
 
617
933
  /**
@@ -619,159 +935,122 @@ export function getSchemaFieldsFromLog(__typename: string, logType: LogTypeEnum)
619
935
  */
620
936
 
621
937
  interface MakeMetadataSchemaParams {
622
- __typename: string;
623
- scrollAreaDOMId: string;
624
- formId: string;
625
- timeZone: string | null | undefined;
626
- focusedName: string;
627
- 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;
628
945
  }
629
946
 
947
+ /*
948
+ * Build the registry-driven generic log metadata editor schema.
949
+ */
950
+
630
951
  export function makeLogMetadataSchema(
631
- formValues: Record<string, any> = {},
632
- metadataParams: MakeMetadataSchemaParams,
952
+ formValues: Record<string, any> = {},
953
+ metadataParams: MakeMetadataSchemaParams,
633
954
  ) {
634
- const { __typename, scrollAreaDOMId, formId, timeZone, focusedName, isCreateNew } = metadataParams;
635
-
636
- let activitiesList: any[] = [];
637
- let schemaItems: any[] = [];
638
-
639
- const basePopOverProps = {
640
- scrollAreaDOMId,
641
- zClassName: 'z9',
642
- position: 'bottom_left',
643
- offsetX: 0,
644
- offsetY: 7,
645
- };
646
-
647
- const minDate = new Date();
648
- minDate.setFullYear(minDate.getFullYear() - 10);
649
-
650
- const maxDate = new Date();
651
- maxDate.setMonth(maxDate.getMonth() + 1);
652
-
653
- const namespace = {
654
- LogArable: 'arableDetails',
655
- LogFarmersMarket: 'farmersMarketDetails',
656
- LogLivestock: 'livestockDetails',
657
- }[__typename] || '';
658
-
659
- const logActivity = formValues[namespace]?.activity;
660
- const logType = getLogTypeFromActivity(__typename, logActivity)!;
661
- const schemaFields = getSchemaFieldsFromLog(__typename, logType);
662
- const isAITask = logType === 'AI_TASK';
663
-
664
- switch (__typename) {
665
- case 'LogArable': {
666
- activitiesList = ARABLE_ACTIVITIES_GROUPED;
667
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
668
- } break;
669
- case 'LogFarmersMarket': {
670
- activitiesList = FARMERS_MARKET_ACTIVITIES_GROUPED;
671
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
672
- } break;
673
- case 'LogLivestock': {
674
- activitiesList = LIVESTOCK_ACTIVITIES_GROUPED;
675
- schemaItems = makeMetadataSchema(namespace, formValues, metadataParams, basePopOverProps, schemaFields);
676
- } break;
677
- default:
678
- }
679
-
680
- if (!isAITask) {
681
- activitiesList = activitiesList.filter(([type]) => type !== 'AI_TASK');
682
- }
683
-
684
- // Date, time, createdBy is common across all log types
685
-
686
- if (schemaItems.length) {
687
- const timeZoneCode = getTimeZoneCode(timeZone);
688
-
689
- schemaItems = schemaItems.concat([{
690
- __type: 'input_click',
691
- forceClickId: 'input_click_date',
692
- label: i18n.t('form.date'),
693
- item: {
694
- name: 'date',
695
- focused: focusedName === (formId + '_date'),
696
- getter: (value: string) => getCalDate(new Date(value), timeZone).calDate,
697
- },
698
- popOverProps: {
699
- id: formId + '_date',
700
- ...basePopOverProps,
701
- iface: {
702
- name: 'PO_LIST',
703
- variables: {
704
- designClassName: 'w_350',
705
- className: 'max_h_40vh',
706
- initialState: {
707
- date: formValues.date ? new Date(formValues.date) : new Date(),
708
- },
709
- options: [{
710
- __type: 'DATE_PICKER',
711
- name: 'date',
712
- minDate,
713
- maxDate,
714
- }]
715
- }
716
- }
717
- }
718
- }, {
719
- __type: 'input_time_from_date',
720
- label: i18n.t(timeZoneCode ? 'form.time_with_zone' : 'form.time', { timeZone: timeZoneCode }),
721
- scrollAreaDOMId,
722
- item: {
723
- name: 'date', // date value will be used to extract time
724
- type: 'time',
725
- timeZone,
726
- },
727
- }]);
728
- }
729
-
730
- if (schemaItems[0] && activitiesList.length) {
731
- // First item is always activity
732
- const activityValue = getObject(formValues, schemaItems[0].item.name);
733
- schemaItems[0].item.popOverProps = {
734
- id: formId + '_activity',
735
- ...basePopOverProps,
736
- disabled: isAITask, // AI tasks' activity cannot be changed
737
- iface: {
738
- name: 'PO_LIST',
739
- variables: {
740
- designClassName: 'w_250',
741
- className: 'max_h_40vh',
742
- options: activitiesList.reduce((acc, [type, activities], i) => {
743
- const colorIndicator = getLogCategoryColor(type);
744
- const isEnd = i === activitiesList.length - 1;
745
-
746
- const updatedList = acc.concat({
747
- __type: 'LIST_SUBTITLE' as const,
748
- colorIndicator,
749
- text: i18n.t(`log.type_short.${type}`),
750
- className: 'mt_sm',
751
- textClassName: `cl_${colorIndicator}`,
752
- }).concat(activities.map((activity: string) => ({
753
- __type: 'LIST_ITEM' as const,
754
- // colorIndicator,
755
- text: i18n.t(`log.activity.${activity}`),
756
- textClassName: 'ft_xs',
757
- rightIconClassName: 'ft_xs mb_2',
758
- name: schemaItems[0].item.name,
759
- value: activity,
760
- selected: activityValue === activity,
761
- })));
762
-
763
- if (!isEnd) {
764
- updatedList.push({
765
- __type: 'BREAK' as const,
766
- });
767
- }
768
-
769
- return updatedList;
770
- }, [])
771
- }
772
- }
773
- };
774
- }
775
-
776
- 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;
777
1056
  }