Skip to content

Commit

Permalink
chore(galaxpay): define new shipping method
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 27, 2023
1 parent 137208e commit 3e3374a
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ const getNewFreight = async (
(serviceFind) => serviceFind.service_code === shippingLineOriginal.app.service_code,
);

return service || sameApp.response?.shipping_services[0];
return {
app: sameApp,
service: service || sameApp.response?.shipping_services[0],
};
}

let minPrice = result[0]?.response?.shipping_services[0]?.shipping_line?.total_price;
Expand All @@ -99,7 +102,7 @@ const getNewFreight = async (
const service = app.response?.shipping_services[j];

if (service.service_code === shippingLineOriginal.app.service_code) {
return service;
return { app, service };
}

if (minPrice > service?.shipping_line?.total_price) {
Expand All @@ -110,7 +113,10 @@ const getNewFreight = async (
}
}

return result[indexPosition.app]?.response?.shipping_services[indexPosition.service];
return {
app: result[indexPosition.app],
service: result[indexPosition.app]?.response?.shipping_services[indexPosition.service],
};
} catch (err) {
logger.error(err);
return null;
Expand Down Expand Up @@ -151,15 +157,35 @@ const checkItemsAndRecalculeteOrder = async (

if (subtotal > 0) {
if (shippingLine) {
const service = await getNewFreight(items, shippingLine?.to, subtotal, shippingLine);
const newFreight = await getNewFreight(items, shippingLine?.to, subtotal, shippingLine);
let service;
let app;

if (service && service?.shipping_line?.total_price) {
shippingLine = { ...shippingLine, ...service.shipping_line };
if (shippingLine) {
delete shippingLine._id;
}
if (newFreight?.service) {
service = newFreight.service;
}

if (newFreight?.app) {
app = newFreight.app;
}

if (service && service?.service_code !== shippingLine?.app?.service_code) {
shippingLine = {
...service.shipping_line,
app: {
_id: app?._id,
service_code: service?.service_code,
label: service?.label,
},
};
amount.freight = service.shipping_line.total_price;
}

if (shippingLine) {
delete shippingLine._id;
delete shippingLine.tracking_codes;
delete shippingLine.invoices;
}
}

amount.subtotal = subtotal;
Expand All @@ -179,9 +205,12 @@ const checkItemsAndRecalculeteOrder = async (
amount.discount = planDiscount || amount.discount || 0;

amount.total -= amount.discount || 0;
return amount.total > 0 ? Math.floor(parseFloat(amount.total.toFixed(2)) * 1000) / 10 : 0;
return {
value: amount.total > 0 ? Math.floor(parseFloat((amount.total).toFixed(2)) * 1000) / 10 : 0,
shippingLine,
};
}
return 0;
return { value: 0, shippingLine };
};

const getSubscriptionsByListMyIds = async (
Expand Down Expand Up @@ -229,7 +258,7 @@ const updateValueSubscriptionGalaxpay = async (
galaxpayAxios,
subscriptionId: string,
value: number,
oldValue: number,
oldValue?: number,
) => {
if (!oldValue) {
const { data } = await galaxpayAxios.axios.get(`subscriptions?myIds=${subscriptionId}&startAt=0&limit=1`);
Expand Down Expand Up @@ -259,7 +288,7 @@ const checkAndUpdateSubscriptionGalaxpay = async (
if (shippingLine) {
copyShippingLine = { ...shippingLine };
}
const value = await checkItemsAndRecalculeteOrder(
const { value } = await checkItemsAndRecalculeteOrder(
{ ...amount },
[...items],
{ ...plan },
Expand Down
103 changes: 75 additions & 28 deletions packages/apps/galaxpay/src/functions-lib/galaxpay/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ import {
findOrderById,
getOrderIntermediatorTId,
} from '../ecom/request-api';
import { createItemsAndAmount } from '../firestore/utils';
import {
createItemsAndAmount,
updateDocSubscription,
} from '../firestore/utils';
import GalaxpayAxios from './auth/create-access';
import {
checkAndUpdateSubscriptionGalaxpay,
checkItemsAndRecalculeteOrder,
compareDocItemsWithOrder,
updateValueSubscriptionGalaxpay,
} from './update-subscription';

type FinancialStatusCurrent = Exclude<Orders['financial_status'], undefined>['current']
Expand Down Expand Up @@ -121,10 +125,16 @@ const createTransaction = async (
}
// recalculate order
const shippingLine = shippingLines && shippingLines[0];
await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine);
const { shippingLine: newShippingLine } = await checkItemsAndRecalculeteOrder(
amount,
items,
plan,
null,
shippingLine,
);

if (shippingLines?.length && shippingLine) {
shippingLines[0] = shippingLine;
if (shippingLines?.length && newShippingLine) {
shippingLines[0] = newShippingLine;
}

if (amount.balance) {
Expand Down Expand Up @@ -243,6 +253,31 @@ const handleWehook = async (req: Request, res: Response) => {
);

try {
const app = await getApp();

if (!process.env.GALAXPAY_ID) {
const galaxpayId = app.hidden_data?.galaxpay_id;
if (galaxpayId && typeof galaxpayId === 'string') {
process.env.GALAXPAY_ID = galaxpayId;
} else {
logger.warn('Missing GalaxPay ID');
}
}

if (!process.env.GALAXPAY_HASH) {
const galaxpayHash = app.hidden_data?.galaxpay_hash;
if (galaxpayHash && typeof galaxpayHash === 'string') {
process.env.GALAXPAY_HASH = galaxpayHash;
} else {
logger.warn('Missing GalaxPay Hash');
}
}

const galaxpayAxios = new GalaxpayAxios({
galaxpayId: process.env.GALAXPAY_ID,
galaxpayHash: process.env.GALAXPAY_HASH,
});

if (type === 'transaction.updateStatus') {
const documentSnapshot = await collectionSubscription.doc(originalOrderId).get();
if (documentSnapshot && documentSnapshot.exists) {
Expand All @@ -258,32 +293,9 @@ const handleWehook = async (req: Request, res: Response) => {
let galaxPayTransactionStatus: string | undefined;
let galaxpaySubscriptionStatus: string | undefined;
let transactionCreatedAt: string | undefined;
const app = await getApp();

try {
// check subscription and transaction status before in galaxpay
if (!process.env.GALAXPAY_ID) {
const galaxpayId = app.hidden_data?.galaxpay_id;
if (galaxpayId && typeof galaxpayId === 'string') {
process.env.GALAXPAY_ID = galaxpayId;
} else {
logger.warn('Missing GalaxPay ID');
}
}

if (!process.env.GALAXPAY_HASH) {
const galaxpayHash = app.hidden_data?.galaxpay_hash;
if (galaxpayHash && typeof galaxpayHash === 'string') {
process.env.GALAXPAY_HASH = galaxpayHash;
} else {
logger.warn('Missing GalaxPay Hash');
}
}

const galaxpayAxios = new GalaxpayAxios({
galaxpayId: process.env.GALAXPAY_ID,
galaxpayHash: process.env.GALAXPAY_HASH,
});
await galaxpayAxios.preparing;

if (galaxpayAxios.axios) {
Expand Down Expand Up @@ -321,7 +333,7 @@ const handleWehook = async (req: Request, res: Response) => {
[shippingLine] = order.shipping_lines;
}

const newValue = await checkItemsAndRecalculeteOrder(
const { value: newValue } = await checkItemsAndRecalculeteOrder(
order.amount,
order.items,
plan,
Expand Down Expand Up @@ -542,6 +554,41 @@ const handleWehook = async (req: Request, res: Response) => {
},
{ merge: true },
);

try {
await galaxpayAxios.preparing;

if (galaxpayAxios.axios) {
const { data } = await galaxpayAxios.axios
.get(`/transactions?galaxPayIds=${whGalaxPayTransaction.galaxPayId}&startAt=0&limit=1`);

const value = itemsAndAmount?.amount?.total
&& Math.floor(parseFloat((itemsAndAmount.amount.total).toFixed(2)) * 100);
const hasUpdateValue = value && data?.Transactions[0]?.value
&& value !== data?.Transactions[0]?.value;

if (hasUpdateValue) {
const resp = await updateValueSubscriptionGalaxpay(
galaxpayAxios,
originalOrderId,
value,
);

if (resp) {
logger.log('> Successful signature edit on Galax Pay');
const body = { itemsAndAmount };
if (value) {
Object.assign(body, { value });
}

await updateDocSubscription(collectionSubscription, body, originalOrderId);
}
}
}
} catch (error) {
logger.error(error);
}

return res.sendStatus(200);
}
// console.log('>> Transaction Original')
Expand Down

0 comments on commit 3e3374a

Please sign in to comment.