feat(payments): log initial Helcim charge to Payment on subscription creation
After a paid subscription is created and the Member row is flipped to active, fetches the newest paid transaction from Helcim and upserts a Payment row. Passes paymentType from the chosen cadence and sendConfirmation: true. Wrapped in try/catch: a logging failure here never breaks subscription creation — the reconcile-helcim-payments script will pick up any misses on the next run.
This commit is contained in:
parent
be7145f96c
commit
49cfb47fff
2 changed files with 127 additions and 2 deletions
|
|
@ -4,8 +4,9 @@ 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'
|
import { createHelcimSubscription, generateIdempotencyKey, listHelcimCustomerTransactions } from '../../utils/helcim.js'
|
||||||
import { sendWelcomeEmail } from '../../utils/resend.js'
|
import { sendWelcomeEmail } from '../../utils/resend.js'
|
||||||
|
import { upsertPaymentFromHelcim } from '../../utils/payments.js'
|
||||||
|
|
||||||
// Function to invite member to Slack
|
// Function to invite member to Slack
|
||||||
async function inviteToSlack(member) {
|
async function inviteToSlack(member) {
|
||||||
|
|
@ -189,6 +190,19 @@ export default defineEventHandler(async (event) => {
|
||||||
|
|
||||||
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
logActivity(member._id, 'subscription_created', { amount: body.contributionAmount })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const txs = await listHelcimCustomerTransactions(body.customerCode)
|
||||||
|
const latestPaid = txs.find((t) => t.status === 'paid')
|
||||||
|
if (latestPaid) {
|
||||||
|
await upsertPaymentFromHelcim(member, latestPaid, {
|
||||||
|
paymentType: cadence,
|
||||||
|
sendConfirmation: true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[payments] initial charge log failed, will be picked up by reconciliation:', err?.message || err)
|
||||||
|
}
|
||||||
|
|
||||||
await inviteToSlack(member)
|
await inviteToSlack(member)
|
||||||
if (isFirstActivation) await sendWelcomeEmail(member)
|
if (isFirstActivation) await sendWelcomeEmail(member)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
import Member from '../../../server/models/member.js'
|
import Member from '../../../server/models/member.js'
|
||||||
import { requireAuth } from '../../../server/utils/auth.js'
|
import { requireAuth } from '../../../server/utils/auth.js'
|
||||||
import { requiresPayment, getHelcimPlanId } from '../../../server/config/contributions.js'
|
import { requiresPayment, getHelcimPlanId } from '../../../server/config/contributions.js'
|
||||||
import { createHelcimSubscription } from '../../../server/utils/helcim.js'
|
import { createHelcimSubscription, listHelcimCustomerTransactions } from '../../../server/utils/helcim.js'
|
||||||
|
import { upsertPaymentFromHelcim } from '../../../server/utils/payments.js'
|
||||||
import subscriptionHandler from '../../../server/api/helcim/subscription.post.js'
|
import subscriptionHandler from '../../../server/api/helcim/subscription.post.js'
|
||||||
import { createMockEvent } from '../helpers/createMockEvent.js'
|
import { createMockEvent } from '../helpers/createMockEvent.js'
|
||||||
|
|
||||||
|
|
@ -25,6 +26,10 @@ vi.mock('../../../server/utils/resend.js', () => ({
|
||||||
vi.mock('../../../server/utils/helcim.js', () => ({
|
vi.mock('../../../server/utils/helcim.js', () => ({
|
||||||
createHelcimSubscription: vi.fn(),
|
createHelcimSubscription: vi.fn(),
|
||||||
generateIdempotencyKey: vi.fn().mockReturnValue('idem-key-123'),
|
generateIdempotencyKey: vi.fn().mockReturnValue('idem-key-123'),
|
||||||
|
listHelcimCustomerTransactions: vi.fn().mockResolvedValue([]),
|
||||||
|
}))
|
||||||
|
vi.mock('../../../server/utils/payments.js', () => ({
|
||||||
|
upsertPaymentFromHelcim: vi.fn().mockResolvedValue({ created: true, payment: { _id: 'p1' } })
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// helcimSubscriptionSchema is a Nitro auto-import used by validateBody
|
// helcimSubscriptionSchema is a Nitro auto-import used by validateBody
|
||||||
|
|
@ -262,6 +267,112 @@ describe('helcim subscription endpoint', () => {
|
||||||
expect(Member.findOneAndUpdate).not.toHaveBeenCalled()
|
expect(Member.findOneAndUpdate).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('logs the newest paid Helcim transaction to Payment on paid monthly creation', async () => {
|
||||||
|
requireAuth.mockResolvedValue(undefined)
|
||||||
|
requiresPayment.mockReturnValue(true)
|
||||||
|
getHelcimPlanId.mockReturnValue('99999')
|
||||||
|
|
||||||
|
const mockMember = {
|
||||||
|
_id: 'member-9',
|
||||||
|
email: 'log@example.com',
|
||||||
|
name: 'Logger',
|
||||||
|
circle: 'founder',
|
||||||
|
contributionAmount: 15,
|
||||||
|
status: 'active',
|
||||||
|
}
|
||||||
|
Member.findOneAndUpdate.mockResolvedValue(mockMember)
|
||||||
|
createHelcimSubscription.mockResolvedValue({
|
||||||
|
data: [{ id: 'sub-log-1', status: 'active', nextBillingDate: '2026-05-18' }]
|
||||||
|
})
|
||||||
|
listHelcimCustomerTransactions.mockResolvedValueOnce([
|
||||||
|
{ id: 'tx-newest', date: '2026-04-20', amount: 15, status: 'paid', currency: 'CAD' },
|
||||||
|
{ id: 'tx-older', date: '2026-04-19', amount: 15, status: 'paid', currency: 'CAD' }
|
||||||
|
])
|
||||||
|
|
||||||
|
const event = createMockEvent({
|
||||||
|
method: 'POST',
|
||||||
|
path: '/api/helcim/subscription',
|
||||||
|
body: { customerId: 'cust-log', contributionAmount: 15, customerCode: 'code-log', cardToken: 'tok', cadence: 'monthly' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await subscriptionHandler(event)
|
||||||
|
|
||||||
|
expect(result.success).toBe(true)
|
||||||
|
expect(listHelcimCustomerTransactions).toHaveBeenCalledWith('code-log')
|
||||||
|
expect(upsertPaymentFromHelcim).toHaveBeenCalledWith(
|
||||||
|
mockMember,
|
||||||
|
expect.objectContaining({ id: 'tx-newest' }),
|
||||||
|
{ paymentType: 'monthly', sendConfirmation: true }
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses cadence=annual when logging the initial charge on annual creation', async () => {
|
||||||
|
requireAuth.mockResolvedValue(undefined)
|
||||||
|
requiresPayment.mockReturnValue(true)
|
||||||
|
getHelcimPlanId.mockReturnValue('88888')
|
||||||
|
|
||||||
|
const mockMember = {
|
||||||
|
_id: 'member-10',
|
||||||
|
email: 'annuallog@example.com',
|
||||||
|
name: 'AnnualLogger',
|
||||||
|
circle: 'founder',
|
||||||
|
contributionAmount: 15,
|
||||||
|
status: 'active',
|
||||||
|
}
|
||||||
|
Member.findOneAndUpdate.mockResolvedValue(mockMember)
|
||||||
|
createHelcimSubscription.mockResolvedValue({
|
||||||
|
data: [{ id: 'sub-annual-log', status: 'active', nextBillingDate: '2027-04-20' }]
|
||||||
|
})
|
||||||
|
listHelcimCustomerTransactions.mockResolvedValueOnce([
|
||||||
|
{ id: 'tx-annual', date: '2026-04-20', amount: 180, status: 'paid', currency: 'CAD' }
|
||||||
|
])
|
||||||
|
|
||||||
|
const event = createMockEvent({
|
||||||
|
method: 'POST',
|
||||||
|
path: '/api/helcim/subscription',
|
||||||
|
body: { customerId: 'cust-a', contributionAmount: 15, customerCode: 'code-a', cardToken: 'tok', cadence: 'annual' }
|
||||||
|
})
|
||||||
|
|
||||||
|
await subscriptionHandler(event)
|
||||||
|
|
||||||
|
expect(upsertPaymentFromHelcim).toHaveBeenCalledWith(
|
||||||
|
mockMember,
|
||||||
|
expect.objectContaining({ id: 'tx-annual' }),
|
||||||
|
{ paymentType: 'annual', sendConfirmation: true }
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('still returns success when payment logging throws (reconciliation will catch)', async () => {
|
||||||
|
requireAuth.mockResolvedValue(undefined)
|
||||||
|
requiresPayment.mockReturnValue(true)
|
||||||
|
getHelcimPlanId.mockReturnValue('99999')
|
||||||
|
|
||||||
|
const mockMember = {
|
||||||
|
_id: 'member-11',
|
||||||
|
email: 'boom@example.com',
|
||||||
|
name: 'Boom',
|
||||||
|
circle: 'founder',
|
||||||
|
contributionAmount: 15,
|
||||||
|
status: 'active',
|
||||||
|
}
|
||||||
|
Member.findOneAndUpdate.mockResolvedValue(mockMember)
|
||||||
|
createHelcimSubscription.mockResolvedValue({
|
||||||
|
data: [{ id: 'sub-boom', status: 'active', nextBillingDate: '2026-05-18' }]
|
||||||
|
})
|
||||||
|
listHelcimCustomerTransactions.mockRejectedValueOnce(new Error('helcim down'))
|
||||||
|
|
||||||
|
const event = createMockEvent({
|
||||||
|
method: 'POST',
|
||||||
|
path: '/api/helcim/subscription',
|
||||||
|
body: { customerId: 'cust-boom', contributionAmount: 15, customerCode: 'code-boom', cardToken: 'tok', cadence: 'monthly' }
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await subscriptionHandler(event)
|
||||||
|
|
||||||
|
expect(result.success).toBe(true)
|
||||||
|
expect(upsertPaymentFromHelcim).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
it('Helcim API failure returns 500 and does NOT activate member', async () => {
|
it('Helcim API failure returns 500 and does NOT activate member', async () => {
|
||||||
requireAuth.mockResolvedValue(undefined)
|
requireAuth.mockResolvedValue(undefined)
|
||||||
requiresPayment.mockReturnValue(true)
|
requiresPayment.mockReturnValue(true)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue