mts-booking-library 1.2.35 → 1.3.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,705 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ };
37
+ var __generator = (this && this.__generator) || function (thisArg, body) {
38
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
+ function verb(n) { return function (v) { return step([n, v]); }; }
41
+ function step(op) {
42
+ if (f) throw new TypeError("Generator is already executing.");
43
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
+ if (y = 0, t) op = [op[0] & 2, t.value];
46
+ switch (op[0]) {
47
+ case 0: case 1: t = op; break;
48
+ case 4: _.label++; return { value: op[1], done: false };
49
+ case 5: _.label++; y = op[1]; op = [0]; continue;
50
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
+ default:
52
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
+ if (t[2]) _.ops.pop();
57
+ _.trys.pop(); continue;
58
+ }
59
+ op = body.call(thisArg, _);
60
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
+ }
63
+ };
64
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
65
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
66
+ if (ar || !(i in from)) {
67
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
68
+ ar[i] = from[i];
69
+ }
70
+ }
71
+ return to.concat(ar || Array.prototype.slice.call(from));
72
+ };
73
+ Object.defineProperty(exports, "__esModule", { value: true });
74
+ exports.TplBooking = void 0;
75
+ var config_1 = require("../config");
76
+ var mtsStorage_1 = require("../mtsStorage");
77
+ var ErrorResponse_1 = require("../types/ErrorResponse");
78
+ var Reduction_1 = require("../types/common/Reduction");
79
+ var processBookingSteps_1 = require("../utils/processBookingSteps");
80
+ var booking_1 = require("./booking");
81
+ var TplBooking = /** @class */ (function (_super) {
82
+ __extends(TplBooking, _super);
83
+ /**
84
+ * This is the constructor of the TplBooking class.
85
+ * @param {MTSEnvs} env The environment in which the app is running. Can be "DEV", "STAGING" or "PROD"
86
+ * @param {string} sub_key The subscription key for using the APIs
87
+ * @param {boolean} [debug=false] If true, the app will run in debug mode (meaning that will print requests and responses in the console)
88
+ * @param {string} [language=Booking.Languages.EN] The language in which the app is running. Can be "it", "en", "fr", "de" or "es"
89
+ * @param {string} [access_token=undefined] The access token for calling MTS APIs
90
+ * @param {number} [sellerId=undefined] The id of the seller. If not set, it will return the results for all sellers
91
+ * @param {number} [resellerId=undefined] The id of the reseller.
92
+ */
93
+ function TplBooking(env, sub_key, debug, language, access_token, sellerId, resellerId) {
94
+ if (debug === void 0) { debug = false; }
95
+ if (language === void 0) { language = booking_1.Booking.Languages.EN; }
96
+ // Call Booking constructor
97
+ var _this = _super.call(this, env, sub_key, booking_1.Booking.BookingTypes.TPL, debug, language, access_token, sellerId, resellerId) || this;
98
+ // Set cartId
99
+ var cartId = _this.getStorage().getState().cartId;
100
+ if (cartId) {
101
+ _this.cartId = cartId;
102
+ }
103
+ return _this;
104
+ }
105
+ TplBooking.prototype.getStorage = function () {
106
+ if (this.config.ENV !== config_1.MTSEnvs.TEST) {
107
+ return (0, mtsStorage_1.useMtsBookingState)();
108
+ }
109
+ return (0, mtsStorage_1.useTestState)();
110
+ };
111
+ TplBooking.prototype.getCart = function () {
112
+ return this.cart;
113
+ };
114
+ TplBooking.prototype.resetBooking = function () {
115
+ this.cart = undefined;
116
+ this.cartId = undefined;
117
+ this.bookingStepsToStatus = new Map();
118
+ this.bookingDueDate = undefined;
119
+ try {
120
+ this.getStorage().getState().updateCartId(undefined);
121
+ }
122
+ catch (e) {
123
+ if (this.config.ENV !== config_1.MTSEnvs.TEST) {
124
+ throw new Error("Error while deleting cartId from storage");
125
+ }
126
+ console.log(e);
127
+ }
128
+ };
129
+ TplBooking.prototype.fetchAndSetCart = function (cartId) {
130
+ return __awaiter(this, void 0, void 0, function () {
131
+ var _this = this;
132
+ return __generator(this, function (_a) {
133
+ switch (_a.label) {
134
+ case 0: return [4 /*yield*/, this.fetchCart(cartId).then(function (cart) {
135
+ if (cart) {
136
+ var cartDate = new Date(cart.bookingDueDate);
137
+ if (cartDate > new Date() && !cart.hasIssuedTickets) {
138
+ _this.cart = cart;
139
+ _this.cartId = cart.id;
140
+ _this.bookingDueDate = cartDate; // See Booking class
141
+ // Update the sellerId. This is particularly important in Linkavel
142
+ _this.updateSellerId(cart.sellerId);
143
+ // Fill the booking process status
144
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(cart.stepsToStatus);
145
+ }
146
+ else {
147
+ // This should never happen, but just in case
148
+ _this.resetBooking();
149
+ }
150
+ }
151
+ })];
152
+ case 1:
153
+ _a.sent();
154
+ return [2 /*return*/];
155
+ }
156
+ });
157
+ });
158
+ };
159
+ TplBooking.prototype.fetchCart = function (cartId) {
160
+ return __awaiter(this, void 0, void 0, function () {
161
+ var url;
162
+ var _this = this;
163
+ return __generator(this, function (_a) {
164
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart?").concat(new URLSearchParams({ cartId: cartId.toString() }));
165
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
166
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
167
+ _this.resetBooking();
168
+ throw new Error(response);
169
+ }
170
+ // Check that the cart doe not have issued tickets
171
+ if (response.cart.hasIssuedTickets) {
172
+ _this.resetBooking();
173
+ }
174
+ return response.cart;
175
+ })];
176
+ });
177
+ });
178
+ };
179
+ /**
180
+ * This method allows to delete a cart, thus allowing the user to exit from the booking process.
181
+ * @returns An {@link ErrorResponse} object in case of error, nothing otherwise. Note that also in case of error, all
182
+ * data will be deleted.
183
+ */
184
+ TplBooking.prototype.deleteCart = function () {
185
+ return __awaiter(this, void 0, void 0, function () {
186
+ var url;
187
+ var _this = this;
188
+ return __generator(this, function (_a) {
189
+ // First check that it is possible to call this API
190
+ if (!this.cart || !this.cartId) {
191
+ throw Error("Cart is not initialized yet");
192
+ }
193
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/carts?").concat(new URLSearchParams({ cartId: this.cartId.toString() }));
194
+ return [2 /*return*/, this.callDeleteApi(url).then(function (response) {
195
+ // Clear all data
196
+ _this.resetBooking();
197
+ return (0, ErrorResponse_1.objectIsMTSErrorResponse)(response) ? response : response;
198
+ })];
199
+ });
200
+ });
201
+ };
202
+ /**
203
+ * This method allows to get the list of cities where it is possible to book a TPL service.
204
+ * @returns An array of {@link City} objects representing the cities where it is possible to book a TPL service
205
+ * if the call is successful, an {@link ErrorResponse} object otherwise.
206
+ */
207
+ TplBooking.prototype.getCities = function () {
208
+ return __awaiter(this, void 0, void 0, function () {
209
+ var url;
210
+ return __generator(this, function (_a) {
211
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/tpl/cities?");
212
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
213
+ return (0, ErrorResponse_1.objectIsMTSErrorResponse)(response) ? response : response.cities;
214
+ })];
215
+ });
216
+ });
217
+ };
218
+ /**
219
+ * This method fetches the list of super areas for a given city. A super area is a region of the city in which
220
+ * the TPL service is available at a certain price.
221
+ * @returns An array of {@link SuperArea} objects representing the SuperAreas if the call is successful, an {@link ErrorResponse} object otherwise.
222
+ */
223
+ TplBooking.prototype.getSuperAreas = function (cityId) {
224
+ return __awaiter(this, void 0, void 0, function () {
225
+ var searchParams, url;
226
+ return __generator(this, function (_a) {
227
+ searchParams = new URLSearchParams({ cityId: cityId.toString() });
228
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/tpl/superAreasByCity?").concat(searchParams);
229
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
230
+ return (0, ErrorResponse_1.objectIsMTSErrorResponse)(response) ? response : response.superAreas;
231
+ })];
232
+ });
233
+ });
234
+ };
235
+ /**
236
+ * This method fetches the list of terms types in a given super area.
237
+ * @returns An array of {@link TermsType} objects representing the available terms types if the call is successful, an {@link ErrorResponse} object otherwise.
238
+ */
239
+ TplBooking.prototype.getTermsTypes = function (superAreaId) {
240
+ return __awaiter(this, void 0, void 0, function () {
241
+ var searchParams, url;
242
+ return __generator(this, function (_a) {
243
+ searchParams = new URLSearchParams({ superAreaId: superAreaId.toString() });
244
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/tpl/termsTypesBySuperArea?").concat(searchParams);
245
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
246
+ return (0, ErrorResponse_1.objectIsMTSErrorResponse)(response) ? response : response.termsTypes;
247
+ })];
248
+ });
249
+ });
250
+ };
251
+ /**
252
+ * This method fetches the list of available tariffs for the selected terms type in a given super area.
253
+ * @returns An array of {@link GetTariffsResponse} if the call is successful, an {@link ErrorResponse} object otherwise.
254
+ */
255
+ TplBooking.prototype.getTariffs = function (superAreaId, termsTypeId) {
256
+ return __awaiter(this, void 0, void 0, function () {
257
+ var searchParams, url;
258
+ return __generator(this, function (_a) {
259
+ searchParams = new URLSearchParams({ superAreaId: superAreaId.toString(), termsTypeId: termsTypeId.toString() });
260
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/tpl/tariffs?").concat(searchParams);
261
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
262
+ // Check for error
263
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
264
+ return response;
265
+ }
266
+ // Convert the dictionary in the response and return the the correct object
267
+ var tariffPlanToTariffs = new Map(Object.entries(response.tariffPlanToTariffs).map(function (_a) {
268
+ var tariffPlanId = _a[0], tariffs = _a[1];
269
+ return [
270
+ +tariffPlanId,
271
+ tariffs
272
+ ];
273
+ }));
274
+ return { tariffs: response.tariffs, tariffPlanToTariffs: tariffPlanToTariffs };
275
+ })];
276
+ });
277
+ });
278
+ };
279
+ /**
280
+ * This method allows to create a TPL cart.
281
+ * @param {Map<number, number>} tariffIdToQuantity A map that associates a tariff id (the one chosen by the user) to the number of tickets to buy for that tariff.
282
+ * @param {Booking.Currencies} currency The currency in which the ticket is priced.
283
+ * @param {string} [startDate] The start date of the ticket. This is optional and should be used only for subscriptions.
284
+ */
285
+ TplBooking.prototype.createTplCart = function (tariffIdToQuantity, currency, startDate) {
286
+ return __awaiter(this, void 0, void 0, function () {
287
+ var url, processedTariffIdToQuantity, request;
288
+ var _this = this;
289
+ return __generator(this, function (_a) {
290
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/tpl/cart");
291
+ processedTariffIdToQuantity = {};
292
+ tariffIdToQuantity.forEach(function (value, key) {
293
+ processedTariffIdToQuantity[key] = value;
294
+ });
295
+ request = __assign({ tariffIdToQuantity: processedTariffIdToQuantity, currency: currency }, (startDate && { startDate: startDate }));
296
+ // Call the API
297
+ return [2 /*return*/, this.callPostApi(url, request).then(function (response) {
298
+ // Check for errors
299
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
300
+ // If there was an error, reset cartId and remove it from the mts-storage
301
+ _this.resetBooking();
302
+ return response;
303
+ }
304
+ _this.cart = response.cart;
305
+ _this.cartId = response.cart.id;
306
+ // Save the cartId in the mts-storage
307
+ _this.getStorage().getState().updateCartId(response.cart.id);
308
+ // Fill the booking process status
309
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(response.cart.stepsToStatus);
310
+ _this.bookingDueDate = new Date(response.cart.bookingDueDate);
311
+ // Update the sellerId. This is particularly important in Linkavel
312
+ _this.updateSellerId(response.cart.sellerId);
313
+ return response.cart;
314
+ })];
315
+ });
316
+ });
317
+ };
318
+ //#region Buyer data API
319
+ /**
320
+ * @description This method shall be called when the user wants to retrieve information about the buyer and the passengers.
321
+ * @returns An object of type {@link GetBuyerPassengersDetailsResponse} containing the buyer and the passengers information,
322
+ * as well as a list of the available tariffs for each trip.
323
+ */
324
+ TplBooking.prototype.getBuyerPassengersDetails = function () {
325
+ return __awaiter(this, void 0, void 0, function () {
326
+ var buyerPassengersDetails, url;
327
+ return __generator(this, function (_a) {
328
+ // First check that it is possible to call this API
329
+ if (!this.cart) {
330
+ throw Error("Cart is not initialized yet");
331
+ }
332
+ buyerPassengersDetails = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.BUYER_PASSENGERS);
333
+ if (!buyerPassengersDetails || !buyerPassengersDetails[0]) {
334
+ throw Error("The status of the cart does not allow to call this API");
335
+ }
336
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cart.id, "/details?");
337
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
338
+ // Check for errors
339
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
340
+ return response;
341
+ }
342
+ return {
343
+ buyerDataStatus: response.buyerDataStatus,
344
+ buyer: response.buyer,
345
+ passengers: [],
346
+ };
347
+ })];
348
+ });
349
+ });
350
+ };
351
+ /**
352
+ * @description This method shall be called when the user wants to retrieve information about an esisting buyer.
353
+ * @param {string} [linkavelCardNumber=undefined] The linkavel card number of the buyer. This parameter is required if linkavelCardPhoneNumber is not set.
354
+ * A linkavelCardNumber is a string of 9 digits.
355
+ * @param {string} [linkavelCardPhoneNumber=undefined] The linkavel card phone number of the buyer. This parameter is required if linkavelCardNumber is not set.
356
+ * @returns An object of type {@link GetBuyerPassengersDetailsResponse} containing the buyer and the passengers information,
357
+ * as well as a list of the available tariffs for each trip.
358
+ */
359
+ TplBooking.prototype.getBuyerFromLinkavelCard = function (linkavelCardNumber, linkavelCardPhoneNumber) {
360
+ return __awaiter(this, void 0, void 0, function () {
361
+ var buyerPassengersDetails, searchParams, url;
362
+ return __generator(this, function (_a) {
363
+ // First check that it is possible to call this API
364
+ if (!this.cart) {
365
+ throw Error("Cart is not initialized yet");
366
+ }
367
+ buyerPassengersDetails = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.BUYER_PASSENGERS);
368
+ if (!buyerPassengersDetails || !buyerPassengersDetails[0]) {
369
+ throw Error("The status of the cart does not allow to call this API");
370
+ }
371
+ if (!linkavelCardNumber && !linkavelCardPhoneNumber) {
372
+ throw Error("At least one of the parameters linkavelCardNumber and linkavelCardPhoneNumber must be set");
373
+ }
374
+ searchParams = new URLSearchParams(__assign(__assign({}, (linkavelCardNumber && { linkavelCardNumber: linkavelCardNumber })), (linkavelCardPhoneNumber && { linkavelCardPhoneNumber: linkavelCardPhoneNumber })));
375
+ url = "".concat(this.config.API_ENDPOINT, "/v3_resources/buyers?").concat(searchParams);
376
+ return [2 /*return*/, this.callGetApi(url).then(function (response) {
377
+ // Check for errors
378
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
379
+ return response;
380
+ }
381
+ return response.buyers[0];
382
+ })];
383
+ });
384
+ });
385
+ };
386
+ /**
387
+ * @description This method shall be called when the user wants to update the buyer information.
388
+ * @param {Person | null} buyerDetails The object containing the buyer information.
389
+ * It should be null if the buyer data cannot be specified (see {@link GetBuyerPassengersDetailsResponse.buyerDataStatus}).
390
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise.
391
+ */
392
+ TplBooking.prototype.updateBuyerPassengersDetails = function (buyerDetails) {
393
+ return __awaiter(this, void 0, void 0, function () {
394
+ var buyerPassengersDetails, request, url;
395
+ var _this = this;
396
+ return __generator(this, function (_a) {
397
+ // First check that it is possible to call this API
398
+ if (!this.cart) {
399
+ throw Error("Cart is not initialized yet");
400
+ }
401
+ buyerPassengersDetails = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.BUYER_PASSENGERS);
402
+ if (!buyerPassengersDetails || !buyerPassengersDetails[0]) {
403
+ throw Error("The status of the cart does not allow to call this API");
404
+ }
405
+ request = {
406
+ buyer: buyerDetails,
407
+ passengers: [],
408
+ };
409
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cart.id, "/details");
410
+ return [2 /*return*/, this.callPostApi(url, request).then(function (response) {
411
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
412
+ return response;
413
+ }
414
+ // Update the booking process status
415
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(response.stepsToStatus);
416
+ return true;
417
+ })];
418
+ });
419
+ });
420
+ };
421
+ //#endregion
422
+ //#region Reductions APIs
423
+ /**
424
+ * @description This method allows to add a reduction to the whole cart or to a single trip in the cart.
425
+ * @param {AddReductionRequest} request The information about the reduction to add
426
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise. Also, the cart is updated.
427
+ */
428
+ TplBooking.prototype.addReduction = function (request) {
429
+ return __awaiter(this, void 0, void 0, function () {
430
+ var discountsStep, _i, _a, step, url;
431
+ var _this = this;
432
+ var _b;
433
+ return __generator(this, function (_c) {
434
+ switch (_c.label) {
435
+ case 0:
436
+ // First check that it is possible to call this API
437
+ if (!this.cartId || this.cartId === 0) {
438
+ throw Error("Cart is not initialized yet");
439
+ }
440
+ discountsStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.DISCOUNTS);
441
+ if (!discountsStep)
442
+ throw Error("Booking step not found!");
443
+ if (!!discountsStep[0]) return [3 /*break*/, 5];
444
+ _i = 0, _a = [booking_1.Booking.BookingSteps.SEATS_SELECTION, booking_1.Booking.BookingSteps.EXTRAS];
445
+ _c.label = 1;
446
+ case 1:
447
+ if (!(_i < _a.length)) return [3 /*break*/, 4];
448
+ step = _a[_i];
449
+ if (!!((_b = this.bookingStepsToStatus.get(step)) !== null && _b !== void 0 ? _b : [false])[0]) return [3 /*break*/, 3];
450
+ return [4 /*yield*/, this.markBookingStepCompleted(step)];
451
+ case 2:
452
+ _c.sent();
453
+ _c.label = 3;
454
+ case 3:
455
+ _i++;
456
+ return [3 /*break*/, 1];
457
+ case 4:
458
+ // Check again if the discounts step is accessible
459
+ discountsStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.DISCOUNTS);
460
+ if (!discountsStep || !discountsStep[0]) {
461
+ throw Error("The status of the cart does not allow to call this API");
462
+ }
463
+ _c.label = 5;
464
+ case 5:
465
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cartId, "/payment/reduction");
466
+ return [2 /*return*/, this.callPostApi(url, request).then(function (response) {
467
+ var _a, _b;
468
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
469
+ return response;
470
+ }
471
+ var reductionResponse = response;
472
+ // Update the booking process status
473
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(reductionResponse.stepsToStatus);
474
+ // Update the cart
475
+ _this.cart = __assign(__assign({}, _this.cart), { totalAmountToPay: reductionResponse.totalAmountToPay, reductions: __spreadArray(__spreadArray([], ((_b = (_a = _this.cart) === null || _a === void 0 ? void 0 : _a.reductions) !== null && _b !== void 0 ? _b : []), true), [reductionResponse.reduction], false) });
476
+ return true;
477
+ })];
478
+ }
479
+ });
480
+ });
481
+ };
482
+ /**
483
+ * @description This method allows to remove a reduction from the whole cart or from a single trip in the cart.
484
+ * @param tripId The id of the trip from which the reduction should be removed. If the tripId is 0, then the reduction
485
+ * will be removed from the whole cart.
486
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise. Also, the cart is updated.
487
+ */
488
+ TplBooking.prototype.removeReduction = function (tripId) {
489
+ return __awaiter(this, void 0, void 0, function () {
490
+ var discountsStep, queryParams, url;
491
+ var _this = this;
492
+ return __generator(this, function (_a) {
493
+ // First check that it is possible to call this API
494
+ if (!this.cartId || this.cartId === 0) {
495
+ throw Error("Cart is not initialized yet");
496
+ }
497
+ discountsStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.DISCOUNTS);
498
+ if (!discountsStep || !discountsStep[0]) {
499
+ throw Error("The status of the cart does not allow to call this API");
500
+ }
501
+ queryParams = new URLSearchParams({ tripId: tripId.toString() });
502
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cartId, "/payment/reduction?").concat(queryParams);
503
+ return [2 /*return*/, this.callDeleteApi(url).then(function (response) {
504
+ var _a, _b, _c;
505
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
506
+ return response;
507
+ }
508
+ var reductionResponse = response;
509
+ // Update the booking process status
510
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(reductionResponse.stepsToStatus);
511
+ // Update the cart
512
+ _this.cart = __assign(__assign({}, _this.cart), { totalAmountToPay: reductionResponse.totalAmountToPay, reductions: (_c = (_b = (_a = _this.cart) === null || _a === void 0 ? void 0 : _a.reductions) === null || _b === void 0 ? void 0 : _b.filter(function (reduction) { return reduction.type === Reduction_1.ReductionType.WALLET ||
513
+ reduction.type === Reduction_1.ReductionType.VOUCHER ||
514
+ (reduction.type === Reduction_1.ReductionType.CASH && reduction.tripId !== tripId); })) !== null && _c !== void 0 ? _c : [] });
515
+ return true;
516
+ })];
517
+ });
518
+ });
519
+ };
520
+ /**
521
+ * @description This method allows the user to use the balance in his wallet to pay the cart. If the balance of
522
+ * the wallet is enough to pay the cart, the cart will be paid fully. Otherwise, the user will be asked to pay the
523
+ * remaining amount with another payment method.
524
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise.
525
+ */
526
+ TplBooking.prototype.useWallet = function () {
527
+ return __awaiter(this, void 0, void 0, function () {
528
+ var issueStep, _i, _a, step, url;
529
+ var _this = this;
530
+ var _b;
531
+ return __generator(this, function (_c) {
532
+ switch (_c.label) {
533
+ case 0:
534
+ // First check that it is possible to call this API
535
+ if (!this.cartId || this.cartId === 0) {
536
+ throw Error("Cart is not initialized yet");
537
+ }
538
+ issueStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.ISSUE);
539
+ if (!issueStep)
540
+ throw Error("Booking step: ".concat(booking_1.Booking.BookingSteps.ISSUE, " not found!"));
541
+ if (!!issueStep[0]) return [3 /*break*/, 5];
542
+ _i = 0, _a = [booking_1.Booking.BookingSteps.SEATS_SELECTION, booking_1.Booking.BookingSteps.EXTRAS, booking_1.Booking.BookingSteps.DISCOUNTS];
543
+ _c.label = 1;
544
+ case 1:
545
+ if (!(_i < _a.length)) return [3 /*break*/, 4];
546
+ step = _a[_i];
547
+ if (!!((_b = this.bookingStepsToStatus.get(step)) !== null && _b !== void 0 ? _b : [false])[0]) return [3 /*break*/, 3];
548
+ return [4 /*yield*/, this.markBookingStepCompleted(step)];
549
+ case 2:
550
+ _c.sent();
551
+ _c.label = 3;
552
+ case 3:
553
+ _i++;
554
+ return [3 /*break*/, 1];
555
+ case 4:
556
+ // Check again if the discounts step is accessible
557
+ issueStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.ISSUE);
558
+ if (!issueStep || !issueStep[0]) {
559
+ throw Error("The status of the cart does not allow to call the API: booking/cart/".concat(this.cartId, "/payment/wallet"));
560
+ }
561
+ _c.label = 5;
562
+ case 5:
563
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cartId, "/payment/wallet");
564
+ return [2 /*return*/, this.callPostApi(url, {}).then(function (response) {
565
+ var _a, _b;
566
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
567
+ return response;
568
+ }
569
+ var reductionResponse = response;
570
+ // Update the booking process status
571
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(reductionResponse.stepsToStatus);
572
+ // Update the cart
573
+ _this.cart = __assign(__assign({}, _this.cart), { totalAmountToPay: reductionResponse.totalAmountToPay, reductions: __spreadArray(__spreadArray([], ((_b = (_a = _this.cart) === null || _a === void 0 ? void 0 : _a.reductions) !== null && _b !== void 0 ? _b : []), true), [reductionResponse.reduction], false) });
574
+ return true;
575
+ })];
576
+ }
577
+ });
578
+ });
579
+ };
580
+ /**
581
+ * @description This method allows to remove a waller reduction from the cart.
582
+ *
583
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise. Also, the cart is updated.
584
+ */
585
+ TplBooking.prototype.removeWalletReduction = function () {
586
+ return __awaiter(this, void 0, void 0, function () {
587
+ var url;
588
+ var _this = this;
589
+ return __generator(this, function (_a) {
590
+ // First check that it is possible to call this API
591
+ if (!this.cartId || this.cartId === 0) {
592
+ throw Error("Cart is not initialized yet");
593
+ }
594
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cartId, "/payment/wallet");
595
+ return [2 /*return*/, this.callDeleteApi(url).then(function (response) {
596
+ var _a, _b, _c;
597
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
598
+ return response;
599
+ }
600
+ var reductionResponse = response;
601
+ // Update the booking process status
602
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(reductionResponse.stepsToStatus);
603
+ // Update the cart
604
+ _this.cart = __assign(__assign({}, _this.cart), { totalAmountToPay: reductionResponse.totalAmountToPay, reductions: (_c = (_b = (_a = _this.cart) === null || _a === void 0 ? void 0 : _a.reductions) === null || _b === void 0 ? void 0 : _b.filter(function (reduction) { return reduction.type !== Reduction_1.ReductionType.WALLET; })) !== null && _c !== void 0 ? _c : [] });
605
+ return true;
606
+ })];
607
+ });
608
+ });
609
+ };
610
+ /**
611
+ * @description This method allows the user to use a voucher to pay the cart.
612
+ * If the balance of the value of the voucher is enough to pay the cart, the cart will be paid fully.
613
+ * Otherwise, the user will be asked to pay the remaining amount with another payment method.
614
+ * @param {string} voucherCode The code of the voucher to use
615
+ * @returns An {@link ErrorResponse} object in case of error, true otherwise.
616
+ */
617
+ TplBooking.prototype.useVoucher = function (voucherCode) {
618
+ return __awaiter(this, void 0, void 0, function () {
619
+ var discountsStep, _i, _a, step, url;
620
+ var _this = this;
621
+ var _b;
622
+ return __generator(this, function (_c) {
623
+ switch (_c.label) {
624
+ case 0:
625
+ // First check that it is possible to call this API
626
+ if (!this.cartId || this.cartId === 0) {
627
+ throw Error("Cart is not initialized yet");
628
+ }
629
+ discountsStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.DISCOUNTS);
630
+ if (!discountsStep)
631
+ throw Error("Booking step not found!");
632
+ if (!!discountsStep[0]) return [3 /*break*/, 5];
633
+ _i = 0, _a = [booking_1.Booking.BookingSteps.SEATS_SELECTION, booking_1.Booking.BookingSteps.EXTRAS];
634
+ _c.label = 1;
635
+ case 1:
636
+ if (!(_i < _a.length)) return [3 /*break*/, 4];
637
+ step = _a[_i];
638
+ if (!!((_b = this.bookingStepsToStatus.get(step)) !== null && _b !== void 0 ? _b : [false])[0]) return [3 /*break*/, 3];
639
+ return [4 /*yield*/, this.markBookingStepCompleted(step)];
640
+ case 2:
641
+ _c.sent();
642
+ _c.label = 3;
643
+ case 3:
644
+ _i++;
645
+ return [3 /*break*/, 1];
646
+ case 4:
647
+ // Check again if the discounts step is accessible
648
+ discountsStep = this.bookingStepsToStatus.get(booking_1.Booking.BookingSteps.DISCOUNTS);
649
+ if (!discountsStep || !discountsStep[0]) {
650
+ throw Error("The status of the cart does not allow to call this API");
651
+ }
652
+ _c.label = 5;
653
+ case 5:
654
+ url = "".concat(this.config.API_ENDPOINT, "/v3_booking/cart/").concat(this.cartId, "/payment/voucher");
655
+ return [2 /*return*/, this.callPostApi(url, { voucherCode: voucherCode }).then(function (response) {
656
+ var _a, _b;
657
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(response)) {
658
+ return response;
659
+ }
660
+ var reductionResponse = response;
661
+ // Update the booking process status
662
+ _this.bookingStepsToStatus = (0, processBookingSteps_1.processBookingSteps)(reductionResponse.stepsToStatus);
663
+ // Update the cart
664
+ _this.cart = __assign(__assign({}, _this.cart), { totalAmountToPay: reductionResponse.totalAmountToPay, reductions: __spreadArray(__spreadArray([], ((_b = (_a = _this.cart) === null || _a === void 0 ? void 0 : _a.reductions) !== null && _b !== void 0 ? _b : []), true), [reductionResponse.reduction], false) });
665
+ return true;
666
+ })];
667
+ }
668
+ });
669
+ });
670
+ };
671
+ return TplBooking;
672
+ }(booking_1.Booking));
673
+ exports.TplBooking = TplBooking;
674
+ (function (TplBooking) {
675
+ var _this = this;
676
+ TplBooking.createBooking = function (env, sub_key, debug, language, access_token, sellerId, resellerId) { return __awaiter(_this, void 0, void 0, function () {
677
+ var booking, error_1;
678
+ return __generator(this, function (_a) {
679
+ switch (_a.label) {
680
+ case 0:
681
+ booking = new TplBooking(env, sub_key, debug, language, access_token, sellerId, resellerId);
682
+ _a.label = 1;
683
+ case 1:
684
+ _a.trys.push([1, 4, , 5]);
685
+ if (!booking.cartId) return [3 /*break*/, 3];
686
+ return [4 /*yield*/, booking.fetchAndSetCart(booking.cartId)];
687
+ case 2:
688
+ _a.sent();
689
+ _a.label = 3;
690
+ case 3: return [2 /*return*/, booking];
691
+ case 4:
692
+ error_1 = _a.sent();
693
+ // Check if the error is due to an expired cart. In this case, delete the cartId from the mts-storage
694
+ // This error can occur when the user refreshes the page and the cart has expired
695
+ if ((0, ErrorResponse_1.objectIsMTSErrorResponse)(error_1) && error_1.mtsCode === 40053) {
696
+ booking.getStorage().getState().updateCartId(undefined);
697
+ booking.cartId = undefined;
698
+ return [2 /*return*/, booking];
699
+ }
700
+ throw new Error("Could not instantiate TplBooking");
701
+ case 5: return [2 /*return*/];
702
+ }
703
+ });
704
+ }); };
705
+ })(TplBooking || (exports.TplBooking = TplBooking = {}));