Skip to content

Commit

Permalink
fix(galaxPay): Update App
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 22, 2023
1 parent e6ca8c4 commit 137208e
Show file tree
Hide file tree
Showing 10 changed files with 664 additions and 226 deletions.
6 changes: 0 additions & 6 deletions packages/apps/galaxpay/src/functions-lib/all-parses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@

// type Gateway = ListPaymentsResponse['payment_gateways'][number]

const gerateId = (id: string | number) => {
const length = 24 - id.toString().length + 1;
return Array(length).join('0') + id;
};

const parsePeriodicityToEcom = (periodicity?: string) => {
switch (periodicity) {
case 'weekly':
Expand Down Expand Up @@ -84,7 +79,6 @@ const parsePeriodicityToGalaxPay = (periodicity?: string) => {
};

export {
gerateId,
parsePeriodicityToEcom,
parsePeriodicityToGalaxPay,
parseStatus,
Expand Down
28 changes: 28 additions & 0 deletions packages/apps/galaxpay/src/functions-lib/ecom/request-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import api from '@cloudcommerce/api';

const findOrderById = async (orderId: string) => {
const { data } = await api.get(`orders/${orderId}`);
return data;
};

const getProductsById = async (productId:string) => {
const { data } = await api.get(`products/${productId}`);
return data;
};

const getOrderWithQueryString = async (queryString:string) => {
const { data } = await api.get(`orders?${queryString}`);
return data;
};

const getOrderIntermediatorTId = (tId: string) => {
const queryString = `?transactions.intermediator.transaction_id=${tId}`;
return getOrderWithQueryString(queryString);
};

export {
findOrderById,
getOrderIntermediatorTId,
getOrderWithQueryString,
getProductsById,
};
80 changes: 80 additions & 0 deletions packages/apps/galaxpay/src/functions-lib/firestore/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { Orders } from '@cloudcommerce/types';
import logger from 'firebase-functions/logger';

const getDocSubscription = (
orderId,
collectionSubscription,
) => new Promise((resolve, reject) => {
const subscription = collectionSubscription.doc(orderId);

subscription.get()
.then((documentSnapshot) => {
if (documentSnapshot.exists) {
const data = documentSnapshot.data();
if (data.storeId) {
resolve(data);
} else {
reject(new Error('StoreId property not found in document'));
}
} else {
reject(new Error('Document does not exist Firestore'));
}
}).catch((err) => {
reject(err);
});
});

const updateDocSubscription = async (
collectionSubscription,
body,
subscriptionId,
) => {
const updatedAt = new Date().toISOString();
body.updatedAt = updatedAt;

await collectionSubscription.doc(subscriptionId)
.set(body, { merge: true })
.catch(logger.error);
};

const createItemsAndAmount = (
amount: Orders['amount'],
items: Orders['items'],
) => {
const itemsAndAmount = {
amount,
items: items?.reduce((
accumulator: {
sku?: string,
final_price?: number,
price:number,
quantity: number,
product_id: string & {length: 24}
}[],
itemOrder,
) => {
const item = {
sku: itemOrder.sku,
final_price: itemOrder.final_price,
price: itemOrder.price,
quantity: itemOrder.quantity,
product_id: itemOrder.product_id,
};

if (itemOrder.variation_id) {
Object.assign(item, { variation_id: itemOrder.variation_id });
}

accumulator.push(item);
return accumulator;
}, []),
};

return itemsAndAmount;
};

export {
getDocSubscription,
updateDocSubscription,
createItemsAndAmount,
};
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default class GalaxPay {
.then((documentSnapshot) => {
if (documentSnapshot.exists
&& Date.now() - documentSnapshot.updateTime.toDate().getTime()
<= 9 * 60 * 1000 // access token expires in 10 minutes
<= 5 * 60 * 1000 // access token expires in 5 minutes
) {
authenticate(documentSnapshot.get('accessToken'));
} else {
Expand Down
37 changes: 27 additions & 10 deletions packages/apps/galaxpay/src/functions-lib/galaxpay/handle-plans.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { GalaxpayApp } from '../../../types/config-app';
import type { ListPaymentsParams } from '@cloudcommerce/types';

// type Gateway = ListPaymentsResponse['payment_gateways'][number]
type Plan = Exclude<GalaxpayApp['plans'], undefined>[number]
type Amount = Exclude<ListPaymentsParams['amount'], undefined>

const handleGateway = (appData: GalaxpayApp) => {
const plans: Exclude<GalaxpayApp['plans'], undefined> = [];
Expand Down Expand Up @@ -40,15 +41,27 @@ const findPlanToCreateTransction = (label: string | undefined, appData: Galaxpay
};

const discountPlan = (
planDiscount: Exclude<GalaxpayApp['plans'], undefined>[number]['discount'],
amount: Exclude<ListPaymentsParams['amount'], undefined>,
planName: string,
plan: Plan,
amount: Omit<Amount, 'total'> & { total?: number },
) => {
let planDiscount: Plan['discount'];
if (plan.discount_first_installment && !plan.discount_first_installment?.disable) {
planDiscount = plan.discount_first_installment;
} else {
planDiscount = plan.discount;
}

if (planDiscount && planDiscount.value > 0) {
// default discount option
const type = planDiscount.type;

const applyAt: string = planDiscount.apply_at === 'frete' ? 'freight' : planDiscount.apply_at;

const discountOption = {
value: planDiscount.value,
apply_at: (planDiscount.apply_at === 'frete' ? 'freight' : planDiscount) as 'total' | 'subtotal' | 'freight',
type: planDiscount.percentage ? 'percentage' : 'fixed' as 'percentage' | 'fixed' | undefined,
label: planName,
value: planDiscount.value as number | undefined,
type,
};

if (amount.total) {
Expand All @@ -58,15 +71,16 @@ const discountPlan = (
} else {
delete planDiscount.min_amount;

const maxDiscount = amount[discountOption.apply_at || 'subtotal'];
const maxDiscount = amount[applyAt || 'subtotal'];
let discountValue: number | undefined;

if (maxDiscount && discountOption.type === 'percentage') {
discountValue = (maxDiscount * planDiscount.value) / 100;
} else {
discountValue = planDiscount.value;
if (maxDiscount && discountValue > maxDiscount) {
discountValue = maxDiscount;
if (maxDiscount) {
discountValue = (discountValue && discountValue > maxDiscount)
? maxDiscount : discountValue;
}
}

Expand All @@ -79,7 +93,10 @@ const discountPlan = (
}
}
}
return discountOption;
const discount = planDiscount as Omit<Plan['discount'], 'apply_at'>
& { apply_at: 'total' | 'subtotal' | 'freight' };

return { amount, discountOption, discount };
}
return null;
};
Expand Down
Loading

0 comments on commit 137208e

Please sign in to comment.