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