feat(helcim): create subscription by cadence with recurringAmount
Replace tier-based plan lookup with cadence-keyed lookup, compute recurringAmount via getTierAmount, persist billingCadence on member. Delete both manual-fallback blocks; Helcim failure now surfaces as 500.
This commit is contained in:
parent
be0e6e7699
commit
8d43804c7f
2 changed files with 218 additions and 153 deletions
|
|
@ -1,5 +1,5 @@
|
|||
// Create a Helcim subscription
|
||||
import { getHelcimPlanId, requiresPayment, getContributionTierByValue } from '../../config/contributions.js'
|
||||
import { getHelcimPlanId, requiresPayment, getContributionTierByValue, getTierAmount } from '../../config/contributions.js'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
import { getSlackService } from '../../utils/slack.ts'
|
||||
|
|
@ -124,9 +124,6 @@ export default defineEventHandler(async (event) => {
|
|||
}
|
||||
}
|
||||
|
||||
// Get the Helcim plan ID
|
||||
const planId = getHelcimPlanId(body.contributionTier)
|
||||
|
||||
// Validate card token is provided
|
||||
if (!body.cardToken) {
|
||||
throw createError({
|
||||
|
|
@ -135,142 +132,70 @@ export default defineEventHandler(async (event) => {
|
|||
})
|
||||
}
|
||||
|
||||
// Check if we have a configured plan for this tier
|
||||
if (!planId) {
|
||||
const member = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{
|
||||
status: 'active',
|
||||
contributionTier: body.contributionTier,
|
||||
subscriptionStartDate: new Date(),
|
||||
paymentMethod: 'card',
|
||||
cardToken: body.cardToken,
|
||||
notes: `Payment successful but no Helcim plan configured for tier ${body.contributionTier}`
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
const tierInfo = getContributionTierByValue(body.contributionTier)
|
||||
const cadence = body.cadence
|
||||
const paymentPlanId = getHelcimPlanId(cadence)
|
||||
|
||||
await inviteToSlack(member)
|
||||
if (isFirstActivation) await sendWelcomeEmail(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
subscriptionId: 'manual-' + Date.now(),
|
||||
status: 'needs_plan_setup',
|
||||
nextBillingDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
|
||||
},
|
||||
member: {
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
status: member.status
|
||||
},
|
||||
warning: `Payment successful but recurring plan needs to be set up in Helcim for the ${body.contributionTier} tier`
|
||||
}
|
||||
if (!paymentPlanId) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: cadence === 'annual'
|
||||
? 'Annual plan id not configured'
|
||||
: 'Monthly plan id not configured',
|
||||
})
|
||||
}
|
||||
|
||||
// Try to create subscription in Helcim
|
||||
const idempotencyKey = generateIdempotencyKey()
|
||||
|
||||
// Get contribution tier details to set recurring amount
|
||||
const tierInfo = getContributionTierByValue(body.contributionTier)
|
||||
|
||||
const subscriptionPayload = {
|
||||
dateActivated: new Date().toISOString().split('T')[0], // Today in YYYY-MM-DD format
|
||||
paymentPlanId: parseInt(planId),
|
||||
dateActivated: new Date().toISOString().split('T')[0],
|
||||
paymentPlanId: parseInt(paymentPlanId),
|
||||
customerCode: body.customerCode,
|
||||
recurringAmount: parseFloat(tierInfo.amount),
|
||||
paymentMethod: 'card'
|
||||
recurringAmount: getTierAmount(tierInfo, cadence),
|
||||
paymentMethod: 'card',
|
||||
}
|
||||
|
||||
try {
|
||||
const subscriptionData = await createHelcimSubscription(subscriptionPayload, idempotencyKey)
|
||||
const subscriptionData = await createHelcimSubscription(subscriptionPayload, idempotencyKey)
|
||||
|
||||
// Extract the first subscription from the response array
|
||||
const subscription = subscriptionData.data?.[0]
|
||||
if (!subscription) {
|
||||
throw new Error('No subscription returned in response')
|
||||
}
|
||||
// Extract the first subscription from the response array
|
||||
const subscription = subscriptionData.data?.[0]
|
||||
if (!subscription) {
|
||||
throw createError({ statusCode: 500, statusMessage: 'Subscription creation failed' })
|
||||
}
|
||||
|
||||
// Update member in database
|
||||
const member = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{
|
||||
status: 'active',
|
||||
// Update member in database
|
||||
const member = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{ $set: {
|
||||
contributionTier: body.contributionTier,
|
||||
helcimSubscriptionId: subscription.id,
|
||||
subscriptionStartDate: new Date(),
|
||||
paymentMethod: 'card'
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
logActivity(member._id, 'subscription_created', { tier: body.contributionTier })
|
||||
|
||||
await inviteToSlack(member)
|
||||
if (isFirstActivation) await sendWelcomeEmail(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
subscriptionId: subscription.id,
|
||||
status: subscription.status,
|
||||
nextBillingDate: subscription.nextBillingDate
|
||||
},
|
||||
member: {
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
status: member.status
|
||||
}
|
||||
}
|
||||
} catch (helcimError) {
|
||||
// The helper throws createError on non-OK responses (statusCode = upstream HTTP status)
|
||||
// and lets network errors propagate. We treat 400/404 from upstream AND any network
|
||||
// error as the "manual setup needed" fallback. Re-throw other upstream errors (e.g. 5xx).
|
||||
if (helcimError.statusCode && helcimError.statusCode !== 400 && helcimError.statusCode !== 404) {
|
||||
throw helcimError
|
||||
}
|
||||
console.error('Error during subscription creation:', helcimError)
|
||||
|
||||
// Still mark member as active since payment was successful
|
||||
const member = await Member.findOneAndUpdate(
|
||||
{ helcimCustomerId: body.customerId },
|
||||
{
|
||||
status: 'active',
|
||||
contributionTier: body.contributionTier,
|
||||
subscriptionStartDate: new Date(),
|
||||
helcimCustomerId: body.customerId,
|
||||
paymentMethod: 'card',
|
||||
cardToken: body.cardToken,
|
||||
notes: `Payment successful but subscription creation failed: ${helcimError.message || 'unknown error'}`
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
billingCadence: cadence,
|
||||
status: 'active',
|
||||
} },
|
||||
{ new: true, runValidators: false }
|
||||
)
|
||||
|
||||
await inviteToSlack(member)
|
||||
if (isFirstActivation) await sendWelcomeEmail(member)
|
||||
logActivity(member._id, 'subscription_created', { tier: body.contributionTier })
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
subscriptionId: 'manual-' + Date.now(),
|
||||
status: 'needs_setup',
|
||||
nextBillingDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
|
||||
},
|
||||
member: {
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
status: member.status
|
||||
},
|
||||
warning: 'Payment successful but recurring subscription needs manual setup'
|
||||
await inviteToSlack(member)
|
||||
if (isFirstActivation) await sendWelcomeEmail(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
subscriptionId: subscription.id,
|
||||
status: subscription.status,
|
||||
nextBillingDate: subscription.nextBillingDate
|
||||
},
|
||||
member: {
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
status: member.status
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue