59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
// Get existing or create new Helcim customer (for upgrading members)
|
|
import { requireAuth } from '../../utils/auth.js'
|
|
import { findHelcimCustomerByEmail, createHelcimCustomer } from '../../utils/helcim.js'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
const member = await requireAuth(event)
|
|
|
|
// First, try to find an existing customer
|
|
let existingCustomer = null
|
|
try {
|
|
const searchData = await findHelcimCustomerByEmail(member.email)
|
|
if (searchData.customers && searchData.customers.length > 0) {
|
|
existingCustomer = searchData.customers.find(c => c.email === member.email) || null
|
|
}
|
|
} catch (searchError) {
|
|
console.error('Error searching for customer:', searchError)
|
|
// Fall through to create
|
|
}
|
|
|
|
if (existingCustomer) {
|
|
if (!member.helcimCustomerId) {
|
|
member.helcimCustomerId = existingCustomer.id
|
|
await member.save()
|
|
}
|
|
return {
|
|
success: true,
|
|
customerId: existingCustomer.id,
|
|
customerCode: existingCustomer.customerCode,
|
|
existing: true
|
|
}
|
|
}
|
|
|
|
// No existing customer found — create one
|
|
const customerData = await createHelcimCustomer({
|
|
contactName: member.name,
|
|
businessName: member.name,
|
|
email: member.email
|
|
})
|
|
|
|
member.helcimCustomerId = customerData.id
|
|
await member.save()
|
|
|
|
return {
|
|
success: true,
|
|
customerId: customerData.id,
|
|
customerCode: customerData.customerCode,
|
|
existing: false
|
|
}
|
|
|
|
} catch (error) {
|
|
if (error.statusCode) throw error
|
|
console.error('Error in get-or-create-customer:', error)
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'An unexpected error occurred'
|
|
})
|
|
}
|
|
})
|