ghostguild-org/server/utils/payments.js
Jennie Robinson Faber 04eb33df6e
Some checks failed
Test / vitest (push) Successful in 11m10s
Test / playwright (push) Failing after 14m51s
Test / visual (push) Failing after 11m1s
Test / Notify on failure (push) Successful in 3s
refactor(env): unify required-env validation through useRuntimeConfig
validate-env.js now reads all four required vars (MONGODB_URI, JWT_SECRET,
RESEND_API_KEY, HELCIM_API_TOKEN) from useRuntimeConfig() instead of mixing
direct process.env reads with a JWT-only special case. Mongoose and the six
Resend instantiations follow suit. Either bare or NUXT_-prefixed env names
are accepted, so Dokploy no longer needs duplicate entries.
2026-04-26 14:47:02 +01:00

63 lines
1.9 KiB
JavaScript

import { Resend } from 'resend'
import Payment from '../models/payment.js'
import { paymentConfirmationEmail } from '../emails/paymentConfirmation.js'
const resend = new Resend(useRuntimeConfig().resendApiKey)
function mapStatus(helcimStatus) {
if (helcimStatus === 'paid') return 'success'
if (helcimStatus === 'refunded') return 'refunded'
if (helcimStatus === 'failed') return 'failed'
return null
}
export async function upsertPaymentFromHelcim(memberDoc, helcimTx, opts = {}) {
const status = mapStatus(helcimTx?.status)
if (!status) return { created: false, payment: null }
const existing = await Payment.findOne({ helcimTransactionId: helcimTx.id })
if (existing) return { created: false, payment: existing }
const paymentType = opts.paymentType || memberDoc.billingCadence
const fields = {
memberId: memberDoc._id,
helcimTransactionId: helcimTx.id,
helcimCustomerId: memberDoc.helcimCustomerId || null,
helcimSubscriptionId: memberDoc.helcimSubscriptionId || null,
amount: helcimTx.amount,
currency: helcimTx.currency || 'CAD',
paymentDate: helcimTx.date ? new Date(helcimTx.date) : new Date(),
paymentType,
status,
rawHelcim: helcimTx
}
let payment
try {
payment = await Payment.create(fields)
} catch (err) {
if (err?.code === 11000) {
const racer = await Payment.findOne({ helcimTransactionId: helcimTx.id })
return { created: false, payment: racer }
}
throw err
}
if (opts.sendConfirmation) {
try {
await resend.emails.send(
paymentConfirmationEmail({
member: memberDoc,
amount: fields.amount,
paymentDate: fields.paymentDate,
transactionId: fields.helcimTransactionId
})
)
} catch (err) {
console.error('[payments] failed to send payment confirmation email:', err?.message || err)
}
}
return { created: true, payment }
}