Skip to content

Commit

Permalink
Merge branch 'main' into 1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcrammer committed Jun 21, 2024
2 parents e849bc2 + d6002ac commit 44edad7
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 12 deletions.
5 changes: 3 additions & 2 deletions src/cron/subscriptionsCron.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default async function subscriptionsCron() {
},
})

const usersResponse = await fetch(process.env.API_URL + "/users", {
const usersResponse = await fetch(process.env.API_URL + "/users/mini?page=1&limit=10000", {
headers: {
"x-api-token": process.env.API_MASTER_TOKEN,
},
Expand All @@ -44,7 +44,8 @@ export default async function subscriptionsCron() {
return
}

const email = users?.data?.find((user) => user.user_id === subscription.user_id).email
const email = users?.data?.find((user) => user.user_id === subscription.user_id)?.email || ""
if (!email) return console.log("No email found for user_id: ", subscription.user_id)
await handlePaymentOfSubscription(subscription, email)
})
} catch (error) {
Expand Down
8 changes: 5 additions & 3 deletions src/routes/payment.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,20 @@ const router = express.Router()
const Op = Sequelize.Op

router.get("/:user_id", authMiddleware("payments_read"), async (req, res) => {
const { all } = req.query
const { all, page = 1, limit = 20 } = req.query

try {
const { user_id } = req.params
if (!user_id) throw new Error("user_id is required")

const order = [["createdAt", "DESC"]]
const where = { type: { [Op.or]: ["payment", "card"] }, user_id }

if (all && userCan(req, "payments_read_all")) delete where.user_id

const payments = await Transaction.findAll({ where, order })
res.json({ success: "success", data: payments })
const payments = await Transaction.findAll({ where, order, limit, offset: (page - 1) * limit })
const total = await Transaction.count({ where })
res.json({ success: "success", data: payments, page: Number(page), limit: Number(limit), total })
} catch (error) {
res.json({ success: "error", error: error.message })
}
Expand Down
11 changes: 9 additions & 2 deletions src/routes/purchase.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (
const {
product_id,
email,
coupon,
phone,
card_token,
exp_month,
Expand All @@ -26,9 +27,12 @@ router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (
api_token,
whitelabel,
slug,
url,
isInvestor,
} = req.body

console.log(req.body)

try {
if (!product_id) throw new CodedError("product_id is required", "PUR01")
if (!email) throw new CodedError("email is required", "PUR02")
Expand Down Expand Up @@ -120,7 +124,8 @@ router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (

newUser = await newUserRequest.json()

if (newUser?.success !== "success") throw new CodedError(JSON.stringify(newUser), "PUR11")
if (newUser?.success !== "success" && newUser?.success !== "warning")
throw new CodedError(JSON.stringify(newUser), "PUR11")
user = { ...newUser?.data }

// add new card to user
Expand All @@ -146,8 +151,10 @@ router.post("/", authMiddleware("payments_create", { allowSelf: true }), async (
}
}

const waiveSignupFee = coupon === "CPStart"

// we create the product first, because if it fails, we don't want to charge the user
const purchase = await handlePurchase(product_id, user, userIsSubscribed) // handle subscription change in here
const purchase = await handlePurchase(product_id, user, userIsSubscribed, userWithEmailExists, waiveSignupFee) // handle subscription change in here
if (purchase.success !== "success") {
throw new CodedError(JSON.stringify(purchase), "PUR13", {
actions: ["emailAdmin", "removeNewUser"],
Expand Down
7 changes: 6 additions & 1 deletion src/routes/subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@ import toggleSubscription from "../utils/toggleSubscription"
const router = express.Router()

router.get("/", authMiddleware("payments_read_all", { allowSelf: true }), async (req, res) => {
const { page = 1, limit = 20 } = req.query

try {
// sort by most recent
const subscriptions = await Subscription.findAll({
order: [["createdAt", "DESC"]],
limit,
offset: (page - 1) * limit,
})
res.json({ success: "success", data: subscriptions })
const total = await Subscription.count()
res.json({ success: "success", data: subscriptions, page, limit, total })
} catch (error) {
res.json({ success: "error", error: error.message })
}
Expand Down
6 changes: 4 additions & 2 deletions src/utils/createNewSubscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import fetch from "node-fetch"
import convertToFormata from "./convertToFormdata"
import handlePaymentOfSubscription from "./handlePaymentOfSubscription"

export default async function createNewSubscription(product, user) {
export default async function createNewSubscription(product, user, userWithEmailExists, waiveSignupFee) {
try {
const subscriptionData = { ...product?.dataValues?.data }
if (!subscriptionData?.duration) throw new CodedError("duration is required", "CNS01")
Expand Down Expand Up @@ -78,9 +78,11 @@ export default async function createNewSubscription(product, user) {
if (!subscription) throw new CodedError("subscription creation failed", "CNS03")

// charge the subscription for the first time right away
const signupFee = userWithEmailExists || waiveSignupFee ? null : product?.dataValues?.price || null
console.log("signupFee", signupFee)
await handlePaymentOfSubscription(subscription, user.email, {
sendCreationEmail: true,
signupFee: product?.dataValues?.price || null,
signupFee,
})

// log subscription creation
Expand Down
4 changes: 2 additions & 2 deletions src/utils/handlePurchase.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import createNewSubscription from "./createNewSubscription"
import updateExistingSubscription from "./updateExistingSubscription"
import CodedError from "../config/CodedError"

export default async function handlePurchase(product_id, user, userIsSubscribed) {
export default async function handlePurchase(product_id, user, userIsSubscribed, userWithEmailExists, waiveSignupFee) {
try {
const product = await Product.findOne({ where: { product_id } })
if (!product) throw new CodedError("product not found", "HPUR01")

switch (product.product_type) {
case "subscription":
if (userIsSubscribed) return await updateExistingSubscription(product, user)
return await createNewSubscription(product, user)
return await createNewSubscription(product, user, userWithEmailExists, waiveSignupFee)
}

throw new CodedError("invalid product_type", "HPUR02")
Expand Down
4 changes: 4 additions & 0 deletions src/utils/sendEmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export default async function sendEmail(msg) {
template,
}

// // for testing, we will send all emails to the admin
// msg.to = process.env.ADMIN_EMAIL
// msg.bcc = null

try {
if (process.env.SEND_EMAILS === "false") return console.info("Emails are disabled", to, from, subject, text, html)

Expand Down

0 comments on commit 44edad7

Please sign in to comment.