feat(billing): record subscription-covered token usage in usage records
Memind CI / Test, build, and release guards (pull_request) Successful in 4m8s

Write h5_usage_records when plan quota fully covers a session bill so
WeChat and H5 consumption stays visible in admin usage history.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
john
2026-08-06 18:51:11 +08:00
parent 7c18c998bd
commit 6b586e0951
4 changed files with 145 additions and 6 deletions
+108
View File
@@ -770,6 +770,114 @@ test('billSessionUsage auto gifts low-balance bonus once for eligible new users'
assert.deepEqual(notificationTypes, ['low_balance_gift']);
});
test('billSessionUsage writes usage record when subscription fully covers tokens', async () => {
const userRow = {
id: 'user-sub-1',
username: 'pro_user',
slug: 'pro_user',
email: 'pro@example.com',
display_name: 'Pro User',
role: 'user',
status: 'active',
plan_type: 'pro',
workspace_root: '/tmp/pro-user',
balance_cents: 200,
tokens_used: 0,
spent_cents: 0,
};
const stateBySession = new Map();
let walletBalance = 200;
let tokensUsed = 0;
const usageRecords = [];
let ledgerCount = 0;
let consumeQuotaCalls = 0;
const subscriptionService = {
async consumeQuota(userId, deltaTokens) {
consumeQuotaCalls += 1;
assert.equal(userId, userRow.id);
assert.equal(deltaTokens, 15_000);
return { fullyCovers: true, overageRate: 0.5 };
},
};
const pool = {
async query(sql) {
if (sql.includes('FROM h5_users u') && sql.includes('WHERE u.id = ?')) {
return [[{ ...userRow, balance_cents: walletBalance, tokens_used: tokensUsed }]];
}
throw new Error(`unexpected pool query: ${sql}`);
},
async getConnection() {
return {
async beginTransaction() {},
async commit() {},
async rollback() {},
release() {},
async query(sql, params = []) {
if (sql.includes('SELECT cost_cents FROM h5_usage_records WHERE request_id = ? LIMIT 1')) return [[]];
if (sql.includes('INSERT INTO h5_session_billing_state') && sql.includes('agent_session_id = agent_session_id')) {
return [{ affectedRows: 1 }, []];
}
if (sql.includes('FROM h5_session_billing_state') && sql.includes('FOR UPDATE')) {
const row = stateBySession.get(params[0]);
return [row ? [row] : []];
}
if (sql.includes('INSERT INTO h5_session_billing_state') && sql.includes('ON DUPLICATE KEY UPDATE')) {
stateBySession.set(params[0], {
last_accumulated_cost: params[2],
last_input_tokens: params[3],
last_output_tokens: params[4],
});
return [{ affectedRows: 1 }, []];
}
if (sql.includes('SELECT balance_cents, tokens_used FROM h5_user_wallets WHERE user_id = ?')) {
return [[{ balance_cents: walletBalance, tokens_used: tokensUsed }]];
}
if (sql.includes('INSERT INTO h5_usage_records')) {
const subscription = sql.includes("'subscription'");
usageRecords.push({
user_id: params[0],
agent_session_id: params[1],
request_id: params[2],
input_tokens: params[3],
output_tokens: params[4],
cost_cents: subscription ? 0 : params[5],
balance_after_cents: subscription ? params[5] : params[6],
billing_source: subscription ? 'subscription' : 'wallet',
});
return [{ affectedRows: 1 }, []];
}
if (sql.includes("INSERT INTO h5_billing_ledger") && sql.includes("'deduct'")) {
ledgerCount += 1;
return [{ affectedRows: 1 }, []];
}
throw new Error(`unexpected connection query: ${sql}`);
},
};
},
};
const auth = createUserAuth(pool, { persistSessions: false, subscriptionService });
const result = await auth.billSessionUsage(
userRow.id,
'session-sub-1',
{ accumulatedOutputTokens: 15_000 },
'req-sub-1',
);
assert.equal(result.ok, true);
assert.equal(result.costCents, 0);
assert.equal(result.balanceCents, 200);
assert.equal(consumeQuotaCalls, 1);
assert.equal(ledgerCount, 0);
assert.equal(usageRecords.length, 1);
assert.equal(usageRecords[0].cost_cents, 0);
assert.equal(usageRecords[0].billing_source, 'subscription');
assert.equal(usageRecords[0].output_tokens, 15_000);
assert.equal(walletBalance, 200);
});
test('updateUser rejects quota smaller than occupied bytes', async () => {
const userRow = {
id: 'user-3',