refactor(helcim): use helper in subscription endpoint
This commit is contained in:
parent
7b4b6feb51
commit
03d6a66b84
1 changed files with 26 additions and 92 deletions
|
|
@ -1,11 +1,10 @@
|
||||||
// Create a Helcim subscription
|
// Create a Helcim subscription
|
||||||
import { getHelcimPlanId, requiresPayment } from '../../config/contributions.js'
|
import { getHelcimPlanId, requiresPayment, getContributionTierByValue } from '../../config/contributions.js'
|
||||||
import Member from '../../models/member.js'
|
import Member from '../../models/member.js'
|
||||||
import { connectDB } from '../../utils/mongoose.js'
|
import { connectDB } from '../../utils/mongoose.js'
|
||||||
import { getSlackService } from '../../utils/slack.ts'
|
import { getSlackService } from '../../utils/slack.ts'
|
||||||
import { requireAuth } from '../../utils/auth.js'
|
import { requireAuth } from '../../utils/auth.js'
|
||||||
|
import { createHelcimSubscription, generateIdempotencyKey } from '../../utils/helcim.js'
|
||||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
|
||||||
|
|
||||||
// Function to invite member to Slack
|
// Function to invite member to Slack
|
||||||
async function inviteToSlack(member) {
|
async function inviteToSlack(member) {
|
||||||
|
|
@ -75,7 +74,6 @@ export default defineEventHandler(async (event) => {
|
||||||
try {
|
try {
|
||||||
await requireAuth(event)
|
await requireAuth(event)
|
||||||
await connectDB()
|
await connectDB()
|
||||||
const config = useRuntimeConfig(event)
|
|
||||||
const body = await validateBody(event, helcimSubscriptionSchema)
|
const body = await validateBody(event, helcimSubscriptionSchema)
|
||||||
|
|
||||||
// Check if payment is required
|
// Check if payment is required
|
||||||
|
|
@ -159,91 +157,21 @@ export default defineEventHandler(async (event) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to create subscription in Helcim
|
// Try to create subscription in Helcim
|
||||||
const helcimToken = config.helcimApiToken
|
const idempotencyKey = generateIdempotencyKey()
|
||||||
|
|
||||||
// Generate a proper alphanumeric idempotency key (exactly 25 characters)
|
|
||||||
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
|
||||||
let idempotencyKey = ''
|
|
||||||
for (let i = 0; i < 25; i++) {
|
|
||||||
idempotencyKey += chars.charAt(Math.floor(Math.random() * chars.length))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get contribution tier details to set recurring amount
|
// Get contribution tier details to set recurring amount
|
||||||
const { getContributionTierByValue } = await import('../../config/contributions.js')
|
|
||||||
const tierInfo = getContributionTierByValue(body.contributionTier)
|
const tierInfo = getContributionTierByValue(body.contributionTier)
|
||||||
|
|
||||||
const requestBody = {
|
const subscriptionPayload = {
|
||||||
subscriptions: [{
|
dateActivated: new Date().toISOString().split('T')[0], // Today in YYYY-MM-DD format
|
||||||
dateActivated: new Date().toISOString().split('T')[0], // Today in YYYY-MM-DD format
|
paymentPlanId: parseInt(planId),
|
||||||
paymentPlanId: parseInt(planId),
|
customerCode: body.customerCode,
|
||||||
customerCode: body.customerCode,
|
recurringAmount: parseFloat(tierInfo.amount),
|
||||||
recurringAmount: parseFloat(tierInfo.amount),
|
paymentMethod: 'card'
|
||||||
paymentMethod: 'card'
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
const requestHeaders = {
|
|
||||||
'accept': 'application/json',
|
|
||||||
'content-type': 'application/json',
|
|
||||||
'api-token': helcimToken,
|
|
||||||
'idempotency-key': idempotencyKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const subscriptionResponse = await fetch(`${HELCIM_API_BASE}/subscriptions`, {
|
const subscriptionData = await createHelcimSubscription(subscriptionPayload, idempotencyKey)
|
||||||
method: 'POST',
|
|
||||||
headers: requestHeaders,
|
|
||||||
body: JSON.stringify(requestBody)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!subscriptionResponse.ok) {
|
|
||||||
const errorText = await subscriptionResponse.text()
|
|
||||||
console.error('Subscription creation failed:', subscriptionResponse.status)
|
|
||||||
|
|
||||||
// If it's a validation error, let's try to get more info about available plans
|
|
||||||
if (subscriptionResponse.status === 400 || subscriptionResponse.status === 404) {
|
|
||||||
// Plan might not exist -- update member status and proceed
|
|
||||||
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 subscription creation failed: ${errorText}`
|
|
||||||
},
|
|
||||||
{ new: true }
|
|
||||||
)
|
|
||||||
|
|
||||||
// Send Slack invitation even when subscription setup fails
|
|
||||||
await inviteToSlack(member)
|
|
||||||
|
|
||||||
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'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw createError({
|
|
||||||
statusCode: subscriptionResponse.status,
|
|
||||||
statusMessage: 'Subscription creation failed'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const subscriptionData = await subscriptionResponse.json()
|
|
||||||
|
|
||||||
// Extract the first subscription from the response array
|
// Extract the first subscription from the response array
|
||||||
const subscription = subscriptionData.data?.[0]
|
const subscription = subscriptionData.data?.[0]
|
||||||
|
|
@ -285,8 +213,14 @@ export default defineEventHandler(async (event) => {
|
||||||
status: member.status
|
status: member.status
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (fetchError) {
|
} catch (helcimError) {
|
||||||
console.error('Error during subscription creation:', fetchError)
|
// 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
|
// Still mark member as active since payment was successful
|
||||||
const member = await Member.findOneAndUpdate(
|
const member = await Member.findOneAndUpdate(
|
||||||
|
|
@ -297,12 +231,12 @@ export default defineEventHandler(async (event) => {
|
||||||
subscriptionStartDate: new Date(),
|
subscriptionStartDate: new Date(),
|
||||||
paymentMethod: 'card',
|
paymentMethod: 'card',
|
||||||
cardToken: body.cardToken,
|
cardToken: body.cardToken,
|
||||||
notes: `Payment successful but subscription creation failed: ${fetchError.message}`
|
notes: `Payment successful but subscription creation failed: ${helcimError.message || 'unknown error'}`
|
||||||
},
|
},
|
||||||
{ new: true }
|
{ new: true }
|
||||||
)
|
)
|
||||||
|
|
||||||
// Send Slack invitation even when subscription fetch fails
|
// Send Slack invitation even when subscription setup fails
|
||||||
await inviteToSlack(member)
|
await inviteToSlack(member)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue