feat(payments): persist helcimCustomerCode + skip getOrCreateCustomer on card-on-file
This commit is contained in:
parent
0a41b30db7
commit
ac5e979c78
10 changed files with 330 additions and 33 deletions
145
tests/client/composables/useMemberPayment.test.js
Normal file
145
tests/client/composables/useMemberPayment.test.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
import { useMemberPayment } from '../../../app/composables/useMemberPayment.js'
|
||||
|
||||
// Stub Vue's ref/readonly as Nuxt auto-imports
|
||||
vi.stubGlobal('ref', ref)
|
||||
vi.stubGlobal('readonly', (v) => v)
|
||||
|
||||
const memberData = ref(null)
|
||||
const checkMemberStatus = vi.fn()
|
||||
vi.stubGlobal('useAuth', () => ({ memberData, checkMemberStatus }))
|
||||
|
||||
const initializeHelcimPay = vi.fn()
|
||||
const verifyPayment = vi.fn()
|
||||
const cleanupHelcimPay = vi.fn()
|
||||
vi.stubGlobal('useHelcimPay', () => ({
|
||||
initializeHelcimPay,
|
||||
verifyPayment,
|
||||
cleanup: cleanupHelcimPay,
|
||||
}))
|
||||
|
||||
const $fetch = vi.fn()
|
||||
vi.stubGlobal('$fetch', $fetch)
|
||||
|
||||
describe('useMemberPayment.initiatePaymentSetup — shortcut path', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
memberData.value = null
|
||||
$fetch.mockReset()
|
||||
})
|
||||
|
||||
it('skips getOrCreateCustomer when both helcim ids are cached AND a card is on file', async () => {
|
||||
memberData.value = {
|
||||
helcimCustomerId: 'cust-123',
|
||||
helcimCustomerCode: 'CST-ABC',
|
||||
contributionAmount: 15,
|
||||
}
|
||||
|
||||
$fetch.mockImplementation((path) => {
|
||||
if (path === '/api/helcim/existing-card') {
|
||||
return Promise.resolve({ cardToken: 'tok-xyz' })
|
||||
}
|
||||
if (path === '/api/helcim/subscription') {
|
||||
return Promise.resolve({ success: true })
|
||||
}
|
||||
return Promise.reject(new Error(`Unexpected $fetch call: ${path}`))
|
||||
})
|
||||
|
||||
const { initiatePaymentSetup } = useMemberPayment()
|
||||
const result = await initiatePaymentSetup()
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
|
||||
// The whole point: get-or-create-customer was NOT called.
|
||||
const calledPaths = $fetch.mock.calls.map((c) => c[0])
|
||||
expect(calledPaths).not.toContain('/api/helcim/get-or-create-customer')
|
||||
expect(calledPaths).not.toContain('/api/helcim/customer-code')
|
||||
|
||||
// We did call existing-card (once) and subscription (once).
|
||||
expect(calledPaths.filter((p) => p === '/api/helcim/existing-card')).toHaveLength(1)
|
||||
expect(calledPaths.filter((p) => p === '/api/helcim/subscription')).toHaveLength(1)
|
||||
|
||||
// HelcimPay modal not opened — card was already on file.
|
||||
expect(initializeHelcimPay).not.toHaveBeenCalled()
|
||||
expect(verifyPayment).not.toHaveBeenCalled()
|
||||
|
||||
// Subscription called with the cached id/code from memberData.
|
||||
const subscriptionCall = $fetch.mock.calls.find((c) => c[0] === '/api/helcim/subscription')
|
||||
expect(subscriptionCall[1].body).toMatchObject({
|
||||
customerId: 'cust-123',
|
||||
customerCode: 'CST-ABC',
|
||||
cardToken: 'tok-xyz',
|
||||
contributionAmount: 15,
|
||||
})
|
||||
})
|
||||
|
||||
it('falls through to get-or-create-customer when helcimCustomerCode is missing', async () => {
|
||||
memberData.value = {
|
||||
helcimCustomerId: 'cust-123',
|
||||
// helcimCustomerCode missing — must NOT take shortcut
|
||||
contributionAmount: 15,
|
||||
}
|
||||
|
||||
$fetch.mockImplementation((path) => {
|
||||
if (path === '/api/helcim/customer-code') {
|
||||
return Promise.resolve({ customerId: 'cust-123', customerCode: 'CST-FRESH' })
|
||||
}
|
||||
if (path === '/api/helcim/existing-card') {
|
||||
return Promise.resolve({ cardToken: 'tok-xyz' })
|
||||
}
|
||||
if (path === '/api/helcim/subscription') {
|
||||
return Promise.resolve({ success: true })
|
||||
}
|
||||
return Promise.reject(new Error(`Unexpected $fetch call: ${path}`))
|
||||
})
|
||||
|
||||
const { initiatePaymentSetup } = useMemberPayment()
|
||||
await initiatePaymentSetup()
|
||||
|
||||
const calledPaths = $fetch.mock.calls.map((c) => c[0])
|
||||
// Existing helcimCustomerId path -> /api/helcim/customer-code is called.
|
||||
expect(calledPaths).toContain('/api/helcim/customer-code')
|
||||
})
|
||||
|
||||
it('falls through to get-or-create-customer when no card is on file', async () => {
|
||||
memberData.value = {
|
||||
helcimCustomerId: 'cust-123',
|
||||
helcimCustomerCode: 'CST-ABC',
|
||||
contributionAmount: 15,
|
||||
}
|
||||
|
||||
initializeHelcimPay.mockResolvedValue(undefined)
|
||||
verifyPayment.mockResolvedValue({ success: true, cardToken: 'tok-new' })
|
||||
|
||||
let existingCardCalls = 0
|
||||
$fetch.mockImplementation((path) => {
|
||||
if (path === '/api/helcim/existing-card') {
|
||||
existingCardCalls++
|
||||
return Promise.resolve(null) // no card on file
|
||||
}
|
||||
if (path === '/api/helcim/customer-code') {
|
||||
return Promise.resolve({ customerId: 'cust-123', customerCode: 'CST-ABC' })
|
||||
}
|
||||
if (path === '/api/helcim/verify-payment') {
|
||||
return Promise.resolve({ success: true })
|
||||
}
|
||||
if (path === '/api/helcim/subscription') {
|
||||
return Promise.resolve({ success: true })
|
||||
}
|
||||
return Promise.reject(new Error(`Unexpected $fetch call: ${path}`))
|
||||
})
|
||||
|
||||
const { initiatePaymentSetup } = useMemberPayment()
|
||||
await initiatePaymentSetup()
|
||||
|
||||
// Falls into the full flow — modal opens, verify runs.
|
||||
expect(initializeHelcimPay).toHaveBeenCalled()
|
||||
expect(verifyPayment).toHaveBeenCalled()
|
||||
|
||||
const calledPaths = $fetch.mock.calls.map((c) => c[0])
|
||||
expect(calledPaths).toContain('/api/helcim/customer-code')
|
||||
// existing-card was reused from the shortcut probe — should not refetch.
|
||||
expect(existingCardCalls).toBe(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -2,19 +2,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|||
|
||||
import Member from '../../../server/models/member.js'
|
||||
import Payment from '../../../server/models/payment.js'
|
||||
import { listHelcimCustomerTransactions } from '../../../server/utils/helcim.js'
|
||||
import { getHelcimCustomer, listHelcimCustomerTransactions } from '../../../server/utils/helcim.js'
|
||||
import { upsertPaymentFromHelcim } from '../../../server/utils/payments.js'
|
||||
import reconcileHandler from '../../../server/api/internal/reconcile-payments.post.js'
|
||||
import { createMockEvent } from '../helpers/createMockEvent.js'
|
||||
|
||||
vi.mock('../../../server/models/member.js', () => ({
|
||||
default: { find: vi.fn() }
|
||||
default: { find: vi.fn(), findByIdAndUpdate: vi.fn() }
|
||||
}))
|
||||
vi.mock('../../../server/models/payment.js', () => ({
|
||||
default: { findOne: vi.fn() }
|
||||
}))
|
||||
vi.mock('../../../server/utils/mongoose.js', () => ({ connectDB: vi.fn() }))
|
||||
vi.mock('../../../server/utils/helcim.js', () => ({
|
||||
getHelcimCustomer: vi.fn(),
|
||||
listHelcimCustomerTransactions: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../server/utils/payments.js', () => ({
|
||||
|
|
@ -88,6 +89,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
_id: 'm1',
|
||||
email: 'a@example.com',
|
||||
helcimCustomerId: 'cust-1',
|
||||
helcimCustomerCode: 'CST-1',
|
||||
helcimSubscriptionId: 'sub-1',
|
||||
billingCadence: 'monthly'
|
||||
}
|
||||
|
|
@ -113,6 +115,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
{ helcimCustomerId: { $exists: true, $ne: null } },
|
||||
expect.objectContaining({
|
||||
helcimCustomerId: 1,
|
||||
helcimCustomerCode: 1,
|
||||
helcimSubscriptionId: 1,
|
||||
billingCadence: 1
|
||||
})
|
||||
|
|
@ -134,7 +137,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
|
||||
it('does NOT pass sendConfirmation: true (no duplicate confirmation emails)', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([
|
||||
{ id: 'tx-paid', status: 'paid', amount: 10, currency: 'CAD' }
|
||||
|
|
@ -157,9 +160,9 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
|
||||
it('continues iterating when listHelcimCustomerTransactions throws for one member', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' },
|
||||
{ _id: 'm2', helcimCustomerId: 'cust-2' },
|
||||
{ _id: 'm3', helcimCustomerId: 'cust-3' }
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-1' },
|
||||
{ _id: 'm2', helcimCustomerId: 'cust-2', helcimCustomerCode: 'CST-2' },
|
||||
{ _id: 'm3', helcimCustomerId: 'cust-3', helcimCustomerCode: 'CST-3' }
|
||||
]))
|
||||
// m1 succeeds first try, m2 fails all 3 retries, m3 succeeds first try.
|
||||
// Keyed by customerCode so it works regardless of call order (chunked Promise.all).
|
||||
|
|
@ -191,7 +194,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
it('retries transient Helcim errors with exponential backoff (3 attempts)', async () => {
|
||||
vi.useFakeTimers()
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions
|
||||
.mockRejectedValueOnce(new Error('boom 1'))
|
||||
|
|
@ -219,7 +222,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
it('counts memberErrors when all 3 retry attempts fail', async () => {
|
||||
vi.useFakeTimers()
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockRejectedValue(new Error('persistent 503'))
|
||||
|
||||
|
|
@ -241,7 +244,7 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
|
||||
it('honors ?apply=false dry-run mode (Payment.findOne, no upsert)', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-1' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([
|
||||
{ id: 'tx-existing', status: 'paid', amount: 10 },
|
||||
|
|
@ -266,4 +269,63 @@ describe('POST /api/internal/reconcile-payments', () => {
|
|||
existed: 1
|
||||
})
|
||||
})
|
||||
|
||||
describe('helcimCustomerCode backfill', () => {
|
||||
it('writes helcimCustomerCode when missing on the member doc', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' } // no helcimCustomerCode
|
||||
]))
|
||||
getHelcimCustomer.mockResolvedValue({ id: 'cust-1', customerCode: 'CST-NEW' })
|
||||
listHelcimCustomerTransactions.mockResolvedValue([])
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
await reconcileHandler(event)
|
||||
|
||||
expect(getHelcimCustomer).toHaveBeenCalledWith('cust-1')
|
||||
expect(Member.findByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'm1',
|
||||
{ $set: { helcimCustomerCode: 'CST-NEW' } },
|
||||
{ runValidators: false }
|
||||
)
|
||||
})
|
||||
|
||||
it('skips backfill when helcimCustomerCode is already present', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1', helcimCustomerCode: 'CST-EXISTING' }
|
||||
]))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([])
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
await reconcileHandler(event)
|
||||
|
||||
expect(getHelcimCustomer).not.toHaveBeenCalled()
|
||||
expect(Member.findByIdAndUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not fail the run when getHelcimCustomer throws during backfill', async () => {
|
||||
Member.find.mockReturnValue(leanResolver([
|
||||
{ _id: 'm1', helcimCustomerId: 'cust-1' }
|
||||
]))
|
||||
getHelcimCustomer.mockRejectedValue(new Error('helcim 503'))
|
||||
listHelcimCustomerTransactions.mockResolvedValue([])
|
||||
|
||||
const event = createMockEvent({
|
||||
method: 'POST',
|
||||
path: '/api/internal/reconcile-payments',
|
||||
headers: { 'x-reconcile-token': RECONCILE_TOKEN }
|
||||
})
|
||||
const result = await reconcileHandler(event)
|
||||
|
||||
expect(Member.findByIdAndUpdate).not.toHaveBeenCalled()
|
||||
expect(result.memberErrors).toBe(0) // backfill failure is best-effort, not fatal
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue