@vendit-dev/thirdparty-adapters 0.1.0

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.
@@ -0,0 +1,171 @@
1
+ import { UserServiceGrpcCaller } from '@vendit-dev/utility-modules';
2
+ import { Redis } from 'ioredis';
3
+ import MutexLock from '../utils/mutex';
4
+ declare type VenditWingsAuthInfo = {
5
+ scope: string;
6
+ credential: {
7
+ companyId: string;
8
+ vendorId: string;
9
+ apiKey: string;
10
+ kioskIp: string;
11
+ HOTEL_FAX_NO: string;
12
+ HOTEL_MAIL_ADDR: string;
13
+ HOTEL_TEL_NO: string;
14
+ BSNS_ENG_NAME: string;
15
+ CEO_NAME: string;
16
+ BSNS_OTH_NAME: string;
17
+ BSNS_NAME: string;
18
+ HOTEL_DTL_ADDR: string;
19
+ BSNS_CODE: string;
20
+ BRN: string;
21
+ };
22
+ expiresAt: number;
23
+ };
24
+ declare type WingsCommonCredential = {
25
+ vendorId: string;
26
+ companyId: string;
27
+ apiKey: string;
28
+ kioskIp: string;
29
+ };
30
+ declare type WingsApiCommonResponse = {
31
+ resultData: any;
32
+ };
33
+ export declare class WingsApiController {
34
+ URI: string;
35
+ CONTEXT: string;
36
+ constructor({ contextApi }: {
37
+ contextApi: string;
38
+ });
39
+ callWingsApi: ({ route, params, auth }: {
40
+ route: string;
41
+ params?: any;
42
+ auth: {
43
+ params: any;
44
+ headers: any;
45
+ };
46
+ }) => Promise<WingsApiCommonResponse>;
47
+ }
48
+ export default class WingsAdapter {
49
+ static indexAccommodation: ({ accommodationId }: {
50
+ accommodationId: string;
51
+ }) => string;
52
+ static authFromCredentials: ({ vendorId, companyId, apiKey, kioskIp, }: WingsCommonCredential) => {
53
+ headers: {
54
+ 'API-KEY': string;
55
+ VENDOR_ID: string;
56
+ 'API-COMPANY': string;
57
+ };
58
+ params: {
59
+ KIOSK_IP: string;
60
+ };
61
+ };
62
+ mutexLock: MutexLock;
63
+ authenticator: UserServiceGrpcCaller;
64
+ redis: Redis;
65
+ PROVIDER_KEY: string;
66
+ constructor({ authenticator, redis }: {
67
+ authenticator: UserServiceGrpcCaller;
68
+ redis: Redis;
69
+ });
70
+ checkWingsIntegration: ({ accommodationId }: {
71
+ accommodationId: string;
72
+ }) => Promise<boolean>;
73
+ getAccommodationAuthInfo: ({ accommodationId }: {
74
+ accommodationId: string;
75
+ }) => Promise<VenditWingsAuthInfo>;
76
+ getHotelInformation: ({ accommodationId }: {
77
+ accommodationId: string;
78
+ }) => Promise<any>;
79
+ checkInReservation: ({ accommodationId, reservationNumber, sequenceNumber, startDate, endDate, }: {
80
+ accommodationId: string;
81
+ reservationNumber: string;
82
+ sequenceNumber: string;
83
+ startDate: string;
84
+ endDate: string;
85
+ }) => Promise<any>;
86
+ cancelCheckInReservation: ({ accommodationId, folioNumber }: {
87
+ accommodationId: string;
88
+ folioNumber: string;
89
+ }) => Promise<boolean>;
90
+ getReservationByNumber: ({ accommodationId, reservationNumber }: {
91
+ accommodationId: string;
92
+ reservationNumber: string;
93
+ }) => Promise<any>;
94
+ getPurchaseAmount: ({ accommodationId, folioNumber }: {
95
+ accommodationId: string;
96
+ folioNumber: string;
97
+ }) => Promise<null | undefined>;
98
+ getWalkinInfo: ({ accommodationId, startDate, endDate, adultCount, childCount, langType, }: {
99
+ accommodationId: string;
100
+ startDate: string;
101
+ endDate: string;
102
+ adultCount: number;
103
+ childCount: number;
104
+ langType: string;
105
+ }) => Promise<{
106
+ walkinInfo: any;
107
+ roomInfo: any;
108
+ } | null>;
109
+ getWalkInRoomRate: ({ accommodationId, roomTypeCode, startDate, endDate, salesDate, }: {
110
+ accommodationId: string;
111
+ startDate: string;
112
+ endDate: string;
113
+ roomTypeCode: string;
114
+ salesDate: string;
115
+ }) => Promise<any>;
116
+ queryWalkinRoomTypesWithPrices: ({ accommodationId, startDate, endDate, adultCount, childCount, langType, }: {
117
+ accommodationId: string;
118
+ startDate: string;
119
+ endDate: string;
120
+ adultCount: number;
121
+ childCount: number;
122
+ langType: string;
123
+ }) => Promise<{
124
+ walkinInfo: any;
125
+ roomInfo: any[];
126
+ } | null>;
127
+ processWalkIn: ({ accommodationId, roomTypeCode, startDate, endDate, nights, salesDate, guestName, adultCount, childCount, dailyRoomFees, }: {
128
+ accommodationId: string;
129
+ roomTypeCode: string;
130
+ startDate: string;
131
+ endDate: string;
132
+ nights: number;
133
+ salesDate: string;
134
+ guestName: string;
135
+ adultCount: number;
136
+ childCount: number;
137
+ dailyRoomFees: Array<string>;
138
+ }) => Promise<any>;
139
+ getCheckOutInfo: ({ accommodationId, folioNumber, }: {
140
+ accommodationId: string;
141
+ folioNumber: string;
142
+ }) => Promise<any>;
143
+ processCheckOut: ({ accommodationId, folioNumber, }: {
144
+ accommodationId: string;
145
+ folioNumber: string;
146
+ }) => Promise<any>;
147
+ reportKeyIssue: ({ accommodationId, folioNumber, roomNumber, registerDate, issuedCount, resultMessage, }: {
148
+ accommodationId: string;
149
+ folioNumber: string;
150
+ roomNumber: string;
151
+ registerDate: string;
152
+ issuedCount: number;
153
+ resultMessage: string;
154
+ }) => Promise<any>;
155
+ reportKeyRetrieve: ({ accommodationId, folioNumber, }: {
156
+ accommodationId: string;
157
+ folioNumber: string;
158
+ }) => Promise<any>;
159
+ savePayment: ({ accommodationId, folioNumber, paymentAmount, saleDate, paymentInfo, }: {
160
+ accommodationId: string;
161
+ folioNumber: string;
162
+ paymentAmount: string;
163
+ saleDate: string;
164
+ paymentInfo: string;
165
+ }) => Promise<any>;
166
+ savePaymentWithPaymentId: ({ paymentId, folioNumber, }: {
167
+ paymentId: string;
168
+ folioNumber: string;
169
+ }) => Promise<null | undefined>;
170
+ }
171
+ export {};
@@ -0,0 +1,476 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import fetch from 'node-fetch';
11
+ import moment from 'moment';
12
+ import MutexLock from '../utils/mutex';
13
+ const WINGS_API_ENDPOINT = 'https://wingsapi.sanhait.com';
14
+ const WINGS_COMMON_REQUEST_HEADERS = {
15
+ 'Content-Type': 'application/json',
16
+ 'Echo-Token': '',
17
+ };
18
+ const WINGS_COMMON_REQUEST_PARAMS = {
19
+ LANG_TYPE: 'KOR',
20
+ KIOSK_ID: 'KIOSK',
21
+ };
22
+ export class WingsApiController {
23
+ constructor({ contextApi }) {
24
+ this.callWingsApi = ({ route, params = {}, auth }) => __awaiter(this, void 0, void 0, function* () {
25
+ const requestOptions = {
26
+ method: 'POST',
27
+ headers: Object.assign(Object.assign({}, WINGS_COMMON_REQUEST_HEADERS), auth.headers),
28
+ body: JSON.stringify(Object.assign(Object.assign(Object.assign({}, auth.params), WINGS_COMMON_REQUEST_PARAMS), params)),
29
+ };
30
+ if (process.env.NODE_ENV === 'development') {
31
+ console.log(requestOptions);
32
+ }
33
+ const response = yield fetch(`${this.URI}/${this.CONTEXT}/${route}`, requestOptions);
34
+ return response.json();
35
+ });
36
+ this.URI = WINGS_API_ENDPOINT;
37
+ this.CONTEXT = contextApi;
38
+ }
39
+ }
40
+ const apiController = new WingsApiController({
41
+ contextApi: 'kiosk',
42
+ });
43
+ export default class WingsAdapter {
44
+ constructor({ authenticator, redis }) {
45
+ this.PROVIDER_KEY = 'SanhaWings';
46
+ this.checkWingsIntegration = ({ accommodationId }) => __awaiter(this, void 0, void 0, function* () { return !!this.getAccommodationAuthInfo({ accommodationId }); });
47
+ this.getAccommodationAuthInfo = ({ accommodationId }) => __awaiter(this, void 0, void 0, function* () {
48
+ let existingAuth = yield this.redis.get(WingsAdapter.indexAccommodation({ accommodationId }));
49
+ if (existingAuth) {
50
+ if (existingAuth === 'NOT_FOUND') {
51
+ throw new Error('THIRDPARTY_AUTH_NOT_FOUND');
52
+ }
53
+ return JSON.parse(existingAuth);
54
+ }
55
+ const lockId = `WINGS-HKEY|${accommodationId}`;
56
+ const lockHash = yield this.mutexLock.getMutexLock(lockId);
57
+ existingAuth = yield this.redis.get(WingsAdapter.indexAccommodation({ accommodationId }));
58
+ try {
59
+ if (existingAuth) {
60
+ return JSON.parse(existingAuth);
61
+ }
62
+ const newAuth = yield this.authenticator.getThirdPartyCredential({ accommodationId, provider: this.PROVIDER_KEY });
63
+ if (!newAuth) {
64
+ yield this.redis.set(WingsAdapter.indexAccommodation({ accommodationId }), 'NOT_FOUND', 'EX', 60 * 10);
65
+ throw new Error('THIRDPARTY_AUTH_NOT_FOUND');
66
+ }
67
+ newAuth.credential = JSON.parse(newAuth.credential);
68
+ yield this.redis.set(WingsAdapter.indexAccommodation({ accommodationId }), JSON.stringify(newAuth), 'EX', 60 * 10);
69
+ return newAuth;
70
+ }
71
+ catch (err) {
72
+ console.log(err);
73
+ throw err;
74
+ }
75
+ finally {
76
+ yield this.mutexLock.unlockMutexLock(lockId, lockHash);
77
+ }
78
+ });
79
+ this.getHotelInformation = ({ accommodationId }) => __awaiter(this, void 0, void 0, function* () {
80
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
81
+ const response = yield apiController.callWingsApi({
82
+ route: 'ki00/getHotelInformation',
83
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
84
+ });
85
+ return response.resultData;
86
+ });
87
+ this.checkInReservation = ({ accommodationId, reservationNumber, sequenceNumber, startDate, endDate, }) => __awaiter(this, void 0, void 0, function* () {
88
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
89
+ try {
90
+ const response = yield apiController.callWingsApi({
91
+ route: 'ki01/kioskCheckIn',
92
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
93
+ params: {
94
+ RSVN_NO: reservationNumber,
95
+ RSVN_SEQ_NO: sequenceNumber,
96
+ ARRV_DATE: startDate,
97
+ DEPT_DATE: endDate,
98
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
99
+ },
100
+ });
101
+ const { resultData } = response;
102
+ if (!resultData) {
103
+ throw new Error('FAILED_TO_CHECKIN');
104
+ }
105
+ return resultData;
106
+ }
107
+ catch (err) {
108
+ console.log(err);
109
+ throw err;
110
+ }
111
+ });
112
+ this.cancelCheckInReservation = ({ accommodationId, folioNumber }) => __awaiter(this, void 0, void 0, function* () {
113
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
114
+ try {
115
+ const response = yield apiController.callWingsApi({
116
+ route: 'ki00/kioskCancel',
117
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
118
+ params: {
119
+ FOLIO_NO: folioNumber,
120
+ },
121
+ });
122
+ const { resultData: { RESULT_YN, RESULT_MSG } } = response;
123
+ if (RESULT_YN !== 'Y') {
124
+ throw new Error(RESULT_MSG || 'DATA_NOT_FOUND');
125
+ }
126
+ return true;
127
+ }
128
+ catch (err) {
129
+ console.log(err);
130
+ throw err;
131
+ }
132
+ });
133
+ this.getReservationByNumber = ({ accommodationId, reservationNumber }) => __awaiter(this, void 0, void 0, function* () {
134
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
135
+ try {
136
+ const response = yield apiController.callWingsApi({
137
+ route: 'ki01/kioskRsvnInfo',
138
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
139
+ params: {
140
+ RSVN_NO: reservationNumber,
141
+ },
142
+ });
143
+ const { resultData: { rsvnInfo } } = response;
144
+ if (!rsvnInfo) {
145
+ throw new Error('Data not found');
146
+ }
147
+ return rsvnInfo;
148
+ }
149
+ catch (err) {
150
+ console.log(err);
151
+ return null;
152
+ }
153
+ });
154
+ this.getPurchaseAmount = ({ accommodationId, folioNumber }) => __awaiter(this, void 0, void 0, function* () {
155
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
156
+ try {
157
+ const response = yield apiController.callWingsApi({
158
+ route: 'ki01/searchPaymentAmount',
159
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
160
+ params: {
161
+ FOLIO_NO: folioNumber,
162
+ },
163
+ });
164
+ }
165
+ catch (err) {
166
+ console.log(err);
167
+ return null;
168
+ }
169
+ });
170
+ this.getWalkinInfo = ({ accommodationId, startDate, endDate, adultCount, childCount, langType, }) => __awaiter(this, void 0, void 0, function* () {
171
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
172
+ try {
173
+ const response = yield apiController.callWingsApi({
174
+ route: 'ki02/kioskWalkInInfo',
175
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
176
+ params: {
177
+ ARRV_DATE: moment(startDate).format('YYYYMMDD'),
178
+ DEPT_DATE: moment(endDate).format('YYYYMMDD'),
179
+ ADULT_CNT: adultCount,
180
+ CHILD_CNT: childCount,
181
+ LANG_TYPE: langType,
182
+ },
183
+ });
184
+ const { resultData: { walkinInfo, roomInfo } } = response;
185
+ return {
186
+ walkinInfo,
187
+ roomInfo,
188
+ };
189
+ }
190
+ catch (err) {
191
+ console.log(err);
192
+ return null;
193
+ }
194
+ });
195
+ this.getWalkInRoomRate = ({ accommodationId, roomTypeCode, startDate, endDate, salesDate, }) => __awaiter(this, void 0, void 0, function* () {
196
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
197
+ try {
198
+ const response = yield apiController.callWingsApi({
199
+ route: 'ki02/kioskWalkInRoomRate',
200
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
201
+ params: {
202
+ ARRV_DATE: moment(startDate).format('YYYYMMDD'),
203
+ DEPT_DATE: moment(endDate).format('YYYYMMDD'),
204
+ ROOM_TYPE_CODE: roomTypeCode,
205
+ SALES_DATE: moment(salesDate).format('YYYYMMDD'),
206
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
207
+ },
208
+ });
209
+ const { resultData } = response;
210
+ return resultData;
211
+ }
212
+ catch (err) {
213
+ console.log(err);
214
+ return null;
215
+ }
216
+ });
217
+ this.queryWalkinRoomTypesWithPrices = ({ accommodationId, startDate, endDate, adultCount, childCount, langType, }) => __awaiter(this, void 0, void 0, function* () {
218
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
219
+ try {
220
+ const response = yield apiController.callWingsApi({
221
+ route: 'ki02/kioskWalkInInfo',
222
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
223
+ params: {
224
+ ARRV_DATE: moment(startDate).format('YYYYMMDD'),
225
+ DEPT_DATE: moment(endDate).format('YYYYMMDD'),
226
+ ADULT_CNT: adultCount,
227
+ CHILD_CNT: childCount,
228
+ LANG_TYPE: langType,
229
+ },
230
+ });
231
+ const { resultData: { walkinInfo, roomInfo } } = response;
232
+ const roomInfoWithPrices = yield Promise.all(roomInfo.map((roomType) => __awaiter(this, void 0, void 0, function* () {
233
+ const { ROOM_TYPE_CODE } = roomType;
234
+ const priceData = yield this.getWalkInRoomRate({
235
+ accommodationId,
236
+ endDate,
237
+ startDate,
238
+ salesDate: startDate,
239
+ roomTypeCode: ROOM_TYPE_CODE,
240
+ });
241
+ priceData.rawData = JSON.stringify(priceData);
242
+ priceData.dailyPrices = priceData.walkinRoomDaily.map((dailyPrice) => ({
243
+ rawData: JSON.stringify(dailyPrice),
244
+ amount: dailyPrice.ROOM_FEE,
245
+ date: dailyPrice.LODG_DATE,
246
+ }));
247
+ delete priceData.walkinRoomDaily;
248
+ return Object.assign(Object.assign({}, roomType), { price: priceData });
249
+ })));
250
+ return {
251
+ walkinInfo,
252
+ roomInfo: roomInfoWithPrices,
253
+ };
254
+ }
255
+ catch (err) {
256
+ console.log(err);
257
+ return null;
258
+ }
259
+ });
260
+ this.processWalkIn = ({ accommodationId, roomTypeCode, startDate, endDate, nights, salesDate, guestName, adultCount, childCount, dailyRoomFees, }) => __awaiter(this, void 0, void 0, function* () {
261
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
262
+ try {
263
+ const response = yield apiController.callWingsApi({
264
+ route: 'ki02/walkinProcess',
265
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
266
+ params: {
267
+ walkinInfo: {
268
+ ARRV_DATE: startDate,
269
+ DEPT_DATE: endDate,
270
+ NIGHTS: nights,
271
+ ROOM_TYPE_CODE: roomTypeCode,
272
+ SALES_DATE: salesDate,
273
+ ADULT_CNT: adultCount,
274
+ CHILD_CNT: childCount,
275
+ INHS_GEST_NAME: guestName,
276
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
277
+ },
278
+ walkinRoomDaily: dailyRoomFees === null || dailyRoomFees === void 0 ? void 0 : dailyRoomFees.map(value => JSON.parse(value)),
279
+ },
280
+ });
281
+ const { resultData } = response;
282
+ return resultData;
283
+ }
284
+ catch (err) {
285
+ console.log(err);
286
+ return null;
287
+ }
288
+ });
289
+ this.getCheckOutInfo = ({ accommodationId, folioNumber, }) => __awaiter(this, void 0, void 0, function* () {
290
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
291
+ try {
292
+ const response = yield apiController.callWingsApi({
293
+ route: 'ki03/kioskCheckOutInfo',
294
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
295
+ params: {
296
+ FOLIO_NO: folioNumber,
297
+ },
298
+ });
299
+ const { resultData } = response;
300
+ return resultData;
301
+ }
302
+ catch (err) {
303
+ console.log(err);
304
+ return null;
305
+ }
306
+ });
307
+ this.processCheckOut = ({ accommodationId, folioNumber, }) => __awaiter(this, void 0, void 0, function* () {
308
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
309
+ try {
310
+ const response = yield apiController.callWingsApi({
311
+ route: 'ki03/kioskCheckOutProcess',
312
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
313
+ params: {
314
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
315
+ FOLIO_NO: folioNumber,
316
+ },
317
+ });
318
+ const { resultData } = response;
319
+ return resultData;
320
+ }
321
+ catch (err) {
322
+ console.log(err);
323
+ return null;
324
+ }
325
+ });
326
+ this.reportKeyIssue = ({ accommodationId, folioNumber, roomNumber, registerDate, issuedCount, resultMessage, }) => __awaiter(this, void 0, void 0, function* () {
327
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
328
+ try {
329
+ const response = yield apiController.callWingsApi({
330
+ route: 'ki01/kioskRoomKeyIssue',
331
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
332
+ params: {
333
+ FOLIO_NO: folioNumber,
334
+ ROOM_NO: roomNumber,
335
+ REG_DATE: registerDate,
336
+ REG_TIME: moment().format('HHmmSS'),
337
+ ISSUE_CNT: issuedCount,
338
+ RESULT_MSG: resultMessage,
339
+ },
340
+ });
341
+ const { resultData } = response;
342
+ if (!resultData) {
343
+ throw new Error('Data not found');
344
+ }
345
+ return resultData;
346
+ }
347
+ catch (err) {
348
+ console.log(err);
349
+ return null;
350
+ }
351
+ });
352
+ this.reportKeyRetrieve = ({ accommodationId, folioNumber, }) => __awaiter(this, void 0, void 0, function* () {
353
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
354
+ try {
355
+ const response = yield apiController.callWingsApi({
356
+ route: 'ki03/kioskCheckOutRoomKey',
357
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
358
+ params: {
359
+ FOLIO_NO: folioNumber,
360
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
361
+ ROOM_KEY_CHECK_YN: 'Y',
362
+ RETURN_KEY_CNT: 1,
363
+ },
364
+ });
365
+ const { resultData } = response;
366
+ if (!resultData) {
367
+ throw new Error('Data not found');
368
+ }
369
+ return resultData;
370
+ }
371
+ catch (err) {
372
+ console.log(err);
373
+ return null;
374
+ }
375
+ });
376
+ this.savePayment = ({ accommodationId, folioNumber, paymentAmount, saleDate, paymentInfo, }) => __awaiter(this, void 0, void 0, function* () {
377
+ const authInfo = yield this.getAccommodationAuthInfo({ accommodationId });
378
+ const parsedData = JSON.parse(paymentInfo);
379
+ let refinedData;
380
+ switch (parsedData.vanType) {
381
+ case ('KSNET'): {
382
+ refinedData = {
383
+ // KSNET data
384
+ APPR_TYPE_CODE: parsedData.APPR_TYPE_CODE || '11',
385
+ COMT: parsedData.NOTICE2.trim(),
386
+ PUR_CPNY_NAME: parsedData.PURCHASENAME.trim(),
387
+ PUR_CPNY_CODE: parsedData.PURCHASECODE.trim(),
388
+ ISSUE_CPMY_NAME: parsedData.MESSAGE1.trim(),
389
+ ISSUE_CPMY_CODE: parsedData.ISSUERCODE.trim(),
390
+ FRNC_STORE_NO: parsedData.MERCHANTNUMBER.trim(),
391
+ CRDT_CARD_NO: parsedData.FILLER.trim(),
392
+ RSPNS_CODE: parsedData.CORPRESPCODE.trim(),
393
+ TERM_NO: parsedData.TERMID.trim(),
394
+ APPR_NO: parsedData.APPROVALNO.trim(),
395
+ APPR_DATE: `20${parsedData.TRADETIME.slice(0, 6)}`,
396
+ APPR_TIME: parsedData.TRADETIME.slice(6, 10),
397
+ CNFM_DATE: `20${parsedData.TRADETIME.slice(0, 6)}`,
398
+ CNFM_TYPE: parsedData.TRADETIME.slice(6, 10),
399
+ // Generated data
400
+ INSTA_MMS_CNT: parsedData.INSTA_MMS_CNT || '00',
401
+ APPR_LINE_TYPE_CODE: parsedData.APPR_LINE_TYPE_CODE || 'A',
402
+ KEY_IN_TYPE_CODE: parsedData.KEY_IN_TYPE_CODE || 'S',
403
+ SPC_UNIQUE_ALIAS: parsedData.SPC_UNIQUE_ALIAS || 'SEND_GB_APP',
404
+ CARD_READING_DATA: parsedData.CARD_READING_DATA || '0000000000000000:00000000000000000000',
405
+ SPC_TYPE_CODE: parsedData.SPC_TYPE_CODE,
406
+ };
407
+ break;
408
+ }
409
+ case ('CASH'): {
410
+ refinedData = {
411
+ CRDT_CARD_NO: 'KICASH',
412
+ COMT: 'KISOK_CASH_PURCHASE',
413
+ };
414
+ break;
415
+ }
416
+ default: {
417
+ throw new Error('NOT_REGISTERED_VAN');
418
+ }
419
+ }
420
+ try {
421
+ const response = yield apiController.callWingsApi({
422
+ route: 'ki00/payment',
423
+ auth: WingsAdapter.authFromCredentials(authInfo.credential),
424
+ params: {
425
+ FOLIO_NO: folioNumber,
426
+ PAY_AMT: paymentAmount,
427
+ SALE_DATE: saleDate,
428
+ CREDIT_RESULT: Object.assign({ APPR_AMT: paymentAmount, FOLIO_NO: folioNumber }, refinedData),
429
+ BSNS_CODE: authInfo.credential.BSNS_CODE,
430
+ },
431
+ });
432
+ const { resultData } = response;
433
+ console.log(response);
434
+ console.log(resultData);
435
+ return resultData;
436
+ }
437
+ catch (err) {
438
+ console.log(err);
439
+ return false;
440
+ }
441
+ });
442
+ this.savePaymentWithPaymentId = ({ paymentId, folioNumber, }) => __awaiter(this, void 0, void 0, function* () {
443
+ const foundPaymentInfo = yield this.redis.get(`SanhaWings|${paymentId}`);
444
+ if (!foundPaymentInfo)
445
+ return null;
446
+ try {
447
+ const parsedPayment = JSON.parse(foundPaymentInfo);
448
+ yield this.savePayment({
449
+ accommodationId: parsedPayment.accommodationId,
450
+ folioNumber,
451
+ paymentAmount: parsedPayment.amount.toString(),
452
+ paymentInfo: parsedPayment.data,
453
+ saleDate: moment(parsedPayment.createdAt).format('YYYYMMDD'),
454
+ });
455
+ }
456
+ catch (err) {
457
+ console.log(err);
458
+ throw new Error('FAILED_TO_SAVE_PAYMENT');
459
+ }
460
+ });
461
+ this.authenticator = authenticator;
462
+ this.redis = redis;
463
+ this.mutexLock = new MutexLock({ hashPrefix: 'RES_WINGS_MUTEX_', mutexLockInterval: 50, redis });
464
+ }
465
+ }
466
+ WingsAdapter.indexAccommodation = ({ accommodationId }) => `AUTH|WINGS-API|${accommodationId}`;
467
+ WingsAdapter.authFromCredentials = ({ vendorId, companyId, apiKey, kioskIp, }) => ({
468
+ headers: {
469
+ 'API-KEY': apiKey,
470
+ VENDOR_ID: vendorId,
471
+ 'API-COMPANY': companyId,
472
+ },
473
+ params: {
474
+ KIOSK_IP: kioskIp,
475
+ },
476
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import SanhaWingsAdapter from './adapters/sanhaWings';
2
+ export { SanhaWingsAdapter, };
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import SanhaWingsAdapter from './adapters/sanhaWings';
2
+ export { SanhaWingsAdapter, };
@@ -0,0 +1,15 @@
1
+ import { Redis } from 'ioredis';
2
+ export default class MutexLock {
3
+ redis: Redis;
4
+ hashPrefix: string;
5
+ mutexLockInterval: number;
6
+ constructor({ redis, hashPrefix, mutexLockInterval }: {
7
+ redis: Redis;
8
+ hashPrefix: string;
9
+ mutexLockInterval?: number;
10
+ });
11
+ getMutexLockKey: (id: string) => string;
12
+ tryMutexLock: (streamId: string, lockHash: string) => Promise<"OK" | null>;
13
+ getMutexLock: (streamId: string) => Promise<string>;
14
+ unlockMutexLock: (streamId: string, lockHash: string) => Promise<string | null>;
15
+ }
@@ -0,0 +1,37 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { v4 as uuid } from 'uuid';
11
+ const sleep = (sleepTime) => new Promise(resolve => setTimeout(resolve, sleepTime));
12
+ export default class MutexLock {
13
+ constructor({ redis, hashPrefix, mutexLockInterval = 50 }) {
14
+ this.getMutexLockKey = (id) => `${this.hashPrefix}${id}`;
15
+ this.tryMutexLock = (streamId, lockHash) => this.redis.set(this.getMutexLockKey(streamId), lockHash, 'EX', 60, 'NX');
16
+ this.getMutexLock = (streamId) => __awaiter(this, void 0, void 0, function* () {
17
+ const lockHash = uuid();
18
+ let lock;
19
+ while (!lock) {
20
+ lock = yield this.tryMutexLock(streamId, lockHash); // eslint-disable-line
21
+ yield sleep(this.mutexLockInterval); // eslint-disable-line
22
+ }
23
+ return lockHash;
24
+ });
25
+ this.unlockMutexLock = (streamId, lockHash) => __awaiter(this, void 0, void 0, function* () {
26
+ const existingLockHash = yield this.redis.get(this.getMutexLockKey(streamId));
27
+ if (existingLockHash === lockHash) {
28
+ yield this.redis.del(this.getMutexLockKey(streamId));
29
+ return existingLockHash;
30
+ }
31
+ return null;
32
+ });
33
+ this.redis = redis;
34
+ this.hashPrefix = hashPrefix;
35
+ this.mutexLockInterval = mutexLockInterval;
36
+ }
37
+ }
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@vendit-dev/thirdparty-adapters",
3
+ "version": "0.1.0",
4
+ "description": "Third party adapters between v-cloud and other PMS/CMS providers.",
5
+ "main": "lib/index.js",
6
+ "scripts": {
7
+ "build": "tsc",
8
+ "dev": "node ./test/index.js"
9
+ },
10
+ "keywords": [
11
+ "vendit"
12
+ ],
13
+ "author": "Vendit <dev@vendit.co.kr> (https://vendit.co.kr)",
14
+ "license": "MIT",
15
+ "devDependencies": {
16
+ "@typescript-eslint/eslint-plugin": "^5.18.0",
17
+ "@typescript-eslint/parser": "^5.18.0",
18
+ "@vendit-dev/utility-modules": "^0.10.3",
19
+ "eslint-config-airbnb-base": "^13.1.0",
20
+ "eslint-plugin-import": "^2.16.0",
21
+ "eslint": "^8.12.0",
22
+ "tslint": "^6.1.3",
23
+ "typescript": "^4.6.3"
24
+ },
25
+ "dependencies": {
26
+ "ioredis": "^5.0.4",
27
+ "moment": "^2.29.2",
28
+ "node-fetch": "^3.2.3",
29
+ "uuid": "^8.3.2"
30
+ }
31
+ }
package/readme.md ADDED
@@ -0,0 +1,131 @@
1
+ # Passive Promise
2
+
3
+ Promise that's resolvable from outside of executor context.
4
+
5
+ It comes with super light-weighted bundle with 0 dependencies.
6
+
7
+ ## What is this?
8
+
9
+ This library exports the class named `PassivePromise` which works exactly like normal Promises, but can be resolved outside of promise executor context.
10
+
11
+ ## Installation
12
+
13
+ `npm install passive-promise`
14
+
15
+ or
16
+
17
+ `yarn add passive-promise`
18
+
19
+ The library exported with esnext module syntax.
20
+
21
+ ## Usage Examples
22
+
23
+ Just use exactly like normal promise, but returned promise (which is extended Promise class) also comes with the `resolve()` and `reject()` method in it, which you can use them to force resolve or reject the promise from outside.
24
+
25
+ All the chain methods such as then, catch, finally works as expected, but remind that the both resolve, reject method of any chained PassivePromise instance will propagate to the root PassivePromise instance regardless of its depth.
26
+
27
+ ### Common Usage
28
+
29
+ ```javascript
30
+ import PassivePromise from 'passive-promise';
31
+
32
+ (async () => {
33
+ const foo = new PassivePromise((resolve, reject) => setTimeout(() => resolve(1), 1000));
34
+
35
+ console.log(await foo); // 1 after 1 sec
36
+
37
+ const bar = new PassivePromise((resolve, reject) => setTimeout(() => resolve(1), 1000));
38
+
39
+ bar.resolve(-1);
40
+
41
+ console.log(await bar); // -1 immedietly
42
+
43
+ const baz = new PassivePromise((resolve, reject) => setTimeout(() => resolve(1), 1000));
44
+
45
+ baz.reject(0) // Unhandled promise rejection.
46
+ })()
47
+
48
+ (async () => {
49
+ const foo = new PassivePromise(() => {})
50
+ .then((fulfilled) => console.log(fulfilled));
51
+
52
+ foo.resolve(1); // 1
53
+
54
+
55
+ const bar = new PassivePromise(() => {})
56
+ .then((fulfilled) => console.log(fulfilled))
57
+ .catch((errored) => console.log('Promise rejected!', errored));
58
+
59
+ bar.reject(-1); // Promise rejected! -1
60
+
61
+ const baz = new PassivePromise(() => {})
62
+ .then(
63
+ (fulfilled) => console.log(fulfilled),
64
+ (errored) => console.log('Promise rejected!', errored),
65
+ )
66
+ .finally(() => console.log('Finally.'));
67
+
68
+ baz.reject(-1) // Promise rejected! -1 Finally.
69
+ })()
70
+
71
+ ```
72
+
73
+ ### Chain propagation
74
+
75
+
76
+ ```javascript
77
+ import PassivePromise from 'passive-promise';
78
+
79
+ (async () => {
80
+ const chainedPromise = new PassivePromise(() => {})
81
+ .then((firstRes) => {
82
+ console.log('first.');
83
+ })
84
+ .then((secondRes) => {
85
+ console.log('second.');
86
+ })
87
+ .then((thirdRes) => {
88
+ console.log('third.');
89
+ });
90
+
91
+ chainedPromise.resolve(1);
92
+
93
+ await chainedPromise; // first. second. third.
94
+
95
+ const middleChain = new PassivePromise(() => {})
96
+ .then((firstRes) => {
97
+ console.log('first.');
98
+ })
99
+ .then((secondRes) => {
100
+ console.log('second.');
101
+ });
102
+
103
+ middleChain.then((thirdRes) => {
104
+ console.log('third.');
105
+ });
106
+
107
+ // Regardless of position of PassivePromise instance in the chained promises, they always resolve root promise in the chain.
108
+ middleChain.resolve(1);
109
+
110
+ await middleChain; // first. second. third.
111
+
112
+ // If you want to resolve the instance itself rather than root instance, use passiveResolve() and passiveReject() instead.
113
+
114
+ const anotherChain = new PassivePromise(() => {})
115
+ .then((firstRes) => {
116
+ console.log('first.');
117
+ })
118
+ .then((secondRes) => {
119
+ console.log('second.');
120
+ });
121
+
122
+ anotherChain.then((thirdRes) => {
123
+ console.log('third.');
124
+ });
125
+
126
+ // We want to directly resolve this promise rather than the whole promise chain here.
127
+ anotherChain.passiveResolve(1);
128
+
129
+ await anotherChain; // third.
130
+ })()
131
+ ```