@cloudcommerce/app-galaxpay 2.9.0 → 2.10.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.
Files changed (35) hide show
  1. package/lib/functions-lib/all-parses.js.map +1 -1
  2. package/lib/functions-lib/ecom/events-to-galaxpay.js.map +1 -1
  3. package/lib/functions-lib/galaxpay/auth/create-access.js.map +1 -1
  4. package/lib/functions-lib/galaxpay/auth/create-axios.js.map +1 -1
  5. package/lib/functions-lib/galaxpay/auth/gerate-token.js.map +1 -1
  6. package/lib/functions-lib/galaxpay/handle-plans.js.map +1 -1
  7. package/lib/functions-lib/galaxpay/update-subscription.js.map +1 -1
  8. package/lib/functions-lib/galaxpay/webhook.d.ts +1 -0
  9. package/lib/functions-lib/galaxpay/webhook.js.map +1 -1
  10. package/lib/galaxpay-create-transaction.js +2 -2
  11. package/lib/galaxpay-create-transaction.js.map +1 -1
  12. package/lib/galaxpay-events.js.map +1 -1
  13. package/lib/galaxpay-list-payments.js +1 -1
  14. package/lib/galaxpay-list-payments.js.map +1 -1
  15. package/package.json +12 -6
  16. package/.turbo/turbo-build.log +0 -5
  17. package/CHANGELOG.md +0 -1
  18. package/assets/onload-expression.js +0 -23
  19. package/assets/onload-expression.min.js +0 -1
  20. package/scripts/build.sh +0 -4
  21. package/src/functions-lib/all-parses.ts +0 -91
  22. package/src/functions-lib/ecom/events-to-galaxpay.ts +0 -104
  23. package/src/functions-lib/galaxpay/auth/create-access.ts +0 -80
  24. package/src/functions-lib/galaxpay/auth/create-axios.ts +0 -21
  25. package/src/functions-lib/galaxpay/auth/gerate-token.ts +0 -36
  26. package/src/functions-lib/galaxpay/handle-plans.ts +0 -91
  27. package/src/functions-lib/galaxpay/update-subscription.ts +0 -92
  28. package/src/functions-lib/galaxpay/webhook.ts +0 -484
  29. package/src/functions-lib/utils.ts +0 -23
  30. package/src/galaxpay-create-transaction.ts +0 -257
  31. package/src/galaxpay-events.ts +0 -28
  32. package/src/galaxpay-list-payments.ts +0 -148
  33. package/src/galaxpay.ts +0 -12
  34. package/src/index.ts +0 -2
  35. package/tsconfig.json +0 -6
@@ -1,484 +0,0 @@
1
- import type {
2
- Orders,
3
- Applications,
4
- ResourceListResult,
5
- ResourceId,
6
- } from '@cloudcommerce/types';
7
- import type { Request, Response } from 'firebase-functions';
8
- import api from '@cloudcommerce/api';
9
- import { getFirestore } from 'firebase-admin/firestore';
10
- import logger from 'firebase-functions/logger';
11
- import config from '@cloudcommerce/firebase/lib/config';
12
- import { parseStatus, parsePeriodicityToEcom, gerateId } from '../all-parses';
13
- import GalaxpayAxios from './auth/create-access';
14
- import { updateValueSubscription, checkAmountItemsOrder } from './update-subscription';
15
-
16
- type FinancialStatusCurrent = Exclude<Orders['financial_status'], undefined>['current']
17
-
18
- const collectionSubscription = getFirestore().collection('galaxpaySubscriptions');
19
-
20
- const getApp = async (): Promise<Applications> => {
21
- return new Promise((resolve, reject) => {
22
- api.get(
23
- `applications?app_id=${config.get().apps.galaxPay.appId}&fields=hidden_data`,
24
- )
25
- .then(({ data: result }) => {
26
- resolve(result[0]);
27
- })
28
- .catch((err) => {
29
- reject(err);
30
- });
31
- });
32
- };
33
-
34
- const checkStatusIsEqual = (
35
- financialStatus: Exclude<Orders['financial_status'], undefined>,
36
- galaxPayTransactionStatus?: string,
37
- ) => {
38
- if (financialStatus.current === parseStatus(galaxPayTransactionStatus)) {
39
- return true;
40
- }
41
- return false;
42
- };
43
-
44
- const checkStatusPaid = (status?: string) => {
45
- const parsedStatus = parseStatus(status);
46
- logger.log(`>> Status is ${status} => ${parsedStatus}`);
47
- if (parsedStatus === 'paid') {
48
- return true;
49
- }
50
- return false;
51
- };
52
-
53
- const checkPayDay = (strDate: string) => {
54
- // check if today is 3 days before payday.
55
- const payDay = new Date(strDate);
56
- const nowTime = new Date().getTime() + 259200000; // add 3day to today
57
- const now = new Date(nowTime);
58
- return (now >= payDay);
59
- };
60
-
61
- const findOrderByTransactionId = (transactionId: string): Promise<ResourceListResult<'orders'>> => {
62
- return new Promise((resolve, reject) => {
63
- api.get(`orders?transactions._id=${transactionId}`)
64
- .then(({ data: response }) => {
65
- const resp = response as unknown as ResourceListResult<'orders'>; // TODO:
66
- resolve(resp);
67
- })
68
- .catch((err) => {
69
- reject(err);
70
- });
71
- });
72
- };
73
-
74
- const findOrderById = async (orderId: ResourceId): Promise<Orders> => new Promise((resolve) => {
75
- api.get(`orders/${orderId}`)
76
- .then(({ data: order }) => {
77
- resolve(order);
78
- });
79
- });
80
-
81
- const createTransaction = async (
82
- res: Response,
83
- subscriptionLabel: string,
84
- plan: { [x: string]: any },
85
- orderNumber: string,
86
- galaxpayFristTransactionId: string,
87
- GalaxPayTransaction: { [x: string]: any },
88
- GalaxPaySubscription: { [x: string]: any },
89
- GalaxPayTransactionValue: number,
90
- originalOrderId: ResourceId,
91
- ) => {
92
- if (galaxpayFristTransactionId !== GalaxPayTransaction.galaxPayId) {
93
- // let body;
94
- const originalOrder = (await api.get(`orders/${originalOrderId}`)).data;
95
-
96
- // logger.log('> Create new Order ')
97
- if (originalOrder.transactions && originalOrder.items) {
98
- const { installment } = GalaxPayTransaction;
99
- const {
100
- buyers, items, domain, amount,
101
- } = originalOrder;
102
- const channelType = originalOrder.channel_type;
103
- const shippingLines = originalOrder.shipping_lines;
104
- const shippingMethodLabel = originalOrder.shipping_method_label;
105
- const paymentMethodLabel = originalOrder.payment_method_label;
106
- const originalTransaction = originalOrder.transactions[0];
107
- const quantity = installment;
108
- const periodicity = parsePeriodicityToEcom(GalaxPaySubscription.periodicity);
109
- const dateUpdate = GalaxPayTransaction.datetimeLastSentToOperator
110
- ? new Date(GalaxPayTransaction.datetimeLastSentToOperator).toISOString()
111
- : new Date().toISOString();
112
-
113
- // remove items free in new orders subscription
114
- checkAmountItemsOrder(amount, items, plan);
115
- if (amount.balance) {
116
- delete amount.balance;
117
- }
118
-
119
- const transactionId = String(gerateId(GalaxPayTransaction.galaxPayId));
120
-
121
- const transactions: Orders['transactions'] = [
122
- {
123
- amount: originalTransaction.amount,
124
- status: {
125
- updated_at: dateUpdate,
126
- current: parseStatus(GalaxPayTransaction.status),
127
- },
128
- intermediator: {
129
- transaction_id: GalaxPayTransaction.tid || '',
130
- transaction_code: GalaxPayTransaction.authorizationCode || '',
131
- },
132
- payment_method: originalTransaction.payment_method,
133
- app: originalTransaction.app,
134
- _id: transactionId as ResourceId,
135
- notes: `Parcela #${quantity} referente à ${subscriptionLabel} ${periodicity}`,
136
- custom_fields: originalTransaction.custom_fields,
137
- },
138
- ];
139
-
140
- transactions[0].payment_link = GalaxPaySubscription.paymentLink;
141
-
142
- const financialStatus = {
143
- updated_at: dateUpdate,
144
- current: parseStatus(GalaxPayTransaction.status) as FinancialStatusCurrent,
145
- };
146
- const body = {
147
- opened_at: new Date().toISOString(),
148
- items,
149
- shipping_lines: shippingLines,
150
- buyers,
151
- channel_type: channelType,
152
- domain,
153
- amount,
154
- shipping_method_label: shippingMethodLabel,
155
- payment_method_label: paymentMethodLabel,
156
- transactions,
157
- financial_status: financialStatus,
158
- subscription_order: {
159
- _id: originalOrderId as string & { length: 24 },
160
- number: parseInt(orderNumber, 10),
161
- },
162
- notes: `Pedido #${quantity} referente à ${subscriptionLabel} ${periodicity}`,
163
- staff_notes: `Valor cobrado no GalaxPay R$${GalaxPayTransactionValue}`,
164
- };
165
-
166
- const { result } = await findOrderByTransactionId(transactionId);
167
-
168
- if (!result.length) {
169
- await api.post('orders', body);
170
- // logger.log('> Created new order API')
171
- return res.sendStatus(200);
172
- }
173
- // Order Exists
174
- return res.sendStatus(200);
175
- }
176
- }
177
- // logger.log('> Not Found Subscritpion or Transaction exists')
178
- return res.sendStatus(404);
179
- };
180
-
181
- const handleWehook = async (req: Request, res: Response) => {
182
- // https://docs.galaxpay.com.br/webhooks
183
-
184
- // POST transaction.updateStatus update Transation status
185
- // POST subscription.addTransaction add transation in subscription
186
-
187
- const galaxpayHook = req.body;
188
- const type = galaxpayHook.event;
189
- const GalaxPaySubscription = galaxpayHook.Subscription;
190
- const GalaxPaySubscriptionQuantity = GalaxPaySubscription.quantity;
191
- const originalOrderId = GalaxPaySubscription.myId;
192
- const GalaxPayTransaction = galaxpayHook.Transaction;
193
- const GalaxPayTransactionValue = GalaxPayTransaction.value / 100;
194
-
195
- logger.log(
196
- `> (App GalaxPay) WebHook ${type}, Body ${JSON.stringify(galaxpayHook)}, quantity:
197
- ${GalaxPaySubscriptionQuantity}, status: ${GalaxPayTransaction.status} <`,
198
- );
199
-
200
- try {
201
- if (type === 'transaction.updateStatus') {
202
- const documentSnapshot = await collectionSubscription.doc(originalOrderId).get();
203
- if (documentSnapshot && documentSnapshot.exists) {
204
- const docSubscription = documentSnapshot.data();
205
- if (docSubscription) {
206
- const {
207
- galaxpayFristTransactionId,
208
- plan,
209
- orderNumber,
210
- subscriptionLabel,
211
- } = docSubscription.data();
212
-
213
- let galaxPayTransactionStatus: string | undefined;
214
- let galaxpaySubscriptionStatus: string | undefined;
215
- let transactionCreatedAt: string | undefined;
216
- const app = await getApp();
217
-
218
- try {
219
- // check subscription and transaction status before in galaxpay
220
- if (!process.env.GALAXPAY_ID) {
221
- const galaxpayId = app.hidden_data?.galaxpay_id;
222
- if (typeof galaxpayId === 'string' && galaxpayId) {
223
- process.env.GALAXPAY_ID = galaxpayId;
224
- } else {
225
- logger.warn('Missing GalaxPay ID');
226
- }
227
- }
228
-
229
- if (!process.env.GALAXPAY_HASH) {
230
- const galaxpayHash = app.hidden_data?.galaxpay_hash;
231
- if (typeof galaxpayHash === 'string' && galaxpayHash) {
232
- process.env.GALAXPAY_HASH = galaxpayHash;
233
- } else {
234
- logger.warn('Missing GalaxPay Hash');
235
- }
236
- }
237
-
238
- const galaxpayAxios = new GalaxpayAxios({
239
- galaxpayId: process.env.GALAXPAY_ID,
240
- galaxpayHash: process.env.GALAXPAY_HASH,
241
- });
242
- await galaxpayAxios.preparing;
243
-
244
- if (galaxpayAxios.axios) {
245
- let { data } = await galaxpayAxios.axios
246
- .get(`/transactions?galaxPayIds=${GalaxPayTransaction.galaxPayId}&startAt=0&limit=1`);
247
-
248
- galaxPayTransactionStatus = data.Transactions[0]?.status;
249
- const dateTimeTransaction = data.Transactions[0]?.createdAt;
250
- transactionCreatedAt = dateTimeTransaction && new Date(`${dateTimeTransaction} UTC-3`);
251
- logger.log(`>> Transaction status: ${galaxPayTransactionStatus}`);
252
-
253
- data = (await galaxpayAxios.axios
254
- .get(`/subscriptions?myIds=${originalOrderId}&startAt=0&limit=1`)).data;
255
-
256
- galaxpaySubscriptionStatus = data.Subscriptions[0]?.status;
257
- logger.log(`>> Subscription status: ${galaxpaySubscriptionStatus}`);
258
- }
259
- } catch (err: any) {
260
- logger.warn(`galaxpay webhook Error: get Transaction/Subscription in Galaxpay => ${err?.message}`);
261
- }
262
-
263
- if (galaxpayFristTransactionId === GalaxPayTransaction.galaxPayId) {
264
- // update frist payment
265
- const order = await findOrderById(originalOrderId);
266
- // Update value Subscription in GalaxPay
267
-
268
- // logger.log('plan-> ', JSON.stringify(plan));
269
- // subscripton is paid
270
- if (checkStatusPaid(galaxPayTransactionStatus) && order.items) {
271
- const oldSubscriptionValue = docSubscription.data()?.value
272
- || ({ ...order.amount }.total * 100);
273
-
274
- const newValue = checkAmountItemsOrder(
275
- { ...order.amount },
276
- [...order.items],
277
- { ...plan },
278
- );
279
- if (newValue && newValue !== oldSubscriptionValue) {
280
- await updateValueSubscription(
281
- app,
282
- originalOrderId,
283
- order.amount,
284
- order.items,
285
- plan,
286
- );
287
-
288
- collectionSubscription.doc(originalOrderId)
289
- .set({
290
- updatedAt: new Date().toISOString(),
291
- value: newValue,
292
- }, { merge: true })
293
- .catch(logger.error);
294
- }
295
- }
296
- // logger.log('ORDER: ', JSON.stringify(order.amount), ' **');
297
- // logger.log('> order ', order)
298
-
299
- if (order.financial_status
300
- && checkStatusIsEqual(order.financial_status, galaxPayTransactionStatus)) {
301
- // check status is equal
302
- return res.sendStatus(200);
303
- } if (order.transactions) {
304
- // update payment
305
- const transactionId = order.transactions[0]._id;
306
- let notificationCode = `;${GalaxPayTransaction.tid || ''};`;
307
- notificationCode += `${GalaxPayTransaction.authorizationCode || ''}`;
308
- const bodyPaymentHistory = {
309
- date_time: transactionCreatedAt || new Date().toISOString(),
310
- status: parseStatus(galaxPayTransactionStatus),
311
- transaction_id: transactionId,
312
- notification_code: `${type};${galaxpayHook.webhookId}${notificationCode}`,
313
- flags: ['GalaxPay'],
314
- } as any; // TODO: incompatible type=> amount and status;;
315
-
316
- await api.post(`orders/${order._id}/payments_history`, bodyPaymentHistory);
317
-
318
- await api.patch(
319
- `orders/${order._id}/transactions/${transactionId}`,
320
- {
321
- intermediator: {
322
- transaction_id: GalaxPayTransaction.tid || '',
323
- transaction_code: GalaxPayTransaction.authorizationCode || '',
324
- },
325
- },
326
- );
327
-
328
- return res.sendStatus(200);
329
- }
330
- } else {
331
- /*
332
- add order, because recurrence creates all transactions in the
333
- first transaction when quantity is non-zero,search for the order by ID,
334
- if not found, create the transaction, and if found, check if it will be
335
- necessary to update the transaction status
336
- */
337
- const transactionId = String(gerateId(GalaxPayTransaction.galaxPayId));
338
-
339
- const { result } = await findOrderByTransactionId(transactionId);
340
-
341
- if (!result || !result.length) {
342
- // logger.log('> Not found Transaction in API')
343
- if (checkStatusPaid(galaxPayTransactionStatus)
344
- && checkPayDay(GalaxPayTransaction.payday)) {
345
- // necessary to create order
346
- return createTransaction(
347
- res,
348
- subscriptionLabel,
349
- plan,
350
- orderNumber,
351
- galaxpayFristTransactionId,
352
- GalaxPayTransaction,
353
- GalaxPaySubscription,
354
- GalaxPayTransactionValue,
355
- originalOrderId,
356
- );
357
- }
358
- // fetches the original order again to avoid delay from other webhooks
359
- let originalOrder: Orders | undefined;
360
- try {
361
- originalOrder = await findOrderById(originalOrderId);
362
- } catch (err) {
363
- logger.warn(`Original Order not found (${originalOrderId}) `);
364
- res.status(404).send({ message: 'Original Order not found' });
365
- }
366
- logger.log(`>> Status Original Order: ${originalOrder?.status} `);
367
-
368
- if (originalOrder && galaxpaySubscriptionStatus === 'canceled'
369
- && originalOrder?.status !== 'cancelled') {
370
- // console.log('>> galaxpay webhook: Subscription canceled at galapay');
371
- try {
372
- await api.patch(`orders/${originalOrderId}`, { status: 'cancelled' });
373
- collectionSubscription.doc(originalOrderId)
374
- .set({
375
- status: 'cancelled',
376
- updatedAt: new Date().toISOString(),
377
- }, { merge: true })
378
- .catch(logger.error);
379
-
380
- return res.sendStatus(200);
381
- } catch (err) {
382
- logger.error(err);
383
- return res.sendStatus(400);
384
- }
385
- } else {
386
- logger.log(`>> galaxpay webhook: Status or checkPayDay invalid => Payday: ${GalaxPayTransaction.payday} now: ${new Date().toISOString()}`);
387
- return res.status(404).send('Status or checkPayDay invalid');
388
- }
389
- }
390
- const order = result[0];
391
- if (order.financial_status
392
- && checkStatusIsEqual(order.financial_status, galaxPayTransactionStatus)) {
393
- // check status is equal
394
- // logger.log('> Equals Status')
395
- return res.sendStatus(200);
396
- }
397
- // logger.log('> Order id ')
398
- // update payment
399
- let notificationCode = `;${GalaxPayTransaction.tid || ''};`;
400
- notificationCode += `${GalaxPayTransaction.authorizationCode || ''}`;
401
- const bodyPaymentHistory = {
402
- date_time: transactionCreatedAt || new Date().toISOString(),
403
- status: parseStatus(galaxPayTransactionStatus),
404
- transaction_id: transactionId,
405
- notification_code: `${type};${galaxpayHook.webhookId}${notificationCode}`,
406
- flags: ['GalaxPay'],
407
- } as any; // TODO: incompatible type=> amount and status;
408
-
409
- await api.post(`orders/${order._id}/payments_history`, bodyPaymentHistory);
410
-
411
- // logger.log('> create Payment History')
412
-
413
- await api.patch(
414
- `orders/${order._id}/transactions/${transactionId}`,
415
- {
416
- intermediator: {
417
- transaction_id: GalaxPayTransaction.tid || '',
418
- transaction_code: GalaxPayTransaction.authorizationCode || '',
419
- },
420
- },
421
- );
422
-
423
- if (parseStatus(galaxPayTransactionStatus) === 'voided'
424
- || parseStatus(galaxPayTransactionStatus) === 'refunded') {
425
- await api.patch(`orders/${order._id}`, { status: 'cancelled' });
426
-
427
- // logger.log('> UPDATE ORDER OK')
428
- return res.sendStatus(200);
429
- }
430
- // logger.log('> UPDATE Transaction OK')
431
- return res.sendStatus(200);
432
- }
433
- }
434
- }
435
- //
436
- return res.status(404).send('Document not found in firestore');
437
- } if (type === 'subscription.addTransaction') {
438
- if (GalaxPaySubscriptionQuantity === 0) {
439
- // find transaction in firebase
440
- const documentSnapshot = await collectionSubscription.doc(originalOrderId).get();
441
- if (documentSnapshot && documentSnapshot.exists) {
442
- const docSubscription = documentSnapshot.data();
443
-
444
- if (docSubscription) {
445
- const {
446
- galaxpayFristTransactionId,
447
- plan,
448
- orderNumber,
449
- subscriptionLabel,
450
- } = docSubscription.data();
451
-
452
- if (checkPayDay(GalaxPayTransaction.payday)) {
453
- return createTransaction(
454
- res,
455
- subscriptionLabel,
456
- plan,
457
- orderNumber,
458
- galaxpayFristTransactionId,
459
- GalaxPayTransaction,
460
- GalaxPaySubscription,
461
- GalaxPayTransactionValue,
462
- originalOrderId,
463
- );
464
- }
465
- }
466
- }
467
- //
468
- return res.status(404).send('Document not found in firestore');
469
- }
470
- // Avoid retries of this GalaxPay webhook
471
- return res.status(200)
472
- .send(`Subscription webhook with non-zero quantity.
473
- The Order will be analyzed with the updateStatus webhook.`);
474
- }
475
- //
476
- return res.status(404).send('Unidentified webhook type');
477
- } catch (err: any) {
478
- // verificar catch
479
- logger.error(err);
480
- return res.sendStatus(500);
481
- }
482
- };
483
-
484
- export default handleWehook;
@@ -1,23 +0,0 @@
1
- import * as fs from 'node:fs';
2
- import url from 'node:url';
3
- import { join as joinPath } from 'node:path';
4
-
5
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
6
-
7
- const readFile = (path: string) => fs.readFileSync(joinPath(__dirname, path), 'utf8');
8
-
9
- const responseError = (status: number | null, error: string, message: string) => {
10
- return {
11
- status: status || 409,
12
- error,
13
- message,
14
- };
15
- };
16
-
17
- const isSandbox = false; // TODO: false
18
-
19
- export {
20
- readFile,
21
- responseError,
22
- isSandbox,
23
- };