@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,805 @@
1
+ import { serviceTypeNamesMap } from './constants';
2
+ import { timezoneMap, makeOrderTimes, makeReadableDateStrFromIso, isoToDate, time24ToDate, formatDateStr, makeWeekday, fmtDate } from './datetimes';
3
+ import { capitalize } from './helpers';
4
+ export const displayPrice = (price) => {
5
+ return parseFloat(price).toFixed(2);
6
+ };
7
+ export const makeDisplayPrice = (item) => {
8
+ const sizeGroup = item.option_groups && item.option_groups.find(i => i.is_size);
9
+ if (sizeGroup) {
10
+ const prices = sizeGroup.option_items.map(i => `$${displayPrice(i.price)}`);
11
+ return prices.join(' / ');
12
+ }
13
+ const { totalPrice } = makeOrderItem(item);
14
+ return totalPrice > 0 ? `$${displayPrice(`${totalPrice}`)}` : null;
15
+ };
16
+ export const addCommas = (x, d) => {
17
+ return x.toFixed(d).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
18
+ };
19
+ export const formatQuantity = (n) => {
20
+ return addCommas(parseFloat(n), 0);
21
+ };
22
+ export const formatDollars = (str, space = '', decimals = 2) => {
23
+ const floatPrice = parseFloat(str);
24
+ return floatPrice < 0
25
+ ? `($${addCommas(Math.abs(floatPrice), decimals)})`
26
+ : `$${addCommas(floatPrice, decimals)}${space}`;
27
+ };
28
+ export const getItemOptions = (item) => {
29
+ if (!item.groups || !item.groups.length)
30
+ return [];
31
+ const options = item.groups
32
+ .map(group => { var _a; return (_a = group.options) === null || _a === void 0 ? void 0 : _a.filter(option => option.quantity > 0); })
33
+ .reduce((arr, i) => [...(arr !== null && arr !== void 0 ? arr : []), ...(i !== null && i !== void 0 ? i : [])], []);
34
+ return options;
35
+ };
36
+ export const makeModifierNames = (item) => {
37
+ var _a;
38
+ return (_a = getItemOptions(item)) === null || _a === void 0 ? void 0 : _a.map(option => option.name).join(', ');
39
+ };
40
+ export const convertStringToArray = (str) => {
41
+ return str
42
+ ? str
43
+ .split(',')
44
+ .map(i => i.trim())
45
+ .filter(i => i.length)
46
+ : [];
47
+ };
48
+ export const makeOrderTypeFromParam = (param) => {
49
+ switch (param) {
50
+ case 'outpost':
51
+ return ['OLO', 'PICKUP', true];
52
+ case 'pickup':
53
+ return ['OLO', 'PICKUP'];
54
+ case 'delivery':
55
+ return ['OLO', 'DELIVERY'];
56
+ case 'catering':
57
+ return ['CATERING', 'DELIVERY'];
58
+ case 'merch':
59
+ return ['MERCH', 'DELIVERY'];
60
+ default:
61
+ return null;
62
+ }
63
+ };
64
+ export const makeServiceTypeName = (serviceType, isCatering, isOutpost, outpostName) => {
65
+ let serviceTypeName = serviceTypeNamesMap[serviceType];
66
+ if (isCatering) {
67
+ serviceTypeName = `Catering ${serviceTypeName}`;
68
+ }
69
+ else if (isOutpost) {
70
+ serviceTypeName = `${outpostName || 'Outpost'} ${serviceTypeName}`;
71
+ }
72
+ return serviceTypeName;
73
+ };
74
+ export const makeOrderTypeName = (orderType, serviceType) => {
75
+ return orderType === 'OLO'
76
+ ? serviceTypeNamesMap[serviceType]
77
+ : capitalize(orderType);
78
+ };
79
+ const makeOrderMsg = (tz, serviceType, requestedAt, firstTime, orderTime, waitTime) => {
80
+ var _a, _b;
81
+ if (!firstTime && !orderTime)
82
+ return null;
83
+ let readableDate;
84
+ if (firstTime) {
85
+ const seconds = firstTime.utc ? isoToDate(firstTime.utc).getSeconds() : 0;
86
+ const estimate = requestedAt !== 'asap' && seconds ? 'at about' : 'at';
87
+ readableDate =
88
+ requestedAt === 'asap' && firstTime.has_asap
89
+ ? `in about ${waitTime} minutes`
90
+ : makeReadableDateStrFromIso(firstTime.utc, tz, true)
91
+ .replace('Today', 'today')
92
+ .replace('Tomorrow', 'TOMORROW')
93
+ .replace('@', estimate);
94
+ }
95
+ else {
96
+ const orderTimes = makeOrderTimes([orderTime], tz);
97
+ const { start_time, end_time } = orderTimes[0];
98
+ const startTime = time24ToDate(start_time);
99
+ const startTimeStr = (_a = formatDateStr(startTime.toISOString(), 'h:mma')) === null || _a === void 0 ? void 0 : _a.toLowerCase();
100
+ const endTime = time24ToDate(end_time);
101
+ const endTimeStr = (_b = formatDateStr(endTime.toISOString(), 'h:mma')) === null || _b === void 0 ? void 0 : _b.toLowerCase();
102
+ const todayWeekday = makeWeekday();
103
+ const weekday = orderTimes[0].weekday === todayWeekday
104
+ ? ''
105
+ : `${capitalize(orderTimes[0].weekday)}, ${fmtDate(orderTimes[0].date, 'MMMM d')} @ `;
106
+ readableDate =
107
+ startTimeStr === endTimeStr
108
+ ? `${weekday}${startTimeStr}`
109
+ : `${weekday}${startTimeStr} to ${endTimeStr}`;
110
+ }
111
+ const serviceTypeName = serviceTypeNamesMap[serviceType];
112
+ const orderMsg = `The first available ${serviceTypeName === null || serviceTypeName === void 0 ? void 0 : serviceTypeName.toLowerCase()} time is ${readableDate}`;
113
+ return orderMsg;
114
+ };
115
+ export const makeNotAcceptingOrdersMsg = (serviceType) => {
116
+ const serviceTypeName = serviceTypeNamesMap[serviceType];
117
+ if (!serviceTypeName) {
118
+ return 'This location is not currently accepting orders.';
119
+ }
120
+ return `This location is not currently accepting ${serviceTypeName.toLowerCase()} orders. Please try switching to a different order type.`;
121
+ };
122
+ export const makeRevenueCenterMsg = (revenueCenter, serviceType, requestedAt, statusMessages) => {
123
+ var _a;
124
+ const settings = revenueCenter.settings || revenueCenter;
125
+ const { first_times, order_times, wait_times } = settings;
126
+ const tz = timezoneMap[(_a = revenueCenter === null || revenueCenter === void 0 ? void 0 : revenueCenter.timezone) !== null && _a !== void 0 ? _a : 'US/Central'];
127
+ const st = serviceType === 'WALKIN' ? 'PICKUP' : serviceType;
128
+ const firstTime = first_times ? first_times[st] : null;
129
+ const orderTime = order_times ? order_times[st] : null;
130
+ const waitTime = wait_times ? wait_times[st] : null;
131
+ const tempClosed = revenueCenter.status === 'CLOSED_TEMPORARILY';
132
+ const statusMsg = !tempClosed ? statusMessages[revenueCenter.status] : null;
133
+ const orderMsg = !statusMsg && (firstTime || (orderTime && orderTime.length))
134
+ ? makeOrderMsg(tz, serviceType, requestedAt, firstTime, orderTime ? orderTime[0] : null, waitTime !== null && waitTime !== void 0 ? waitTime : 0)
135
+ : null;
136
+ let message = orderMsg ||
137
+ (statusMsg ? statusMsg.subtitle : makeNotAcceptingOrdersMsg(serviceType));
138
+ let color = orderMsg ? 'success' : 'alert';
139
+ if (tempClosed) {
140
+ color = 'alert';
141
+ message = message.charAt(0).toLowerCase() + message.substring(1);
142
+ message = `This location is temporarily closed for technical or operational reasons. Please try back later today, otherwise ${message} if you want to place an order now.`;
143
+ }
144
+ return { message, color };
145
+ };
146
+ const makeOrderItemGroups = (optionGroups, isEdit, soldOut = []) => {
147
+ if (!optionGroups)
148
+ return [];
149
+ const groups = optionGroups.map(g => {
150
+ const options = g.option_items.map(o => {
151
+ const isSoldOut = soldOut.includes(o.id);
152
+ const quantity = isSoldOut
153
+ ? 0
154
+ : o.opt_is_default && !isEdit
155
+ ? o.min_quantity || 1
156
+ : 0;
157
+ const cals = o.nutritional_info
158
+ ? o.nutritional_info.calories
159
+ : null;
160
+ const option = {
161
+ id: o.id,
162
+ name: o.name,
163
+ shortName: o.short_name,
164
+ description: o.description,
165
+ imageUrl: o.small_image_url,
166
+ allergens: convertStringToArray(o.allergens),
167
+ tags: convertStringToArray(o.tags),
168
+ ingredients: o.ingredients,
169
+ nutritionalInfo: o.nutritional_info,
170
+ cals: isNaN(cals !== null && cals !== void 0 ? cals : 0) ? null : cals,
171
+ price: parseFloat(o.price),
172
+ quantity: quantity,
173
+ isDefault: o.opt_is_default,
174
+ increment: o.increment,
175
+ max: isSoldOut ? 0 : o.max_quantity,
176
+ min: o.min_quantity,
177
+ isSoldOut: isSoldOut,
178
+ points: o.points || 0
179
+ };
180
+ return option;
181
+ });
182
+ const group = {
183
+ id: g.id,
184
+ name: g.name,
185
+ description: g.description,
186
+ imageUrl: g.small_image_url,
187
+ included: g.included_options,
188
+ max: g.max_options,
189
+ min: g.min_options,
190
+ isSize: !!g.is_size,
191
+ options: options
192
+ };
193
+ return group;
194
+ });
195
+ return groups;
196
+ };
197
+ export const calcPrices = (item) => {
198
+ var _a, _b, _c, _d, _e;
199
+ const groups = (_a = item.groups) === null || _a === void 0 ? void 0 : _a.map(g => {
200
+ var _a;
201
+ let groupQuantity = 0;
202
+ const options = (_a = g.options) === null || _a === void 0 ? void 0 : _a.map(o => {
203
+ var _a, _b;
204
+ const includedRemaining = Math.max(((_a = g.included) !== null && _a !== void 0 ? _a : 0) - groupQuantity, 0);
205
+ const priceQuantity = Math.max(o.quantity - includedRemaining, 0);
206
+ const option = Object.assign(Object.assign({}, o), { totalPrice: priceQuantity * o.price, totalPoints: priceQuantity * ((_b = o.points) !== null && _b !== void 0 ? _b : 0), totalCals: o.cals ? o.quantity * o.cals : 0 });
207
+ groupQuantity += o.quantity || 0;
208
+ return option;
209
+ });
210
+ return Object.assign(Object.assign({}, g), { quantity: groupQuantity, options });
211
+ });
212
+ const optionsPrice = groups === null || groups === void 0 ? void 0 : groups.reduce((t, g) => {
213
+ var _a, _b;
214
+ return t + ((_b = (_a = g.options) === null || _a === void 0 ? void 0 : _a.reduce((ot, o) => ot + o.totalPrice, 0.0)) !== null && _b !== void 0 ? _b : 0);
215
+ }, 0.0);
216
+ const totalPrice = ((_b = item.quantity) !== null && _b !== void 0 ? _b : 0) * (((_c = item.price) !== null && _c !== void 0 ? _c : 0) + (optionsPrice !== null && optionsPrice !== void 0 ? optionsPrice : 0));
217
+ const optionsPoints = groups === null || groups === void 0 ? void 0 : groups.reduce((t, g) => {
218
+ var _a, _b;
219
+ return t + ((_b = (_a = g.options) === null || _a === void 0 ? void 0 : _a.reduce((ot, o) => ot + o.totalPoints, 0)) !== null && _b !== void 0 ? _b : 0);
220
+ }, 0.0);
221
+ const totalPoints = item.points
222
+ ? ((_d = item.quantity) !== null && _d !== void 0 ? _d : 0) * (item.points + (optionsPoints !== null && optionsPoints !== void 0 ? optionsPoints : 0))
223
+ : null;
224
+ const optionsCals = groups === null || groups === void 0 ? void 0 : groups.reduce((t, g) => {
225
+ var _a, _b;
226
+ return t + ((_b = (_a = g.options) === null || _a === void 0 ? void 0 : _a.reduce((ot, o) => ot + o.totalCals, 0)) !== null && _b !== void 0 ? _b : 0);
227
+ }, 0.0);
228
+ const totalCals = item.cals || item.cals === 0
229
+ ? ((_e = item.quantity) !== null && _e !== void 0 ? _e : 0) * (item.cals + (optionsCals !== null && optionsCals !== void 0 ? optionsCals : 0))
230
+ : null;
231
+ return Object.assign(Object.assign({}, item), { groups, totalPrice, totalPoints, totalCals });
232
+ };
233
+ export const makeOrderItem = (item, isEdit, soldOut = [], simpleItem, hasPoints = false) => {
234
+ const groups = makeOrderItemGroups(item.option_groups, isEdit, soldOut);
235
+ const cals = item.nutritional_info ? item.nutritional_info.calories : null;
236
+ const orderItem = {
237
+ id: item.id,
238
+ name: item.name,
239
+ shortName: item.short_name,
240
+ category: item.category_name,
241
+ description: item.description,
242
+ imageUrl: item.large_image_url,
243
+ slug: item.slug,
244
+ allergens: convertStringToArray(item.allergens),
245
+ tags: convertStringToArray(item.tags),
246
+ ingredients: item.ingredients,
247
+ nutritionalInfo: item.nutritional_info,
248
+ cals: isNaN(cals !== null && cals !== void 0 ? cals : 0) ? null : cals,
249
+ groups: groups,
250
+ quantity: item.min_quantity || 1 * item.increment,
251
+ price: parseFloat(item.price),
252
+ increment: item.increment,
253
+ max: item.max_quantity,
254
+ min: item.min_quantity,
255
+ points: hasPoints ? item.points || null : null,
256
+ upsellItems: item.upsell_items || [],
257
+ similarItems: item.similar_items || []
258
+ };
259
+ if (simpleItem) {
260
+ const { cart_guest_id, customer_id, made_for, notes } = simpleItem;
261
+ if (cart_guest_id)
262
+ orderItem.cart_guest_id = cart_guest_id;
263
+ if (customer_id)
264
+ orderItem.customer_id = customer_id;
265
+ if (made_for)
266
+ orderItem.madeFor = made_for;
267
+ if (notes)
268
+ orderItem.notes = notes;
269
+ }
270
+ const pricedItem = calcPrices(orderItem);
271
+ return pricedItem;
272
+ };
273
+ export const rehydrateOrderItem = (menuItem, simpleCartItem) => {
274
+ var _a;
275
+ const orderItem = makeOrderItem(menuItem, true, [], simpleCartItem);
276
+ orderItem.quantity = simpleCartItem.quantity || 1;
277
+ if (simpleCartItem.groups && simpleCartItem.groups.length) {
278
+ const groupsLookup = makeGroupsLookup(simpleCartItem);
279
+ (_a = orderItem.groups) === null || _a === void 0 ? void 0 : _a.forEach(group => {
280
+ var _a;
281
+ const simpleGroup = group.id ? groupsLookup[group.id] : null;
282
+ if (simpleGroup) {
283
+ (_a = group.options) === null || _a === void 0 ? void 0 : _a.forEach(option => {
284
+ const simpleOption = simpleGroup.options[option.id];
285
+ option.quantity = simpleOption ? simpleOption.quantity : 0;
286
+ });
287
+ }
288
+ });
289
+ }
290
+ const pricedItem = calcPrices(orderItem);
291
+ return pricedItem;
292
+ };
293
+ export const rehydrateCart = (menuItems, simpleCartItems) => {
294
+ const orderItems = [];
295
+ simpleCartItems.forEach(item => {
296
+ const menuItem = menuItems.find(i => i.id === item.id);
297
+ if (menuItem) {
298
+ const orderItem = rehydrateOrderItem(menuItem, item);
299
+ orderItems.push(orderItem);
300
+ }
301
+ });
302
+ const cart = orderItems.map((i, index) => (Object.assign(Object.assign({}, i), { index })));
303
+ const cartCounts = calcCartCounts(cart);
304
+ return { cart, cartCounts };
305
+ };
306
+ const rehydrateDetails = (details) => {
307
+ return {
308
+ cart_id: details === null || details === void 0 ? void 0 : details.cart_id,
309
+ eating_utensils: details === null || details === void 0 ? void 0 : details.eating_utensils,
310
+ notes: details === null || details === void 0 ? void 0 : details.notes,
311
+ person_count: details === null || details === void 0 ? void 0 : details.person_count,
312
+ serving_utensils: details === null || details === void 0 ? void 0 : details.serving_utensils,
313
+ tax_exempt_id: details === null || details === void 0 ? void 0 : details.tax_exempt_id
314
+ };
315
+ };
316
+ const rehydrateCustomer = (customer) => {
317
+ const newCustomer = {
318
+ first_name: customer === null || customer === void 0 ? void 0 : customer.first_name,
319
+ last_name: customer === null || customer === void 0 ? void 0 : customer.last_name,
320
+ email: customer === null || customer === void 0 ? void 0 : customer.email,
321
+ phone: customer === null || customer === void 0 ? void 0 : customer.phone,
322
+ company: customer === null || customer === void 0 ? void 0 : customer.company
323
+ };
324
+ if (customer === null || customer === void 0 ? void 0 : customer.customer_id) {
325
+ newCustomer.customer_id = customer.customer_id;
326
+ }
327
+ return newCustomer;
328
+ };
329
+ const rehydrateAddress = (address) => {
330
+ if (!address)
331
+ return {};
332
+ return {
333
+ unit: address.unit,
334
+ company: address.company,
335
+ contact: address.contact,
336
+ phone: address.phone
337
+ };
338
+ };
339
+ const rehydrateSurcharges = (surcharges) => {
340
+ return surcharges
341
+ .filter(i => i.is_optional)
342
+ .map(i => ({ id: i.surcharge_id }));
343
+ };
344
+ const rehydrateDiscounts = (discounts) => {
345
+ return discounts
346
+ .filter(i => !i.is_promo_code)
347
+ .map(i => ({ id: i.discount_id || i.id, ext_id: i.ext_id }));
348
+ };
349
+ const rehydratePromoCodes = (discounts) => {
350
+ return discounts.filter(i => i.is_promo_code).map(i => i.name);
351
+ };
352
+ const rehydrateTenders = (tenders) => {
353
+ // const giftCards = tenders.filter((i) => i.tender_type === 'GIFT_CARD')
354
+ const other = tenders
355
+ // .filter((i) => i.tender_type !== 'GIFT_CARD')
356
+ .map(i => {
357
+ if (i.tender_type === 'CREDIT') {
358
+ return Object.assign(Object.assign({}, i), i.credit_card);
359
+ }
360
+ else if (i.tender_type === 'HOUSE_ACCOUNT') {
361
+ return Object.assign(Object.assign({}, i), i.house_account);
362
+ }
363
+ else {
364
+ return i;
365
+ }
366
+ });
367
+ return other;
368
+ };
369
+ export const rehydrateCheckoutForm = (order) => {
370
+ const form = {
371
+ details: rehydrateDetails(order.details),
372
+ customer: rehydrateCustomer(order.customer),
373
+ address: rehydrateAddress(order.address),
374
+ surcharges: rehydrateSurcharges(order.surcharges),
375
+ discounts: rehydrateDiscounts(order.discounts),
376
+ promoCodes: rehydratePromoCodes(order.discounts),
377
+ tenders: rehydrateTenders(order.tenders),
378
+ tip: order.totals.tip
379
+ };
380
+ return form;
381
+ };
382
+ // group orders
383
+ export const makeGuestLookup = (cartGuests) => {
384
+ return cartGuests.reduce((obj, i) => (i.cart_guest_id ? Object.assign(Object.assign({}, obj), { [i.cart_guest_id]: i }) : Object.assign({}, obj)), {});
385
+ };
386
+ export const combineCarts = (cart, guestCart, cartOwner, cartGuests) => {
387
+ const guestLookup = makeGuestLookup(cartGuests);
388
+ const withGuestNames = guestCart
389
+ .filter(i => guestLookup[i.cart_guest_id])
390
+ .map(i => {
391
+ const guest = guestLookup[i.cart_guest_id];
392
+ return Object.assign(Object.assign({}, i), { madeFor: `${guest === null || guest === void 0 ? void 0 : guest.first_name} ${guest === null || guest === void 0 ? void 0 : guest.last_name}` });
393
+ });
394
+ const withOwnerName = cart.map(i => {
395
+ return Object.assign(Object.assign({}, i), { customer_id: cartOwner.customer_id, madeFor: `${cartOwner.first_name} ${cartOwner.last_name}` });
396
+ });
397
+ return [...withOwnerName, ...withGuestNames];
398
+ };
399
+ // display items from past orders
400
+ export const makeItemImageUrl = (images) => {
401
+ const imageMap = images
402
+ .filter(i => i.url)
403
+ .reduce((obj, i) => (Object.assign(Object.assign({}, obj), { [i.type]: i.url })), {});
404
+ return (imageMap.SMALL_IMAGE || imageMap.LARGE_IMAGE || imageMap.APP_IMAGE || null);
405
+ };
406
+ export const makeItemSignature = (item) => {
407
+ const optionIds = !item.groups
408
+ ? []
409
+ : item.groups
410
+ .reduce((arr, group) => {
411
+ var _a;
412
+ const ids = (_a = group.options) === null || _a === void 0 ? void 0 : _a.map(o => o.id);
413
+ return [...arr, ...(ids !== null && ids !== void 0 ? ids : [])];
414
+ }, [])
415
+ .sort((a, b) => a - b);
416
+ return [item.id, ...optionIds].join('.');
417
+ };
418
+ export const makeCartItemSignature = (item) => {
419
+ const optionIds = !item.groups
420
+ ? []
421
+ : item.groups
422
+ .reduce((arr, group) => {
423
+ var _a;
424
+ const ids = (_a = group.options) === null || _a === void 0 ? void 0 : _a.filter(o => o.quantity > 0).reduce((optionsArr, o) => {
425
+ const optionArr = new Array(o.quantity);
426
+ optionArr.fill(o.id);
427
+ return [...optionsArr, ...optionArr];
428
+ }, []);
429
+ return [...arr, ...(ids !== null && ids !== void 0 ? ids : [])];
430
+ }, [])
431
+ .sort((a, b) => a - b);
432
+ const itemIds = [item.id, ...optionIds].join('.');
433
+ const signature = `${itemIds}.${item.madeFor}.${item.notes}`;
434
+ return signature;
435
+ };
436
+ export const makeDisplayItemGroups = (optionGroups) => {
437
+ if (!optionGroups || !optionGroups.length)
438
+ return [];
439
+ return optionGroups.map((g) => {
440
+ var _a;
441
+ const options = (_a = g.options) === null || _a === void 0 ? void 0 : _a.map(o => makeDisplayItem(o));
442
+ return Object.assign(Object.assign({}, g), { options });
443
+ });
444
+ };
445
+ export const makeDisplayItem = (item, isOption = false) => {
446
+ var _a, _b, _c;
447
+ const cals = item.nutritional_info ? (_a = item.nutritional_info) === null || _a === void 0 ? void 0 : _a.calories : null;
448
+ let displayItem = {
449
+ id: item.id,
450
+ name: item.name,
451
+ shortDescription: item.short_description,
452
+ description: item.description,
453
+ imageUrl: makeItemImageUrl((_b = item.images) !== null && _b !== void 0 ? _b : []),
454
+ allergens: item.allergens || [],
455
+ tags: item.tags || [],
456
+ nutritionalInfo: item.nutritional_info || null,
457
+ cals: isNaN(cals !== null && cals !== void 0 ? cals : 0) ? null : cals,
458
+ groups: makeDisplayItemGroups((_c = item.groups) !== null && _c !== void 0 ? _c : []),
459
+ quantity: item.quantity || 1,
460
+ price: item.price !== undefined ? item.price : undefined,
461
+ totalPrice: item.price_total !== undefined ? item.price_total : undefined
462
+ };
463
+ if (!isOption) {
464
+ const itemDetails = {
465
+ madeFor: item.made_for,
466
+ notes: item.notes,
467
+ favoriteId: item.favorite_id,
468
+ signature: makeItemSignature(item)
469
+ };
470
+ displayItem = Object.assign(Object.assign({}, displayItem), itemDetails);
471
+ }
472
+ return displayItem;
473
+ };
474
+ export const makeDisplayItems = (orders) => {
475
+ const items = orders.reduce((items, order) => [...items, ...order.cart], []);
476
+ return items.map(i => makeDisplayItem(i));
477
+ };
478
+ export const makeUniqueDisplayItems = (orders) => {
479
+ const items = makeDisplayItems(orders);
480
+ const unique = [];
481
+ const signatures = [];
482
+ items.forEach(item => {
483
+ var _a;
484
+ if (signatures.includes((_a = item.signature) !== null && _a !== void 0 ? _a : ''))
485
+ return;
486
+ item.signature && signatures.push(item.signature);
487
+ unique.push(item);
488
+ });
489
+ return unique;
490
+ };
491
+ export const makeFavoritesLookup = (favorites) => {
492
+ if (!favorites)
493
+ return {};
494
+ return favorites
495
+ .filter(i => i.cart)
496
+ .reduce((obj, i) => (Object.assign(Object.assign({}, obj), { [makeItemSignature(i.cart)]: i.favorite_id })), {});
497
+ };
498
+ export const makeOrderAddress = (address) => {
499
+ const { street, unit, city, state, postal_code } = address || {};
500
+ return street
501
+ ? `${street}${unit ? `, ${unit}` : ''}`
502
+ : postal_code
503
+ ? `${postal_code} ${city}, ${state}`
504
+ : 'No address provided';
505
+ };
506
+ export const makeFullAddress = (address) => {
507
+ const { street, city, state, postal_code } = address || {};
508
+ return `${street ? `${street}, ` : ''}${city}, ${state} ${postal_code}`;
509
+ };
510
+ export const calcCartCounts = (cart) => {
511
+ return cart.reduce((obj, item) => {
512
+ var _a;
513
+ const newCount = (obj[(_a = item.id) !== null && _a !== void 0 ? _a : 0] || 0) + item.quantity;
514
+ return item.id ? Object.assign(Object.assign({}, obj), { [item.id]: newCount }) : Object.assign({}, obj);
515
+ }, {});
516
+ };
517
+ export const addItem = (cart, item) => {
518
+ var _a;
519
+ if (typeof item.index === 'undefined') {
520
+ const itemSignature = makeCartItemSignature(item);
521
+ const itemSignatures = cart.map(i => (Object.assign({ signature: makeCartItemSignature(i) }, i)));
522
+ const match = itemSignatures.find(i => i.signature === itemSignature);
523
+ if (match) {
524
+ const quantity = item.quantity + match.quantity;
525
+ const newItem = Object.assign(Object.assign({}, item), { quantity });
526
+ const updated = calcPrices(newItem);
527
+ cart[(_a = match.index) !== null && _a !== void 0 ? _a : 0] = Object.assign(Object.assign({}, updated), { index: match.index });
528
+ }
529
+ else {
530
+ cart.push(Object.assign(Object.assign({}, item), { index: cart.length }));
531
+ }
532
+ }
533
+ else {
534
+ cart[item.index] = item;
535
+ }
536
+ const cartCounts = calcCartCounts(cart);
537
+ return { cart, cartCounts };
538
+ };
539
+ const getItemRealIndex = (cart, index) => cart.findIndex(item => item.index === index);
540
+ export const removeItem = (cart, index) => {
541
+ const realIndex = getItemRealIndex(cart, index);
542
+ if (realIndex > -1) {
543
+ cart.splice(realIndex, 1);
544
+ cart = cart.map((i, _index) => (Object.assign(Object.assign({}, i), { index: _index })));
545
+ }
546
+ const cartCounts = calcCartCounts(cart);
547
+ return { cart, cartCounts };
548
+ };
549
+ export const incrementItem = (cart, index) => {
550
+ const realIndex = getItemRealIndex(cart, index);
551
+ if (realIndex > -1) {
552
+ const item = cart[realIndex];
553
+ if (item.max === 0 || item.quantity < item.max) {
554
+ let newQuantity = item.quantity + item.increment;
555
+ newQuantity =
556
+ item.max === 0 ? newQuantity : Math.min(item.max, newQuantity);
557
+ const newItem = calcPrices(Object.assign(Object.assign({}, item), { quantity: newQuantity }));
558
+ cart[realIndex !== null && realIndex !== void 0 ? realIndex : 0] = newItem;
559
+ }
560
+ }
561
+ const cartCounts = calcCartCounts(cart);
562
+ return { cart, cartCounts };
563
+ };
564
+ export const decrementItem = (cart, index) => {
565
+ const realIndex = getItemRealIndex(cart, index);
566
+ if (realIndex > -1) {
567
+ const item = cart[realIndex];
568
+ const newQuantity = Math.max(item.quantity - item.increment, 0);
569
+ if (newQuantity === 0 || newQuantity < item.min) {
570
+ cart.splice(realIndex, 1);
571
+ cart = cart.map((i, _index) => (Object.assign(Object.assign({}, i), { index: _index })));
572
+ }
573
+ else {
574
+ const newItem = calcPrices(Object.assign(Object.assign({}, item), { quantity: newQuantity }));
575
+ cart[realIndex] = newItem;
576
+ }
577
+ }
578
+ const cartCounts = calcCartCounts(cart);
579
+ return { cart, cartCounts };
580
+ };
581
+ export const makeSimpleCart = (cart) => {
582
+ const simpleCart = cart.map(i => {
583
+ var _a;
584
+ const groups = (_a = i.groups) === null || _a === void 0 ? void 0 : _a.map(g => {
585
+ var _a;
586
+ const options = (_a = g.options) === null || _a === void 0 ? void 0 : _a.filter(o => o.quantity !== 0).map(o => ({ id: o.id, quantity: o.quantity }));
587
+ return { id: g.id, options: options };
588
+ });
589
+ return {
590
+ id: i.id,
591
+ quantity: i.quantity,
592
+ groups: groups,
593
+ made_for: i.madeFor || '',
594
+ notes: i.notes || ''
595
+ };
596
+ });
597
+ return simpleCart;
598
+ };
599
+ /* cart validation */
600
+ // convert menu items to order items for validation but only include
601
+ // items that are already in the cart to save wasted effort
602
+ const makeItemLookup = (categories, itemIds) => {
603
+ const itemLookup = {};
604
+ categories.forEach(category => {
605
+ category.items.forEach(item => {
606
+ if (itemIds.includes(item.id)) {
607
+ itemLookup[item.id] = makeOrderItem(item, true);
608
+ }
609
+ });
610
+ category.children.forEach(child => {
611
+ child.items.forEach(item => {
612
+ if (itemIds.includes(item.id)) {
613
+ itemLookup[item.id] = makeOrderItem(item, true);
614
+ }
615
+ });
616
+ });
617
+ });
618
+ return itemLookup;
619
+ };
620
+ const makeGroupsLookup = (item) => {
621
+ var _a;
622
+ return (_a = item.groups) === null || _a === void 0 ? void 0 : _a.reduce((grpObj, i) => {
623
+ const options = i.options.reduce((optObj, o) => {
624
+ optObj[o.id] = o;
625
+ return optObj;
626
+ }, {});
627
+ grpObj[i.id] = Object.assign(Object.assign({}, i), { options });
628
+ return grpObj;
629
+ }, {});
630
+ };
631
+ export const validateCart = (cart, categories, soldOut) => {
632
+ const itemIds = cart.map(item => item.id);
633
+ const itemLookup = makeItemLookup(categories, itemIds);
634
+ let errors = null;
635
+ const missingItems = [];
636
+ const invalidItems = [];
637
+ let newCart = cart.map(oldItem => {
638
+ var _a, _b;
639
+ const newItem = itemLookup[oldItem.id];
640
+ if (!newItem || soldOut.includes(oldItem.id)) {
641
+ missingItems.push(oldItem);
642
+ return null;
643
+ }
644
+ let missingGroups = [];
645
+ const invalidGroups = [];
646
+ const missingOptions = [];
647
+ const invalidOptions = [];
648
+ const newGroups = makeGroupsLookup(newItem);
649
+ // check if any required groups for the new item are missing from the old item
650
+ const newRequiredGroups = Object.values(newGroups).filter((i) => i.min > 0);
651
+ const oldGroupIds = (_a = oldItem.groups) === null || _a === void 0 ? void 0 : _a.map(i => i.id);
652
+ missingGroups = newRequiredGroups.filter((i) => !(oldGroupIds === null || oldGroupIds === void 0 ? void 0 : oldGroupIds.includes(i.id)));
653
+ const newEmptyGroups = Object.values(newGroups).filter((i) => {
654
+ return i.min === 0 && !(oldGroupIds === null || oldGroupIds === void 0 ? void 0 : oldGroupIds.includes(i.id));
655
+ })
656
+ .map((i) => (Object.assign(Object.assign({}, i), { options: Object.values(i.options) })));
657
+ const updatedGroups = (_b = oldItem.groups) === null || _b === void 0 ? void 0 : _b.map((group) => {
658
+ const optionCount = group.options.reduce((t, i) => (t += i.quantity), 0);
659
+ const newGroup = newGroups[group.id];
660
+ // check if option group is still part of the item
661
+ if (!newGroup) {
662
+ if (optionCount > 0) {
663
+ invalidGroups.push(group);
664
+ return group;
665
+ }
666
+ else {
667
+ return null;
668
+ }
669
+ }
670
+ else {
671
+ const updatedOptions = group.options.map((option) => {
672
+ const newOption = newGroup.options[option.id];
673
+ // check to see if any OLD options aren't avaiilable on the current menu
674
+ // or if any of the options are currently sold out
675
+ if (!newOption ||
676
+ (option.quantity > 0 && soldOut.includes(option.id))) {
677
+ missingOptions.push(option);
678
+ return option;
679
+ }
680
+ else {
681
+ // check to see if option quantity is valid relative to option min & max
682
+ // ignore the option increment setting for the time being
683
+ if ((newOption.max && option.quantity > newOption.max) ||
684
+ (newOption.min && option.quantity < newOption.min)) {
685
+ invalidOptions.push(option);
686
+ return option;
687
+ }
688
+ else {
689
+ // update the old option price to the new option price
690
+ const updatedOption = Object.assign(Object.assign({}, option), { price: newOption.price });
691
+ return updatedOption;
692
+ }
693
+ }
694
+ });
695
+ // check to see if the option count is greater than the max (if one exists)
696
+ // or less than the min (if one exists)
697
+ if ((newGroup.max && optionCount > newGroup.max) ||
698
+ (newGroup.min && optionCount < newGroup.min)) {
699
+ invalidGroups.push(group);
700
+ }
701
+ const updatedGroup = Object.assign(Object.assign({}, group), { options: updatedOptions });
702
+ return updatedGroup;
703
+ }
704
+ });
705
+ if (missingGroups.length ||
706
+ invalidGroups.length ||
707
+ missingOptions.length ||
708
+ invalidOptions.length) {
709
+ const invalidItem = Object.assign(Object.assign({}, oldItem), { missingGroups,
710
+ invalidGroups,
711
+ missingOptions,
712
+ invalidOptions });
713
+ invalidItems.push(invalidItem);
714
+ return null;
715
+ }
716
+ else {
717
+ // check to see if this item's quantity is below the min or
718
+ // above the max from the current menu
719
+ if ((newItem.max && oldItem.quantity > newItem.max) ||
720
+ (newItem.min && oldItem.quantity < newItem.min)) {
721
+ invalidItems.push(oldItem);
722
+ return null;
723
+ }
724
+ const nonNullGroups = updatedGroups === null || updatedGroups === void 0 ? void 0 : updatedGroups.filter(i => i !== null);
725
+ const allNewGroups = [...(nonNullGroups !== null && nonNullGroups !== void 0 ? nonNullGroups : []), ...newEmptyGroups];
726
+ const updatedItem = Object.assign(Object.assign({}, oldItem), { groups: allNewGroups });
727
+ // update the old item price to the new item price
728
+ updatedItem.price = newItem.price;
729
+ const pricedItem = calcPrices(updatedItem);
730
+ return pricedItem;
731
+ }
732
+ });
733
+ newCart = newCart.filter(i => i !== null);
734
+ if (missingItems.length || invalidItems.length) {
735
+ errors = { missingItems, invalidItems };
736
+ }
737
+ return { newCart, errors };
738
+ };
739
+ /* order submission */
740
+ export const getDefaultTip = (config) => {
741
+ if (!config || !config.gratuity || !config.gratuity.has_tip)
742
+ return null;
743
+ return config.gratuity.default ? config.gratuity.default.amount : null;
744
+ };
745
+ export const prepareOrder = (data) => {
746
+ data = data || {};
747
+ const requestedIso = !data.requestedAt ? 'asap' : data.requestedAt;
748
+ const order = {
749
+ revenue_center_id: data.revenueCenterId || null,
750
+ service_type: data.serviceType || 'PICKUP',
751
+ requested_at: requestedIso,
752
+ cart: data.cart ? makeSimpleCart(data.cart) : []
753
+ };
754
+ if (data.customer)
755
+ order.customer = data.customer;
756
+ if (data.details) {
757
+ const details = Object.assign({}, data.details);
758
+ // person_count must be submitted as integer
759
+ if (details.person_count)
760
+ details.person_count = parseInt(`${details.person_count}`) || null;
761
+ if (data.deviceType)
762
+ details.device_type = data.deviceType;
763
+ if (data.table || data.prepType) {
764
+ const prepType = data.prepType
765
+ ? data.prepType
766
+ : data.table
767
+ ? 'EAT_HERE'
768
+ : 'TAKE_OUT';
769
+ details.notes_internal =
770
+ prepType === 'EAT_HERE'
771
+ ? data.table
772
+ ? `DINE IN -- TABLE ${data.table}`
773
+ : 'DINE IN'
774
+ : 'TAKE OUT';
775
+ }
776
+ order.details = Object.assign({}, details);
777
+ }
778
+ if (data.surcharges)
779
+ order.surcharges = data.surcharges;
780
+ if (data.discounts)
781
+ order.discounts = data.discounts;
782
+ if (data.promoCodes)
783
+ order.promo_codes = data.promoCodes;
784
+ if (data.points)
785
+ order.points = data.points;
786
+ if (data.tip)
787
+ order.tip = data.tip;
788
+ if (data.tenders)
789
+ order.tenders = data.tenders;
790
+ if (data.address)
791
+ order.address = data.address;
792
+ if (data.orderId)
793
+ order.order_id = data.orderId;
794
+ if (data.cartId)
795
+ order.cart_id = data.cartId;
796
+ return order;
797
+ };
798
+ export const checkAmountRemaining = (total, tenders) => {
799
+ if (!tenders)
800
+ return total ? parseFloat(total) : 0.0;
801
+ let remaining = parseFloat(total) -
802
+ tenders.reduce((t, i) => { var _a; return (t += parseFloat((_a = i.amount) !== null && _a !== void 0 ? _a : '0')); }, 0.0);
803
+ remaining = Math.round((remaining + Number.EPSILON) * 100) / 100;
804
+ return Object.is(remaining, -0) ? 0.0 : remaining;
805
+ };