-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
696 lines (679 loc) · 19.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
const R = require('ramda');
const Promise = require('bluebird');
const assert = require('assert');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const wildcardMatch = require('./utils/wildcardMatch');
const { translateProduct } = require('./resolvers/product');
const { translateAvailability } = require('./resolvers/availability');
const { translateBooking } = require('./resolvers/booking');
const { translatePickupPoint } = require('./resolvers/pickup-point');
const CONCURRENCY = 3; // is this ok ?
const isNilOrEmpty = R.either(R.isNil, R.isEmpty);
const getHeaders = ({
apiKey,
acceptLanguage,
octoEnv,
// resellerId,
}) => ({
Authorization: `Bearer ${apiKey}`,
...octoEnv ? { 'Octo-Env': octoEnv } : {},
...acceptLanguage ? { 'Accept-Language': acceptLanguage } : {},
'Content-Type': 'application/json',
// ...resellerId ? { Referer: resellerId } : {},+
'Octo-Capabilities': 'octo/pricing,octo/pickups,octo/cart,octo/offers,octo/questions',
// 'Octo-Capabilities': 'octo/pricing',
});
class Plugin {
constructor(params) { // we get the env variables from here
Object.entries(params).forEach(([attr, value]) => {
this[attr] = value;
});
this.tokenTemplate = () => ({
apiKey: {
type: 'text',
regExp: /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/,
description: 'the Api Key provided from Ventrata, should be in uuid format',
},
resellerId: {
type: 'text',
regExp: /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/,
description: 'the Reseller Id provided from Ventrata, should be in uuid format',
},
endpoint: {
type: 'text',
regExp: /^(?!mailto:)(?:(?:http|https|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:(\/|\?|#)[^\s]*)?$/i,
default: 'https://api.ventrata.com/octo',
description: 'The url api endpoint from Ventata',
},
octoEnv: {
type: 'text',
list: ['live', 'test'],
regExp: /^(live|test)$/,
description: 'If on test it will not consume any availability, the barcodes will not work, and you will not be invoiced for it',
default: 'live',
},
acceptLanguage: {
type: 'text',
regExp: /^[a-z]{2}$/,
description: 'This conforms to the regular HTTP specification for language but if the supplier has translated their content it will return the content in the specified language if possible',
default: 'en',
},
});
this.errorPathsAxiosErrors = () => ([ // axios triggered errors
['response', 'data', 'errorMessage'],
]);
this.errorPathsAxiosAny = () => ([]); // 200's that should be errors
}
async validateToken({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
}) {
const url = `${endpoint || this.endpoint}/whoami?token=${apiKey}`;
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
try {
const connectionId = R.path(['data', 'connection', 'id'], await axios({
method: 'get',
url,
headers,
}));
return /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/.test(connectionId);
} catch (err) {
return false;
}
}
async searchProducts({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
payload,
typeDefsAndQueries: {
productTypeDefs,
productQuery,
},
}) {
let url = `${endpoint || this.endpoint}/products`;
if (!isNilOrEmpty(payload)) {
if (payload.productId) {
url = `${url}/${payload.productId}`;
}
}
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
let results = R.pathOr([], ['data'], await axios({
method: 'get',
url,
headers,
}));
if (!Array.isArray(results)) results = [results];
let products = await Promise.map(
results,
product => translateProduct({
rootValue: product,
typeDefs: productTypeDefs,
query: productQuery,
}),
);
// dynamic extra filtering
if (!isNilOrEmpty(payload)) {
const extraFilters = R.omit(['productId'], payload);
if (Object.keys(extraFilters).length > 0) {
products = products.filter(
product => Object.entries(extraFilters).every(
([key, value]) => {
if (typeof value === 'string') return wildcardMatch(value, product[key]);
return true;
},
),
);
}
}
return ({ products });
}
async searchQuote({
// token: {
// apiKey,
// endpoint,
// octoEnv,
// acceptLanguage,
// resellerId,
// },
// payload: {
// productIds,
// optionIds,
// occupancies,
// },
}) {
return { quote: [] };
}
async searchAvailability({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
payload: {
productIds,
optionIds,
units,
startDate,
endDate,
dateFormat,
currency,
},
typeDefsAndQueries: {
availTypeDefs,
availQuery,
},
}) {
assert(this.jwtKey, 'JWT secret should be set');
assert(
productIds.length === optionIds.length,
'mismatched productIds/options length',
);
assert(
optionIds.length === units.length,
'mismatched options/units length',
);
assert(productIds.every(Boolean), 'some invalid productId(s)');
assert(optionIds.every(Boolean), 'some invalid optionId(s)');
const localDateStart = moment(startDate, dateFormat).format('YYYY-MM-DD');
const localDateEnd = moment(endDate, dateFormat).format('YYYY-MM-DD');
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const url = `${endpoint || this.endpoint}/availability`;
const availability = (
await Promise.map(productIds, async (productId, ix) => {
const data = {
productId,
optionId: optionIds[ix],
localDateStart,
localDateEnd,
units: units[ix].map(u => ({ id: u.unitId, quantity: u.quantity })),
};
if (currency) data.currency = currency;
const result = R.path(['data'], await axios({
method: 'post',
url,
data,
headers,
}));
return Promise.map(result, avail => translateAvailability({
typeDefs: availTypeDefs,
query: availQuery,
rootValue: avail,
variableValues: {
productId,
optionId: optionIds[ix],
currency,
unitsWithQuantity: units[ix],
jwtKey: this.jwtKey,
},
}));
}, { concurrency: CONCURRENCY })
);
return { availability };
}
async availabilityCalendar({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
payload: {
productIds,
optionIds,
units,
startDate,
endDate,
currency,
dateFormat,
},
typeDefsAndQueries: {
availTypeDefs,
availQuery,
},
}) {
assert(this.jwtKey, 'JWT secret should be set');
assert(
productIds.length === optionIds.length,
'mismatched productIds/options length',
);
assert(
optionIds.length === units.length,
'mismatched options/units length',
);
assert(productIds.every(Boolean), 'some invalid productId(s)');
assert(optionIds.every(Boolean), 'some invalid optionId(s)');
const localDateStart = moment(startDate, dateFormat).format('YYYY-MM-DD');
const localDateEnd = moment(endDate, dateFormat).format('YYYY-MM-DD');
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const url = `${endpoint || this.endpoint}/availability/calendar`;
const availability = (
await Promise.map(productIds, async (productId, ix) => {
const data = {
productId,
optionId: optionIds[ix],
localDateStart,
localDateEnd,
// units is required here to get the total pricing for the calendar
units: units[ix].map(u => ({ id: u.unitId, quantity: u.quantity })),
};
if (currency) data.currency = currency;
const result = await axios({
method: 'post',
url,
data,
headers,
});
return Promise.map(result.data, avail => translateAvailability({
rootValue: avail,
typeDefs: availTypeDefs,
query: availQuery,
}));
}, { concurrency: CONCURRENCY })
);
return { availability };
}
async createBooking({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
},
payload: {
orderId,
partialOrder,
rebookingId,
availabilityKey,
holder,
notes,
reference,
pickupPoint,
customFieldValues,
},
typeDefsAndQueries: {
bookingTypeDefs,
bookingQuery,
},
}) {
assert(availabilityKey, 'an availability code is required !');
assert(R.path(['name'], holder), 'First Name is required');
assert(R.path(['surname'], holder), 'Last Name is required');
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
});
const dataForCreateBooking = await jwt.verify(availabilityKey, this.jwtKey);
// if customFieldValues contains perUnitItem fields
// we need to overwrite unitItems from the availabilityKey
if (customFieldValues && customFieldValues.length) {
const productCFV = customFieldValues.filter(o => !R.isNil(o.value) && !o.field.isPerUnitItem);
const unitItemCFV = customFieldValues.filter(o => !R.isNil(o.value) && o.field.isPerUnitItem);
if (productCFV.length) {
dataForCreateBooking.questionAnswers = productCFV.map(o => ({
questionId: o.field.id,
value: o.value,
}));
}
if (unitItemCFV.length) {
dataForCreateBooking.unitItems = R.call(R.compose(
R.map(arr => ({
unitId: arr[0].field.unitId,
questionAnswers: arr.map(o => ({
questionId: o.field.id.split('|')[0],
value: o.value,
})),
})),
R.values,
R.groupBy(o => {
const [questionId, unitItemIndex] = o.field.id.split('|');
return unitItemIndex;
}),
), unitItemCFV);
}
}
let booking = R.path(['data'], await axios({
method: rebookingId ? 'patch' : 'post',
url: `${endpoint || this.endpoint}/bookings${rebookingId ? `/${rebookingId}` : ''}`,
data: {
orderId,
settlementMethod: reference ? 'VOUCHER' : 'DEFERRED',
...dataForCreateBooking,
notes,
...(pickupPoint ? { pickupRequested: true, pickupPointId: pickupPoint } : {}),
},
headers,
}));
// for booking update, we may not need to confirm again
if (!booking.utcConfirmedAt && !partialOrder) {
const dataForConfirmBooking = {
contact: {
fullName: `${holder.name} ${holder.surname}`,
emailAddress: R.path(['emailAddress'], holder),
phoneNumber: R.path(['phone'], holder),
locales: R.path(['locales'], holder),
country: R.path(['country'], holder),
},
notes,
resellerReference: reference,
settlementMethod: reference ? 'VOUCHER' : 'DEFERRED',
};
booking = R.path(['data'], await axios({
method: 'post',
url: `${endpoint || this.endpoint}/bookings/${booking.uuid}/confirm`,
data: dataForConfirmBooking,
headers,
}));
}
return ({
booking: await translateBooking({
rootValue: booking,
typeDefs: bookingTypeDefs,
query: bookingQuery,
}),
});
}
async cancelBooking({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
payload: {
bookingId,
id,
reason,
},
typeDefsAndQueries: {
bookingTypeDefs,
bookingQuery,
},
}) {
assert(!isNilOrEmpty(bookingId) || !isNilOrEmpty(id), 'Invalid booking id');
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const url = `${endpoint || this.endpoint}/bookings/${bookingId || id}`;
const booking = R.path(['data'], await axios({
method: 'delete',
url,
data: { reason },
headers,
}));
return ({
cancellation: await translateBooking({
rootValue: booking,
typeDefs: bookingTypeDefs,
query: bookingQuery,
}),
});
}
async searchBooking({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
payload: {
bookingId,
resellerReference,
supplierBookingId,
travelDateStart,
travelDateEnd,
dateFormat,
},
typeDefsAndQueries: {
bookingTypeDefs,
bookingQuery,
},
}) {
assert(
!isNilOrEmpty(bookingId)
|| !isNilOrEmpty(resellerReference)
|| !isNilOrEmpty(supplierBookingId)
|| !(
isNilOrEmpty(travelDateStart) && isNilOrEmpty(travelDateEnd) && isNilOrEmpty(dateFormat)
),
'at least one parameter is required',
);
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const searchByUrl = async url => {
try {
return R.path(['data'], await axios({
method: 'get',
url,
headers,
}));
} catch (err) {
return [];
}
};
const bookings = await (async () => {
let url;
if (!isNilOrEmpty(bookingId)) {
return Promise.all([
searchByUrl(`${endpoint || this.endpoint}/bookings/${bookingId}`),
searchByUrl(`${endpoint || this.endpoint}/bookings?resellerReference=${bookingId}`),
searchByUrl(`${endpoint || this.endpoint}/bookings?supplierReference=${bookingId}`),
]);
}
if (!isNilOrEmpty(resellerReference)) {
url = `${endpoint || this.endpoint}/bookings?resellerReference=${resellerReference}`;
return R.path(['data'], await axios({
method: 'get',
url,
headers,
}));
}
if (!isNilOrEmpty(supplierBookingId)) {
url = `${endpoint || this.endpoint}/bookings?supplierReference=${supplierBookingId}`;
return R.path(['data'], await axios({
method: 'get',
url,
headers,
}));
}
if (!isNilOrEmpty(travelDateStart)) {
const localDateStart = moment(travelDateStart, dateFormat).format();
const localDateEnd = moment(travelDateEnd, dateFormat).format();
url = `${endpoint || this.endpoint}/bookings?localDateStart=${encodeURIComponent(localDateStart)}&localDateEnd=${encodeURIComponent(localDateEnd)}`;
return R.path(['data'], await axios({
method: 'get',
url,
headers,
}));
}
return [];
})();
return ({
bookings: await Promise.map(R.flatten(bookings), booking => translateBooking({
rootValue: booking,
typeDefs: bookingTypeDefs,
query: bookingQuery,
})),
});
}
async getPickupPoints({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
typeDefsAndQueries: {
pickupTypeDefs,
pickupQuery,
},
}) {
const url = `${endpoint || this.endpoint}/products`;
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const products = R.pathOr([], ['data'], await axios({
method: 'get',
url,
headers,
}));
const pickupPoints = R.call(R.compose(
R.uniqBy(R.prop('id')),
R.chain(R.propOr([], 'pickupPoints')),
R.filter(o => o.pickupPoints && o.pickupPoints.length),
R.chain(R.propOr([], 'options')),
), products);
return {
pickupPoints: await Promise.map(pickupPoints, async pickup => translatePickupPoint({
rootValue: pickup,
typeDefs: pickupTypeDefs,
query: pickupQuery,
})),
};
}
// eslint-disable-next-line class-methods-use-this
async getCreateBookingFields({
axios,
token: {
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
},
query: {
productId,
},
}) {
const headers = getHeaders({
apiKey,
endpoint,
octoEnv,
acceptLanguage,
resellerId,
});
const convertQToField = o => ({
id: o.id,
subtitle: o.description === o.label ? '' : o.description,
title: o.label,
type: (() => {
if (o.inputType === 'radio') return 'radio';
if (Array.isArray(o.selectOptions) && o.selectOptions.length) return 'extended-option';
if (o.inputType === 'number') return 'count';
if (o.inputType === 'text') return 'long';
if (o.inputType === 'textarea') return 'long';
return 'long';
})(),
options: o.selectOptions,
isPerUnitItem: o.isPerUnitItem,
});
if (!productId) {
const allProducts = R.pathOr([], ['data'], await axios({
method: 'get',
url: `${endpoint || this.endpoint}/products`,
headers,
}));
const allOptions = R.chain(R.propOr([], 'options'), allProducts);
const allUnits = R.chain(R.propOr([], 'units'), allOptions).map(o => ({ ...o, isPerUnitItem: true }));
const allQuestions = R.call(R.compose(
R.uniqBy(R.prop('id')),
R.chain(obj => (obj.questions || []).map(q => ({
...q,
isPerUnitItem: Boolean(obj.isPerUnitItem),
}))),
R.filter(o => o.questions && o.questions.length),
), [...allOptions, ...allUnits]);
return {
fields: [],
customFields: allQuestions.map(convertQToField),
};
}
const url = `${endpoint || this.endpoint}/products/${productId}`;
const product = R.pathOr([], ['data'], await axios({
method: 'get',
url,
headers,
}));
const allOptions = R.propOr([], 'options', product);
const allQuestions = R.call(R.compose(
R.uniqBy(R.prop('id')),
R.chain(obj => (obj.questions || []).map(q => ({
...q,
isPerUnitItem: Boolean(obj.isPerUnitItem),
}))),
R.filter(o => o.questions && o.questions.length),
), [
...allOptions,
...R.chain(R.propOr([], 'units'), allOptions).map(o => ({ ...o, isPerUnitItem: true })),
]);
if (!product) return { fields: [] };
return {
fields: [],
customFields: allQuestions.map(convertQToField),
};
}
}
module.exports = Plugin;