@jsb188/app 1.1.7 → 1.1.9

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.
@@ -65,6 +65,17 @@ function getMonthsDiff(date1: Date, date2: Date) {
65
65
  return (date1.getFullYear() - date2.getFullYear()) * 12 + (date1.getMonth() - date2.getMonth());
66
66
  }
67
67
 
68
+ /**
69
+ * Get UTC week number in year (1-based)
70
+ */
71
+
72
+ export function getUtcWeekOfYear(date: Date) {
73
+ const startOfYear = Date.UTC(date.getUTCFullYear(), 0, 1);
74
+ const currentDay = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
75
+ const dayOfYear = Math.floor((currentDay - startOfYear) / 86400000) + 1;
76
+ return Math.floor((dayOfYear - 1) / 7) + 1;
77
+ }
78
+
68
79
  /**
69
80
  * Get date period from date
70
81
  */
@@ -272,9 +283,11 @@ export function getCalDate(d: Date, timeZone_?: string | null) {
272
283
  * @returns Date - Enforced calendar date in the specified timezone
273
284
  */
274
285
 
275
- export function getReadableCalDate(d_: string | Date, timeZone?: string | null) {
286
+ export function getReadableCalDate(d_: string | Date, timeZone?: string | null, locales?: string) {
287
+ let isCalDateString = false;
276
288
  let d;
277
289
  if (typeof d_ === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(d_)) {
290
+ isCalDateString = true;
278
291
  // Assume YYYY-MM-DD format
279
292
  const [year, month, day] = d_.split('-').map(Number);
280
293
  d = new Date(year, month - 1, day);
@@ -288,17 +301,105 @@ export function getReadableCalDate(d_: string | Date, timeZone?: string | null)
288
301
  return null;
289
302
  }
290
303
 
291
- let dt = DateTime.fromJSDate(d, { zone: timeZone || undefined });
292
- // If timezone is invalid, fallback to system/local
293
- if (!dt.isValid) {
294
- dt = DateTime.fromJSDate(d); // system default zone
304
+ // let dt = DateTime.fromJSDate(d, { zone: timeZone || undefined });
305
+ // // If timezone is invalid, fallback to system/local
306
+ // if (!dt.isValid) {
307
+ // dt = DateTime.fromJSDate(d); // system default zone
308
+ // }
309
+
310
+ // if (!dt.isValid) {
311
+ // return null;
312
+ // }
313
+
314
+ // return dt.toFormat('MM/dd/yyyy');
315
+
316
+ return new Intl.DateTimeFormat(locales || 'en-US', {
317
+ timeZone: isCalDateString ? undefined : timeZone || undefined, // null is not allowed, it will throw error
318
+ }).format(d);
319
+ }
320
+
321
+ /**
322
+ * Get report period DateTime value with timezone support.
323
+ */
324
+
325
+ function getReportPeriodDateTime(period: string | Date, timeZone: string | null) {
326
+ const zone = timeZone || undefined;
327
+
328
+ if (typeof period === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(period)) {
329
+ const dt = DateTime.fromISO(period, zone ? { zone } : undefined);
330
+ return dt.isValid ? dt : null;
295
331
  }
296
332
 
297
- if (!dt.isValid) {
333
+ if (period instanceof Date) {
334
+ let dt = DateTime.fromJSDate(period, zone ? { zone } : undefined);
335
+ if (!dt.isValid) {
336
+ dt = DateTime.fromJSDate(period);
337
+ }
338
+ return dt.isValid ? dt : null;
339
+ }
340
+
341
+ const dt = DateTime.fromISO(String(period), zone ? { zone } : undefined);
342
+ return dt.isValid ? dt : null;
343
+ }
344
+
345
+ /**
346
+ * Format report period range label.
347
+ */
348
+
349
+ function formatReportPeriodRange(start: DateTime, end: DateTime, separator: string) {
350
+ if (start.year !== end.year) {
351
+ return `${start.toFormat('MMM d, yyyy')}${separator}${end.toFormat('MMM d, yyyy')}`;
352
+ }
353
+
354
+ if (start.month !== end.month) {
355
+ return `${start.toFormat('MMM d')}${separator}${end.toFormat('MMM d, yyyy')}`;
356
+ }
357
+
358
+ return `${start.toFormat('MMM d')}${separator}${end.toFormat('d, yyyy')}`;
359
+ }
360
+
361
+ /**
362
+ * Get formatted report period label from period start and frequency.
363
+ */
364
+
365
+ export function getReportPeriod(
366
+ period: string | Date,
367
+ frequency: any,
368
+ timeZone: string | null,
369
+ ) {
370
+ const start = getReportPeriodDateTime(period, timeZone);
371
+ if (!start) {
298
372
  return null;
299
373
  }
300
374
 
301
- return dt.toFormat('MM/dd/yyyy');
375
+ switch (frequency) {
376
+ case 'DAILY':
377
+ return start.toFormat('MMM d, yyyy');
378
+ case 'WEEKLY':
379
+ return formatReportPeriodRange(start, start.plus({ days: 6 }), '–');
380
+ case 'MONTHLY':
381
+ return formatReportPeriodRange(start, start.plus({ months: 1 }).minus({ days: 1 }), '-');
382
+ case 'QUARTERLY':
383
+ return formatReportPeriodRange(start, start.plus({ months: 3 }).minus({ days: 1 }), '-');
384
+ case 'ANNUALLY':
385
+ return formatReportPeriodRange(start, start.plus({ years: 1 }).minus({ days: 1 }), '-');
386
+ default:
387
+ return start.toFormat('MMM d, yyyy');
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Date objects create different calendar dates based on timezone,
393
+ * to avoid such issue, use this funciton to convert JS date to string format.
394
+ */
395
+
396
+ export function getReadableCalDateFromUTC(d: string | Date) {
397
+ if (typeof d === 'string') {
398
+ return getReadableCalDate(d);
399
+ }
400
+
401
+ const dStr = d.toISOString().split('T')[0]; // Get date part in YYYY-MM-DD format
402
+ return getReadableCalDate(dStr);
302
403
  }
303
404
 
304
405
  /**
@@ -392,7 +493,7 @@ export function convertIntToCalDate(
392
493
  */
393
494
 
394
495
  export function isValidCalDate(
395
- calDate_: string | number,
496
+ calDate_: string | number | bigint,
396
497
  allowDashes: boolean = false,
397
498
  minCalDate: number = 19500101,
398
499
  ): boolean {
@@ -435,87 +536,96 @@ export function isFutureCalDate(
435
536
  }
436
537
 
437
538
  /**
438
- * Convert date time "time" ago
439
- * @param d_ - Date to convert
440
- * @param params - Optional parameters for time ago conversion
539
+ * Get timezone-aware DateTime object from one date input.
441
540
  */
442
541
 
443
- export function getTimeAgo(
444
- d_: Date | string | number | null,
445
- params?: Partial<TimeAgoParams>,
542
+ function getDateTimeWithTimeZone(
543
+ date: string | Date,
544
+ timeZone: string | null,
446
545
  ) {
447
- const {
448
- locales = 'en-US',
449
- justNowThresh = 300000, // 5 minutes
450
- nowThresh = 8.64e+7,
451
- disableFuture = false,
452
- isToday,
453
- skipTodayCheck,
454
- } = params || {};
546
+ const zone = timeZone && isValidTimeZone(timeZone) ? timeZone : undefined;
455
547
 
456
- let d;
457
- if (d_ instanceof Date) {
458
- d = d_;
459
- } else if (!isNaN(Number(d_))) {
460
- d = new Date(Number(d_));
461
- } else {
462
- // Make sure date is not null, before using this function
463
- d = d_ ? new Date(d_) : new Date(-1);
548
+ if (date instanceof Date) {
549
+ const dt = DateTime.fromJSDate(date, zone ? { zone } : undefined);
550
+ return dt.isValid ? dt : null;
464
551
  }
465
552
 
466
- const ts = d.getTime();
467
- const now = Date.now();
468
- const diff = now - ts;
469
- const isFuture = diff < 0;
553
+ let dt = DateTime.fromISO(date, zone ? { zone } : undefined);
554
+ if (dt.isValid) {
555
+ return dt;
556
+ }
470
557
 
471
- if (isFuture && !disableFuture) {
472
- // Future date
558
+ dt = DateTime.fromJSDate(new Date(date), zone ? { zone } : undefined);
559
+ return dt.isValid ? dt : null;
560
+ }
473
561
 
474
- const minutesFromNow = Math.round(diff / 60000 * -1);
475
- if (minutesFromNow < 60) {
476
- return i18n.t('datetime.in_minutes_ct', { smart_count: minutesFromNow });
477
- }
562
+ /**
563
+ * Convert today/yesterday date time into a label with time
564
+ * @param dt - Parsed Luxon date time
565
+ * @param timeZone - Optional timezone for time formatting
566
+ */
478
567
 
479
- const fromIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
480
- if (fromIsToday) {
481
- const hoursFromNow = Math.round(diff / 3600000 * -1);
482
- if (hoursFromNow <= 8) {
483
- return i18n.t('datetime.in_hours_ct', { smart_count: hoursFromNow });
484
- }
568
+ function getTodayYesterdayTime(
569
+ dt: DateTime,
570
+ timeZone: string | null,
571
+ ) {
572
+ const now = timeZone && isValidTimeZone(timeZone)
573
+ ? DateTime.now().setZone(timeZone)
574
+ : DateTime.now();
575
+ const timeText = getFullDateTime(dt.toJSDate(), {
576
+ timeZone,
577
+ hideDate: true,
578
+ });
485
579
 
486
- return getFullDateTime(d, {
487
- locales,
488
- hideDate: true,
489
- });
490
- }
580
+ if (dt.hasSame(now, 'day')) {
581
+ return `${i18n.t('datetime.period_TODAY')}, ${timeText}`;
491
582
  }
492
583
 
493
- if (!isFuture && diff < nowThresh) {
494
- if (diff < justNowThresh) {
495
- return i18n.t('datetime.just_now');
496
- }
584
+ if (dt.hasSame(now.minus({ days: 1 }), 'day')) {
585
+ return `${i18n.t('datetime.period_YESTERDAY')}, ${timeText}`;
586
+ }
497
587
 
498
- const minutesAgo = Math.round(diff / 60000);
499
- if (minutesAgo < 60) {
500
- return i18n.t('datetime.minutes_ago_ct', { smart_count: minutesAgo });
501
- }
588
+ return null;
589
+ }
502
590
 
503
- const agoIsToday = isToday || (!skipTodayCheck && getDatePeriod(d, new Date()) === 'TODAY');
504
- if (agoIsToday) {
505
- const hoursAgo = Math.round(diff / 3600000);
506
- if (hoursAgo <= 8) {
507
- return i18n.t('datetime.hours_ago_ct', { smart_count: hoursAgo });
508
- }
591
+ /**
592
+ * Convert date time "time" ago
593
+ * @param date - Date to convert
594
+ * @param timeZone - Optional timezone for day boundary checks
595
+ */
509
596
 
510
- return getFullDateTime(d, {
511
- locales,
512
- hideDate: true,
513
- });
514
- }
597
+ export function getTimeAgo(
598
+ date: string | Date,
599
+ timeZone: string | null,
600
+ ) {
601
+ const dt = getDateTimeWithTimeZone(date, timeZone);
602
+ if (!dt) {
603
+ return null;
604
+ }
605
+
606
+ const now = timeZone && isValidTimeZone(timeZone)
607
+ ? DateTime.now().setZone(timeZone)
608
+ : DateTime.now();
609
+ const todayYesterdayTime = getTodayYesterdayTime(dt, timeZone);
610
+
611
+ if (todayYesterdayTime) {
612
+ return todayYesterdayTime;
613
+ }
614
+
615
+ const diffMs = now.toMillis() - dt.toMillis();
616
+
617
+ if (diffMs < 0) {
618
+ return getFullDateTime(dt.toJSDate(), {
619
+ timeZone,
620
+ alwaysShowYear: true,
621
+ textDateStyle: 'short',
622
+ });
515
623
  }
516
624
 
517
- return getFullDateTime(d, {
518
- locales,
625
+ return getFullDateTime(dt.toJSDate(), {
626
+ timeZone,
627
+ alwaysShowYear: true,
628
+ textDateStyle: 'short',
519
629
  });
520
630
  }
521
631
 
@@ -571,22 +681,35 @@ export function getFullDate(
571
681
  }
572
682
 
573
683
  switch (outputStyle) {
574
- case 'NUMERIC':
684
+ case 'NUMERIC':
575
685
  // Expected output: "9/1/2024"
576
686
  return new Intl.DateTimeFormat(locales, {
577
687
  timeZone: timeZone || undefined, // null is not allowed, it will throw error
578
688
  }).format(d);
579
- case 'NUMERIC_TIME':
580
- // Expected output: "9/1/2024, 8:30 PM"
581
- return new Intl.DateTimeFormat(locales, {
582
- month: '2-digit',
583
- day: '2-digit',
584
- year: 'numeric',
585
- hour: 'numeric',
586
- minute: '2-digit',
587
- hour12: true,
689
+ case 'NUMERIC_TIME': { // Expected output: "9/1/2024, 8:30 PM"
690
+ const numericDate = new Intl.DateTimeFormat(locales, {
588
691
  timeZone: timeZone || undefined, // null is not allowed, it will throw error
589
692
  }).format(d);
693
+
694
+ const numericTime = new Intl.DateTimeFormat(locales, {
695
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
696
+ hour: 'numeric',
697
+ minute: '2-digit',
698
+ hour12: true,
699
+ }).format(d);
700
+
701
+ return `${numericDate}, ${numericTime}`;
702
+
703
+ // return new Intl.DateTimeFormat(locales, {
704
+ // month: '2-digit',
705
+ // day: '2-digit',
706
+ // year: 'numeric',
707
+ // hour: 'numeric',
708
+ // minute: '2-digit',
709
+ // hour12: true,
710
+ // timeZone: timeZone || undefined, // null is not allowed, it will throw error
711
+ // }).format(d);
712
+ }
590
713
  case 'MINIMAL':
591
714
  // Expected output: "Sep 1, 2024, 6:54 PM"
592
715
  return new Intl.DateTimeFormat(locales, {
@@ -940,4 +1063,4 @@ export function groupByDateMonth<T extends { date: Date }>(
940
1063
  }
941
1064
 
942
1065
  return { byDate, byMonth };
943
- }
1066
+ }
@@ -1,3 +1,5 @@
1
+ import type { FilterLogEntriesArgs } from '@jsb188/mday/types/log.d.ts';
2
+ import { isFutureCalDate, isValidCalDate } from './datetime.ts';
1
3
  import { sortObjectByKeys, stringifyJSON } from './object.ts';
2
4
 
3
5
  /**
@@ -11,6 +13,11 @@ type DatabaseActionResult = {
11
13
  documentData: any;
12
14
  };
13
15
 
16
+ export interface GetFiltersFromURLResult {
17
+ filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'> | null;
18
+ sort: string | null;
19
+ }
20
+
14
21
  /**
15
22
  * Check if database document needs an update, insert, or do nothing based on the user API arguments
16
23
  * NOTE: There is a copy paste of this function in @jsb188/react/utils/hooks.ts
@@ -103,6 +110,109 @@ export function delay(ms: number) {
103
110
  return new Promise((resolve) => setTimeout(resolve, ms));
104
111
  }
105
112
 
113
+ /**
114
+ * Convert an indexed bit-string into a list of selected values.
115
+ */
116
+
117
+ function getIndexedValues(
118
+ value: string | null,
119
+ options?: string[],
120
+ ) {
121
+ if (!value || !options?.length) {
122
+ return null;
123
+ }
124
+
125
+ const selectedValues = options.map((option, i) => {
126
+ return value.charAt(i) === '1' ? option : null;
127
+ }).filter(Boolean) as string[];
128
+
129
+ return selectedValues.length ? selectedValues : null;
130
+ }
131
+
132
+ /**
133
+ * Check whether a URL search-param value is a serialized generic ID.
134
+ */
135
+
136
+ export function isValidGenericIdSearchParam(value?: string | number | bigint | null) {
137
+ if (!value) {
138
+ return true;
139
+ }
140
+
141
+ const stringValue = String(value);
142
+ return stringValue !== '0' && /^\d+$/.test(stringValue);
143
+ }
144
+
145
+ /**
146
+ * Validate parsed URL filters using the same date and timezone rules as the logs filter schema.
147
+ */
148
+
149
+ function parsedFilterIsValid(filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'>) {
150
+ if (!isValidGenericIdSearchParam(filter.siteId)) {
151
+ return false;
152
+ }
153
+
154
+ if (filter.startDate) {
155
+ if (!isValidCalDate(filter.startDate)) {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ if (filter.endDate && !isValidCalDate(filter.endDate)) {
161
+ return false;
162
+ }
163
+
164
+ if (filter.endDate && !filter.startDate) {
165
+ return false;
166
+ }
167
+
168
+ return true;
169
+ }
170
+
171
+ /**
172
+ * Parse indexed filters and sort values from URL search params without including operation in the output.
173
+ */
174
+
175
+ export function getFiltersFromURL(
176
+ searchQuery: string,
177
+ sortOptions?: string[],
178
+ types?: string[],
179
+ activities?: string[],
180
+ ): GetFiltersFromURLResult {
181
+ const urlParams = new URLSearchParams(searchQuery);
182
+
183
+ let startDate = urlParams.get('sd');
184
+ let endDate = urlParams.get('ed');
185
+ if (startDate && !endDate) {
186
+ endDate = startDate;
187
+ } else if (endDate && !startDate) {
188
+ startDate = endDate;
189
+ }
190
+
191
+ const filter: Omit<Partial<FilterLogEntriesArgs>, 'operation'> = {
192
+ siteId: urlParams.get('sid') || null,
193
+ types: getIndexedValues(urlParams.get('t'), types) as FilterLogEntriesArgs['types'],
194
+ activities: getIndexedValues(urlParams.get('a'), activities) as FilterLogEntriesArgs['activities'],
195
+ startDate,
196
+ endDate,
197
+ query: urlParams.get('q') || '',
198
+ };
199
+
200
+ const sortIndex = urlParams.get('s');
201
+ const sort = sortOptions?.[Number(sortIndex) - 1] || null;
202
+
203
+ if (!parsedFilterIsValid(filter)) {
204
+ return {
205
+ filter: null,
206
+ sort,
207
+ };
208
+ }
209
+
210
+ return {
211
+ filter,
212
+ sort,
213
+ };
214
+ }
215
+
106
216
  /**
107
217
  * Promise with timeout
108
218
  */
@@ -282,7 +282,7 @@ export function convertToMilitaryTime(time?: number | string | null): string | n
282
282
  export function calculateTotalAmount(values: any[], tax: number = 0): number {
283
283
  return (values || []).reduce((acc, obj) => {
284
284
  // NOTE: obj.value is the total, so obj.quantity can be ignored
285
- const val = parseFloat(obj?.value);
285
+ const val = parseFloat(obj?.value) * (obj?.quantity || 1);
286
286
  if (!isNaN(val)) {
287
287
  return acc + val;
288
288
  }
@@ -299,6 +299,69 @@ export function groupCollections(
299
299
  innerCollectionPrimaryKeys?: Record<string, (obj: any) => string>,
300
300
  isTest?: boolean,
301
301
  ): any[] {
302
+ /**
303
+ * Check if object has a meaningful (non-null) value, including nested objects.
304
+ */
305
+
306
+ function hasMeaningfulValue(obj: any): boolean {
307
+ if (obj === null || typeof obj === 'undefined') {
308
+ return false;
309
+ }
310
+
311
+ if (typeof obj !== 'object') {
312
+ return true;
313
+ }
314
+
315
+ if (Array.isArray(obj)) {
316
+ return obj.some((item) => hasMeaningfulValue(item));
317
+ }
318
+
319
+ const proto = Object.getPrototypeOf(obj);
320
+ if (proto && proto !== Object.prototype) {
321
+ return true;
322
+ }
323
+
324
+ for (const key in obj) {
325
+ if (!Object.prototype.hasOwnProperty.call(obj, key) || key.startsWith('__')) {
326
+ continue;
327
+ }
328
+
329
+ if (hasMeaningfulValue(obj[key])) {
330
+ return true;
331
+ }
332
+ }
333
+
334
+ return false;
335
+ }
336
+
337
+ /**
338
+ * Build a stable key for dedupe checks.
339
+ */
340
+
341
+ function makeMergeKey(
342
+ obj: any,
343
+ pkFn?: (obj: any) => string,
344
+ pkName?: string,
345
+ ): string | number | undefined {
346
+ if (!obj) {
347
+ return undefined;
348
+ }
349
+
350
+ if (pkFn) {
351
+ return pkFn(obj);
352
+ }
353
+
354
+ if (obj.id !== null && typeof obj.id !== 'undefined') {
355
+ return obj.id;
356
+ }
357
+
358
+ if (pkName && obj[pkName] !== null && typeof obj[pkName] !== 'undefined') {
359
+ return obj[pkName];
360
+ }
361
+
362
+ return Object.entries(obj).flat().join('|');
363
+ }
364
+
302
365
  let hasHash = false;
303
366
  let primaryKeyName;
304
367
  let collections = collections_;
@@ -342,15 +405,7 @@ export function groupCollections(
342
405
  // }
343
406
 
344
407
  if (ref) {
345
- let isNull = true;
346
- for (const key in ref) {
347
- if (!key.startsWith('__') && ref[key] !== null) {
348
- isNull = false;
349
- break;
350
- }
351
- }
352
-
353
- if (!isNull) {
408
+ if (hasMeaningfulValue(ref)) {
354
409
  setObject(obj, name, Array.isArray(defaultValue) ? [ref] : ref);
355
410
  } else {
356
411
  setObject(obj, name, defaultValue);
@@ -386,10 +441,12 @@ export function groupCollections(
386
441
  const innerObj = getObject(obj, name);
387
442
  const ref = getObject(acc[i], name);
388
443
 
444
+ const hasInnerObj = hasMeaningfulValue(innerObj);
445
+
389
446
  if (!ref) {
390
- setObject(acc[i], name, innerObj && Array.isArray(innerObj) ? [innerObj] : (innerObj || defaultValue));
447
+ setObject(acc[i], name, hasInnerObj ? [innerObj] : defaultValue);
391
448
  } else if (
392
- innerObj &&
449
+ hasInnerObj &&
393
450
  !ref.find((o: any) => {
394
451
  const innerPKFn = innerCollectionPrimaryKeys?.[name];
395
452
  if (innerPKFn) {
@@ -426,33 +483,39 @@ export function groupCollections(
426
483
  }
427
484
 
428
485
  const flatName = name.replace('.#.', '.');
486
+ const parentPKFn = innerCollectionPrimaryKeys?.[beforeHash];
487
+ const childPKFn = innerCollectionPrimaryKeys?.[flatName];
429
488
 
430
489
  collections.forEach((obj) => {
431
490
  const innerObj = getObject(obj, flatName);
432
491
  const primaryKey = obj[primaryKeyName];
433
492
  const i = groupedCollections.findIndex((o: any) => o[primaryKeyName] === primaryKey);
434
493
  const innerParent = getObject(obj, beforeHash);
435
- const innerParentId = innerParent?.[primaryKeyName];
494
+ const innerParentId = makeMergeKey(innerParent, parentPKFn, primaryKeyName);
436
495
 
437
- if (!innerObj) {
496
+ if (!innerObj || !hasMeaningfulValue(innerObj)) {
438
497
  return;
439
498
  }
440
499
 
441
500
  if (innerParentId && i >= 0) {
442
501
  const innerArr = getObject(groupedCollections[i], beforeHash) || [];
443
- const j = innerArr.findIndex((o: any) => o[primaryKeyName] === innerParentId);
502
+ const j = innerArr.findIndex((o: any) => makeMergeKey(o, parentPKFn, primaryKeyName) === innerParentId);
444
503
 
445
504
  if (j >= 0) {
446
505
  const currentValue = innerArr[j][afterHash];
447
506
  const currentValueIsArray = Array.isArray(currentValue);
448
507
  const actualPathName = `${beforeHash}.${j}.${afterHash}`;
508
+ const nextInnerObjKey = makeMergeKey(innerObj, childPKFn);
449
509
 
450
510
  let newValue;
451
511
  if (currentValueIsArray) {
452
- if (!currentValue.find((o) => o.id === innerObj.id)) {
512
+ if (!currentValue.find((o) => makeMergeKey(o, childPKFn) === nextInnerObjKey)) {
453
513
  newValue = currentValue.concat(innerObj);
454
514
  }
455
- } else if (currentValue && currentValue.id !== innerObj.id) {
515
+ } else if (
516
+ currentValue &&
517
+ makeMergeKey(currentValue, childPKFn) !== nextInnerObjKey
518
+ ) {
456
519
  newValue = [currentValue].concat(innerObj);
457
520
  } else if (!currentValue) {
458
521
  newValue = [innerObj];
@@ -473,12 +536,18 @@ export function groupCollections(
473
536
  if (Array.isArray(innerParent)) {
474
537
  innerParent.forEach((obj: any) => {
475
538
  const innerParentObj = getObject(obj, afterHash);
476
- if (innerParentObj) {
539
+ if (innerParentObj && hasMeaningfulValue(innerParentObj)) {
477
540
  if (Array.isArray(innerParentObj)) {
478
- setObject(obj, afterHash, uniqBy(innerParentObj, primaryKeyName));
541
+ if (childPKFn) {
542
+ setObject(obj, afterHash, uniqBy(innerParentObj, childPKFn));
543
+ } else {
544
+ setObject(obj, afterHash, uniqBy(innerParentObj, (iObj: any) => makeMergeKey(iObj)));
545
+ }
479
546
  } else {
480
547
  setObject(obj, afterHash, [innerParentObj]);
481
548
  }
549
+ } else {
550
+ setObject(obj, afterHash, []);
482
551
  }
483
552
  });
484
553
  }