@open-tender/utils 0.0.1

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 (67) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +3 -0
  3. package/dist/cjs/index.d.ts +1 -0
  4. package/dist/cjs/index.js +4 -0
  5. package/dist/cjs/utils/cards.d.ts +20 -0
  6. package/dist/cjs/utils/cards.js +153 -0
  7. package/dist/cjs/utils/cart.d.ts +422 -0
  8. package/dist/cjs/utils/cart.js +848 -0
  9. package/dist/cjs/utils/checkout.d.ts +23 -0
  10. package/dist/cjs/utils/checkout.js +108 -0
  11. package/dist/cjs/utils/constants.d.ts +52 -0
  12. package/dist/cjs/utils/constants.js +58 -0
  13. package/dist/cjs/utils/customer.d.ts +3 -0
  14. package/dist/cjs/utils/customer.js +23 -0
  15. package/dist/cjs/utils/datetimes.d.ts +174 -0
  16. package/dist/cjs/utils/datetimes.js +704 -0
  17. package/dist/cjs/utils/errors.d.ts +48 -0
  18. package/dist/cjs/utils/errors.js +143 -0
  19. package/dist/cjs/utils/helpers.d.ts +30 -0
  20. package/dist/cjs/utils/helpers.js +141 -0
  21. package/dist/cjs/utils/index.d.ts +14 -0
  22. package/dist/cjs/utils/index.js +17 -0
  23. package/dist/cjs/utils/keypad.d.ts +9 -0
  24. package/dist/cjs/utils/keypad.js +105 -0
  25. package/dist/cjs/utils/maps.d.ts +264 -0
  26. package/dist/cjs/utils/maps.js +287 -0
  27. package/dist/cjs/utils/orders.d.ts +40 -0
  28. package/dist/cjs/utils/orders.js +191 -0
  29. package/dist/cjs/utils/refunds.d.ts +35 -0
  30. package/dist/cjs/utils/refunds.js +98 -0
  31. package/dist/cjs/utils/rewards.d.ts +18 -0
  32. package/dist/cjs/utils/rewards.js +69 -0
  33. package/dist/cjs/utils/version.d.ts +4 -0
  34. package/dist/cjs/utils/version.js +38 -0
  35. package/dist/esm/index.d.ts +1 -0
  36. package/dist/esm/index.js +1 -0
  37. package/dist/esm/utils/cards.d.ts +20 -0
  38. package/dist/esm/utils/cards.js +144 -0
  39. package/dist/esm/utils/cart.d.ts +422 -0
  40. package/dist/esm/utils/cart.js +805 -0
  41. package/dist/esm/utils/checkout.d.ts +23 -0
  42. package/dist/esm/utils/checkout.js +100 -0
  43. package/dist/esm/utils/constants.d.ts +52 -0
  44. package/dist/esm/utils/constants.js +55 -0
  45. package/dist/esm/utils/customer.d.ts +3 -0
  46. package/dist/esm/utils/customer.js +18 -0
  47. package/dist/esm/utils/datetimes.d.ts +174 -0
  48. package/dist/esm/utils/datetimes.js +631 -0
  49. package/dist/esm/utils/errors.d.ts +48 -0
  50. package/dist/esm/utils/errors.js +135 -0
  51. package/dist/esm/utils/helpers.d.ts +30 -0
  52. package/dist/esm/utils/helpers.js +117 -0
  53. package/dist/esm/utils/index.d.ts +14 -0
  54. package/dist/esm/utils/index.js +14 -0
  55. package/dist/esm/utils/keypad.d.ts +9 -0
  56. package/dist/esm/utils/keypad.js +97 -0
  57. package/dist/esm/utils/maps.d.ts +264 -0
  58. package/dist/esm/utils/maps.js +269 -0
  59. package/dist/esm/utils/orders.d.ts +40 -0
  60. package/dist/esm/utils/orders.js +171 -0
  61. package/dist/esm/utils/refunds.d.ts +35 -0
  62. package/dist/esm/utils/refunds.js +90 -0
  63. package/dist/esm/utils/rewards.d.ts +18 -0
  64. package/dist/esm/utils/rewards.js +63 -0
  65. package/dist/esm/utils/version.d.ts +4 -0
  66. package/dist/esm/utils/version.js +34 -0
  67. package/package.json +65 -0
@@ -0,0 +1,631 @@
1
+ import { parseISO, add, sub, differenceInMinutes, differenceInSeconds } from 'date-fns';
2
+ import { format, toDate, zonedTimeToUtc, utcToZonedTime } from 'date-fns-tz';
3
+ /* CONSTANTS */
4
+ const DATE = 'yyyy-MM-dd';
5
+ const HUMAN_DATE = 'MMM d, yyyy';
6
+ const DATETIME = 'yyyy-MM-dd h:mma';
7
+ const TIME = 'h:mma';
8
+ export const timezoneMap = {
9
+ 'US/Eastern': 'America/New_York',
10
+ 'US/Central': 'America/Chicago',
11
+ 'US/Mountain': 'America/Denver',
12
+ 'US/Pacific': 'America/Los_Angeles'
13
+ };
14
+ export const weekdays = [
15
+ 'Sunday',
16
+ 'Monday',
17
+ 'Tuesday',
18
+ 'Wednesday',
19
+ 'Thursday',
20
+ 'Friday',
21
+ 'Saturday'
22
+ ];
23
+ export const weekdaysUpper = weekdays.map(weekday => weekday.toUpperCase());
24
+ export const weekdaysLower = weekdays.map(weekday => weekday.toLowerCase());
25
+ export const weekdayOptions = weekdays.map(weekday => ({
26
+ value: weekday.toUpperCase(),
27
+ name: weekday
28
+ }));
29
+ export const makeWeekday = (date = new Date()) => {
30
+ return format(date, 'EEEE').toUpperCase();
31
+ };
32
+ export const minutesLeft = (start, end) => {
33
+ return Math.max(differenceInMinutes(start, end), 0);
34
+ };
35
+ export const secondsLeft = (start, end) => {
36
+ return Math.max(differenceInSeconds(start, end), 0);
37
+ };
38
+ export const secondsToTime = (seconds) => {
39
+ const mins = Math.floor(seconds / 60);
40
+ const secs = `${seconds % 60}`.padStart(2, '0');
41
+ return `${mins}:${secs}`;
42
+ };
43
+ export const timeLeft = (start, end) => {
44
+ const seconds = secondsLeft(start, end);
45
+ return secondsToTime(seconds);
46
+ };
47
+ export const dateForWeekday = (weekday) => {
48
+ const currentWeekday = makeWeekday();
49
+ const currentIndex = weekdaysUpper.findIndex(i => i === currentWeekday);
50
+ const index = weekdaysUpper.findIndex(i => i === weekday.toUpperCase());
51
+ const offset = index - currentIndex + (index >= currentIndex ? 0 : 7);
52
+ return add(new Date(), { days: offset });
53
+ };
54
+ export const weekdayAndTimeToDate = (weekday, timeStr) => {
55
+ const date = dateForWeekday(weekday);
56
+ const [hours, minutes] = timeStr.split(':').map(i => parseInt(i));
57
+ return setTimeForDate(date, hours, minutes);
58
+ };
59
+ /* HELPERS */
60
+ export const parseIsoToDate = (iso) => parseISO(iso);
61
+ export const fmtDate = (date, fmt) => {
62
+ return format(date, fmt);
63
+ };
64
+ // https://stackoverflow.com/questions/54555491/how-to-guess-users-timezone-using-date-fns-in-a-vuejs-app
65
+ export const getUserTimezone = () => {
66
+ try {
67
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
68
+ }
69
+ catch (err) {
70
+ return 'America/New_York';
71
+ }
72
+ };
73
+ export const makeLocalDate = (dateStr) => {
74
+ const tz = getUserTimezone();
75
+ return toDate(dateStr, { timeZone: tz });
76
+ };
77
+ export const zonedTimeToDate = (str, timezone) => {
78
+ const tz = timezoneMap[timezone];
79
+ return toDate(str.split('.')[0], { timeZone: tz });
80
+ };
81
+ export const zonedTimeToDateStr = (str, timezone, fmt = DATE) => {
82
+ const date = zonedTimeToDate(str, timezone);
83
+ return format(date, fmt);
84
+ };
85
+ // returns a date string in a user's local time
86
+ export const makeLocalDateStr = (date, days = 0, fmt = DATE) => {
87
+ return format(add(date || new Date(), { days: days }), fmt);
88
+ };
89
+ export const todayDate = () => makeLocalDateStr();
90
+ export const tomorrowDate = () => makeLocalDateStr(null, 1);
91
+ export const isoToDate = (iso, tz) => {
92
+ return tz ? utcToZonedTime(parseISO(iso), tz) : parseISO(iso);
93
+ };
94
+ export const isoToDateStr = (iso, tz, fmt = DATETIME) => {
95
+ return format(isoToDate(iso, tz), fmt);
96
+ };
97
+ export const cleanISOString = (date) => {
98
+ return (date.toISOString().split('.')[0] + 'Z');
99
+ };
100
+ export const dateToIso = (date, tz) => {
101
+ return cleanISOString(zonedTimeToUtc(date, tz));
102
+ };
103
+ export const adjustIso = (iso, tz, adjustment) => {
104
+ const date = isoToDate(iso, tz);
105
+ return dateToIso(add(date, adjustment), tz);
106
+ };
107
+ export const adjustZonedIso = (zonedIso, tz, adjustment) => {
108
+ const adjusted = add(toDate(zonedIso), adjustment);
109
+ const zoned = utcToZonedTime(adjusted, tz);
110
+ const dateStr = format(zoned, "yyyy-MM-dd'T'HH:mm:ssXXX", { timeZone: tz });
111
+ return dateStr;
112
+ };
113
+ export const dateToZonedDateStr = (date, tz, fmt = "yyyy-MM-dd'T'HH:mm:ssXXX") => {
114
+ const zoned = utcToZonedTime(date, tz);
115
+ return format(zoned, fmt, { timeZone: tz });
116
+ };
117
+ export const dateToZonedIso = (date, tz) => {
118
+ const zoned = utcToZonedTime(date, tz);
119
+ return format(zoned, "yyyy-MM-dd'T'HH:mm:ssXXX", { timeZone: tz });
120
+ };
121
+ export const currentLocalDate = (tz) => {
122
+ const date = new Date();
123
+ return isoToDate(date.toISOString(), tz);
124
+ };
125
+ export const currentLocalDateStr = (tz, fmt = DATE) => {
126
+ const date = new Date();
127
+ return format(isoToDate(date.toISOString(), tz), fmt);
128
+ };
129
+ export const dateStrToDate = (str) => toDate(str);
130
+ export const dateStrToZonedDate = (str, tz) => {
131
+ return toDate(str, { timeZone: tz });
132
+ };
133
+ export const dateStrToZonedWeekday = (str) => {
134
+ return makeWeekday(toDate(str));
135
+ };
136
+ export const formatDateStr = (str, fmt = HUMAN_DATE) => {
137
+ return str ? format(toDate(str), fmt) : null;
138
+ };
139
+ export const formatTimeStr = (str) => {
140
+ const clean = str.replace(/\s/g, '').toLowerCase();
141
+ const parts = clean.split('-');
142
+ if (parts.length === 1)
143
+ return clean;
144
+ const [part1, part2] = parts;
145
+ const end1 = part1.substr(part1.length - 2);
146
+ const end2 = part2.substr(part1.length - 2);
147
+ const newPart1 = ['am', 'pm'].includes(end1) && end1 === end2
148
+ ? part1.slice(0, part1.length - 2)
149
+ : part1;
150
+ return [newPart1, part2].join('-');
151
+ };
152
+ export const dateStrMinutesToIso = (dateStr, minutes, tz) => {
153
+ const orderDate = tz ? toDate(dateStr, { timeZone: tz }) : toDate(dateStr);
154
+ const hours = Math.floor(minutes / 60);
155
+ const mins = minutes % 60;
156
+ const orderDateTime = setTimeForDate(orderDate, hours, mins);
157
+ return tz ? dateToIso(orderDateTime, tz) : cleanISOString(orderDateTime);
158
+ };
159
+ export const isoToDateStrMinutes = (iso, tz) => {
160
+ const dateObj = isoToDate(iso, tz);
161
+ const minutes = getMinutesfromDate(dateObj);
162
+ const date = format(dateObj, DATE);
163
+ return { date, minutes };
164
+ };
165
+ export const makeReadableDateStrFromIso = (iso, tz, verbose = false) => {
166
+ if (!iso || iso.toLowerCase() === 'asap')
167
+ return 'ASAP';
168
+ const date = utcToZonedTime(parseISO(iso), tz);
169
+ const timeString = format(date, TIME).toLowerCase();
170
+ const dateString = makeLocalDateStr(date);
171
+ if (dateString === todayDate()) {
172
+ return verbose ? `Today @ ${timeString}` : timeString;
173
+ }
174
+ else if (dateString === tomorrowDate()) {
175
+ return `${verbose ? 'Tomorrow' : 'Tmrw'} @ ${timeString}`;
176
+ }
177
+ else {
178
+ return `${verbose ? format(date, 'EEE, MMM d') : format(date, 'M/d')} @ ${timeString}`;
179
+ }
180
+ };
181
+ export const makeRequestedIso = (requestedAt) => {
182
+ return !requestedAt || requestedAt === 'asap'
183
+ ? cleanISOString(new Date())
184
+ : requestedAt;
185
+ };
186
+ export const makeRequestedAtStr = (requestedAt, tz, verbose = false) => {
187
+ if (!requestedAt || requestedAt.toLowerCase() === 'asap')
188
+ return 'ASAP';
189
+ return makeReadableDateStrFromIso(requestedAt, tz, verbose);
190
+ };
191
+ export const makeEstimatedTime = (requestedAt, revenueCenter, serviceType, verbose = false) => {
192
+ var _a, _b;
193
+ if (requestedAt !== 'asap' || !serviceType || !revenueCenter)
194
+ return null;
195
+ const settings = revenueCenter.settings || revenueCenter;
196
+ const { first_times } = settings;
197
+ if (!first_times)
198
+ return null;
199
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
200
+ const firstTime = first_times[st];
201
+ if ((firstTime === null || firstTime === void 0 ? void 0 : firstTime.date) === todayDate()) {
202
+ return `around ${firstTime.time}`;
203
+ }
204
+ else if ((firstTime === null || firstTime === void 0 ? void 0 : firstTime.date) === tomorrowDate()) {
205
+ return `tomorrow @ ${formatTimeStr(firstTime === null || firstTime === void 0 ? void 0 : firstTime.time)}`;
206
+ }
207
+ else {
208
+ const tz = timezoneMap[(_a = revenueCenter.timezone) !== null && _a !== void 0 ? _a : 'US/Eastern'];
209
+ const date = toDate((_b = firstTime === null || firstTime === void 0 ? void 0 : firstTime.date) !== null && _b !== void 0 ? _b : new Date(), { timeZone: tz });
210
+ return `${verbose ? format(date, 'EEEE, MMMM d') : format(date, 'M/d')} @ ${firstTime === null || firstTime === void 0 ? void 0 : firstTime.time}`;
211
+ }
212
+ };
213
+ function* range(start, end, step) {
214
+ for (let i = start; i <= end; i += step) {
215
+ yield i;
216
+ }
217
+ }
218
+ export const makeOppositeTimes = (times, interval, min = 0, max = 1440) => {
219
+ return [...range(min, max - interval, interval)].filter(i => !times.includes(i));
220
+ };
221
+ export const makeWeekdaysExcluded = (validTimes) => {
222
+ return Object.entries(validTimes).reduce((obj, entry) => {
223
+ const [weekday, dayparts] = entry;
224
+ const orderableDayparts = dayparts.filter(d => d.is_orderable);
225
+ if (!orderableDayparts.length) {
226
+ obj[weekday.toUpperCase()] = null;
227
+ return obj;
228
+ }
229
+ const interval = orderableDayparts[0].interval;
230
+ const orderableTimes = orderableDayparts.reduce((all, daypart) => {
231
+ var _a, _b;
232
+ return all.concat((_b = (_a = daypart.times) === null || _a === void 0 ? void 0 : _a.filter(i => i.is_orderable).map(i => i.minutes)) !== null && _b !== void 0 ? _b : []);
233
+ }, []);
234
+ obj[weekday.toUpperCase()] = makeOppositeTimes(orderableTimes, interval);
235
+ return obj;
236
+ }, {});
237
+ };
238
+ export const makeClosedWeekdays = (weekdayTimes) => {
239
+ return Object.entries(weekdayTimes)
240
+ .filter(([, times]) => !times)
241
+ .map(([weekday]) => weekdaysUpper.indexOf(weekday));
242
+ };
243
+ export const time24ToMinutes = (str) => {
244
+ const [hours, minutes] = str.split(':');
245
+ return parseInt(hours) * 60 + parseInt(minutes);
246
+ };
247
+ export const setTimeForDate = (date, hours, minutes, seconds = 0) => {
248
+ date.setHours(hours);
249
+ date.setMinutes(minutes);
250
+ date.setSeconds(seconds);
251
+ date.setMilliseconds(0);
252
+ return date;
253
+ };
254
+ export const minutesToDate = (minutes, date) => {
255
+ const hours = Math.floor(minutes / 60);
256
+ const mins = minutes % 60;
257
+ const dateCloned = date ? new Date(date.getTime()) : new Date();
258
+ return setTimeForDate(dateCloned, hours, mins);
259
+ };
260
+ export const time24ToDate = (str) => {
261
+ const minutes = time24ToMinutes(str);
262
+ return minutesToDate(minutes);
263
+ };
264
+ export const time24ToDateStr = (str, fmt = TIME) => {
265
+ const minutes = time24ToMinutes(str);
266
+ return format(minutesToDate(minutes), fmt).replace(':00', '').toLowerCase();
267
+ };
268
+ export const minutesToDates = (minutes, date) => {
269
+ return minutes.map(minute => {
270
+ return minutesToDate(minute, date);
271
+ });
272
+ };
273
+ export const getMinutesfromDate = (date) => {
274
+ return date.getHours() * 60 + date.getMinutes();
275
+ };
276
+ export const getNextIntervalMinutes = (minutes, interval) => {
277
+ const hours = Math.floor(minutes / 60);
278
+ const mins = minutes % 60;
279
+ const intervals = interval === 15 ? [0, 15, 30, 45, 60] : [0, 30, 60];
280
+ const nextMinute = intervals.filter(i => i >= mins)[0];
281
+ return hours * 60 + nextMinute;
282
+ };
283
+ // start and end should be submitted as minutes (integers)
284
+ export const makeTimeIntervals = (date, start, end, interval, excludeTimes = []) => {
285
+ const nextStart = getNextIntervalMinutes(start, interval);
286
+ const excluded = excludeTimes.map(i => getMinutesfromDate(i));
287
+ const minutes = [...range(nextStart, end, interval)].filter(i => !excluded.includes(i));
288
+ const dates = minutesToDates(minutes, date);
289
+ return dates.map(d => ({ label: format(d, 'h:mm aa'), value: d }));
290
+ };
291
+ export const makeDates = (startDateStr, days, fmt = HUMAN_DATE) => {
292
+ const startDate = dateStrToDate(startDateStr);
293
+ const dateArray = [];
294
+ for (let step = 0; step < days + 1; step++) {
295
+ const nextDate = add(startDate, { days: step });
296
+ const value = format(nextDate, DATE);
297
+ const label = value === todayDate()
298
+ ? 'Today'
299
+ : value === tomorrowDate()
300
+ ? 'Tomorrow'
301
+ : format(nextDate, fmt);
302
+ dateArray.push({ label, value });
303
+ }
304
+ return dateArray;
305
+ };
306
+ export const makeTimes = (date, firstTime, validTimes, holidays, serviceType) => {
307
+ var _a;
308
+ const weekday = dateStrToZonedWeekday(date);
309
+ let times = null;
310
+ const holiday = holidays
311
+ ? holidays[date]
312
+ : null;
313
+ if (holiday) {
314
+ times = holiday[serviceType] ? (_a = holiday[serviceType]) === null || _a === void 0 ? void 0 : _a.valid_times : null;
315
+ }
316
+ else {
317
+ const validTime = validTimes[serviceType];
318
+ times = validTime ? validTime[weekday] : null;
319
+ }
320
+ if (!times)
321
+ return null;
322
+ // if first available date, remove times before first available time
323
+ if (date === firstTime.date) {
324
+ times = times.filter(t => t.minutes >= firstTime.minutes);
325
+ }
326
+ return times.map(t => ({
327
+ name: t.time,
328
+ value: t.minutes,
329
+ disabled: !t.is_orderable
330
+ }));
331
+ };
332
+ export const makeDatepickerArgs = (requestedAtDate, weekdayTimes, excludedTimes, firstTimes, interval = 15, daysAhead) => {
333
+ const minDate = dateStrToDate(firstTimes.date);
334
+ const maxDate = daysAhead != null ? add(new Date(), { days: daysAhead }) : null;
335
+ const currentDate = requestedAtDate || new Date();
336
+ const weekday = format(currentDate, 'EEEE').toUpperCase();
337
+ const dateStr = format(currentDate, 'yyyy-MM-dd');
338
+ const minutes = requestedAtDate ? getMinutesfromDate(requestedAtDate) : null;
339
+ const isToday = dateStr === todayDate();
340
+ /* if today, excluded all times before the first minute */
341
+ const lastTime = Math.ceil((firstTimes.minutes - interval) / interval) * interval;
342
+ const todayExcludeded = isToday ? [...range(0, lastTime, interval)] : [];
343
+ /* weekdayExcluded = times excluded based on regular hours + blocked hours */
344
+ const weekdayExcluded = weekdayTimes[weekday] || [];
345
+ /* otherExcluded = times excluded due to holiday hours + throttled times */
346
+ const otherExcluded = excludedTimes[dateStr] || [];
347
+ const allExcluded = [
348
+ ...new Set([...todayExcludeded, ...weekdayExcluded, ...otherExcluded])
349
+ ].sort();
350
+ const orderableTimes = makeOppositeTimes(allExcluded, interval);
351
+ const minOrderableTime = Math.min(...orderableTimes);
352
+ // minTime and maxTime aren't necessary because they're already
353
+ // blocked out by the exluded times
354
+ // const minTime = minutesToDate(minOrderableTime)
355
+ // const maxOrderableTime = Math.max(...orderableTimes)
356
+ // const maxTime = minutesToDate(maxOrderableTime)
357
+ let updatedDate = null;
358
+ if (minutes && allExcluded.includes(minutes)) {
359
+ updatedDate = new Date(requestedAtDate.getTime());
360
+ updatedDate.setHours(Math.floor(minOrderableTime / 60));
361
+ updatedDate.setMinutes(minOrderableTime % 60);
362
+ }
363
+ /* TODO: figure out how to use this to hide times before open & after close */
364
+ // const minOrderableTime = Math.min(...orderableTimes)
365
+ // const maxOrderableTime = Math.max(...orderableTimes)
366
+ // const adjustedExcluded = makeOppositeTimes(
367
+ // orderableTimes,
368
+ // interval,
369
+ // minOrderableTime,
370
+ // maxOrderableTime
371
+ // )
372
+ // const injectTimes = minutesToDates(orderableTimes)
373
+ // const excludeTimes = minutesToDates(adjustedExcluded)
374
+ /* convert excluded minutes to excluded dates */
375
+ const excludeTimes = minutesToDates(allExcluded);
376
+ /* filter out days of the week that are always closed */
377
+ const closedWeekdays = makeClosedWeekdays(weekdayTimes);
378
+ const isClosed = (date) => {
379
+ return !closedWeekdays.includes(date.getDay());
380
+ };
381
+ return { excludeTimes, isClosed, updatedDate, minDate, maxDate };
382
+ };
383
+ export const makeDatePickerTimes = (settings, serviceType, date) => {
384
+ var _a, _b;
385
+ if (!date)
386
+ return { excludeTimes: [], interval: 15 };
387
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
388
+ const interval = (_a = settings.first_times[st]) === null || _a === void 0 ? void 0 : _a.interval;
389
+ const firstTimes = settings.first_times[st];
390
+ const excludedTimes = settings.excluded_times
391
+ ? settings.excluded_times[st]
392
+ : {};
393
+ const validTimes = settings.valid_times[st];
394
+ const weekdayTimes = makeWeekdaysExcluded(validTimes !== null && validTimes !== void 0 ? validTimes : {});
395
+ const weekday = format(date, 'EEEE').toUpperCase();
396
+ const dateStr = format(date, 'yyyy-MM-dd');
397
+ const isToday = dateStr === todayDate();
398
+ /* if today, excluded all times before the first minute */
399
+ const lastTime = Math.ceil((((_b = firstTimes === null || firstTimes === void 0 ? void 0 : firstTimes.minutes) !== null && _b !== void 0 ? _b : 0) - (interval !== null && interval !== void 0 ? interval : 0)) / (interval !== null && interval !== void 0 ? interval : 1)) * (interval !== null && interval !== void 0 ? interval : 0);
400
+ const todayExcludeded = isToday ? [...range(0, lastTime, interval !== null && interval !== void 0 ? interval : 0)] : [];
401
+ /* weekdayExcluded = times excluded based on regular hours + blocked hours */
402
+ const weekdayExcluded = weekdayTimes[weekday] || [];
403
+ /* otherExcluded = times excluded due to holiday hours + throttled times */
404
+ const otherExcluded = excludedTimes[dateStr] || [];
405
+ /* combine exclued times, remove duplicates and sort */
406
+ const allExcluded = [
407
+ ...new Set([...todayExcludeded, ...weekdayExcluded, ...otherExcluded])
408
+ ].sort();
409
+ const excludeTimes = minutesToDates(allExcluded);
410
+ return { excludeTimes, interval: interval !== null && interval !== void 0 ? interval : 0 };
411
+ };
412
+ export const makeDatePickerDates = (settings, serviceType) => {
413
+ var _a;
414
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
415
+ const validTimes = settings.valid_times[st];
416
+ const daysAhead = settings.days_ahead[st];
417
+ const firstTimes = settings.first_times[st];
418
+ const holidays = settings.holidays; //holidays[st] // TODO:- type error
419
+ const excludeDates = holidays === null || holidays === void 0 ? void 0 : holidays.map((i) => makeLocalDate(i));
420
+ const minDate = dateStrToDate((_a = firstTimes === null || firstTimes === void 0 ? void 0 : firstTimes.date) !== null && _a !== void 0 ? _a : new Date().toISOString());
421
+ const maxDate = daysAhead != null ? add(new Date(), { days: daysAhead }) : null;
422
+ const weekdayTimes = makeWeekdaysExcluded(validTimes !== null && validTimes !== void 0 ? validTimes : {});
423
+ const closedWeekdays = makeClosedWeekdays(weekdayTimes);
424
+ const filterDate = (date) => {
425
+ return !closedWeekdays.includes(date.getDay());
426
+ };
427
+ return { minDate, maxDate, excludeDates, filterDate };
428
+ };
429
+ export const makeWeekdayIndices = (weekdays) => {
430
+ if (!weekdays)
431
+ return [];
432
+ return weekdays.map(weekday => weekdaysUpper.indexOf(weekday));
433
+ };
434
+ export const makeOrderTimes = (orderTimes, tz) => {
435
+ var _a;
436
+ const currentDate = new Date();
437
+ const withDates = orderTimes === null || orderTimes === void 0 ? void 0 : orderTimes.map(i => {
438
+ const { weekday, time } = i.order_by;
439
+ let orderByDate = weekdayAndTimeToDate(weekday, time);
440
+ let startDate = weekdayAndTimeToDate(i.weekday, i.start_time);
441
+ // if (orderByDate < currentDate || startDate < currentDate) {
442
+ // startDate = add(startDate, { days: 7 })
443
+ // }
444
+ if (orderByDate < currentDate) {
445
+ orderByDate = add(orderByDate, { days: 7 });
446
+ }
447
+ if (startDate < orderByDate) {
448
+ startDate = add(startDate, { days: 7 });
449
+ }
450
+ const orderBy = Object.assign(Object.assign({}, i.order_by), { date: orderByDate });
451
+ return Object.assign(Object.assign({}, i), { date: startDate, iso: dateToIso(startDate, tz), order_by: orderBy });
452
+ });
453
+ return (_a = withDates === null || withDates === void 0 ? void 0 : withDates.sort((a, b) => a.date.getTime() - b.date.getTime())) !== null && _a !== void 0 ? _a : [];
454
+ };
455
+ export const findOrderTime = (orderTimes, tz, requestedAt) => {
456
+ const sortedTimes = makeOrderTimes(orderTimes, tz);
457
+ const selected = requestedAt
458
+ ? sortedTimes.find(i => i.iso === requestedAt)
459
+ : null;
460
+ return selected || sortedTimes[0];
461
+ };
462
+ export const makeFirstTime = (settings, tz, serviceType, requestedAt) => {
463
+ var _a;
464
+ const { first_times, order_times } = settings;
465
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
466
+ if (!first_times || !first_times[st]) {
467
+ if (!order_times || !order_times[st] || !((_a = order_times[st]) === null || _a === void 0 ? void 0 : _a.length))
468
+ return null;
469
+ const selected = findOrderTime(order_times[st], tz, requestedAt);
470
+ return selected.iso;
471
+ }
472
+ const firstTime = first_times[st];
473
+ const firstDate = firstTime ? isoToDate(firstTime === null || firstTime === void 0 ? void 0 : firstTime.utc, tz) : new Date();
474
+ const hasAsap = firstTime === null || firstTime === void 0 ? void 0 : firstTime.has_asap;
475
+ if (requestedAt === 'asap' && hasAsap) {
476
+ return 'asap';
477
+ }
478
+ const requestedDate = requestedAt && requestedAt !== 'asap'
479
+ ? isoToDate(requestedAt, tz)
480
+ : null;
481
+ if (requestedDate && requestedDate > firstDate) {
482
+ return requestedAt;
483
+ }
484
+ const { minutes, interval } = firstTime || {};
485
+ if (hasAsap && (minutes !== null && minutes !== void 0 ? minutes : 0) % (interval !== null && interval !== void 0 ? interval : 0) !== 0) {
486
+ return 'asap';
487
+ }
488
+ return firstTime === null || firstTime === void 0 ? void 0 : firstTime.utc;
489
+ };
490
+ export const makeFirstRequestedAt = (revenueCenter, serviceType, requestedAt) => {
491
+ const { timezone, revenue_center_type } = revenueCenter;
492
+ const settings = revenueCenter.settings || revenueCenter;
493
+ if (revenue_center_type === 'POS')
494
+ return 'asap';
495
+ const tz = timezoneMap[timezone];
496
+ requestedAt = requestedAt || (revenue_center_type === 'OLO' ? 'asap' : null);
497
+ return makeFirstTime(settings, tz, serviceType, requestedAt);
498
+ };
499
+ export const makeFirstTimes = (revenueCenter, serviceType, requestedAt) => {
500
+ const { timezone } = revenueCenter;
501
+ const settings = revenueCenter.settings || revenueCenter;
502
+ const tz = timezoneMap[timezone];
503
+ const otherServiceType = serviceType === 'DELIVERY' ? 'PICKUP' : 'DELIVERY';
504
+ const current = makeFirstTime(settings, tz, serviceType, requestedAt);
505
+ const other = makeFirstTime(settings, tz, otherServiceType, requestedAt);
506
+ if (!current && !other)
507
+ return null;
508
+ return [
509
+ current ? { serviceType: serviceType, requestedAt: current } : null,
510
+ other ? { serviceType: otherServiceType, requestedAt: other } : null
511
+ ];
512
+ // return { [serviceType]: current, [otherServiceType]: other }
513
+ };
514
+ export const getNextInterval = (requestedAt, tz, interval) => {
515
+ const date = isoToDate(requestedAt, tz);
516
+ const intervals = interval === 15 ? [0, 15, 30, 45, 60] : [0, 30, 60];
517
+ const nextInterval = intervals.filter(i => i >= date.getMinutes())[0];
518
+ const hours = nextInterval === 60 ? date.getHours() + 1 : date.getHours();
519
+ const minutes = nextInterval === 60 ? 0 : nextInterval;
520
+ date.setHours(hours);
521
+ date.setMinutes(minutes);
522
+ date.setSeconds(0);
523
+ date.setMilliseconds(0);
524
+ return date;
525
+ };
526
+ export const adjustRequestedAt = (requestedAt, tz, interval, leadTime) => {
527
+ const nextDate = getNextInterval(requestedAt, tz, interval);
528
+ const adjusted = add(nextDate, { minutes: leadTime });
529
+ return dateToIso(adjusted, tz);
530
+ };
531
+ export const getFirstTime = (settings, serviceType, tz) => {
532
+ var _a;
533
+ const { first_times, order_times } = settings;
534
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
535
+ if (!first_times || !first_times[st]) {
536
+ if (!order_times || !order_times[st])
537
+ return null;
538
+ const orderTimes = makeOrderTimes((_a = order_times[st]) !== null && _a !== void 0 ? _a : [], tz);
539
+ return orderTimes[0];
540
+ }
541
+ return first_times[st];
542
+ };
543
+ export const makeGroupOrderTime = (revenueCenter, serviceType, requestedAt) => {
544
+ const { timezone } = revenueCenter;
545
+ const settings = revenueCenter.settings || revenueCenter;
546
+ const tz = timezoneMap[timezone !== null && timezone !== void 0 ? timezone : 'US/Eastern'];
547
+ const { first_times, order_times, wait_times, group_ordering } = settings;
548
+ const { prep_time, lead_time } = group_ordering || {};
549
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
550
+ const waitTime = wait_times && wait_times[st] ? wait_times[st] : 0;
551
+ const prepTime = `${(waitTime !== null && waitTime !== void 0 ? waitTime : 0) + (prep_time !== null && prep_time !== void 0 ? prep_time : 0)}`;
552
+ if (requestedAt === 'asap')
553
+ return { prepTime };
554
+ const firstTime = first_times && first_times[st] ? first_times[st] : null;
555
+ const orderTimes = order_times && order_times[st] ? order_times[st] : null;
556
+ if (!firstTime && !orderTimes)
557
+ return {};
558
+ let adjustedIso, adjustedDate, cutoffDate, firstIso;
559
+ if (orderTimes) {
560
+ const orderTime = findOrderTime(orderTimes, tz, requestedAt);
561
+ adjustedIso = orderTime.iso;
562
+ adjustedDate = isoToDate(adjustedIso, tz);
563
+ cutoffDate = orderTime.order_by.date;
564
+ const allOrderTimes = makeOrderTimes(orderTimes, tz);
565
+ firstIso = allOrderTimes[0].iso;
566
+ }
567
+ else {
568
+ // first available time depends on both suggested lead time and extra prep time
569
+ // lead_time = how much time cart guests have to place their orders
570
+ // prep_time = how much extra prep time is required for group orders
571
+ // over and above the pickup or delivery wait time
572
+ const leadTime = (prep_time !== null && prep_time !== void 0 ? prep_time : 0) + (lead_time !== null && lead_time !== void 0 ? lead_time : 0);
573
+ const interval = (firstTime === null || firstTime === void 0 ? void 0 : firstTime.interval) || 15;
574
+ firstIso = adjustRequestedAt(firstTime === null || firstTime === void 0 ? void 0 : firstTime.utc, tz, interval, leadTime);
575
+ const firstDate = isoToDate(firstIso, tz);
576
+ const requestedDate = requestedAt !== 'asap' ? isoToDate(requestedAt, tz) : null;
577
+ adjustedIso =
578
+ requestedDate && requestedDate > firstDate ? requestedAt : firstIso;
579
+ adjustedDate = isoToDate(adjustedIso, tz);
580
+ cutoffDate = sub(adjustedDate, { minutes: parseFloat(prepTime) });
581
+ }
582
+ const cutoffIso = dateToIso(cutoffDate, tz);
583
+ return {
584
+ isAdjusted: requestedAt !== adjustedIso,
585
+ firstIso,
586
+ iso: adjustedIso,
587
+ date: adjustedDate,
588
+ dateStr: makeReadableDateStrFromIso(adjustedIso !== null && adjustedIso !== void 0 ? adjustedIso : '', tz, true),
589
+ cutoffIso,
590
+ cutoffDate,
591
+ cutoffDateStr: makeReadableDateStrFromIso(cutoffIso, tz, true)
592
+ };
593
+ };
594
+ export const formatTime = (time) => {
595
+ return time
596
+ ? time.replace('Today', 'today').replace('Tomorrow', 'tomorrow')
597
+ : '';
598
+ };
599
+ export const makeGroupOrderTimeStr = (iso, tz) => {
600
+ if (!iso || iso.toLowerCase() === 'asap')
601
+ return 'ASAP';
602
+ const orderTime = iso && tz ? makeReadableDateStrFromIso(iso, tz, true) : null;
603
+ return orderTime ? formatTime(orderTime) : null;
604
+ };
605
+ export const getLastInterval = (tz) => {
606
+ const date = isoToDate(new Date().toISOString(), tz);
607
+ date.setHours(23);
608
+ date.setMinutes(45);
609
+ date.setSeconds(0);
610
+ date.setMilliseconds(0);
611
+ return date;
612
+ };
613
+ export const makeIntervals = (tz) => {
614
+ const nextInterval = getNextInterval(new Date().toISOString(), tz, 15);
615
+ const lastInterval = getLastInterval(tz);
616
+ const diff = Math.max(differenceInMinutes(lastInterval, nextInterval), 0);
617
+ const steps = 24 * 4 + (diff ? Math.ceil(diff / 15) : 0);
618
+ let start = sub(nextInterval, { minutes: 24 * 60 });
619
+ const intervals = [];
620
+ for (let step = 0; step < steps; step++) {
621
+ const end = add(start, { minutes: 15 });
622
+ intervals.push({ start, end, orders: [] });
623
+ start = end;
624
+ }
625
+ return intervals;
626
+ };
627
+ export const formatTimeList = (dateStr, tz, includeDate) => {
628
+ const date = isoToDate(dateStr, tz);
629
+ const fmt = includeDate ? 'MMM d, h:mma' : 'h:mma';
630
+ return format(date, fmt).replace('AM', 'am').replace('PM', 'pm');
631
+ };
@@ -0,0 +1,48 @@
1
+ import { RequestError } from '@open-tender/types';
2
+ export declare const handleRespError: (err: RequestError) => {
3
+ title: string;
4
+ detail: string | undefined;
5
+ messages: [string, string][];
6
+ errors: {
7
+ [x: string]: any;
8
+ };
9
+ err: RequestError;
10
+ };
11
+ export declare const processError: (msg: string | null) => string;
12
+ export declare const handleFormErrors: (params: Record<string, string | null>) => Record<string, string>;
13
+ export declare const makeFormErrors: (error: RequestError) => Record<string, string>;
14
+ export declare const handleCheckoutErrors: (errors: RequestError, asMessages?: boolean) => {};
15
+ export declare const errMessages: {
16
+ unknown: string;
17
+ forbidden: string;
18
+ expiredToken: string;
19
+ notAllowed: string;
20
+ duplicates: string;
21
+ errorsBelow: string;
22
+ emptyField: string;
23
+ invalidAmount: string;
24
+ invalidEmail: string;
25
+ invalidEmails: string;
26
+ notInteger: string;
27
+ positiveInteger: string;
28
+ invalidTime: string;
29
+ invalidDate: string;
30
+ invalidNumber: string;
31
+ invalidHex: string;
32
+ invalidZip: string;
33
+ invalidPhone: string;
34
+ invalidPassword: string;
35
+ invalidToken: string;
36
+ requiredField: string;
37
+ invalidFilename: string;
38
+ notExist: string;
39
+ serverError: string;
40
+ invalidHours: string;
41
+ revenueCenterClosed: string;
42
+ serviceTypeNotAvailable: string;
43
+ notInZone: string;
44
+ missingAddress: string;
45
+ orderNotFound: string;
46
+ distanceSurcharge: string;
47
+ missingAddressDeliveryZone: string;
48
+ };