Skip to content

Commit 072d4cd

Browse files
committed
pass in logger to auto-topup
1 parent 202bea0 commit 072d4cd

File tree

7 files changed

+143
-102
lines changed

7 files changed

+143
-102
lines changed

backend/src/__tests__/auto-topup.test.ts

Lines changed: 64 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import {
88
afterAll,
99
afterEach,
10+
beforeAll,
1011
beforeEach,
1112
describe,
1213
expect,
@@ -15,26 +16,23 @@ import {
1516
spyOn,
1617
} from 'bun:test'
1718

19+
import type { Logger } from '@codebuff/types/logger'
20+
1821
describe('Auto Top-up System', () => {
1922
describe('checkAndTriggerAutoTopup', () => {
2023
// Create fresh mocks for each test
2124
let dbMock: ReturnType<typeof mock>
2225
let balanceMock: ReturnType<typeof mock>
2326
let validateAutoTopupMock: ReturnType<typeof mock>
2427
let grantCreditsMock: ReturnType<typeof mock>
25-
26-
beforeEach(() => {
27-
// Mock logger for auto-topup functionality
28-
mockModule('@codebuff/common/util/logger', () => ({
29-
logger: {
30-
debug: () => {},
31-
error: () => {},
32-
info: () => {},
33-
warn: () => {},
34-
},
35-
withLoggerContext: async (context: any, fn: () => Promise<any>) => fn(),
36-
}))
37-
28+
const logger: Logger = {
29+
debug: () => {},
30+
error: () => {},
31+
info: () => {},
32+
warn: () => {},
33+
}
34+
35+
beforeAll(() => {
3836
// Set up default mocks
3937
dbMock = mock(() =>
4038
Promise.resolve({
@@ -46,6 +44,38 @@ describe('Auto Top-up System', () => {
4644
}),
4745
)
4846

47+
// Mock the database
48+
mockModule('@codebuff/common/db', () => ({
49+
default: {
50+
query: {
51+
user: {
52+
findFirst: dbMock,
53+
},
54+
},
55+
update: mock(() => ({
56+
set: () => ({
57+
where: () => Promise.resolve(),
58+
}),
59+
})),
60+
},
61+
}))
62+
63+
// Mock Stripe payment intent creation
64+
mockModule('@codebuff/common/util/stripe', () => ({
65+
stripeServer: {
66+
paymentIntents: {
67+
create: mock(() =>
68+
Promise.resolve({
69+
status: 'succeeded',
70+
id: 'pi_123',
71+
}),
72+
),
73+
},
74+
},
75+
}))
76+
})
77+
78+
beforeEach(() => {
4979
balanceMock = mock(() =>
5080
Promise.resolve({
5181
usageThisCycle: 0,
@@ -74,43 +104,17 @@ describe('Auto Top-up System', () => {
74104

75105
grantCreditsMock = mock(() => Promise.resolve())
76106

77-
// Mock the database
78-
mockModule('@codebuff/common/db', () => ({
79-
default: {
80-
query: {
81-
user: {
82-
findFirst: dbMock,
83-
},
84-
},
85-
update: mock(() => ({
86-
set: () => ({
87-
where: () => Promise.resolve(),
88-
}),
89-
})),
90-
},
91-
}))
92-
93107
spyOn(billing, 'calculateUsageAndBalance').mockImplementation(balanceMock)
94108
spyOn(billing, 'validateAutoTopupStatus').mockImplementation(
95109
validateAutoTopupMock,
96110
)
97111
spyOn(billing, 'processAndGrantCredit').mockImplementation(
98112
grantCreditsMock,
99113
)
114+
})
100115

101-
// Mock Stripe payment intent creation
102-
mockModule('@codebuff/common/util/stripe', () => ({
103-
stripeServer: {
104-
paymentIntents: {
105-
create: mock(() =>
106-
Promise.resolve({
107-
status: 'succeeded',
108-
id: 'pi_123',
109-
}),
110-
),
111-
},
112-
},
113-
}))
116+
afterEach(() => {
117+
mock.restore()
114118
})
115119

116120
afterAll(() => {
@@ -119,7 +123,10 @@ describe('Auto Top-up System', () => {
119123

120124
it('should trigger top-up when balance below threshold', async () => {
121125
// Replace direct call with capture of returned amount
122-
const amount = await checkAndTriggerAutoTopup('test-user')
126+
const amount = await checkAndTriggerAutoTopup({
127+
userId: 'test-user',
128+
logger,
129+
})
123130

124131
// Should check user settings
125132
expect(dbMock).toHaveBeenCalled()
@@ -158,7 +165,10 @@ describe('Auto Top-up System', () => {
158165
)
159166

160167
// Capture return value (should be undefined)
161-
const amount = await checkAndTriggerAutoTopup('test-user')
168+
const amount = await checkAndTriggerAutoTopup({
169+
userId: 'test-user',
170+
logger,
171+
})
162172

163173
// Should still check settings and balance
164174
expect(dbMock).toHaveBeenCalled()
@@ -195,7 +205,10 @@ describe('Auto Top-up System', () => {
195205
)
196206

197207
// Capture the returned amount and assert debt coverage
198-
const amount = await checkAndTriggerAutoTopup('test-user')
208+
const amount = await checkAndTriggerAutoTopup({
209+
userId: 'test-user',
210+
logger,
211+
})
199212

200213
expect(amount).toBe(600)
201214
})
@@ -214,9 +227,12 @@ describe('Auto Top-up System', () => {
214227
validateAutoTopupMock,
215228
)
216229

217-
await expect(checkAndTriggerAutoTopup('test-user')).rejects.toThrow(
218-
'No valid payment method found',
219-
)
230+
await expect(
231+
checkAndTriggerAutoTopup({
232+
userId: 'test-user',
233+
logger,
234+
}),
235+
).rejects.toThrow('No valid payment method found')
220236

221237
// Should have called validation
222238
expect(validateAutoTopupMock).toHaveBeenCalled()

backend/src/websockets/middleware.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,11 @@ protec.use(async (action, clientSessionId, ws, userInfo) => {
187187
if (orgLookup.found && orgLookup.organizationId) {
188188
// Check and trigger organization auto top-up if needed
189189
try {
190-
await checkAndTriggerOrgAutoTopup(orgLookup.organizationId, userId)
190+
await checkAndTriggerOrgAutoTopup({
191+
organizationId: orgLookup.organizationId,
192+
userId,
193+
logger,
194+
})
191195
} catch (error) {
192196
logger.error(
193197
{
@@ -318,7 +322,7 @@ protec.use(async (action, clientSessionId, ws, userInfo) => {
318322
// Check if we need to trigger auto top-up and get the amount added (if any)
319323
let autoTopupAdded: number | undefined = undefined
320324
try {
321-
autoTopupAdded = await checkAndTriggerAutoTopup(userId)
325+
autoTopupAdded = await checkAndTriggerAutoTopup({ userId, logger })
322326
} catch (error) {
323327
logger.error(
324328
{

0 commit comments

Comments
 (0)