refactor(helcim): collapse redundant Member queries in subscription.post.js
This commit is contained in:
parent
4442c57223
commit
596754acce
2 changed files with 153 additions and 27 deletions
|
|
@ -90,26 +90,22 @@ export default defineEventHandler(async (event) => {
|
|||
await connectDB()
|
||||
const body = await validateBody(event, helcimSubscriptionSchema)
|
||||
|
||||
// Only send welcome email when a member transitions from pending_payment
|
||||
// to active for the first time — not on tier upgrades (active → active).
|
||||
const priorMember = await Member.findOne(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{ status: 1 }
|
||||
)
|
||||
const isFirstActivation = priorMember?.status === 'pending_payment'
|
||||
|
||||
// Check if payment is required
|
||||
if (!requiresPayment(body.contributionAmount)) {
|
||||
// For free tier, just update member status
|
||||
const member = await Member.findOneAndUpdate(
|
||||
// For free tier, atomically capture pre-update status alongside the write.
|
||||
// Welcome email only fires on pending_payment → active transitions, not
|
||||
// on tier upgrades (active → active).
|
||||
const preMember = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{
|
||||
status: 'active',
|
||||
contributionAmount: body.contributionAmount,
|
||||
subscriptionStartDate: new Date()
|
||||
},
|
||||
{ new: true }
|
||||
{ new: false, projection: { status: 1 } }
|
||||
)
|
||||
const isFirstActivation = preMember?.status === 'pending_payment'
|
||||
const member = await Member.findById(preMember._id)
|
||||
|
||||
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
||||
|
||||
|
|
@ -175,8 +171,10 @@ export default defineEventHandler(async (event) => {
|
|||
? new Date(subscription.nextBillingDate)
|
||||
: null
|
||||
|
||||
// Update member in database
|
||||
const member = await Member.findOneAndUpdate(
|
||||
// Atomically capture pre-update status alongside the write so we can
|
||||
// detect the pending_payment → active transition without a separate read
|
||||
// (which would race with concurrent webhooks/double-clicks).
|
||||
const preMember = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{ $set: {
|
||||
contributionAmount: body.contributionAmount,
|
||||
|
|
@ -190,8 +188,10 @@ export default defineEventHandler(async (event) => {
|
|||
? { nextBillingDate }
|
||||
: {}),
|
||||
} },
|
||||
{ new: true, runValidators: false }
|
||||
{ new: false, runValidators: false, projection: { status: 1 } }
|
||||
)
|
||||
const isFirstActivation = preMember?.status === 'pending_payment'
|
||||
const member = await Member.findById(preMember._id)
|
||||
|
||||
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue