Skip to content

Instantly share code, notes, and snippets.

@diego3g
Created September 9, 2018 23:26
Show Gist options
  • Save diego3g/6c050da5942865eaf682bd3715ab047a to your computer and use it in GitHub Desktop.
Save diego3g/6c050da5942865eaf682bd3715ab047a to your computer and use it in GitHub Desktop.
async approved (data, product, response) {
let user =
(await User.findBy('email', data.email)) ||
(await User.findBy('doc', data.doc))
if (!user) {
user = await User.create({
email: data.email,
doc: data.doc,
name: `${data.first_name} ${data.last_name}`.trim()
})
}
if (data.address_zip_code) {
await Address.findOrCreate(
{
user_id: user.id,
zip_code: data.address_zip_code,
number: data.address_number
},
{
user_id: user.id,
phone: `(${data.phone_local_code}) ${data.phone_number}`,
address: data.address,
number: data.address_number,
country: data.address_country,
address_district: data.address_district,
complement: data.address_comp,
city: data.address_city,
state: data.address_state,
zip_code: data.address_zip_code,
type: 'billing'
}
)
}
const duration = parseInt(data.recurrency_period)
const purchase_info = {
coupon: data.off,
price: data.price.replace('.', ''),
currency: data.currency,
transaction: data.transaction,
transaction_ext: data.transaction_ext,
payment_engine: data.payment_engine,
payment_type: data.payment_type,
warranty_date: data.warranty_date
}
const exists = !!(await user
.purchases()
.where('product_id', product.id)
.first())
if (!exists) {
await user.products().attach(product.id, purchase => {
purchase.merge({
...purchase_info,
start_date: moment(),
end_date: moment().add(duration, 'days')
})
})
} else if (product.type === 'academy') {
const activePurchase = await Purchase.query()
.where('product_id', product.id)
.where('user_id', user.id)
.where('end_date', '>=', moment())
.orderBy('end_date', 'DESC')
.first()
let start_date = moment()
let end_date = moment().add(duration, 'days')
if (activePurchase) {
start_date = moment(activePurchase.end_date).add(1, 'day')
end_date = moment(start_date).add(duration, 'days')
}
await user.purchases().create({
...purchase_info,
product_id: product.id,
start_date,
end_date
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment