@jsb188/app 1.1.1 → 1.1.2

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 (110) hide show
  1. package/package.json +57 -42
  2. package/src/constants/agent.ts +74 -0
  3. package/src/constants/app.ts +389 -0
  4. package/src/constants/emoji.ts +9153 -0
  5. package/src/constants/other.ts +13 -0
  6. package/src/constants/user.ts +27 -0
  7. package/src/constants/wsActions.ts +49 -0
  8. package/src/i18n/account.ts +139 -0
  9. package/src/i18n/agent.ts +397 -0
  10. package/src/i18n/agentToolBusiness.ts +196 -0
  11. package/src/i18n/agentToolGrid.ts +137 -0
  12. package/src/i18n/agentToolWorkflow.ts +101 -0
  13. package/src/i18n/agent_note.ts +109 -0
  14. package/src/i18n/app.ts +124 -0
  15. package/src/i18n/auth.ts +128 -0
  16. package/src/i18n/billing.ts +7 -0
  17. package/src/i18n/c.ts +907 -0
  18. package/src/i18n/campaign.ts +919 -0
  19. package/src/i18n/country.ts +249 -0
  20. package/src/i18n/datetime.ts +66 -0
  21. package/src/i18n/editor.ts +58 -0
  22. package/src/i18n/error.ts +579 -0
  23. package/src/i18n/field_doc_editor.ts +21 -0
  24. package/src/i18n/field_doc_programs.ts +52 -0
  25. package/src/i18n/field_docs.ts +190 -0
  26. package/src/i18n/index.ts +64 -0
  27. package/src/i18n/log.ts +566 -0
  28. package/src/i18n/memory.ts +59 -0
  29. package/src/i18n/message.ts +13 -0
  30. package/src/i18n/note.ts +19 -0
  31. package/src/i18n/org.ts +306 -0
  32. package/src/i18n/schedule.ts +209 -0
  33. package/src/i18n/sheet.ts +339 -0
  34. package/src/i18n/sheet_formula.ts +165 -0
  35. package/src/i18n/workflow.ts +111 -0
  36. package/src/main.ts +89 -0
  37. package/src/platform.ts +166 -0
  38. package/src/types/ai.d.ts +63 -0
  39. package/src/types/app.d.ts +127 -0
  40. package/src/types/auth.d.ts +94 -0
  41. package/src/types/console.d.ts +3 -0
  42. package/src/types/node-polyglot.d.ts +23 -0
  43. package/src/types/other.d.ts +66 -0
  44. package/src/types.d.ts +29 -0
  45. package/src/utils/account.ts +97 -0
  46. package/src/utils/api.ts +358 -0
  47. package/src/utils/authSession.ts +24 -0
  48. package/src/utils/clientIP.ts +213 -0
  49. package/src/utils/color.ts +279 -0
  50. package/src/utils/cron.ts +310 -0
  51. package/src/utils/csv.ts +19 -0
  52. package/src/utils/datetime.ts +1394 -0
  53. package/src/utils/deferredSave.ts +89 -0
  54. package/src/utils/email.ts +39 -0
  55. package/src/utils/emoji.ts +174 -0
  56. package/src/utils/expression.helpers.ts +470 -0
  57. package/src/utils/expression.test.ts +793 -0
  58. package/src/utils/expression.ts +2261 -0
  59. package/src/utils/interval.ts +80 -0
  60. package/src/utils/language.ts +9 -0
  61. package/src/utils/logic.ts +299 -0
  62. package/src/utils/managedSession.ts +34 -0
  63. package/src/utils/managedSessionBff.test.ts +60 -0
  64. package/src/utils/managedSessionBff.ts +117 -0
  65. package/src/utils/number.ts +338 -0
  66. package/src/utils/object.ts +916 -0
  67. package/src/utils/promise.ts +98 -0
  68. package/src/utils/queryReset.ts +266 -0
  69. package/src/utils/recurringTask.ts +60 -0
  70. package/src/utils/schema.ts +293 -0
  71. package/src/utils/string.test.ts +278 -0
  72. package/src/utils/string.ts +709 -0
  73. package/{utils → src/utils}/timeZone.ts +531 -852
  74. package/src/utils/url_client.ts +206 -0
  75. package/tsconfig.json +12 -0
  76. package/constants/app.ts +0 -47
  77. package/constants/billing.ts +0 -146
  78. package/constants/emoji.ts +0 -8945
  79. package/constants/journal.ts +0 -74
  80. package/constants/user.ts +0 -36
  81. package/constants/ws.ts +0 -47
  82. package/i18n/app.ts +0 -101
  83. package/i18n/auth.ts +0 -63
  84. package/i18n/billing.ts +0 -94
  85. package/i18n/datetime.ts +0 -21
  86. package/i18n/error.ts +0 -143
  87. package/i18n/form.ts +0 -74
  88. package/i18n/index.ts +0 -5
  89. package/i18n/user.ts +0 -101
  90. package/main.ts +0 -94
  91. package/platform.ts +0 -125
  92. package/types/ai.d.ts +0 -30
  93. package/types/app.d.ts +0 -48
  94. package/types/auth.d.ts +0 -63
  95. package/types/form.d.ts +0 -56
  96. package/types/journal.d.ts +0 -24
  97. package/types/organization.d.ts +0 -38
  98. package/types/user.d.ts +0 -52
  99. package/types.d.ts +0 -31
  100. package/utils/api.ts +0 -99
  101. package/utils/billing.ts +0 -134
  102. package/utils/datetime.ts +0 -542
  103. package/utils/emoji.ts +0 -151
  104. package/utils/journal.ts +0 -17
  105. package/utils/logic.ts +0 -118
  106. package/utils/number.ts +0 -139
  107. package/utils/object.ts +0 -425
  108. package/utils/string.ts +0 -323
  109. package/utils/url_client.ts +0 -138
  110. package/utils/user.ts +0 -273
@@ -0,0 +1,1394 @@
1
+ import { DateTime } from 'luxon';
2
+ import i18n from '../i18n/index.ts';
3
+ import { getObject } from './object.ts';
4
+ import {
5
+ DEFAULT_TIMEZONE,
6
+ isValidTimeZone,
7
+ parseDateInTimezone,
8
+ } from './timeZone.ts';
9
+
10
+ /**
11
+ * Types
12
+ */
13
+
14
+ export type DatePeriodEnum =
15
+ | 'UPCOMING'
16
+ | 'TOMORROW'
17
+ | 'TODAY'
18
+ | 'YESTERDAY'
19
+ | 'THIS_WEEK'
20
+ | 'THIS_MONTH'
21
+ | 'LAST_WEEK'
22
+ | 'LAST_MONTH'
23
+ | 'OLDER';
24
+
25
+ export interface DatePeriodObj {
26
+ datePeriod: DatePeriodEnum;
27
+ date: Date;
28
+ item: any;
29
+ }
30
+
31
+ interface TimeAgoParams {
32
+ locales: string;
33
+ justNowThresh: number;
34
+ nowThresh: number;
35
+ disableFuture: boolean;
36
+ isToday: boolean;
37
+ skipTodayCheck: boolean;
38
+ }
39
+
40
+ /**
41
+ * Get start of day
42
+ */
43
+
44
+ function getStartOfDay(date: Date) {
45
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
46
+ }
47
+
48
+ /**
49
+ * Get difference in days
50
+ */
51
+
52
+ function getDaysDiff(date1: Date, date2: Date) {
53
+ return Math.floor(
54
+ (getStartOfDay(date1).getTime() - getStartOfDay(date2).getTime()) /
55
+ (1000 * 60 * 60 * 24),
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Get difference in weeks
61
+ */
62
+
63
+ function getWeeksDiff(date1: Date, date2: Date) {
64
+ return Math.floor(getDaysDiff(date1, date2) / 7);
65
+ }
66
+
67
+ /**
68
+ * Get difference in months
69
+ */
70
+
71
+ function getMonthsDiff(date1: Date, date2: Date) {
72
+ return (
73
+ (date1.getFullYear() - date2.getFullYear()) * 12 +
74
+ (date1.getMonth() - date2.getMonth())
75
+ );
76
+ }
77
+
78
+ /**
79
+ * Get UTC week number in year (1-based)
80
+ */
81
+
82
+ export function getUtcWeekOfYear(date: Date) {
83
+ const startOfYear = Date.UTC(date.getUTCFullYear(), 0, 1);
84
+ const currentDay = Date.UTC(
85
+ date.getUTCFullYear(),
86
+ date.getUTCMonth(),
87
+ date.getUTCDate(),
88
+ );
89
+ const dayOfYear = Math.floor((currentDay - startOfYear) / 86400000) + 1;
90
+ return Math.floor((dayOfYear - 1) / 7) + 1;
91
+ }
92
+
93
+ /**
94
+ * Get UTC year-month key (e.g. "2026-07"); zero-padded so keys sort correctly as strings
95
+ */
96
+
97
+ export function getUtcYearMonth(date: Date): string {
98
+ const year = date.getUTCFullYear();
99
+ const month = String(date.getUTCMonth() + 1).padStart(2, '0');
100
+ return `${year}-${month}`;
101
+ }
102
+
103
+ /**
104
+ * Format a future date as a month label, showing the year only when it differs from the reference date.
105
+ */
106
+
107
+ function getFutureMonthLabel(date: Date, referenceDate: Date) {
108
+ return date.toLocaleDateString('en-US', {
109
+ month: 'long',
110
+ year:
111
+ date.getFullYear() === referenceDate.getFullYear()
112
+ ? undefined
113
+ : 'numeric',
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Get date period from date
119
+ */
120
+
121
+ export function getWeeksMonthAgo(d1: Date, d2: Date, weeksThresh = 12): string {
122
+ if (getStartOfDay(d1).getTime() > getStartOfDay(d2).getTime()) {
123
+ return getFutureMonthLabel(d1, d2);
124
+ }
125
+
126
+ const diffWeeks = getWeeksDiff(d2, d1);
127
+ if (diffWeeks === 0) {
128
+ return i18n.t('datetime.period_THIS_WEEK');
129
+ } else if (diffWeeks <= weeksThresh) {
130
+ return i18n.t('datetime.weeks_ago_ct', { smart_count: diffWeeks });
131
+ }
132
+
133
+ const diffMonths = getMonthsDiff(d2, d1);
134
+ return i18n.t('datetime.months_ago_ct', { smart_count: diffMonths });
135
+ }
136
+
137
+ /**
138
+ * Get date period from date
139
+ * @param d1 - Date to check
140
+ * @param d2 - Reference date (usually current date)
141
+ */
142
+
143
+ export function getDatePeriod(d1: Date, d2: Date): DatePeriodEnum {
144
+ const diffDays = getDaysDiff(d1, d2);
145
+
146
+ switch (diffDays) {
147
+ case 0:
148
+ return 'TODAY';
149
+ case 1:
150
+ return 'TOMORROW';
151
+ case -1:
152
+ return 'YESTERDAY';
153
+ case -7:
154
+ return 'LAST_WEEK';
155
+ case -30:
156
+ return 'LAST_MONTH';
157
+ default:
158
+ if (diffDays > 1) {
159
+ return 'UPCOMING';
160
+ }
161
+ }
162
+
163
+ const diffInWeeks = Math.ceil(diffDays / 7);
164
+ if (diffInWeeks === 0) {
165
+ return 'THIS_WEEK';
166
+ } else if (diffInWeeks === -1) {
167
+ return 'LAST_WEEK';
168
+ }
169
+
170
+ const diffInMonths =
171
+ (d2.getFullYear() - d1.getFullYear()) * 12 +
172
+ (d2.getMonth() - d1.getMonth());
173
+ if (diffInMonths === 0) {
174
+ return 'THIS_MONTH';
175
+ } else if (diffInMonths === -1) {
176
+ return 'LAST_MONTH';
177
+ }
178
+
179
+ return 'OLDER';
180
+ }
181
+
182
+ /*
183
+ * Format compact display dates consistently, showing the year only outside the current year.
184
+ * Calendar dates use UTC so timezone conversion cannot change their day.
185
+ */
186
+
187
+ export function formatDisplayDate(value: string | Date, timeZone?: string | null): string {
188
+ const dateOnly = typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
189
+ const date = value instanceof Date ? value : new Date(value);
190
+ const zone = dateOnly ? 'UTC' : timeZone || undefined;
191
+ const yearFormat = new Intl.DateTimeFormat('en-US', { timeZone: zone, year: 'numeric' });
192
+ return new Intl.DateTimeFormat('en-US', {
193
+ timeZone: zone,
194
+ month: 'numeric',
195
+ day: '2-digit',
196
+ year: yearFormat.format(date) === yearFormat.format(new Date()) ? undefined : 'numeric',
197
+ hour: dateOnly ? undefined : 'numeric',
198
+ minute: dateOnly ? undefined : '2-digit',
199
+ hour12: true,
200
+ }).format(date);
201
+ }
202
+
203
+ /**
204
+ * Get full date with time
205
+ */
206
+
207
+ export function getFullDateTime(
208
+ d_: Date | string | number | null,
209
+ params?: Partial<{
210
+ timeZone: string | null;
211
+ locales: string;
212
+ hideYear: boolean;
213
+ hideDate: boolean;
214
+ hideTime: boolean;
215
+ textDateStyle: 'long' | 'short' | 'numeric' | null;
216
+ militaryTime: boolean;
217
+ alwaysShowYear: boolean;
218
+ includeWeekday: boolean | 'long' | 'short' | 'narrow';
219
+ }>,
220
+ ) {
221
+ const {
222
+ locales = 'en-US',
223
+ timeZone: timeZone_,
224
+ hideYear,
225
+ hideDate,
226
+ hideTime,
227
+ textDateStyle,
228
+ militaryTime,
229
+ alwaysShowYear,
230
+ includeWeekday,
231
+ } = params || {};
232
+
233
+ let d;
234
+ if (d_ instanceof Date) {
235
+ d = d_;
236
+ } else {
237
+ // Make sure d_ is not null, before using this function
238
+ d = d_ ? new Date(d_) : new Date(-1);
239
+ }
240
+
241
+ let timeZone = timeZone_ || undefined; // cannot be null, else it will throw error
242
+ if (timeZone && !isValidTimeZone(timeZone)) {
243
+ timeZone = undefined;
244
+ }
245
+
246
+ if (hideDate) {
247
+ return d.toLocaleTimeString(locales, {
248
+ timeZone,
249
+ hour: hideTime ? undefined : militaryTime ? '2-digit' : 'numeric',
250
+ minute: hideTime ? undefined : '2-digit',
251
+ hour12: !militaryTime,
252
+ });
253
+ }
254
+
255
+ // If year is same year, then don't show year
256
+ let hideYear_;
257
+ if (!hideYear && !alwaysShowYear) {
258
+ const dateYear = d.getFullYear();
259
+ const currentYear = new Date().getFullYear();
260
+ hideYear_ = dateYear === currentYear;
261
+ } else if (hideYear || hideDate) {
262
+ hideYear_ = true;
263
+ }
264
+
265
+ let weekday;
266
+ if (['long', 'short', 'narrow'].includes(includeWeekday as string)) {
267
+ weekday = includeWeekday;
268
+ } else if (includeWeekday) {
269
+ weekday = textDateStyle === 'long' ? 'long' : 'short';
270
+ }
271
+
272
+ return d.toLocaleDateString(locales, {
273
+ timeZone,
274
+ day: 'numeric',
275
+ weekday: weekday as 'long' | 'short' | 'narrow',
276
+ month: textDateStyle || 'numeric',
277
+ year: hideYear_ ? undefined : 'numeric',
278
+ hour: hideTime ? undefined : militaryTime ? '2-digit' : 'numeric',
279
+ minute: hideTime ? undefined : '2-digit',
280
+ hour12: !militaryTime,
281
+ });
282
+ }
283
+
284
+ /*
285
+ * Convert one canonical instant into the local value required by a
286
+ * datetime-local input in the requested scheduling timezone.
287
+ */
288
+ export function getDateTimeLocalInputValue(
289
+ value?: Date | string | number | null,
290
+ timeZone?: string | null,
291
+ ): string | null {
292
+ const date = value ? new Date(value) : null;
293
+ if (!date || !Number.isFinite(date.getTime())) {
294
+ return null;
295
+ }
296
+
297
+ const inputTimeZone =
298
+ timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
299
+ const { calDate, time } = getCalDate(date, inputTimeZone);
300
+ return `${calDate}T${time.slice(0, 5)}`;
301
+ }
302
+
303
+ /*
304
+ * Convert a datetime-local input value into its canonical ISO instant in the
305
+ * requested scheduling timezone.
306
+ */
307
+ export function normalizeDateTimeLocalInputValue(
308
+ value?: string | null,
309
+ timeZone?: string | null,
310
+ ): string | null {
311
+ const trimmedValue = String(value || '').trim();
312
+ if (
313
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/.test(
314
+ trimmedValue,
315
+ )
316
+ ) {
317
+ return null;
318
+ }
319
+
320
+ const inputTimeZone =
321
+ timeZone && isValidTimeZone(timeZone) ? timeZone : DEFAULT_TIMEZONE;
322
+ const parsedDate = parseDateInTimezone(trimmedValue, inputTimeZone, 0, true);
323
+ if (!Number.isFinite(parsedDate.getTime())) {
324
+ return null;
325
+ }
326
+
327
+ // Luxon advances nonexistent wall-clock times through daylight-saving gaps.
328
+ // A scheduler must reject that silent time change rather than save a
329
+ // different local time from the one the user entered.
330
+ const { calDate, time } = getCalDate(parsedDate, inputTimeZone);
331
+ if (`${calDate}T${time.slice(0, 5)}` !== trimmedValue.slice(0, 16)) {
332
+ return null;
333
+ }
334
+
335
+ return parsedDate.toISOString();
336
+ }
337
+
338
+ /**
339
+ * Check if date is same day
340
+ */
341
+
342
+ export function checkIfSameDay(d1: Date, d2: Date, checkTime: boolean = false) {
343
+ let date1, date2;
344
+ if (checkTime) {
345
+ date1 = new Date(
346
+ d1.getFullYear(),
347
+ d1.getMonth(),
348
+ d1.getDate(),
349
+ d1.getHours(),
350
+ d1.getMinutes(),
351
+ );
352
+ date2 = new Date(
353
+ d2.getFullYear(),
354
+ d2.getMonth(),
355
+ d2.getDate(),
356
+ d2.getHours(),
357
+ d2.getMinutes(),
358
+ );
359
+ } else {
360
+ date1 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate());
361
+ date2 = new Date(d2.getFullYear(), d2.getMonth(), d2.getDate());
362
+ }
363
+
364
+ return date1.getTime() === date2.getTime();
365
+ }
366
+
367
+ /**
368
+ * Return a sortable calendar-date key in the supplied computer timezone.
369
+ */
370
+
371
+ export function getLocalCalendarDateKey(
372
+ date_: Date | string | number,
373
+ timeZone?: string,
374
+ ) {
375
+ const date = date_ instanceof Date ? date_ : new Date(date_);
376
+ if (Number.isNaN(date.getTime())) {
377
+ return null;
378
+ }
379
+
380
+ const parts = new Intl.DateTimeFormat('en-US', {
381
+ timeZone,
382
+ year: 'numeric',
383
+ month: '2-digit',
384
+ day: '2-digit',
385
+ }).formatToParts(date);
386
+ const year = parts.find((part) => part.type === 'year')?.value;
387
+ const month = parts.find((part) => part.type === 'month')?.value;
388
+ const day = parts.find((part) => part.type === 'day')?.value;
389
+ if (!year || !month || !day) {
390
+ return null;
391
+ }
392
+
393
+ return `${year}-${month}-${day}`;
394
+ }
395
+
396
+ /**
397
+ * Format date label parts in the supplied computer timezone.
398
+ */
399
+
400
+ export function getLocalDayTimeParts(
401
+ date_: Date | string | number,
402
+ timeZone: string,
403
+ referenceDate: Date = new Date(),
404
+ locales: string = 'en-US',
405
+ ) {
406
+ const date = date_ instanceof Date ? date_ : new Date(date_);
407
+ if (Number.isNaN(date.getTime())) {
408
+ return null;
409
+ }
410
+
411
+ const dayText =
412
+ getLocalCalendarDateKey(date, timeZone) ===
413
+ getLocalCalendarDateKey(referenceDate, timeZone)
414
+ ? i18n.t('datetime.period_TODAY')
415
+ : new Intl.DateTimeFormat(locales, {
416
+ timeZone,
417
+ weekday: 'long',
418
+ }).format(date);
419
+ const timeText = new Intl.DateTimeFormat(locales, {
420
+ timeZone,
421
+ hour: 'numeric',
422
+ minute: '2-digit',
423
+ hour12: true,
424
+ }).format(date);
425
+
426
+ return {
427
+ dayText,
428
+ timeText,
429
+ };
430
+ }
431
+
432
+ /**
433
+ * Get today at start of day
434
+ */
435
+
436
+ export function getTodayStartOfDay(timeZone?: string | null) {
437
+ const startDate = getFullDateTime(new Date(), {
438
+ locales: 'en-US',
439
+ alwaysShowYear: true,
440
+ hideTime: true,
441
+ });
442
+
443
+ const today = parseDateInTimezone(startDate, timeZone);
444
+ return today;
445
+ }
446
+
447
+ /**
448
+ * Get timezone enforced calendar date
449
+ * @param d - Date to convert
450
+ * @param timeZone - Timezone to enforce
451
+ * @returns Date - Enforced calendar date in the specified timezone
452
+ */
453
+
454
+ export function getCalDate(d: Date, timeZone_?: string | null) {
455
+ const timeZone = timeZone_ || undefined;
456
+
457
+ let dt = DateTime.fromJSDate(d, { zone: timeZone });
458
+
459
+ // If timezone is invalid, fallback to system/local
460
+ if (!dt.isValid) {
461
+ dt = DateTime.fromJSDate(d); // system default zone
462
+ }
463
+
464
+ const calDate = dt.toFormat('yyyy-MM-dd');
465
+ const calDateInt = Number(dt.toFormat('yyyyMMdd'));
466
+ const time = dt.toFormat('HH:mm:ss');
467
+
468
+ return {
469
+ calDate,
470
+ calDateInt,
471
+ time,
472
+ };
473
+ }
474
+
475
+ /**
476
+ * Get timezone enforced calendar date; but month-day first
477
+ * @param d - Date to convert
478
+ * @param timeZone - Timezone to enforce
479
+ * @returns Date - Enforced calendar date in the specified timezone
480
+ */
481
+
482
+ export function getReadableCalDate(
483
+ d_: string | Date,
484
+ timeZone?: string | null,
485
+ locales?: string,
486
+ ) {
487
+ let isCalDateString = false;
488
+ let d;
489
+ if (typeof d_ === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(d_)) {
490
+ isCalDateString = true;
491
+ // Assume YYYY-MM-DD format
492
+ const [year, month, day] = d_.split('-').map(Number);
493
+ d = new Date(year, month - 1, day);
494
+ } else if (d_ instanceof Date) {
495
+ d = d_;
496
+ } else {
497
+ d = d_ && new Date(d_);
498
+ }
499
+
500
+ if (!d || isNaN(d.getTime())) {
501
+ return null;
502
+ }
503
+
504
+ // let dt = DateTime.fromJSDate(d, { zone: timeZone || undefined });
505
+ // // If timezone is invalid, fallback to system/local
506
+ // if (!dt.isValid) {
507
+ // dt = DateTime.fromJSDate(d); // system default zone
508
+ // }
509
+
510
+ // if (!dt.isValid) {
511
+ // return null;
512
+ // }
513
+
514
+ // return dt.toFormat('MM/dd/yyyy');
515
+
516
+ return new Intl.DateTimeFormat(locales || 'en-US', {
517
+ timeZone: isCalDateString ? undefined : timeZone || undefined, // null is not allowed, it will throw error
518
+ }).format(d);
519
+ }
520
+
521
+ /**
522
+ * Get fieldDoc period DateTime value with timezone support.
523
+ */
524
+
525
+ function getFieldDocPeriodDateTime(
526
+ period: string | Date,
527
+ timeZone: string | null,
528
+ ) {
529
+ const zone = timeZone || undefined;
530
+
531
+ if (typeof period === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(period)) {
532
+ const dt = DateTime.fromISO(period, zone ? { zone } : undefined);
533
+ return dt.isValid ? dt : null;
534
+ }
535
+
536
+ if (period instanceof Date) {
537
+ let dt = DateTime.fromJSDate(period, zone ? { zone } : undefined);
538
+ if (!dt.isValid) {
539
+ dt = DateTime.fromJSDate(period);
540
+ }
541
+ return dt.isValid ? dt : null;
542
+ }
543
+
544
+ const dt = DateTime.fromISO(String(period), zone ? { zone } : undefined);
545
+ return dt.isValid ? dt : null;
546
+ }
547
+
548
+ /**
549
+ * Format fieldDoc period range label.
550
+ */
551
+
552
+ function formatFieldDocPeriodRange(
553
+ start: DateTime,
554
+ end: DateTime,
555
+ separator: string,
556
+ ) {
557
+ if (start.year !== end.year) {
558
+ return `${start.toFormat('MMM d, yyyy')}${separator}${end.toFormat('MMM d, yyyy')}`;
559
+ }
560
+
561
+ if (start.month !== end.month) {
562
+ return `${start.toFormat('MMM d')}${separator}${end.toFormat('MMM d, yyyy')}`;
563
+ }
564
+
565
+ return `${start.toFormat('MMM d')}${separator}${end.toFormat('d, yyyy')}`;
566
+ }
567
+
568
+ /**
569
+ * Get formatted fieldDoc period label from period start and frequency.
570
+ */
571
+
572
+ export function getFieldDocPeriod(
573
+ period: string | Date,
574
+ frequency: any,
575
+ timeZone: string | null,
576
+ ) {
577
+ const start = getFieldDocPeriodDateTime(period, timeZone);
578
+ if (!start) {
579
+ return null;
580
+ }
581
+
582
+ switch (frequency) {
583
+ case 'DAILY':
584
+ return start.toFormat('MMM d, yyyy');
585
+ case 'WEEKLY':
586
+ return formatFieldDocPeriodRange(start, start.plus({ days: 6 }), '–');
587
+ case 'MONTHLY':
588
+ return formatFieldDocPeriodRange(
589
+ start,
590
+ start.plus({ months: 1 }).minus({ days: 1 }),
591
+ '-',
592
+ );
593
+ case 'QUARTERLY':
594
+ return formatFieldDocPeriodRange(
595
+ start,
596
+ start.plus({ months: 3 }).minus({ days: 1 }),
597
+ '-',
598
+ );
599
+ case 'ANNUALLY':
600
+ return formatFieldDocPeriodRange(
601
+ start,
602
+ start.plus({ years: 1 }).minus({ days: 1 }),
603
+ '-',
604
+ );
605
+ default:
606
+ return start.toFormat('MMM d, yyyy');
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Date objects create different calendar dates based on timezone,
612
+ * to avoid such issue, use this funciton to convert JS date to string format.
613
+ */
614
+
615
+ export function getReadableCalDateFromUTC(d: string | Date) {
616
+ if (typeof d === 'string') {
617
+ return getReadableCalDate(d);
618
+ }
619
+
620
+ const dStr = d.toISOString().split('T')[0]; // Get date part in YYYY-MM-DD format
621
+ return getReadableCalDate(dStr);
622
+ }
623
+
624
+ /**
625
+ * Update JS date with year/month/day and hour/minutes
626
+ */
627
+
628
+ export function updateDate(
629
+ d_: Date | string,
630
+ update: Partial<{
631
+ year: number;
632
+ month: number;
633
+ day: number;
634
+ hour: number;
635
+ minute: number;
636
+ }>,
637
+ timeZone?: string | null,
638
+ ): Date | null {
639
+ if (timeZone) {
640
+ // Use luxon to handle timezone-aware date manipulation
641
+ let dt = DateTime.fromJSDate(d_ instanceof Date ? d_ : new Date(d_), {
642
+ zone: timeZone,
643
+ });
644
+
645
+ if (update.year !== undefined) {
646
+ dt = dt.set({ year: update.year });
647
+ }
648
+ if (update.month !== undefined) {
649
+ dt = dt.set({ month: update.month });
650
+ }
651
+ if (update.day !== undefined) {
652
+ dt = dt.set({ day: update.day });
653
+ }
654
+ if (update.hour !== undefined) {
655
+ dt = dt.set({ hour: update.hour });
656
+ }
657
+ if (update.minute !== undefined) {
658
+ dt = dt.set({ minute: update.minute });
659
+ }
660
+
661
+ return dt.isValid ? dt.toJSDate() : null;
662
+ }
663
+
664
+ const d = d_ instanceof Date ? d_ : new Date(d_);
665
+
666
+ if (update.year) {
667
+ d.setFullYear(update.year);
668
+ }
669
+
670
+ if (update.month !== undefined) {
671
+ d.setMonth(update.month - 1); // JS months are 0-indexed
672
+ }
673
+
674
+ if (update.day) {
675
+ d.setDate(update.day);
676
+ }
677
+
678
+ if (update.hour !== undefined) {
679
+ d.setHours(update.hour);
680
+ }
681
+
682
+ if (update.minute !== undefined) {
683
+ d.setMinutes(update.minute);
684
+ }
685
+
686
+ return d;
687
+ }
688
+
689
+ /**
690
+ * Convert Int cal date to String YYYY-MM-DD format
691
+ */
692
+
693
+ export function convertIntToCalDate(
694
+ calDateInt: number | string,
695
+ delimiter: string = '-',
696
+ yearsFirst: boolean = true,
697
+ ): string {
698
+ const value = String(calDateInt);
699
+ if (value.length === 8) {
700
+ if (yearsFirst) {
701
+ return `${value.slice(0, 4)}${delimiter}${value.slice(4, 6)}${delimiter}${value.slice(6, 8)}`;
702
+ }
703
+ return `${value.slice(4, 6)}${delimiter}${value.slice(6, 8)}${delimiter}${value.slice(0, 4)}`;
704
+ }
705
+ // If not 8 digits, return as is
706
+ return value;
707
+ }
708
+
709
+ /**
710
+ * Check if cal date is valid
711
+ * @param calDate - Cal date in YYYYMMDD format
712
+ * @param minCalDate - Optional minimum cal date to check against (default is 19500101)
713
+ * @returns boolean - true if valid, false otherwise
714
+ */
715
+
716
+ export function isValidCalDate(
717
+ calDate_: string | number | bigint,
718
+ allowDashes: boolean = false,
719
+ minCalDate: number = 19500101,
720
+ ): boolean {
721
+ let calDate;
722
+ if (
723
+ allowDashes &&
724
+ typeof calDate_ === 'string' &&
725
+ /^\d{4}-\d{2}-\d{2}$/.test(calDate_)
726
+ ) {
727
+ calDate = calDate_.replace(/-/g, '');
728
+ } else {
729
+ calDate = calDate_;
730
+ }
731
+
732
+ const value = Number(calDate);
733
+ if (
734
+ !calDate ||
735
+ !Number.isInteger(value) ||
736
+ value < 10000000 ||
737
+ value > 90000000
738
+ ) {
739
+ return false;
740
+ }
741
+ return !minCalDate || value >= minCalDate;
742
+ }
743
+
744
+ /**
745
+ * Check cal date is not a future date
746
+ * @param calDateVal - Cal date in YYYYMMDD format
747
+ * @param addDays - Optional number of days to add to the current date for comparison (default is 0)
748
+ * @param timeZone - Optional timezone to check against
749
+ * @returns boolean - true if date is in the future, false otherwise
750
+ */
751
+
752
+ export function isFutureCalDate(
753
+ calDateVal: number | string,
754
+ addDays: number = 0,
755
+ timeZone?: string | null,
756
+ ): boolean {
757
+ if (!isValidCalDate(calDateVal)) {
758
+ return false;
759
+ }
760
+ const today = getCalDate(new Date(), timeZone);
761
+ return today.calDateInt + addDays < Number(calDateVal);
762
+ }
763
+
764
+ /**
765
+ * Get timezone-aware DateTime object from one date input.
766
+ */
767
+
768
+ function getDateTimeWithTimeZone(date: string | Date, timeZone: string | null) {
769
+ const zone = timeZone && isValidTimeZone(timeZone) ? timeZone : undefined;
770
+
771
+ if (date instanceof Date) {
772
+ const dt = DateTime.fromJSDate(date, zone ? { zone } : undefined);
773
+ return dt.isValid ? dt : null;
774
+ }
775
+
776
+ let dt = DateTime.fromISO(date, zone ? { zone } : undefined);
777
+ if (dt.isValid) {
778
+ return dt;
779
+ }
780
+
781
+ dt = DateTime.fromJSDate(new Date(date), zone ? { zone } : undefined);
782
+ return dt.isValid ? dt : null;
783
+ }
784
+
785
+ /**
786
+ * Convert today/yesterday date time into a label, with the time unless hidden
787
+ * @param dt - Parsed Luxon date time
788
+ * @param timeZone - Optional timezone for time formatting
789
+ * @param hideTime - Return only the day label
790
+ */
791
+
792
+ function getTodayYesterdayTime(
793
+ dt: DateTime,
794
+ now: DateTime,
795
+ timeZone: string | null,
796
+ hideTime?: boolean,
797
+ ) {
798
+ const dayKey = dt.hasSame(now, 'day')
799
+ ? 'datetime.period_TODAY'
800
+ : dt.hasSame(now.minus({ days: 1 }), 'day')
801
+ ? 'datetime.period_YESTERDAY'
802
+ : null;
803
+
804
+ if (!dayKey) {
805
+ return null;
806
+ }
807
+
808
+ if (hideTime) {
809
+ return i18n.t(dayKey);
810
+ }
811
+
812
+ const timeText = getFullDateTime(dt.toJSDate(), {
813
+ timeZone,
814
+ hideDate: true,
815
+ });
816
+ return `${i18n.t(dayKey)}, ${timeText}`;
817
+ }
818
+
819
+ /**
820
+ * Format a date time with a numeric month and day, adding a two-digit year only when it differs from the reference year.
821
+ * @param dt - Parsed Luxon date time
822
+ * @param now - Reference date time used to decide whether to show the year
823
+ * @param timeZone - Optional timezone for date and time formatting
824
+ * @param hideTime - Omit the hour and minute
825
+ */
826
+
827
+ function getCompactDateTime(
828
+ dt: DateTime,
829
+ now: DateTime,
830
+ timeZone: string | null,
831
+ hideTime?: boolean,
832
+ ) {
833
+ return new Intl.DateTimeFormat('en-US', {
834
+ day: 'numeric',
835
+ month: 'numeric',
836
+ timeZone: timeZone && isValidTimeZone(timeZone) ? timeZone : undefined,
837
+ year: dt.year === now.year ? undefined : '2-digit',
838
+ ...(hideTime ? {} : { hour: 'numeric', hour12: true, minute: '2-digit' }),
839
+ }).format(dt.toJSDate());
840
+ }
841
+
842
+ /**
843
+ * Format an edited timestamp as a compact or expanded relative label, falling back to YYYY/MM/DD.
844
+ * @param date - Date to format
845
+ * @param timeZone - Optional timezone for calendar-day comparisons
846
+ * @param longer - Return expanded relative units when true
847
+ */
848
+
849
+ export function getEditedTimeAgo(
850
+ date: string | Date,
851
+ timeZone?: string | null,
852
+ longer?: boolean,
853
+ ) {
854
+ const dt = getDateTimeWithTimeZone(date, timeZone || null);
855
+ if (!dt) {
856
+ return null;
857
+ }
858
+
859
+ const now =
860
+ timeZone && isValidTimeZone(timeZone)
861
+ ? DateTime.now().setZone(timeZone)
862
+ : DateTime.now();
863
+ const diffMinutes = now.diff(dt, 'minutes').minutes;
864
+
865
+ if (diffMinutes < 0) {
866
+ return dt.toFormat('yyyy/MM/dd');
867
+ }
868
+
869
+ if (diffMinutes <= 4) {
870
+ return i18n.t('datetime.just_now');
871
+ }
872
+
873
+ if (diffMinutes < 60) {
874
+ return i18n.t(
875
+ longer ? 'datetime.minutes_ago_ct' : 'datetime.minutes_ago_short_ct',
876
+ {
877
+ smart_count: Math.floor(diffMinutes),
878
+ },
879
+ );
880
+ }
881
+
882
+ const diffHours = diffMinutes / 60;
883
+ if (diffHours < 9) {
884
+ return i18n.t(
885
+ longer ? 'datetime.hours_ago_ct' : 'datetime.hours_ago_short_ct',
886
+ {
887
+ smart_count: Math.floor(diffHours),
888
+ },
889
+ );
890
+ }
891
+
892
+ if (dt.hasSame(now, 'day')) {
893
+ return i18n.t('datetime.today');
894
+ }
895
+
896
+ if (dt.hasSame(now.minus({ days: 1 }), 'day')) {
897
+ return i18n.t('datetime.yesterday');
898
+ }
899
+
900
+ const diffDays = now.startOf('day').diff(dt.startOf('day'), 'days').days;
901
+ if (diffDays < 7) {
902
+ return i18n.t(
903
+ longer ? 'datetime.days_ago_ct' : 'datetime.days_ago_short_ct',
904
+ {
905
+ smart_count: Math.floor(diffDays),
906
+ },
907
+ );
908
+ }
909
+
910
+ return dt.toFormat('yyyy/MM/dd');
911
+ }
912
+
913
+ /**
914
+ * Convert date time "time" ago: "Today, 10:21 PM", "Yesterday, 10:21 PM", or "9/14, 10:21 PM"
915
+ * @param date - Date to convert
916
+ * @param timeZone - Optional timezone for day boundary checks
917
+ * @param hideTime - Return only the day part ("Today", "Yesterday", "9/14") for narrow table cells
918
+ */
919
+
920
+ export function getTimeAgo(
921
+ date: string | Date,
922
+ timeZone: string | null,
923
+ hideTime?: boolean,
924
+ ) {
925
+ const dt = getDateTimeWithTimeZone(date, timeZone);
926
+ if (!dt) {
927
+ return null;
928
+ }
929
+
930
+ const now =
931
+ timeZone && isValidTimeZone(timeZone)
932
+ ? DateTime.now().setZone(timeZone)
933
+ : DateTime.now();
934
+ const todayYesterdayTime = getTodayYesterdayTime(dt, now, timeZone, hideTime);
935
+
936
+ if (todayYesterdayTime) {
937
+ return todayYesterdayTime;
938
+ }
939
+
940
+ return getCompactDateTime(dt, now, timeZone, hideTime);
941
+ }
942
+
943
+ /**
944
+ * Convert date to full date (readable string)
945
+ * type locales = 'en-US' | 'en-GB' | 'en-AU' | 'en-CA' | 'en-IN' | 'en-NZ' | 'en-ZA';
946
+ */
947
+
948
+ export function getFullDate(
949
+ d_: Date | string | number | null,
950
+ outputStyle_:
951
+ | 'NUMERIC'
952
+ | 'NUMERIC_TIME'
953
+ | 'NUMERIC_TIME_COMPACT'
954
+ | 'DATE_ONLY_SHORT'
955
+ | 'DAY_IF_WEEK'
956
+ | 'TOMORROW_OR_NUMERIC'
957
+ | 'DATE_TEXT'
958
+ | 'MINIMAL'
959
+ | 'DETAILED' = 'NUMERIC',
960
+ timeZone: string | null,
961
+ locales: string = 'en-US',
962
+ ) {
963
+ let d;
964
+ if (d_ instanceof Date) {
965
+ d = d_;
966
+ } else {
967
+ // Make sure d_ is not null, before using this function
968
+ d = d_ ? new Date(d_) : new Date(-1);
969
+ }
970
+
971
+ let outputStyle;
972
+ if (['TOMORROW_OR_NUMERIC', 'DAY_IF_WEEK'].includes(outputStyle_)) {
973
+ const datePeriod = getDatePeriod(d, new Date());
974
+ if (['TODAY', 'TOMORROW'].includes(datePeriod)) {
975
+ return i18n.t(`datetime.period_${datePeriod}`);
976
+ }
977
+
978
+ const daysRemaining = getDaysDiff(d, new Date());
979
+ if (daysRemaining >= 0 && daysRemaining <= 6) {
980
+ // return "Monday", "Tuesday", etc.
981
+ const dayOfWeekText = d.toLocaleDateString(locales, {
982
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
983
+ ...(outputStyle_ === 'TOMORROW_OR_NUMERIC'
984
+ ? {}
985
+ : {
986
+ weekday: 'long',
987
+ }),
988
+ });
989
+ return dayOfWeekText;
990
+ }
991
+
992
+ outputStyle = 'NUMERIC';
993
+ } else {
994
+ outputStyle = outputStyle_;
995
+ }
996
+
997
+ switch (outputStyle) {
998
+ case 'NUMERIC':
999
+ // Expected output: "9/1/2024"
1000
+ return new Intl.DateTimeFormat(locales, {
1001
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1002
+ }).format(d);
1003
+ case 'NUMERIC_TIME':
1004
+ case 'NUMERIC_TIME_COMPACT': {
1005
+ // Compact output: "9/01/2024, 8:30 PM"; default output: "9/1/2024, 8:30 PM".
1006
+ const compact = outputStyle === 'NUMERIC_TIME_COMPACT';
1007
+ const numericDate = new Intl.DateTimeFormat(locales, {
1008
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1009
+ ...(compact ? ({ month: 'numeric', day: '2-digit', year: 'numeric' } as const) : {}),
1010
+ }).format(d);
1011
+
1012
+ const numericTime = new Intl.DateTimeFormat(locales, {
1013
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1014
+ hour: 'numeric',
1015
+ minute: '2-digit',
1016
+ hour12: true,
1017
+ }).format(d);
1018
+
1019
+ const numericDateTime = `${numericDate}, ${numericTime}`;
1020
+ return compact ? numericDateTime.toUpperCase() : numericDateTime;
1021
+
1022
+ // return new Intl.DateTimeFormat(locales, {
1023
+ // month: '2-digit',
1024
+ // day: '2-digit',
1025
+ // year: 'numeric',
1026
+ // hour: 'numeric',
1027
+ // minute: '2-digit',
1028
+ // hour12: true,
1029
+ // timeZone: timeZone || undefined, // null is not allowed, it will throw error
1030
+ // }).format(d);
1031
+ }
1032
+ case 'MINIMAL':
1033
+ // Expected output: "Sep 1, 2024, 6:54 PM"
1034
+ return new Intl.DateTimeFormat(locales, {
1035
+ dateStyle: 'medium', // 'full', 'long', 'medium', 'short'
1036
+ timeStyle: 'short', // 'full', 'long', 'medium', 'short'
1037
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1038
+ }).format(d);
1039
+ // return DateTime.fromJSDate(d, timeZone ? { zone: timeZone } : undefined).toFormat('MMM d yyyy, h:mm a');
1040
+ case 'DATE_ONLY_SHORT': {
1041
+ // Expected output: "Sep 1" (or "Sep 1, 25" if not current year)
1042
+ const dateYear = d.getFullYear();
1043
+ const currentYear = new Date().getFullYear();
1044
+
1045
+ // This will crash because "medium" style with "numeric" year is not allowed
1046
+ // return new Intl.DateTimeFormat(locales, {
1047
+ // dateStyle: 'medium',
1048
+ // year: dateYear === currentYear ? undefined : 'numeric',
1049
+ // timeZone: timeZone || undefined, // null is not allowed, it will throw error
1050
+ // }).format(d);
1051
+
1052
+ if (dateYear === currentYear) {
1053
+ return new Intl.DateTimeFormat(locales, {
1054
+ year: undefined,
1055
+ month: 'short',
1056
+ day: 'numeric',
1057
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1058
+ }).format(d);
1059
+ }
1060
+
1061
+ return new Intl.DateTimeFormat(locales, {
1062
+ // Use this if you want 4 digit years
1063
+ // dateStyle: 'medium',
1064
+ // Use this if you want 2 digit years
1065
+ year: '2-digit',
1066
+ month: 'short',
1067
+ day: 'numeric',
1068
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1069
+ })
1070
+ .format(d)
1071
+ .replace(', ', ", '");
1072
+ }
1073
+ case 'DATE_TEXT':
1074
+ // Expected output: "September 1, 2024"
1075
+ return new Intl.DateTimeFormat(locales, {
1076
+ dateStyle: 'long',
1077
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1078
+ }).format(d);
1079
+ case 'DETAILED':
1080
+ default:
1081
+ }
1082
+
1083
+ // Expected output: "Sep 1, 2024 at 6:54 PM"
1084
+ const date = new Intl.DateTimeFormat(locales, {
1085
+ dateStyle: 'long', // 'full', 'long', 'medium', 'short'
1086
+ timeStyle: 'short', // 'full', 'long', 'medium', 'short'
1087
+ timeZone: timeZone || undefined, // null is not allowed, it will throw error
1088
+ }).format(d);
1089
+
1090
+ const parts = new Intl.DateTimeFormat(locales, {
1091
+ dateStyle: 'long',
1092
+ timeStyle: 'long',
1093
+ }).formatToParts(d);
1094
+
1095
+ const timezoneName = parts.find(
1096
+ (part) => part.type === 'timeZoneName',
1097
+ )?.value;
1098
+ if (timezoneName) {
1099
+ // Doing this will make sure {date} does not include [seconds] in the time format
1100
+ return date + ' ' + timezoneName;
1101
+ }
1102
+
1103
+ return date;
1104
+ }
1105
+
1106
+ /**
1107
+ * Get morning, afternoon, evening, or night
1108
+ */
1109
+
1110
+ export function getDayPeriod(): 'MORNING' | 'AFTERNOON' | 'EVENING' | 'NIGHT' {
1111
+ const d = new Date();
1112
+ const h = d.getHours();
1113
+ if (h >= 5 && h < 12) {
1114
+ return 'MORNING';
1115
+ } else if (h >= 12 && h < 17) {
1116
+ return 'AFTERNOON';
1117
+ } else if (h >= 17 && h < 20) {
1118
+ return 'EVENING';
1119
+ }
1120
+ return 'NIGHT';
1121
+ }
1122
+
1123
+ /**
1124
+ * Convert YYYY-MM-DD to Date
1125
+ */
1126
+
1127
+ export function getDateFromCalDate(
1128
+ value: string | number,
1129
+ timeZone?: string | null,
1130
+ ): Date {
1131
+ const calDate =
1132
+ typeof value === 'number' ? convertIntToCalDate(value) : value;
1133
+ const dt = DateTime.fromISO(
1134
+ calDate,
1135
+ timeZone ? { zone: timeZone } : undefined,
1136
+ );
1137
+ const jsDate = dt.toJSDate();
1138
+ // const [year, month, day] = calDate.split('-');
1139
+ // console.log(new Date(Number(year), Number(month) - 1, Number(day)));
1140
+ return jsDate;
1141
+ }
1142
+
1143
+ /**
1144
+ * Group by time period
1145
+ *
1146
+ * @param items - Array of items to group
1147
+ * @param dateKey - Key in each item that contains the date
1148
+ * @param mapFn - Optional function to map each item before grouping
1149
+ *
1150
+ * @returns Array of grouped items, each group contains items for a specific date period
1151
+ */
1152
+
1153
+ export function groupByDatePeriod<T>(
1154
+ items: T[],
1155
+ dateKey: string, // "." delimited getter is allowed here
1156
+ groupByDate?: boolean,
1157
+ timeZone?: string | null,
1158
+ mapFn?: (item: any) => any,
1159
+ ): DatePeriodObj[][] {
1160
+ const ordered = items.sort((a: any, b: any) => {
1161
+ const valueA = getObject(a, dateKey);
1162
+ const valueB = getObject(b, dateKey);
1163
+
1164
+ if (valueA < valueB) {
1165
+ return 1;
1166
+ }
1167
+ if (valueA > valueB) {
1168
+ return -1;
1169
+ }
1170
+ return 0;
1171
+ });
1172
+
1173
+ const output = [];
1174
+ const d = new Date();
1175
+ // const timeZone = timeZone_; // || Intl.DateTimeFormat().resolvedOptions().timeZone;
1176
+
1177
+ let group: any[] | null = [];
1178
+ for (const item of ordered) {
1179
+ // Each group is grouped in date periods,
1180
+ // e.g. "Tomorrow", "Today", "Yesterday", "Last Week", "Last Month", "Older"
1181
+ // Group the ordered list by date period and push item to output
1182
+
1183
+ const lastItem = group[group.length - 1];
1184
+ const lastDatePeriod: any = lastItem?.datePeriod;
1185
+ const date = new Date(getObject(item, dateKey));
1186
+ const datePeriod = groupByDate
1187
+ ? getCalDate(date, timeZone).calDate
1188
+ : getDatePeriod(date, d);
1189
+
1190
+ const dateObj = {
1191
+ datePeriod,
1192
+ date,
1193
+ item: mapFn ? mapFn(item) : item,
1194
+ };
1195
+
1196
+ if (lastDatePeriod && lastDatePeriod !== datePeriod && group.length) {
1197
+ output.push(group);
1198
+ group = [];
1199
+ }
1200
+
1201
+ group.push(dateObj);
1202
+ }
1203
+
1204
+ if (group.length) {
1205
+ output.push(group);
1206
+ }
1207
+
1208
+ return output;
1209
+ }
1210
+
1211
+ /**
1212
+ * Sort and label by date period
1213
+ *
1214
+ * @param items - Array of items to sort and label
1215
+ * @param dateKey - Key in each item that contains the date
1216
+ * @param mapFn - Optional function to map each item before grouping
1217
+ *
1218
+ * @returns Array of items sorted by date period, with labels for each period
1219
+ */
1220
+
1221
+ export function labelSortByDatePeriod<T>(
1222
+ items: T[],
1223
+ dateKey: string,
1224
+ groupByDate?: boolean,
1225
+ timeZone?: string | null,
1226
+ mapFn?: (item: any) => any,
1227
+ ): DatePeriodObj[] {
1228
+ const ordered: any[] = items.sort((a: any, b: any) => {
1229
+ const valueA = a[dateKey];
1230
+ const valueB = b[dateKey];
1231
+
1232
+ if (valueA < valueB) {
1233
+ return 1;
1234
+ }
1235
+ if (valueA > valueB) {
1236
+ return -1;
1237
+ }
1238
+ return 0;
1239
+ });
1240
+
1241
+ const output = [];
1242
+ const d = new Date();
1243
+
1244
+ for (const item of ordered) {
1245
+ const lastItem = output[output.length - 1];
1246
+ const lastDatePeriod: any = lastItem?.datePeriod;
1247
+ const date = new Date(item[dateKey]);
1248
+ const datePeriod = groupByDate
1249
+ ? getCalDate(date, timeZone).calDate
1250
+ : getDatePeriod(date, d);
1251
+
1252
+ const dateObj = {
1253
+ datePeriod,
1254
+ date,
1255
+ item: mapFn ? mapFn(item) : item,
1256
+ };
1257
+
1258
+ if (!output.length || (lastDatePeriod && lastDatePeriod !== datePeriod)) {
1259
+ output.push({
1260
+ datePeriod,
1261
+ date,
1262
+ item: null,
1263
+ });
1264
+ }
1265
+
1266
+ output.push(dateObj);
1267
+ }
1268
+
1269
+ return output as DatePeriodObj[];
1270
+ }
1271
+
1272
+ /**
1273
+ * Check if date is valid
1274
+ */
1275
+
1276
+ export function isValidDate(d?: Date | string | number | null) {
1277
+ if (d instanceof Date) {
1278
+ return !isNaN(d.getTime());
1279
+ }
1280
+ if (typeof d === 'string' || typeof d === 'number') {
1281
+ const date = new Date(d);
1282
+ return !isNaN(date.getTime());
1283
+ }
1284
+ return false;
1285
+ }
1286
+
1287
+ /**
1288
+ * Get HHMM in increments
1289
+ */
1290
+
1291
+ export function getHHMMIncrements(
1292
+ d: Date,
1293
+ minutesIncrement: number,
1294
+ utc: boolean = false,
1295
+ ) {
1296
+ let hh, minutes;
1297
+ if (utc) {
1298
+ hh = d.getUTCHours().toString().padStart(2, '0');
1299
+ minutes = d.getUTCMinutes();
1300
+ } else {
1301
+ hh = d.getHours().toString().padStart(2, '0');
1302
+ minutes = d.getMinutes();
1303
+ }
1304
+
1305
+ const interval = Math.floor(minutes / minutesIncrement) * minutesIncrement;
1306
+ const hhmm = `${hh}${interval.toString().padStart(2, '0')}`;
1307
+
1308
+ return hhmm;
1309
+ }
1310
+
1311
+ /**
1312
+ * Get color indicator based on expiration date
1313
+ * @param expirationDate - Expiration date in YYYY-MM-DD format or Date object
1314
+ * @returns 'red' | 'yellow' | 'green' | null
1315
+ */
1316
+
1317
+ export function getExpirationColor(
1318
+ expirationDate: string | Date, // YYYY-MM-DD format or Date object
1319
+ validColor: 'green' | null = null,
1320
+ ): 'red' | 'yellow' | 'green' | null {
1321
+ let expDate: Date;
1322
+ if (expirationDate instanceof Date) {
1323
+ expDate = expirationDate;
1324
+ } else {
1325
+ expDate = new Date(expirationDate);
1326
+ }
1327
+
1328
+ if (!isValidDate(expDate)) {
1329
+ return 'red'; // Invalid date
1330
+ }
1331
+
1332
+ const now = new Date();
1333
+ const diff = expDate.getTime() - now.getTime();
1334
+ const diffDays = Math.ceil(diff / (1000 * 3600 * 24));
1335
+
1336
+ if (diffDays < 0) {
1337
+ return 'red'; // Expired
1338
+ } else if (diffDays <= 30) {
1339
+ return 'yellow'; // Expiring soon
1340
+ }
1341
+
1342
+ return validColor; // Valid
1343
+ }
1344
+
1345
+ /**
1346
+ * Get HHMM time from "hh:mm" string
1347
+ */
1348
+
1349
+ export function timeToHHMM(timeStr: string): string {
1350
+ const [hh, mm] = timeStr.split(':');
1351
+ if (hh && mm) {
1352
+ return `${hh.padStart(2, '0')}${mm.padStart(2, '0')}`;
1353
+ }
1354
+ return timeStr.padStart(4, '0');
1355
+ }
1356
+
1357
+ /**
1358
+ * Sort & group by date/month
1359
+ */
1360
+
1361
+ export function groupByDateMonth<T extends { date: Date }>(
1362
+ items: T[],
1363
+ timeZone: string,
1364
+ ): {
1365
+ byDate: Record<string, T[]>;
1366
+ byMonth: Record<string, T[]>;
1367
+ } {
1368
+ // 1. Sort by absolute time
1369
+ const sorted = [...items].sort((a, b) => a.date.getTime() - b.date.getTime());
1370
+
1371
+ const byDate: Record<string, T[]> = {};
1372
+ const byMonth: Record<string, T[]> = {};
1373
+
1374
+ for (const item of sorted) {
1375
+ const dt = DateTime.fromJSDate(item.date, { zone: timeZone });
1376
+
1377
+ const dateKey = dt.toFormat('yyyy-MM-dd');
1378
+ const monthKey = dt.toFormat('yyyy-MM');
1379
+
1380
+ // Group by day
1381
+ if (!byDate[dateKey]) {
1382
+ byDate[dateKey] = [];
1383
+ }
1384
+ byDate[dateKey].push(item);
1385
+
1386
+ // Group by month
1387
+ if (!byMonth[monthKey]) {
1388
+ byMonth[monthKey] = [];
1389
+ }
1390
+ byMonth[monthKey].push(item);
1391
+ }
1392
+
1393
+ return { byDate, byMonth };
1394
+ }