@jsb188/mday 1.1.4 → 1.1.5

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.
package/package.json CHANGED
@@ -1,19 +1,23 @@
1
1
  {
2
2
  "name": "@jsb188/mday",
3
- "version": "1.1.4",
3
+ "version": "1.1.5",
4
4
  "description": "Mday specific functions and constants.",
5
5
  "license": "ISC",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "exports": {
9
9
  "./constants/log": "./src/constants/log.ts",
10
- "./schemas/queryString": "./src/schemas/queryString.ts",
10
+ "./schemas/editLogEntry": "./src/schemas/editLogEntry.ts",
11
+ "./schemas/logsQueryParam": "./src/schemas/logsQueryParam.ts",
11
12
  "./types/log.d": "./src/types/log.d.ts",
12
13
  "./utils/log": "./src/utils/log.ts"
13
14
  },
14
15
  "dependencies": {
15
16
  "zod": "^3.25.67"
16
17
  },
18
+ "peerDependencies": {
19
+ "@jsb188/app": "1.1.5"
20
+ },
17
21
  "scripts": {
18
22
  "test": "echo \"Error: no test specified\" && exit 1"
19
23
  }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * *Not* operation-specific activities that could be used for many farming operations
3
+ */
4
+
5
+ export const WATER_TESTING_ACTIVITY_TO_TEXT = {
6
+ WATER_TESTING: 'checking chlorine levels in water',
7
+ OTHER_WATER_TESTING_ACTIVITY: 'other water testing related activities',
8
+ };
9
+
10
+ /**
11
+ * Arable farming activities
12
+ */
13
+
14
+ export const ARABLE_FARMING_ACTIVITY_TO_TEXT = {
15
+ // # Seed purchase activities
16
+ SEED_PURCHASE_INFO: 'seed purchase information',
17
+ SEED_COMPLIANCE_NOTE: 'seed compliance notes',
18
+ OTHER_SEED_ACTIVITY: 'other seed purchase related activities',
19
+
20
+ // # Seeding & transplanting activities
21
+ SEEDING: 'seeding crops',
22
+ DIRECT_SEEDING: 'direct seeding crops',
23
+ TRANSPLANTING: 'transplanting crops',
24
+ OTHER_TRANSPLANT_ACTIVITY: 'other seeding or transplanting activities',
25
+
26
+ // # Field activities
27
+ PREPARE_SOIL: 'soil, beds preparation',
28
+ IRRIGATION: 'irrigation management',
29
+ FERTILIZATION_COMPOST: 'fertilization, compost application',
30
+ PROTECT_CROP: 'hand pulling weed, hoeing, and cultivation work',
31
+ MONITOR_CROP: 'crop monitoring',
32
+ PRUNING: 'pruning',
33
+ STRUCTURE_MAINTENANCE: 'trellising, structure maintenance',
34
+ PREPARE_HARVEST: 'preparing crops for harvest',
35
+ OTHER_FIELD_ACTIVITY: 'other field activities',
36
+
37
+ // # Harvest activities
38
+ HARVEST_CROP: 'harvesting crops',
39
+ HARVEST_COUNT: 'counting, weighing harvested crops',
40
+ SORT_GRADE: 'sorting, grading crops',
41
+ YIELD_LOSS_ESTIMATE: 'estimating yield or loss',
42
+ OTHER_HARVEST_ACTIVITY: 'other harvest activities',
43
+
44
+ // # Post-harvest activities
45
+ POST_HARVEST_HANDLING: 'washing, drying, trimming, sorting, or grading produce',
46
+ POST_HARVEST_PACKAGING: 'packaging, cooling, or moving produce to storage',
47
+ OTHER_POST_HARVEST_ACTIVITY: 'other post-harvest activities',
48
+
49
+ // # Sales activities
50
+ SALE_TRANSACTION: 'sale transactions',
51
+ SALE_DETAILS: 'sale details',
52
+ SALE_FEEDBACK: 'sale feedback or issues',
53
+ OTHER_SALES_ACTIVITY: 'other sales related activities',
54
+ };
55
+
56
+ export const ARABLE_ACTIVITIES_TO_TEXT = {
57
+ // * Arable-specific activities (these have their own functions)
58
+ COLD_STORAGE_TEMPERATURE: 'checking or changing temperature (cold storage)',
59
+
60
+ // # Farming activities
61
+ ...ARABLE_FARMING_ACTIVITY_TO_TEXT,
62
+
63
+ // # Water testing activities
64
+ ...WATER_TESTING_ACTIVITY_TO_TEXT,
65
+ };
66
+
67
+ export const TEXT_TO_ARABLE_ACTIVITIES = Object.fromEntries(
68
+ Object.entries(ARABLE_ACTIVITIES_TO_TEXT).map(([key, value]) => [value, key]),
69
+ ) as Record<string, string>;
@@ -1,192 +1,143 @@
1
1
  import type { LogArableTypeEnum } from '../types/log.d.ts';
2
+ import type { OrganizationOperationEnum } from '@jsb188/app/types/organization.d';
3
+
4
+ /**
5
+ * IMPORTANT: Keep this list updated.
6
+ *
7
+ * These are the function call names where the AI can see the args for after calling the function.
8
+ * When you include the args for functions such as write_log(), it's unnecessary data that only confuses the AI,
9
+ * and makes the AI less accurate.
10
+ */
11
+
12
+ // Not using this any more (?)
13
+ // export const SHOW_ARGS_FUNCTION_CALL_NAMES = [
14
+ // 'search_logs_arable_farming',
15
+ // 'search_logs_livestock_farming',
16
+ // 'get_arable_farming_logs_file',
17
+ // 'get_livestock_farming_logs_file',
18
+ // 'find_persons',
19
+ // ];
2
20
 
3
21
  // Arable farming logs
22
+ // NOTE: This constant defines all the enums and activities for both GraphQL and database
4
23
 
5
24
  export const ARABLE_ACTIVITIES_GROUPED = [
6
- [
7
- 'SEED',
8
- [
9
- 'SEED_PURCHASE_INFO',
10
- 'SEED_COMPLIANCE_NOTE',
11
- 'OTHER_SEED_ACTIVITY',
12
- ]
13
- ],
14
- [
15
- 'FIELD',
16
- [
17
- 'PREPARE_SOIL',
18
- 'PLANTING',
19
- 'IRRIGATION',
20
- 'FERTILIZATION_COMPOST',
21
- 'PROTECT_CROP',
22
- 'MONITOR_CROP',
23
- 'PRUNING',
24
- 'STRUCTURE_MAINTENANCE',
25
- 'PREPARE_HARVEST',
26
- 'OTHER_FIELD_ACTIVITY',
27
- ]
28
- ],
29
- [
30
- 'HARVEST',
31
- [
32
- 'HARVEST_CROP',
33
- 'HARVEST_COUNT',
34
- 'SORT_GRADE',
35
- 'YIELD_LOSS_ESTIMATE',
36
- 'OTHER_HARVEST_ACTIVITY',
37
- ]
38
- ],
39
- [
40
- 'POST_HARVEST',
41
- [
42
- 'POST_HARVEST_HANDLING',
43
- 'POST_HARVEST_PACKAGING',
44
- 'OTHER_POST_HARVEST_ACTIVITY',
45
- ]
46
- ],
47
- [
48
- 'SALES',
49
- [
50
- 'SALE_TRANSACTION',
51
- 'SALE_DETAILS',
52
- 'SALE_FEEDBACK',
53
- 'OTHER_SALES_ACTIVITY',
54
- ]
55
- ]
25
+ [
26
+ 'SEED',
27
+ [
28
+ 'SEED_PURCHASE_INFO',
29
+ 'SEED_COMPLIANCE_NOTE',
30
+ 'OTHER_SEED_ACTIVITY',
31
+ ],
32
+ ],
33
+ [
34
+ 'PLANTING',
35
+ [
36
+ 'SEEDING',
37
+ 'DIRECT_SEEDING',
38
+ 'TRANSPLANTING',
39
+ 'OTHER_TRANSPLANT_ACTIVITY',
40
+ ],
41
+ ],
42
+ [
43
+ 'FIELD',
44
+ [
45
+ 'PREPARE_SOIL',
46
+ // 'PLANTING', // <!--------------------------------- Deprecated & moved to "PLANTING" category
47
+ 'IRRIGATION',
48
+ 'FERTILIZATION_COMPOST',
49
+ 'PROTECT_CROP',
50
+ 'MONITOR_CROP',
51
+ 'PRUNING',
52
+ 'STRUCTURE_MAINTENANCE',
53
+ 'PREPARE_HARVEST',
54
+ 'OTHER_FIELD_ACTIVITY',
55
+ ],
56
+ ],
57
+ [
58
+ 'HARVEST',
59
+ [
60
+ 'HARVEST_CROP',
61
+ 'HARVEST_COUNT',
62
+ 'SORT_GRADE',
63
+ 'YIELD_LOSS_ESTIMATE',
64
+ 'OTHER_HARVEST_ACTIVITY',
65
+ ],
66
+ ],
67
+ [
68
+ 'POST_HARVEST',
69
+ [
70
+ 'POST_HARVEST_HANDLING',
71
+ 'POST_HARVEST_PACKAGING',
72
+ 'COLD_STORAGE_TEMPERATURE',
73
+ 'OTHER_POST_HARVEST_ACTIVITY',
74
+ ],
75
+ ],
76
+ [
77
+ 'SALES',
78
+ [
79
+ 'SALE_TRANSACTION',
80
+ 'SALE_DETAILS',
81
+ 'SALE_FEEDBACK',
82
+ 'OTHER_SALES_ACTIVITY',
83
+ ],
84
+ ],
85
+ [
86
+ 'WATER',
87
+ [
88
+ 'WATER_TESTING',
89
+ 'OTHER_WATER_TESTING_ACTIVITY',
90
+ ],
91
+ ],
56
92
  ] as [LogArableTypeEnum, string[]][];
57
93
 
58
- export const LOG_ARABLE_ACTIVITY_ENUMS = ARABLE_ACTIVITIES_GROUPED.reduce(
59
- (acc, a) => acc.concat(a[1]),
60
- [] as string[]
61
- );
62
-
63
- // All log types for all activities
64
-
65
- export const LOG_TYPE_ENUMS = [
66
- ...ARABLE_ACTIVITIES_GROUPED.map(a => a[0]),
67
- ];
68
-
69
- export const LOG_ACTIVITY_ENUMS = [
70
- ...LOG_ARABLE_ACTIVITY_ENUMS
71
- ];
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
- export const JOURNAL_TYPES_TO_TEXT = {
94
+ export const ARABLE_TYPES_TO_TEXT = {
88
95
  SEED: 'seed purchases',
96
+ PLANTING: 'seeding, transplanting activities',
89
97
  FIELD: 'field activities',
90
98
  HARVEST: 'harvest activities',
91
- POST_HARVEST: 'handling, washing, sorting, grading, packaging after harvest',
92
- SALES: 'sales',
93
- };
94
-
95
- export const TEXT_TO_JOURNAL_TYPES = Object.fromEntries(
96
- Object.entries(JOURNAL_TYPES_TO_TEXT).map(([key, value]) => [value, key]),
97
- ) as Record<string, string>;
99
+ POST_HARVEST: 'after-harvest activities such as handling, packaging produce and cold storage',
100
+ SALES: 'sales related activities',
101
+ WATER: 'water testing activities',
98
102
 
99
- /**
100
- * Activities for each journal types
101
- */
103
+ // This is not part of the enums
104
+ EVERYTHING: 'all activities',
105
+ } as Record<LogArableTypeEnum, string>;
102
106
 
103
- export const SEED_LOG_ACTIVITY_ENUMS = [
104
- 'SEED_PURCHASE_INFO',
105
- 'SEED_COMPLIANCE_NOTE',
106
- 'OTHER_SEED_ACTIVITY',
107
- ] as const;
107
+ export const TEXT_TO_ARABLE_TYPES = Object.fromEntries(
108
+ Object.entries(ARABLE_TYPES_TO_TEXT).map(([key, value]) => [value, key]),
109
+ ) as Record<string, string>;
108
110
 
109
- export const FIELD_LOG_ACTIVITY_ENUMS = [
110
- 'PREPARE_SOIL',
111
+ export const LOG_ARABLE_TYPE_ENUMS = [
112
+ 'SEED',
111
113
  'PLANTING',
112
- 'IRRIGATION',
113
- 'FERTILIZATION_COMPOST',
114
- 'PROTECT_CROP',
115
- 'MONITOR_CROP',
116
- 'PRUNING',
117
- 'STRUCTURE_MAINTENANCE',
118
- 'PREPARE_HARVEST',
119
- 'OTHER_FIELD_ACTIVITY',
120
- ] as const;
121
-
122
- export const HARVEST_LOG_ACTIVITY_ENUMS = [
123
- 'HARVEST_CROP',
124
- 'HARVEST_COUNT',
125
- 'SORT_GRADE',
126
- 'YIELD_LOSS_ESTIMATE',
127
- 'OTHER_HARVEST_ACTIVITY',
128
- ] as const;
129
-
130
- export const POST_HARVEST_LOG_ACTIVITY_ENUMS = [
131
- 'POST_HARVEST_HANDLING',
132
- 'POST_HARVEST_PACKAGING',
133
- 'OTHER_POST_HARVEST_ACTIVITY',
134
- ] as const;
135
-
136
- export const SALES_LOG_ACTIVITY_ENUMS = [
137
- 'SALE_TRANSACTION',
138
- 'SALE_DETAILS',
139
- 'SALE_FEEDBACK',
140
- 'OTHER_SALES_ACTIVITY',
141
- ] as const;
114
+ 'FIELD',
115
+ 'HARVEST',
116
+ 'POST_HARVEST',
117
+ 'SALES',
118
+ 'WATER',
119
+ ] as LogArableTypeEnum[];
142
120
 
143
- /**
144
- * Activity enums to text
145
- */
146
-
147
- export const JOURNAL_ACTIVITIES_TO_TEXT = {
148
- // # Seed log activities
149
- SEED_PURCHASE_INFO: 'seed purchase information',
150
- SEED_COMPLIANCE_NOTE: 'seed compliance notes',
151
- OTHER_SEED_ACTIVITY: 'other seed purchase related notes',
152
-
153
- // # Field log activities
154
- PREPARE_SOIL: 'soil, beds preparation',
155
- PLANTING: 'seeding, transplanting',
156
- IRRIGATION: 'irrigation management',
157
- FERTILIZATION_COMPOST: 'fertilization, compost application',
158
- PROTECT_CROP: 'weed, pest, disease management',
159
- MONITOR_CROP: 'crop monitoring',
160
- PRUNING: 'pruning',
161
- STRUCTURE_MAINTENANCE: 'trellising, structure maintenance',
162
- PREPARE_HARVEST: 'preparing crops for harvest',
163
- OTHER_FIELD_ACTIVITY: 'other field activities',
121
+ export const LOG_ARABLE_ACTIVITY_ENUMS = ARABLE_ACTIVITIES_GROUPED.reduce(
122
+ (acc, a) => acc.concat(a[1]),
123
+ [] as string[],
124
+ );
164
125
 
165
- // # Harvest log activities
166
- HARVEST_CROP: 'harvesting crops',
167
- HARVEST_COUNT: 'counting, weighing harvested crops',
168
- SORT_GRADE: 'sorting, grading crops',
169
- YIELD_LOSS_ESTIMATE: 'estimating yield or loss',
170
- OTHER_HARVEST_ACTIVITY: 'other harvest activities',
126
+ // All log types & activities
171
127
 
172
- // # Post-harvest log activities
173
- POST_HARVEST_HANDLING: 'washing, drying, trimming, sorting, or grading produce',
174
- POST_HARVEST_PACKAGING: 'packaging, cooling, or moving produce to storage',
175
- OTHER_POST_HARVEST_ACTIVITY: 'other post-harvest activities',
128
+ export const LOG_ACTIVITIES_GROUPED = [
129
+ ...ARABLE_ACTIVITIES_GROUPED,
130
+ ];
176
131
 
177
- // # Sales log activities
178
- SALE_TRANSACTION: 'sale transactions',
179
- SALE_DETAILS: 'sale details',
180
- SALE_FEEDBACK: 'sale feedback or issues',
181
- OTHER_SALES_ACTIVITY: 'other sales related notes',
182
- };
132
+ export const LOG_TYPE_ENUMS = [
133
+ ...LOG_ARABLE_TYPE_ENUMS,
134
+ ];
183
135
 
184
- export const TEXT_TO_JOURNAL_ACTIVITIES = Object.fromEntries(
185
- Object.entries(JOURNAL_ACTIVITIES_TO_TEXT).map(([key, value]) => [value, key]),
186
- ) as Record<string, string>;
136
+ export const LOG_ACTIVITY_ENUMS = [
137
+ ...LOG_ARABLE_ACTIVITY_ENUMS,
138
+ ];
187
139
 
188
- // Moved to walk-in
189
- // Hydrocooled immediately after harvest
190
- // Bagged and labeled greens
191
- // Packed in clamshells
192
- // Stickered with farm logo
140
+ export const LOG_TYPES_BY_OPERATION = {
141
+ ARABLE: LOG_ARABLE_TYPE_ENUMS,
142
+ LIVESTOCK: [],
143
+ } as Record<OrganizationOperationEnum, (typeof LOG_TYPE_ENUMS)[number][]>;
@@ -0,0 +1,277 @@
1
+ import i18n from '@jsb188/app/i18n';
2
+ import { getCalDate } from '@jsb188/app/utils/datetime';
3
+ import { getObject } from '@jsb188/app/utils/object';
4
+ import { getTimeZoneCode } from '@jsb188/app/utils/timeZone';
5
+ import { ARABLE_ACTIVITIES_GROUPED } from '../constants/log';
6
+ import type { LogEntryGQLData } from '../types/log.d';
7
+ import { getLogCategoryColor, getLogTypeFromActivity } from '../utils/log';
8
+
9
+ /**
10
+ * Convert GQL data to GQL mutation input format
11
+ */
12
+
13
+ export function makeFormValuesFromData(logEntry: LogEntryGQLData) {
14
+ const formValues = {
15
+ logEntryId: logEntry.id,
16
+ accountId: logEntry.accountId,
17
+ date: logEntry.date,
18
+ } as Record<string, any>;
19
+
20
+ const { details } = logEntry;
21
+ switch (details?.__typename) {
22
+ case 'LogEntryArable':
23
+ formValues.arableDetails = {
24
+ activity: details.activity,
25
+ quantity: details.quantity,
26
+ crop: details.crop,
27
+ unit: details.unit,
28
+ concentration: details.concentration,
29
+ concentrationUnit: details.concentrationUnit,
30
+ price: details.price,
31
+ notes: details.notes,
32
+ };
33
+ break;
34
+ case 'LogEntryLivestock':
35
+ break;
36
+ default:
37
+ console.log(`${details?.__typename} is not done yet.`);
38
+ }
39
+
40
+ return formValues;
41
+ }
42
+
43
+ /**
44
+ * Convert HTML input values to GQL mutation input types
45
+ */
46
+
47
+ export function formatFormValuesForMutation(formValues: Record<string, any>) {
48
+ for (const key in formValues) {
49
+ if (formValues[key] && typeof formValues[key] === 'object') {
50
+
51
+ for (const subKey in formValues[key]) {
52
+ if (['quantity','price','concentration'].includes(subKey)) {
53
+ formValues[key][subKey] = parseFloat(formValues[key][subKey]);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ return formValues;
59
+ }
60
+
61
+ /**
62
+ * Get editable values based on activity & type (which is also used to display UI)
63
+ */
64
+
65
+ export function getLogDetailsInputName(__typename: string) {
66
+ switch (__typename) {
67
+ case 'LogEntryArable':
68
+ // Some of the types omit some fields, but for now, we're including all
69
+ return 'arableDetails';
70
+ default:
71
+ }
72
+ return '';
73
+ }
74
+
75
+ /**
76
+ * Get editable values based on activity & type (which is also used to display UI)
77
+ */
78
+
79
+ export function makeLogEntryDetailsSchema(
80
+ scrollAreaDOMId: string,
81
+ formId: string,
82
+ timeZone: string | null | undefined,
83
+ __typename: string,
84
+ focusedName: string,
85
+ formValues: Record<string, any> = {}
86
+ ) {
87
+
88
+ let activitiesList: any[] = [];
89
+ let schemaItems: any[] = [];
90
+
91
+ const poProps = {
92
+ scrollAreaDOMId,
93
+ zClassName: 'z9',
94
+ position: 'bottom_left',
95
+ offsetX: 0,
96
+ offsetY: 7,
97
+ };
98
+
99
+ const minDate = new Date();
100
+ minDate.setFullYear(minDate.getFullYear() - 10);
101
+
102
+ const maxDate = new Date();
103
+ maxDate.setMonth(maxDate.getMonth() + 1);
104
+
105
+ switch (__typename) {
106
+ case 'LogEntryArable':
107
+ const logType = getLogTypeFromActivity('ARABLE', formValues.arableDetails?.activity);
108
+ const isWaterTesting = logType === 'WATER';
109
+ const isPriceRelated = ['SALES', 'SEED'].includes(logType!);
110
+
111
+ activitiesList = ARABLE_ACTIVITIES_GROUPED;
112
+ schemaItems = [{
113
+ __type: 'input_click',
114
+ forceClickId: 'input_click_arableDetails.activity',
115
+ label: i18n.t('form.activity'),
116
+ item: {
117
+ locked: () => true,
118
+ focused: focusedName === (formId + '_activity'),
119
+ name: 'arableDetails.activity',
120
+ placeholder: i18n.t(`form.activity_ph`),
121
+ getter: (value: string) => value ? i18n.t(`log.activity.${value}`) : '',
122
+ },
123
+ }, {
124
+ // Water testing inputs
125
+ __type: isWaterTesting ? 'input' : 'none',
126
+ label: i18n.t('form.concentration'),
127
+ item: {
128
+ name: 'arableDetails.concentration',
129
+ type: 'number',
130
+ step: 0.1,
131
+ min: 0.1,
132
+ max: 99999999.99, // database max is numeric(10, 2)
133
+ placeholder: i18n.t('form.concentration_ph'),
134
+ },
135
+ }, {
136
+ __type: isWaterTesting ? 'input' : 'none',
137
+ label: i18n.t('form.concentration_unit'),
138
+ item: {
139
+ name: 'arableDetails.concentrationUnit',
140
+ maxLength: 40,
141
+ placeholder: i18n.t('form.concentration_unit_ph'),
142
+ },
143
+ }, {
144
+ // Regular inputs
145
+ __type: 'input',
146
+ label: i18n.t(isWaterTesting ? 'form.water_quantity' : 'form.quantity'),
147
+ item: {
148
+ name: 'arableDetails.quantity',
149
+ type: 'number',
150
+ step: 0.1,
151
+ min: 0.1,
152
+ max: 99999999.99, // database max is numeric(10, 2)
153
+ placeholder: i18n.t('form.quantity_ph'),
154
+ },
155
+ }, {
156
+ __type: 'input',
157
+ label: i18n.t(isWaterTesting ? 'form.water_unit' : 'form.unit'),
158
+ item: {
159
+ name: 'arableDetails.unit',
160
+ maxLength: 40,
161
+ placeholder: i18n.t(isWaterTesting ? 'form.water_unit_ph' : 'log.unit_arable_ph'),
162
+ },
163
+ }, {
164
+ __type: isPriceRelated ? 'input' : 'none',
165
+ label: i18n.t('form.price'),
166
+ item: {
167
+ name: 'arableDetails.price',
168
+ type: 'number',
169
+ step: 0.1,
170
+ min: 0.1,
171
+ max: 99999999.99, // database max is numeric(10, 2)
172
+ placeholder: i18n.t('log.price_arable_ph'),
173
+ },
174
+ }, {
175
+ __type: isWaterTesting ? 'none' : 'input',
176
+ label: i18n.t('form.crop'),
177
+ item: {
178
+ name: 'arableDetails.crop',
179
+ placeholder: 'Tomato, broccoli, etc.',
180
+ }
181
+ }];
182
+ default:
183
+ }
184
+
185
+ // Date, time, createdBy is common across all log types
186
+
187
+ if (schemaItems.length) {
188
+ const timeZoneCode = getTimeZoneCode(timeZone);
189
+
190
+ schemaItems = schemaItems.concat([{
191
+ __type: 'input_click',
192
+ forceClickId: 'input_click_date',
193
+ label: i18n.t('form.date'),
194
+ item: {
195
+ name: 'date',
196
+ focused: focusedName === (formId + '_date'),
197
+ getter: (value: string) => getCalDate(new Date(value), timeZone).calDate,
198
+ },
199
+ popOverProps: {
200
+ id: formId + '_date',
201
+ ...poProps,
202
+ iface: {
203
+ name: 'PO_LIST',
204
+ variables: {
205
+ designClassName: 'w_300',
206
+ className: 'max_h_40vh',
207
+ initialState: {
208
+ date: formValues.date ? new Date(formValues.date) : new Date(),
209
+ },
210
+ options: [{
211
+ __type: 'DATE_PICKER',
212
+ name: 'date',
213
+ minDate,
214
+ maxDate,
215
+ }]
216
+ }
217
+ }
218
+ }
219
+ }, {
220
+ __type: 'input_time_from_date',
221
+ label: i18n.t(timeZoneCode ? 'form.time_with_zone' : 'form.time', { timeZone: timeZoneCode }),
222
+ scrollAreaDOMId,
223
+ item: {
224
+ name: 'date', // date value will be used to extract time
225
+ type: 'time',
226
+ timeZone,
227
+ },
228
+ }]);
229
+ }
230
+
231
+ if (schemaItems[0] && activitiesList.length) {
232
+ // First item is always activity
233
+ const activityValue = getObject(formValues, schemaItems[0].item.name);
234
+ schemaItems[0].item.popOverProps = {
235
+ id: formId + '_activity',
236
+ ...poProps,
237
+ iface: {
238
+ name: 'PO_LIST',
239
+ variables: {
240
+ designClassName: 'w_250',
241
+ className: 'max_h_40vh',
242
+ options: activitiesList.reduce((acc, [type, activities], i) => {
243
+ const colorIndicator = getLogCategoryColor(type);
244
+ const isEnd = i === activitiesList.length - 1;
245
+
246
+ const updatedList = acc.concat({
247
+ __type: 'LIST_SUBTITLE' as const,
248
+ colorIndicator,
249
+ text: i18n.t(`log.type_short.${type}`),
250
+ className: 'mt_sm',
251
+ textClassName: `cl_${colorIndicator}`,
252
+ }).concat(activities.map((activity: string) => ({
253
+ __type: 'LIST_ITEM' as const,
254
+ // colorIndicator,
255
+ text: i18n.t(`log.activity.${activity}`),
256
+ textClassName: 'ft_xs',
257
+ rightIconClassName: 'ft_xs mb_2',
258
+ name: schemaItems[0].item.name,
259
+ value: activity,
260
+ selected: activityValue === activity,
261
+ })));
262
+
263
+ if (!isEnd) {
264
+ updatedList.push({
265
+ __type: 'BREAK' as const,
266
+ });
267
+ }
268
+
269
+ return updatedList;
270
+ }, [])
271
+ }
272
+ }
273
+ };
274
+ }
275
+
276
+ return schemaItems;
277
+ }
@@ -0,0 +1,271 @@
1
+ import type { OrganizationOperationEnum } from '@jsb188/app/types/organization.d';
2
+ import { OPERATION_ENUMS } from '@jsb188/app/constants/organization';
3
+ import { isFutureCalDate, isValidCalDate } from '@jsb188/app/utils/datetime';
4
+ import { indexToTimeZone, isValidTimeZone } from '@jsb188/app/utils/timeZone';
5
+ import { z } from 'zod';
6
+ import { LOG_TYPE_ENUMS, LOG_TYPES_BY_OPERATION } from '../constants/log';
7
+ import type { FilterLogEntriesArgs, LogTypeEnum } from '../types/log.d';
8
+
9
+ /**
10
+ * Zod schema for query params to filter
11
+ */
12
+
13
+ export const FilterLogEntriesSchema = z.object({
14
+ types: z.array(z.enum(LOG_TYPE_ENUMS as [string]))
15
+ .nullable(),
16
+ startDate: z.string()
17
+ .refine((sd) => isValidCalDate(sd), { message: 'START_DATE_INVALID' })
18
+ .refine((sd) => !isFutureCalDate(sd, 1), { message: 'START_DATE_FUTURE_NOT_ALLOWED' })
19
+ .nullable(),
20
+ endDate: z.string()
21
+ .refine((ed) => isValidCalDate(ed), { message: 'END_DATE_INVALID' })
22
+ .nullable(),
23
+ timeZone: z.string()
24
+ .refine((tz) => isValidTimeZone(tz), { message: 'INVALID_TIMEZONE' })
25
+ .nullable(),
26
+ query: z.string()
27
+ .nullable(),
28
+ }).refine((data) => {
29
+ if (!data.endDate) {
30
+ // No need to validate if endDate is not provided
31
+ return true;
32
+ } else if (!data.startDate) {
33
+ // If endDate is provided, startDate is required
34
+ return false;
35
+ }
36
+ // End date must be after or equal to start date
37
+ return data.endDate >= data.startDate;
38
+ }, {
39
+ message: 'END_DATE_MUST_BE_AFTER_START_DATE',
40
+ path: ['endDate'], // where to attach the error
41
+ });
42
+
43
+ /**
44
+ * Convert list of digits to log type enums
45
+ * @param operationType - The type of operation for organization
46
+ * @param types - Comma-separated string of digits representing log types
47
+ * @returns Array of log type enums or null
48
+ */
49
+
50
+ export function convertDigitsToLogTypes(
51
+ operationType: OrganizationOperationEnum | null,
52
+ typesStr?: string | null,
53
+ ) {
54
+ if (!operationType || !typesStr) {
55
+ return null;
56
+ }
57
+
58
+ const logTypes = LOG_TYPES_BY_OPERATION[operationType];
59
+ if (!logTypes) {
60
+ console.warn(`No log types found for operation type: ${operationType}`);
61
+ return null;
62
+ }
63
+
64
+ return logTypes.map((type: LogTypeEnum, i: number) => {
65
+ const value = typesStr.charAt(i);
66
+ if (value === '1') {
67
+ return type;
68
+ }
69
+ return null;
70
+ }).filter(Boolean) as FilterLogEntriesArgs['types'];
71
+ }
72
+
73
+ /**
74
+ * Convert list of log type enums to digits
75
+ * @param operationType - The type of operation for organization
76
+ * @param types - Array of log type enums
77
+ * @returns String made of digits (indexes) representing log types
78
+ */
79
+
80
+ export function convertLogTypesToDigits(
81
+ operationType: OrganizationOperationEnum | null,
82
+ types: FilterLogEntriesArgs['types'],
83
+ ): string | null {
84
+ if (!operationType || !types) {
85
+ return null;
86
+ }
87
+
88
+ const logTypes = LOG_TYPES_BY_OPERATION[operationType];
89
+ if (!logTypes) {
90
+ console.warn(`No log types found for operation type: ${operationType}`);
91
+ return null;
92
+ }
93
+
94
+ return logTypes.map((type: LogTypeEnum) => {
95
+ return types.includes(type) ? '1' : '0';
96
+ }).join('');
97
+ }
98
+
99
+ /**
100
+ * Create a filter object for logEntries() query from the URL search query.
101
+ * @param operationType - The type of operation for organization
102
+ * @param searchQuery - The search query string from the URL
103
+ * @returns FilterLogEntriesArgs - The filter object to be used in the logEntries() query
104
+ */
105
+
106
+ export function createFilterFromURL(
107
+ operationType: OrganizationOperationEnum | null,
108
+ searchQuery: string,
109
+ ) {
110
+ const urlParams = new URLSearchParams(searchQuery);
111
+
112
+ let startDate = urlParams.get('sd');
113
+ let endDate = urlParams.get('ed');
114
+ if (startDate && !endDate) {
115
+ endDate = startDate;
116
+ } else if (endDate && !startDate) {
117
+ startDate = endDate;
118
+ }
119
+
120
+ let operation = urlParams.get('o');
121
+ if (operation) {
122
+ operation = OPERATION_ENUMS[Number(operation) - 1] || operationType;
123
+ } else {
124
+ operation = operationType;
125
+ }
126
+
127
+ if (!operation) {
128
+ operation = OPERATION_ENUMS[0]; // Default to first operation if none provided
129
+ }
130
+
131
+ const filter: FilterLogEntriesArgs = {
132
+ operation: operation!,
133
+ types: convertDigitsToLogTypes(operation, urlParams.get('t')), // (urlParams.get('t') || null) as FilterLogEntriesArgs['type'] | null,
134
+ startDate,
135
+ endDate,
136
+ timeZone: indexToTimeZone(urlParams.get('z')),
137
+ query: urlParams.get('q') || '',
138
+ };
139
+
140
+ const validation = FilterLogEntriesSchema.safeParse(filter);
141
+ if (!validation.success) {
142
+ // Return null and force the client to go to a valid page
143
+ return null;
144
+ }
145
+
146
+ return filter;
147
+ }
148
+
149
+ /**
150
+ * Create URL from search query params.
151
+ * This function assumes the query parameters are valid and well-formed.
152
+ * @param operationType - Type of operation for organization
153
+ * @param orgGenericId - Generic ID of the organization
154
+ * @param searchQuery - Search query string from the URL
155
+ * @param fileType - Type of file ('pdf' or 'csv')
156
+ * @returns FilterLogEntriesArgs - The filter object to be used in the logEntries() query
157
+ */
158
+
159
+ export function createLogsFileNameFromURL(
160
+ operationType: OrganizationOperationEnum | null,
161
+ orgGenericId: string,
162
+ searchQuery: string,
163
+ fileType: string
164
+ ) {
165
+ const urlParams = new URLSearchParams(searchQuery);
166
+ const o = urlParams.get('o');
167
+ const t = urlParams.get('t');
168
+ const a = urlParams.get('a');
169
+ const sd = urlParams.get('sd');
170
+ const ed = urlParams.get('ed');
171
+ const z = urlParams.get('z');
172
+ const q = urlParams.get('q');
173
+
174
+ let checkStr = '';
175
+ let paramStr = '';
176
+
177
+ if (o) {
178
+ checkStr += o;
179
+ } else {
180
+ const ix = OPERATION_ENUMS.indexOf(operationType || '');
181
+ checkStr += String(ix + 1);
182
+ }
183
+
184
+ if (t?.split('')?.some(letter => letter !== '0')) {
185
+ checkStr += '1';
186
+ paramStr += `_${t}`;
187
+ } else {
188
+ checkStr += '0';
189
+ }
190
+
191
+ if (a) {
192
+ checkStr += '1';
193
+ paramStr += `_${a}`;
194
+ } else {
195
+ checkStr += '0';
196
+ }
197
+
198
+ if (sd) {
199
+ checkStr += '1';
200
+ paramStr += `_${sd}`;
201
+ } else {
202
+ checkStr += '0';
203
+ }
204
+
205
+ if (ed) {
206
+ checkStr += '1';
207
+ paramStr += `_${ed}`;
208
+ } else {
209
+ checkStr += '0';
210
+ }
211
+
212
+ if (z) {
213
+ checkStr += '1';
214
+ paramStr += `_${z}`;
215
+ } else {
216
+ checkStr += '0';
217
+ }
218
+
219
+ if (q) {
220
+ checkStr += '1';
221
+ paramStr += `_${q}`;
222
+ } else {
223
+ checkStr += '0';
224
+ }
225
+
226
+ if (checkStr.split('').every(digit => digit === '0')) {
227
+ return `logs_${orgGenericId}_x${paramStr}.${fileType}`;
228
+ }
229
+
230
+ return `logs_${orgGenericId}_${checkStr}${paramStr}.${fileType}`;
231
+ }
232
+
233
+ /**
234
+ * Create URL search params from a filter object
235
+ * @param filter - The filter object to convert to URL search params
236
+ * @returns URLSearchParams - The search params object
237
+ */
238
+
239
+ export function createSearchParamsFromFilter(filter: FilterLogEntriesArgs): URLSearchParams {
240
+ const params = new URLSearchParams();
241
+ const { operation } = filter;
242
+
243
+ if (operation) {
244
+ params.set('o', String(OPERATION_ENUMS.indexOf(operation) + 1));
245
+ }
246
+
247
+ if (filter.types && operation) {
248
+ const typeDigits = convertLogTypesToDigits(operation, filter.types);
249
+ if (typeDigits) {
250
+ params.set('t', typeDigits);
251
+ }
252
+ }
253
+
254
+ if (filter.accountId) {
255
+ params.set('a', filter.accountId);
256
+ }
257
+ if (filter.startDate) {
258
+ params.set('sd', filter.startDate);
259
+ }
260
+ if (filter.endDate) {
261
+ params.set('ed', filter.endDate);
262
+ }
263
+ if (filter.timeZone) {
264
+ params.set('z', filter.timeZone);
265
+ }
266
+ if (filter.query) {
267
+ params.set('q', filter.query);
268
+ }
269
+
270
+ return params;
271
+ }
@@ -1,9 +1,10 @@
1
- import { LOG_ARABLE_ACTIVITY_ENUMS } from '../constants/log.ts';
2
- import type { OrganizationOperationEnum } from './organization.d.ts';
1
+ import type { OrganizationOperationEnum } from '@jsb188/app/types/organization.d';
2
+ import type { AccountObj } from '@jsb188/app/types/account.d';
3
+ import { LOG_ARABLE_ACTIVITY_ENUMS } from '../constants/log';
3
4
 
4
5
  // All logs types
5
6
 
6
- export type LogArableTypeEnum = 'SEED' | 'FIELD' | 'HARVEST' | 'POST_HARVEST' | 'SALES';
7
+ export type LogArableTypeEnum = 'SEED' | 'PLANTING' | 'FIELD' | 'HARVEST' | 'POST_HARVEST' | 'SALES' | 'WATER';
7
8
  export type LogTypeEnum = LogArableTypeEnum;
8
9
 
9
10
  // All logs activities
@@ -11,35 +12,81 @@ export type LogTypeEnum = LogArableTypeEnum;
11
12
  export type LogArableActivityEnum = typeof LOG_ARABLE_ACTIVITY_ENUMS[number];
12
13
  export type LogActivityEnum = LogArableActivityEnum;
13
14
 
15
+ interface LogDetailsGQLBase {
16
+ __typename: string;
17
+ id: string;
18
+ type: any;
19
+ activity: any;
20
+ notes: string;
21
+ }
22
+
14
23
  // Log entry object
15
24
 
16
- export interface LogArableObj {
17
- type: LogTypeEnum;
25
+ interface LogArableMetadata {
26
+ crop: string;
27
+ quantity: number;
28
+ unit: string;
29
+ concentration: number;
30
+ concentrationUnit: string;
31
+ price: number;
32
+ }
33
+
34
+ interface LogArableObj {
35
+ type?: LogArableTypeEnum; // Only set in server if manually extended
18
36
  activity: LogArableActivityEnum;
19
- item?: string;
20
- quantity?: number;
21
- unit?: string;
22
- price?: number;
23
- notes: string | null;
37
+ notes: string | null;
38
+ metadata?: Partial<LogArableMetadata> | null;
39
+ }
40
+
41
+ interface LogArableDetailsObj extends LogArableObj {
42
+ __table: 'logs_arable';
43
+ id: number;
24
44
  }
25
45
 
46
+ export type LogDetailsObj = LogArableObj;
47
+
26
48
  export interface LogEntryGQLData {
27
- id: string
28
- accountId: string
29
- organizationId: string
30
- details: LogArableObj;
49
+ id: string;
50
+ accountId: string;
51
+ organizationId: string;
52
+ details: LogArableMetadata & LogDetailsGQLBase;
53
+
54
+ account: any;
55
+ date: string; // ISO date string
56
+ createdAt: string; // ISO date string
57
+ updatedAt: string; // ISO date string
58
+ }
59
+
60
+ export interface LogEntryInsertObj {
61
+ id?: number; // Only for edits
62
+ accountId: number;
63
+ organizationId: number;
64
+ details: LogDetailsObj;
65
+ date: Date;
66
+ }
67
+
68
+ export interface LogEntryDataObj {
69
+ __table: 'logs';
70
+ id: number;
71
+ accountId: number;
72
+ organizationId: number;
73
+ details: LogArableDetailsObj;
74
+ date: Date;
75
+ createdAt: Date;
76
+ updatedAt: Date;
31
77
 
32
- account: any;
33
- createdAt: string // ISO date string
34
- updatedAt: string // ISO date string
78
+ // This is for outputs, but will never be set for inserts
79
+ account?: AccountObj;
35
80
  }
36
81
 
37
82
  // Filters for search
38
83
 
39
84
  export interface FilterLogEntriesArgs {
40
- operation: OrganizationOperationEnum;
41
- type?: LogTypeEnum | null;
42
- startDate?: string | null;
43
- endDate?: string | null;
44
- query?: string;
85
+ operation: OrganizationOperationEnum;
86
+ accountId?: string | null; // Account ID to filter logs by account
87
+ types?: LogTypeEnum[] | null;
88
+ startDate?: string | null; // CalDate, with dashes (YYYY-MM-DD)
89
+ endDate?: string | null; // CalDate, with dashes (YYYY-MM-DD)
90
+ timeZone?: string | null; // Timezone string, e.g., 'America/New_York'
91
+ query?: string | null;
45
92
  }
package/src/utils/log.ts CHANGED
@@ -1,49 +1,47 @@
1
- import { textWithBrackets, ucFirst } from '../utils/string';
1
+ import i18n from '@jsb188/app/i18n';
2
+ import type { ColorEnum } from '@jsb188/app/types/app.d';
3
+ import type { OrganizationOperationEnum } from '@jsb188/app/types/organization.d';
4
+ import { formatCurrency, formatDecimal } from '@jsb188/app/utils/number';
5
+ import { textWithBrackets, ucFirst } from '@jsb188/app/utils/string';
2
6
  import { ARABLE_ACTIVITIES_GROUPED } from '../constants/log';
3
- import type { OrganizationOperationEnum } from '../types/organization.d';
4
- import type { ColorEnum } from '../types/app';
5
7
  import type { LogTypeEnum } from '../types/log';
6
8
 
7
9
  /**
8
- * Map journal type to a color
10
+ * Map log type to a color
9
11
  * @param type - The type of the log entry
10
12
  * @returns The color associated with the journal type
11
13
  */
12
14
 
13
- export function getJournalTypeColor(type: LogTypeEnum): ColorEnum {
14
- const journalTypeToColor = {
15
- SEED: 'brown',
16
- FIELD: 'yellow',
17
- HARVEST: 'green',
18
- POST_HARVEST: 'cyan',
19
- SALES: 'blue',
20
- } as Record<LogTypeEnum, ColorEnum>;
15
+ export function getLogCategoryColor(type: LogTypeEnum): ColorEnum {
16
+ let logTypeToColor;
21
17
 
22
- // Default to zinc if type is not found
23
- const color = journalTypeToColor[type] || 'zinc';
24
- return color;
25
- }
18
+ // Do switch operation here
19
+ // switch (operation) {
20
+ // case 'ARABLE':
21
+ // case 'LogEntryArable':
22
+ // // ..
23
+ // break;
24
+ // case 'LIVESTOCK':
25
+ // case 'LogEntryLivestock':
26
+ // // ..
27
+ // break;
28
+ // default:
29
+ // }
26
30
 
27
- /**
28
- * Get the title for log entry for each Union interface
29
- * @param details - The details Union interface for log entry
30
- * @return The title for the log entry
31
- */
31
+ logTypeToColor = {
32
+ SEED: 'brown',
33
+ PLANTING: 'amber',
34
+ FIELD: 'lime',
35
+ HARVEST: 'emerald',
36
+ POST_HARVEST: 'cyan',
37
+ SALES: 'blue',
38
+ WATER: 'violet',
39
+ DELETED: 'medium',
40
+ } as Record<LogTypeEnum, ColorEnum>;
32
41
 
33
- export function getLogEntryTitle(details: any): string {
34
- const { __typename, __table } = details;
35
- switch (__typename || __table) {
36
- case 'logs_arable':
37
- case 'LogEntryArable': {
38
- return textWithBrackets(ucFirst(details.crop?.name || details.product?.name), [details.quantity, details.unit]);
39
- }
40
- case 'logs_livestock':
41
- case 'LogEntryLivestock': {
42
- // .. live stock logs here ..
43
- }
44
- default:
45
- }
46
- return '..';
42
+ // Default to zinc if type is not found
43
+ const color = logTypeToColor[type] || 'zinc';
44
+ return color;
47
45
  }
48
46
 
49
47
  /**
@@ -53,14 +51,65 @@ export function getLogEntryTitle(details: any): string {
53
51
  * @returns The log type or null if not found
54
52
  */
55
53
 
56
- export function getLogTypeFromActivity(operation: OrganizationOperationEnum, activity: any) {
54
+ export function getLogTypeFromActivity(operation: OrganizationOperationEnum | string, activity: any) {
57
55
  switch (operation) {
58
56
  case 'ARABLE':
57
+ case 'LogEntryArable':
59
58
  return ARABLE_ACTIVITIES_GROUPED.find((group: any) => group[1].includes(activity))?.[0] || null;
60
59
  case 'LIVESTOCK':
60
+ case 'LogEntryLivestock':
61
61
  return null; // Livestock activities are not defined in this context
62
62
  default:
63
63
  console.warn('(!1) Cannot get log type from unknown operation type:', operation);
64
64
  return null;
65
65
  }
66
66
  }
67
+
68
+ /**
69
+ * Get the title for log entry for each Union interface
70
+ * @param details - The details Union interface for log entry
71
+ * @param isServer - True if used in server
72
+ * @param logType - Use this param if this function is used in server; {d.type} will be undefined unless manually set
73
+ * @param iface - In unique cases (such as client-side form), you can use this for interface name
74
+ * @return The title for the log entry
75
+ */
76
+
77
+ export function getLogEntryTitle(d: any, isServer?: boolean, logType_?: string, iface?: string): string {
78
+ const { __typename, __table, type } = d;
79
+ const logType = logType_ || type;
80
+ const md = isServer ? (d.metadata || {}) : d;
81
+
82
+ switch (iface || __typename || __table) {
83
+ case 'ARABLE':
84
+ case 'logs_arable':
85
+ case 'LogEntryArable': {
86
+ const quantityText = [formatDecimal(md.quantity, true, true), md.unit].filter(Boolean).join(' ');
87
+
88
+ let cropName = ucFirst(md.crop);
89
+ let logSpecificText = '';
90
+
91
+ if (logType === 'WATER') {
92
+ logSpecificText = [md.concentration, md.concentration && md.concentrationUnit].filter(Boolean).join(' ');
93
+ } else if (logType === 'SALES') {
94
+ if (!cropName) {
95
+ cropName = i18n.t('log.unknown_crop');
96
+ }
97
+ logSpecificText = formatCurrency(md.price, 'en-US', 'USD');
98
+ }
99
+
100
+ return textWithBrackets(
101
+ cropName,
102
+ [
103
+ logSpecificText + (logSpecificText && quantityText ? ',' : ''),
104
+ quantityText,
105
+ ],
106
+ );
107
+ }
108
+ case 'logs_livestock':
109
+ case 'LogEntryLivestock': {
110
+ // .. live stock logs here ..
111
+ }
112
+ default:
113
+ }
114
+ return '..';
115
+ }
File without changes