Skip to content

Commit

Permalink
fix(galaxpay-webhook): prevent error in case of undefined plan
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 27, 2023
1 parent fc5f6c1 commit ccd2fa8
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 27 deletions.
25 changes: 25 additions & 0 deletions functions/assets/onload-expression.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
; (function () {
window._galaxyHashcard = function (card) {
return new Promise(function (resolve, reject) {
// https://docs.galaxpay.com.br/tokenizacao-cartao-js
const token = window._galaxPayPublicToken
// const environment = false // !window._galaxPaySandbox // false = sandbox, true = production
const isSandbox = window._galaxPaySandbox
const galaxPay = new GalaxPay(token)
if (isSandbox) {
galaxPay._setApiUrl('https://api.sandbox.cloud.galaxpay.com.br/v2')
}
const galaxpayCard = galaxPay.newCard({
number: card.number,
holder: card.name,
expiresAt: '20' + card.year.toString() + '-' + card.month.toString(),
cvv: card.cvc
})
galaxPay.hashCreditCard(galaxpayCard, function (hash) {
resolve(hash)
}, function (error) {
reject(error)
})
})
}
}())
39 changes: 28 additions & 11 deletions functions/lib/galaxpay/update-subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig
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]
}
} else {
let minPrice = result[0]?.response?.shipping_services[0]?.shipping_line?.total_price
const indexPosition = { app: 0, service: 0 }
Expand All @@ -70,15 +73,18 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig
const service = app.response?.shipping_services[j]

if (service.service_code === shippingLineOriginal.app.service_code) {
return service
return { app, service }
} else if (minPrice > service?.shipping_line?.total_price) {
minPrice = service?.shipping_line?.total_price
indexPosition.app = i
indexPosition.service = j
}
}
}
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) {
console.error(err)
Expand All @@ -103,7 +109,7 @@ const updateValueSubscriptionGalaxpay = async (galaxpayAxios, subscriptionId, va
}

const checkAndUpdateSubscriptionGalaxpay = async (appSdk, storeId, auth, subscriptionId, amount, items, plan, oldValue, shippingLine) => {
const value = await checkItemsAndRecalculeteOrder(
const { value } = await checkItemsAndRecalculeteOrder(
{ ...amount },
[...items],
{ ...plan },
Expand Down Expand Up @@ -150,13 +156,21 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp

if (subtotal > 0) {
if (shippingLine && storeId && appSdk && auth) {
const service = await getNewFreight(storeId, items, shippingLine.to, subtotal, shippingLine, appSdk, auth)

if (service && service?.shipping_line?.total_price) {
shippingLine = { ...shippingLine, ...service.shipping_line }
delete shippingLine._id
const { app, service } = await getNewFreight(storeId, items, shippingLine.to, subtotal, shippingLine, appSdk, auth)
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
}
delete shippingLine._id
delete shippingLine.tracking_codes
delete shippingLine.invoices
}

amount.subtotal = subtotal
Expand All @@ -173,10 +187,13 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp
amount.discount = planDiscount || amount.discount || 0

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

return 0
return { value: 0, shippingLine }
}

const getSubscriptionsByListMyIds = async (
Expand Down
11 changes: 6 additions & 5 deletions functions/routes/ecom/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, storeId)
const collectionSubscription = admin.firestore().collection('subscriptions')

if (trigger.resource === 'orders' && trigger.body.status === 'cancelled') {
if (trigger.resource === 'orders' && trigger.body?.status === 'cancelled') {
console.log('>>> ', JSON.stringify(trigger.body))
galaxpayAxios.preparing
.then(async () => {
Expand Down Expand Up @@ -151,8 +151,9 @@ exports.post = async ({ appSdk, admin }, req, res) => {
})
})
})
} else if (trigger.resource === 'orders' && trigger.body.status !== 'cancelled' &&
trigger.action !== 'create' && trigger.fields.includes('items')) {
} else if (trigger.resource === 'orders' && trigger.body.status
&& trigger.body.status !== 'cancelled' && trigger.action !== 'create'
&& trigger.fields.includes('items')) {
console.log('>> ', JSON.stringify(trigger))
// When the original order is edited
try {
Expand All @@ -163,7 +164,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
const { plan } = docSubscription

// Calculates new value
const newValue = await checkItemsAndRecalculeteOrder(
const { value: newValue } = await checkItemsAndRecalculeteOrder(
{ ...amount },
[...items],
{ ...plan },
Expand Down Expand Up @@ -300,7 +301,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
})

// Calculates new value
const newSubscriptionValue = await checkItemsAndRecalculeteOrder(
const { value: newSubscriptionValue } = await checkItemsAndRecalculeteOrder(
order.amount,
order.items,
docSubscription.plan,
Expand Down
64 changes: 53 additions & 11 deletions functions/routes/galaxpay/webhooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ const { parseId, parseStatus, parsePeriodicity } = require('../../lib/galaxpay/p
const {
checkAndUpdateSubscriptionGalaxpay,
checkItemsAndRecalculeteOrder,
compareDocItemsWithOrder
compareDocItemsWithOrder,
updateValueSubscriptionGalaxpay
} = require('../../lib/galaxpay/update-subscription')
const { createItemsAndAmount } = require('./../../lib/firestore/utils')
const {
createItemsAndAmount,
updateDocSubscription
} = require('./../../lib/firestore/utils')
const getAppData = require('./../../lib/store-api/get-app-data')
const GalaxpayAxios = require('./../../lib/galaxpay/create-access')
const ecomUtils = require('@ecomplus/utils')

exports.post = async ({ appSdk, admin }, req, res) => {
// const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, appData.galaxpay_sandbox)
Expand Down Expand Up @@ -104,7 +109,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
const domain = oldOrder.domain
const amount = oldOrder.amount
const shippingLines = oldOrder.shipping_lines
const shippingMethodLabel = oldOrder.shipping_method_label
let shippingMethodLabel = oldOrder.shipping_method_label
const paymentMethodLabel = oldOrder.payment_method_label
const originalTransaction = oldOrder.transactions[0]
const quantity = installment
Expand All @@ -124,9 +129,16 @@ exports.post = async ({ appSdk, admin }, req, res) => {
compareDocItemsWithOrder(itemsAndAmount, items, amount, GalaxPayTransactionValue)
}
// recalculate order
const shippingLine = shippingLines[0]
await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine, storeId, appSdk, auth)
shippingLines[0] = shippingLine
const shippingLine = { ...shippingLines[0] }
// console.log('>>SL1 ', JSON.stringify(shippingLine))

const { shippingLine: newShippingLine } = await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine, storeId, appSdk, auth)
shippingLines[0] = {
_id: ecomUtils.randomObjectId(),
...newShippingLine
}
shippingMethodLabel = newShippingLine.label


if (amount.balance) {
delete amount.balance
Expand Down Expand Up @@ -169,9 +181,11 @@ exports.post = async ({ appSdk, admin }, req, res) => {
? plan.discount.type === 'percentage' || plan.discount.percentage
: null
let notes = `Parcela #${quantity} desconto de ${planPergentage ? '' : 'R$'}`
notes += ` ${plan.discount.value} ${planPergentage ? '%' : ''}`
notes += ` sobre ${plan.discount.apply_at}`
notes += ` referente à ${subscriptionLabel} ${periodicity}`
if (planPergentage) {
notes += ` ${plan?.discount?.value || ''} ${planPergentage ? '%' : ''}`
notes += ` sobre ${plan?.discount?.apply_at || ''}`
notes += ` referente à ${subscriptionLabel} ${periodicity}`
}

body = {
opened_at: new Date().toISOString(),
Expand Down Expand Up @@ -205,6 +219,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
.then(({ response }) => {
const { result } = response.data
if (!result.length) {
// console.log('>>Test ', JSON.stringify(body))
appSdk.apiRequest(storeId, 'orders.json', 'POST', body, auth)
.then(({ response }) => {
// console.log('> Created new order API')
Expand Down Expand Up @@ -309,7 +324,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
const oldValue = GalaxPayTransactionValue

// Calculates new value
const newValue = await checkItemsAndRecalculeteOrder(
const { value: newValue } = await checkItemsAndRecalculeteOrder(
order.amount,
order.items,
plan,
Expand Down Expand Up @@ -539,7 +554,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
compareDocItemsWithOrder(itemsAndAmount, order.items, order.amount, GalaxPayTransactionValue)
}

await checkItemsAndRecalculeteOrder(
const { value } = await checkItemsAndRecalculeteOrder(
order.amount,
order.items,
plan,
Expand All @@ -558,6 +573,33 @@ exports.post = async ({ appSdk, admin }, req, res) => {
},
{ merge: true }
)

try{
const appData = await getAppData({ appSdk, storeId, auth })

const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, storeId)
await galaxpayAxios.preparing

let { data } = await galaxpayAxios.axios
.get(`/transactions?galaxPayIds=${GalaxPayTransaction.galaxPayId}&startAt=0&limit=1`)

const total = itemsAndAmount?.amount?.total && Math.floor((itemsAndAmount?.amount?.total).toFixed(2) * 100)
// console.log('>> ', data?.Transactions[0]?.value, ' ', total , ' ', JSON.stringify(data))
const hasUpdateValue = total && data?.Transactions[0]?.value && total !== data?.Transactions[0]?.value
if (hasUpdateValue) {
const resp = await updateValueSubscriptionGalaxpay(galaxpayAxios, subscriptionId, total)
if (resp) {
console.log('> Successful signature edit on Galax Pay')
const body = { itemsAndAmount }
if (total) {
body.value = total
}
await updateDocSubscription(collectionSubscription, body, subscriptionId)
}
}
} catch (error){
console.error(error)
}

res.sendStatus(200)
} else {
Expand Down

0 comments on commit ccd2fa8

Please sign in to comment.