Skip to content

Instantly share code, notes, and snippets.

@kvreem
Last active October 21, 2018 16:46
Show Gist options
  • Save kvreem/0b34dc0639615c7dcd67ec50050ba38f to your computer and use it in GitHub Desktop.
Save kvreem/0b34dc0639615c7dcd67ec50050ba38f to your computer and use it in GitHub Desktop.
exports.transferHandler = function transferHandler(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
const time = new Date();
const current_time_unix = moment().unix();
connectToDatabase()
.then(() => {
BookingModel
.find({})
.then((bookings) => {
bookings.forEach((booking, index) => {
const booking_time_unix = moment(booking.bookingDate).unix();
if (booking.isAccepted && (booking_time_unix < current_time_unix) && (booking.refundID === "" && booking.transferID === "")) {
UserModel
.findOne({_id: booking.bookedAccountId})
.then((user) => {
let amount = booking.total;
if (booking.fee)
amount = booking.fee;
stripe.transfers.create({
amount: Math.round((amount - (amount * 0.029 + 0.2) ) - (amount - (amount * 0.029 + 0.2)) * 0.05) * 100,
currency: "usd",
source_transaction: booking.chargeID,
destination: user.accountServices.stripe.stripe_user_id,
}).then(function(transfer) {
// asynchronously called
console.log(`[:Payment Transferr]Successfully transfered "${amount} USD" to "${user.basicInformation.firstname}"(Booked Supplier Account), the transfer ID is "${transfer.id}"`);
booking.transferID = transfer.id;
booking.save((u_err, u_booking) => {
if (u_err)
console.log(u_err);
});
});
})
.catch((err) => {
console.log(err);
});
}
else
console.log("[:Payment Transferr] There is no booking for transfer.");
});
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
process.exit();
});
console.log(`Your cron function "${context.functionName}" ran at ${time}`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment