codebuff 1.0.218 → 1.0.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/checkpoints/checkpoint-manager.d.ts +1 -1
- package/dist/checkpoints/checkpoint-manager.js +8 -6
- package/dist/checkpoints/checkpoint-manager.js.map +1 -1
- package/dist/cli-handlers/api-key.d.ts +25 -0
- package/dist/cli-handlers/api-key.js +66 -0
- package/dist/cli-handlers/api-key.js.map +1 -0
- package/dist/cli-handlers/checkpoint.d.ts +18 -0
- package/dist/cli-handlers/checkpoint.js +195 -0
- package/dist/cli-handlers/checkpoint.js.map +1 -0
- package/dist/cli-handlers/diff.d.ts +2 -0
- package/dist/cli-handlers/diff.js +31 -0
- package/dist/cli-handlers/diff.js.map +1 -0
- package/dist/cli-handlers/easter-egg.d.ts +1 -0
- package/dist/cli-handlers/easter-egg.js +126 -0
- package/dist/cli-handlers/easter-egg.js.map +1 -0
- package/dist/cli.d.ts +0 -18
- package/dist/cli.js +70 -397
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +11 -11
- package/dist/client.js +123 -45
- package/dist/client.js.map +1 -1
- package/dist/code-map/tsconfig.tsbuildinfo +1 -1
- package/dist/common/actions.d.ts +288 -264
- package/dist/common/actions.js +10 -4
- package/dist/common/actions.js.map +1 -1
- package/dist/common/advanced-analyzer.d.ts +19 -0
- package/dist/common/advanced-analyzer.js +140 -0
- package/dist/common/advanced-analyzer.js.map +1 -0
- package/dist/common/billing/auto-topup.d.ts +8 -0
- package/dist/common/billing/auto-topup.js +192 -0
- package/dist/common/billing/auto-topup.js.map +1 -0
- package/dist/common/billing/balance-calculator.d.ts +55 -0
- package/dist/common/billing/balance-calculator.js +207 -0
- package/dist/common/billing/balance-calculator.js.map +1 -0
- package/dist/common/billing/check-auto-topup.d.ts +12 -0
- package/dist/common/billing/check-auto-topup.js +50 -0
- package/dist/common/billing/check-auto-topup.js.map +1 -0
- package/dist/common/billing/conversion.d.ts +9 -0
- package/dist/common/billing/conversion.js +20 -0
- package/dist/common/billing/conversion.js.map +1 -0
- package/dist/common/billing/credit-check.d.ts +8 -0
- package/dist/common/billing/credit-check.js +45 -0
- package/dist/common/billing/credit-check.js.map +1 -0
- package/dist/common/billing/credit-conversion.d.ts +24 -0
- package/dist/common/billing/credit-conversion.js +48 -0
- package/dist/common/billing/credit-conversion.js.map +1 -0
- package/dist/common/billing/grant-credits.d.ts +28 -0
- package/dist/common/billing/grant-credits.js +201 -0
- package/dist/common/billing/grant-credits.js.map +1 -0
- package/dist/common/billing/plans.d.ts +13 -0
- package/dist/common/billing/plans.js +44 -0
- package/dist/common/billing/plans.js.map +1 -0
- package/dist/common/billing/rollover-logic.d.ts +13 -0
- package/dist/common/billing/rollover-logic.js +174 -0
- package/dist/common/billing/rollover-logic.js.map +1 -0
- package/dist/common/billing/stripe-api.d.ts +31 -0
- package/dist/common/billing/stripe-api.js +104 -0
- package/dist/common/billing/stripe-api.js.map +1 -0
- package/dist/common/browser-actions.d.ts +62 -62
- package/dist/common/browser-actions.js +3 -3
- package/dist/common/browser-actions.js.map +1 -1
- package/dist/common/constants/grant-priorities.d.ts +2 -0
- package/dist/common/constants/grant-priorities.js +10 -0
- package/dist/common/constants/grant-priorities.js.map +1 -0
- package/dist/common/constants/tools.d.ts +1 -1
- package/dist/common/constants/tools.js +1 -1
- package/dist/common/constants/tools.js.map +1 -1
- package/dist/common/constants.d.ts +28 -1
- package/dist/common/constants.js +36 -7
- package/dist/common/constants.js.map +1 -1
- package/dist/common/db/schema.d.ts +323 -86
- package/dist/common/db/schema.js +55 -13
- package/dist/common/db/schema.js.map +1 -1
- package/dist/common/env.mjs +4 -1
- package/dist/common/env.mjs.map +1 -1
- package/dist/common/message-image-handling.d.ts +41 -0
- package/dist/common/message-image-handling.js +57 -0
- package/dist/common/message-image-handling.js.map +1 -0
- package/dist/common/types/agent-state.d.ts +8 -8
- package/dist/common/types/grant.d.ts +2 -0
- package/dist/common/types/grant.js +10 -0
- package/dist/common/types/grant.js.map +1 -0
- package/dist/common/types/usage.d.ts +37 -18
- package/dist/common/types/usage.js +9 -6
- package/dist/common/types/usage.js.map +1 -1
- package/dist/common/util/__tests__/saxy.test.d.ts +1 -0
- package/dist/common/util/__tests__/saxy.test.js +262 -0
- package/dist/common/util/__tests__/saxy.test.js.map +1 -0
- package/dist/common/util/credentials.d.ts +2 -2
- package/dist/common/util/dates.d.ts +10 -1
- package/dist/common/util/dates.js +11 -2
- package/dist/common/util/dates.js.map +1 -1
- package/dist/common/util/logger.js +32 -14
- package/dist/common/util/logger.js.map +1 -1
- package/dist/common/util/process-stream.d.ts +8 -0
- package/dist/common/util/process-stream.js +102 -0
- package/dist/common/util/process-stream.js.map +1 -0
- package/dist/common/util/promise.d.ts +1 -1
- package/dist/common/util/promise.js +2 -2
- package/dist/common/util/promise.js.map +1 -1
- package/dist/common/util/referral-credits.d.ts +1 -0
- package/dist/common/util/referral-credits.js +48 -0
- package/dist/common/util/referral-credits.js.map +1 -0
- package/dist/common/util/saxy.d.ts +8 -0
- package/dist/common/util/saxy.js +35 -12
- package/dist/common/util/saxy.js.map +1 -1
- package/dist/common/util/sync-failure.d.ts +1 -0
- package/dist/common/util/sync-failure.js +57 -0
- package/dist/common/util/sync-failure.js.map +1 -0
- package/dist/common/websockets/websocket-schema.d.ts +530 -480
- package/dist/index.js +1 -1
- package/dist/menu.js +5 -0
- package/dist/menu.js.map +1 -1
- package/dist/tool-handlers.js +1 -1
- package/dist/tool-handlers.js.map +1 -1
- package/dist/utils/__tests__/xml-stream-parser.test.js +6 -10
- package/dist/utils/__tests__/xml-stream-parser.test.js.map +1 -1
- package/dist/utils/tool-renderers.js +1 -1
- package/dist/utils/tool-renderers.js.map +1 -1
- package/package.json +1 -1
- package/dist/common/logger.d.ts +0 -1
- package/dist/common/logger.js +0 -7
- package/dist/common/logger.js.map +0 -1
- package/dist/common/util/constants.d.ts +0 -1
- package/dist/common/util/constants.js +0 -7
- package/dist/common/util/constants.js.map +0 -1
- package/dist/common/util/helpers.d.ts +0 -1
- package/dist/common/util/helpers.js +0 -6
- package/dist/common/util/helpers.js.map +0 -1
- package/dist/common/util/token-counter.d.ts +0 -3
- package/dist/common/util/token-counter.js +0 -27
- package/dist/common/util/token-counter.js.map +0 -1
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.getOrderedActiveGrants = getOrderedActiveGrants;
|
|
30
|
+
exports.calculateUsageAndBalance = calculateUsageAndBalance;
|
|
31
|
+
exports.consumeCredits = consumeCredits;
|
|
32
|
+
exports.calculateUsageThisCycle = calculateUsageThisCycle;
|
|
33
|
+
const db_1 = __importDefault(require("../db"));
|
|
34
|
+
const schema = __importStar(require("../db/schema"));
|
|
35
|
+
const drizzle_orm_1 = require("drizzle-orm");
|
|
36
|
+
const logger_1 = require("../util/logger");
|
|
37
|
+
/**
|
|
38
|
+
* Gets active grants for a user, ordered by expiration (soonest first), then priority, and creation date.
|
|
39
|
+
* Added optional `conn` param so callers inside a transaction can supply their TX object.
|
|
40
|
+
*/
|
|
41
|
+
async function getOrderedActiveGrants(userId, now, conn = db_1.default // use DbConn instead of typeof db
|
|
42
|
+
) {
|
|
43
|
+
return conn
|
|
44
|
+
.select()
|
|
45
|
+
.from(schema.creditLedger)
|
|
46
|
+
.where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema.creditLedger.user_id, userId), (0, drizzle_orm_1.or)((0, drizzle_orm_1.isNull)(schema.creditLedger.expires_at), (0, drizzle_orm_1.gt)(schema.creditLedger.expires_at, now))))
|
|
47
|
+
.orderBy(
|
|
48
|
+
// Use grants based on priority, then expiration date, then creation date
|
|
49
|
+
(0, drizzle_orm_1.asc)(schema.creditLedger.priority), (0, drizzle_orm_1.asc)(schema.creditLedger.expires_at), (0, drizzle_orm_1.asc)(schema.creditLedger.created_at));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Updates a single grant's balance and logs the change.
|
|
53
|
+
*/
|
|
54
|
+
async function updateGrantBalance(userId, grant, consumed, newBalance, tx) {
|
|
55
|
+
await tx
|
|
56
|
+
.update(schema.creditLedger)
|
|
57
|
+
.set({ balance: newBalance })
|
|
58
|
+
.where((0, drizzle_orm_1.eq)(schema.creditLedger.operation_id, grant.operation_id));
|
|
59
|
+
logger_1.logger.debug({
|
|
60
|
+
userId,
|
|
61
|
+
grantId: grant.operation_id,
|
|
62
|
+
grantType: grant.type,
|
|
63
|
+
consumed,
|
|
64
|
+
remaining: newBalance,
|
|
65
|
+
expiresAt: grant.expires_at,
|
|
66
|
+
}, 'Updated grant remaining amount after consumption');
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Consumes credits from a list of ordered grants.
|
|
70
|
+
*/
|
|
71
|
+
async function consumeFromOrderedGrants(userId, creditsToConsume, grants, tx) {
|
|
72
|
+
let remainingToConsume = creditsToConsume;
|
|
73
|
+
let consumed = 0;
|
|
74
|
+
let fromPurchased = 0;
|
|
75
|
+
// First pass: try to repay any debt
|
|
76
|
+
for (const grant of grants) {
|
|
77
|
+
if (grant.balance < 0 && remainingToConsume > 0) {
|
|
78
|
+
const debtAmount = Math.abs(grant.balance);
|
|
79
|
+
const repayAmount = Math.min(debtAmount, remainingToConsume);
|
|
80
|
+
const newBalance = grant.balance + repayAmount;
|
|
81
|
+
remainingToConsume -= repayAmount;
|
|
82
|
+
consumed += repayAmount;
|
|
83
|
+
await updateGrantBalance(userId, grant, -repayAmount, newBalance, tx);
|
|
84
|
+
logger_1.logger.debug({ userId, grantId: grant.operation_id, repayAmount, newBalance }, 'Repaid debt in grant');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Second pass: consume from positive balances
|
|
88
|
+
for (const grant of grants) {
|
|
89
|
+
if (remainingToConsume <= 0)
|
|
90
|
+
break;
|
|
91
|
+
if (grant.balance <= 0)
|
|
92
|
+
continue;
|
|
93
|
+
const consumeFromThisGrant = Math.min(remainingToConsume, grant.balance);
|
|
94
|
+
const newBalance = grant.balance - consumeFromThisGrant;
|
|
95
|
+
remainingToConsume -= consumeFromThisGrant;
|
|
96
|
+
consumed += consumeFromThisGrant;
|
|
97
|
+
// Track consumption from purchased credits
|
|
98
|
+
if (grant.type === 'purchase') {
|
|
99
|
+
fromPurchased += consumeFromThisGrant;
|
|
100
|
+
}
|
|
101
|
+
await updateGrantBalance(userId, grant, consumeFromThisGrant, newBalance, tx);
|
|
102
|
+
}
|
|
103
|
+
// If we still have remaining to consume and no grants left, create debt in the last grant
|
|
104
|
+
if (remainingToConsume > 0 && grants.length > 0) {
|
|
105
|
+
const lastGrant = grants[grants.length - 1];
|
|
106
|
+
if (lastGrant.balance <= 0) {
|
|
107
|
+
const newBalance = lastGrant.balance - remainingToConsume;
|
|
108
|
+
await updateGrantBalance(userId, lastGrant, remainingToConsume, newBalance, tx);
|
|
109
|
+
consumed += remainingToConsume;
|
|
110
|
+
logger_1.logger.warn({
|
|
111
|
+
userId,
|
|
112
|
+
grantId: lastGrant.operation_id,
|
|
113
|
+
requested: remainingToConsume,
|
|
114
|
+
consumed: remainingToConsume,
|
|
115
|
+
newDebt: Math.abs(newBalance),
|
|
116
|
+
}, 'Created new debt in grant');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { consumed, fromPurchased };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Calculates both the current balance and usage in this cycle in a single query.
|
|
123
|
+
* This is more efficient than calculating them separately.
|
|
124
|
+
*/
|
|
125
|
+
async function calculateUsageAndBalance(userId, quotaResetDate, now = new Date()) {
|
|
126
|
+
// Get all relevant grants in one query
|
|
127
|
+
const grants = await getOrderedActiveGrants(userId, now);
|
|
128
|
+
// Initialize balance structure
|
|
129
|
+
const balance = {
|
|
130
|
+
totalRemaining: 0,
|
|
131
|
+
totalDebt: 0,
|
|
132
|
+
netBalance: 0,
|
|
133
|
+
breakdown: {},
|
|
134
|
+
principals: {},
|
|
135
|
+
};
|
|
136
|
+
// Calculate both metrics in one pass
|
|
137
|
+
let usageThisCycle = 0;
|
|
138
|
+
for (const grant of grants) {
|
|
139
|
+
const grantType = grant.type;
|
|
140
|
+
// Calculate usage if grant was active in this cycle
|
|
141
|
+
if (grant.created_at > quotaResetDate ||
|
|
142
|
+
!grant.expires_at ||
|
|
143
|
+
grant.expires_at > quotaResetDate) {
|
|
144
|
+
usageThisCycle += grant.principal - grant.balance;
|
|
145
|
+
}
|
|
146
|
+
// Add to balance if grant is currently active
|
|
147
|
+
if (!grant.expires_at || grant.expires_at > now) {
|
|
148
|
+
if (grant.balance > 0) {
|
|
149
|
+
balance.totalRemaining += grant.balance;
|
|
150
|
+
balance.breakdown[grantType] =
|
|
151
|
+
(balance.breakdown[grantType] || 0) + grant.balance;
|
|
152
|
+
balance.principals[grantType] =
|
|
153
|
+
(balance.principals[grantType] || 0) + grant.principal;
|
|
154
|
+
}
|
|
155
|
+
else if (grant.balance < 0) {
|
|
156
|
+
balance.totalDebt += Math.abs(grant.balance);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Calculate net balance
|
|
161
|
+
balance.netBalance = balance.totalRemaining - balance.totalDebt;
|
|
162
|
+
logger_1.logger.debug({ userId, balance, usageThisCycle, grantsCount: grants.length }, 'Calculated usage and balance');
|
|
163
|
+
return { usageThisCycle, balance };
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Updates the remaining amounts in credit grants after consumption.
|
|
167
|
+
* Follows priority order strictly - higher priority grants (lower number) are consumed first.
|
|
168
|
+
* Returns details about credit consumption including how many came from purchased credits.
|
|
169
|
+
*
|
|
170
|
+
* @param userId The ID of the user
|
|
171
|
+
* @param creditsToConsume Number of credits being consumed
|
|
172
|
+
* @returns Promise resolving to number of credits consumed
|
|
173
|
+
* @throws Error if user has any debt
|
|
174
|
+
*/
|
|
175
|
+
async function consumeCredits(userId, creditsToConsume) {
|
|
176
|
+
return await db_1.default.transaction(async (tx) => {
|
|
177
|
+
const now = new Date();
|
|
178
|
+
const activeGrants = await getOrderedActiveGrants(userId, now, tx);
|
|
179
|
+
if (activeGrants.length === 0) {
|
|
180
|
+
logger_1.logger.error({ userId, creditsToConsume }, 'No active grants found to consume credits from');
|
|
181
|
+
throw new Error('No active grants found');
|
|
182
|
+
}
|
|
183
|
+
const hasDebt = activeGrants.some((grant) => grant.balance < 0);
|
|
184
|
+
if (hasDebt) {
|
|
185
|
+
logger_1.logger.error({ userId, creditsToConsume }, 'Cannot consume credits - user has existing debt');
|
|
186
|
+
throw new Error('Cannot use credits while you have unpaid debt. Please add credits to clear your debt first.');
|
|
187
|
+
}
|
|
188
|
+
const result = await consumeFromOrderedGrants(userId, creditsToConsume, activeGrants, tx);
|
|
189
|
+
return result;
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Calculate the total credits used during the current billing cycle for a user
|
|
194
|
+
* by summing the difference between initial and remaining amounts for all relevant grants.
|
|
195
|
+
*/
|
|
196
|
+
async function calculateUsageThisCycle(userId, quotaResetDate) {
|
|
197
|
+
const usageResult = await db_1.default
|
|
198
|
+
.select({
|
|
199
|
+
totalUsed: (0, drizzle_orm_1.sql) `COALESCE(SUM(${schema.creditLedger.principal} - ${schema.creditLedger.balance}), 0)`,
|
|
200
|
+
})
|
|
201
|
+
.from(schema.creditLedger)
|
|
202
|
+
.where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema.creditLedger.user_id, userId),
|
|
203
|
+
// Grant was created during this cycle OR expires after this cycle starts (including never expires)
|
|
204
|
+
(0, drizzle_orm_1.or)((0, drizzle_orm_1.gt)(schema.creditLedger.created_at, quotaResetDate), (0, drizzle_orm_1.and)((0, drizzle_orm_1.or)((0, drizzle_orm_1.isNull)(schema.creditLedger.expires_at), (0, drizzle_orm_1.gt)(schema.creditLedger.expires_at, quotaResetDate))))));
|
|
205
|
+
return usageResult[0].totalUsed;
|
|
206
|
+
}
|
|
207
|
+
//# sourceMappingURL=balance-calculator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"balance-calculator.js","sourceRoot":"","sources":["../../src/billing/balance-calculator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,wDAuBC;AAwHD,4DAsDC;AAYD,wCAoCC;AAMD,0DA0BC;AAxTD,+CAAsB;AACtB,qDAAsC;AACtC,6CAA+D;AAE/D,2CAAuC;AA2BvC;;;GAGG;AACI,KAAK,UAAU,sBAA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ACN,SAAS,EAAE,IAAA,iBAAG,EAAQ,gBAAgB,MAAM,CAAC,YAAY,CAAC,SAAS,MAAM,MAAM,CAAC,YAAY,CAAC,OAAO,OAAO;KAC5G,CAAC;SACD,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC;SACzB,KAAK,CACJ,IAAA,iBAAG,EACD,IAAA,gBAAE,EAAC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC;IACvC,mGAAmG;IACnG,IAAA,gBAAE,EACA,IAAA,gBAAE,EAAC,MAAM,CAAC,YAAY,CAAC,UAAU,EAAE,cAAc,CAAC,EAClD,IAAA,iBAAG,EACD,IAAA,gBAAE,EACA,IAAA,oBAAM,EAAC,MAAM,CAAC,YAAY,CAAC,UAAU,CAAC,EACtC,IAAA,gBAAE,EAAC,MAAM,CAAC,YAAY,CAAC,UAAU,EAAE,cAAc,CAAC,CACnD,CACF,CACF,CACF,CACF,CAAA;IAEH,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AACjC,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type Stripe from 'stripe';
|
|
2
|
+
export interface AutoTopupCheckResult {
|
|
3
|
+
blockedReason: string | null;
|
|
4
|
+
validPaymentMethod: Stripe.PaymentMethod | null;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Checks if auto top-up is allowed for a user by verifying their payment methods.
|
|
8
|
+
* @param userId The ID of the user for logging context
|
|
9
|
+
* @param stripeCustomerId The user's Stripe customer ID
|
|
10
|
+
* @returns Promise<AutoTopupCheckResult>
|
|
11
|
+
*/
|
|
12
|
+
export declare function checkAutoTopupAllowed(userId: string, stripeCustomerId: string | null): Promise<AutoTopupCheckResult>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkAutoTopupAllowed = checkAutoTopupAllowed;
|
|
4
|
+
const stripe_1 = require("../util/stripe");
|
|
5
|
+
const logger_1 = require("../util/logger");
|
|
6
|
+
const env_mjs_1 = require("src/env.mjs");
|
|
7
|
+
/**
|
|
8
|
+
* Checks if auto top-up is allowed for a user by verifying their payment methods.
|
|
9
|
+
* @param userId The ID of the user for logging context
|
|
10
|
+
* @param stripeCustomerId The user's Stripe customer ID
|
|
11
|
+
* @returns Promise<AutoTopupCheckResult>
|
|
12
|
+
*/
|
|
13
|
+
async function checkAutoTopupAllowed(userId, stripeCustomerId) {
|
|
14
|
+
const logContext = { userId };
|
|
15
|
+
if (!stripeCustomerId) {
|
|
16
|
+
return {
|
|
17
|
+
blockedReason: `You don\'t have a valid account with us. Please log in at ${env_mjs_1.env.NEXT_PUBLIC_APP_URL}/login`,
|
|
18
|
+
validPaymentMethod: null,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const paymentMethods = await stripe_1.stripeServer.paymentMethods.list({
|
|
23
|
+
customer: stripeCustomerId,
|
|
24
|
+
type: 'card',
|
|
25
|
+
});
|
|
26
|
+
// Find a valid, non-expired card
|
|
27
|
+
const validPaymentMethod = paymentMethods.data.find((pm) => pm.card?.exp_year &&
|
|
28
|
+
pm.card.exp_month &&
|
|
29
|
+
new Date(pm.card.exp_year, pm.card.exp_month - 1) > new Date());
|
|
30
|
+
if (!validPaymentMethod) {
|
|
31
|
+
logger_1.logger.warn({ ...logContext }, 'No valid payment methods found for auto top-up');
|
|
32
|
+
return {
|
|
33
|
+
blockedReason: 'You need a valid payment method to enable auto top-up. You can add one by manually purchasing credits.',
|
|
34
|
+
validPaymentMethod: null,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
blockedReason: null,
|
|
39
|
+
validPaymentMethod,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
logger_1.logger.error({ ...logContext, error }, 'Failed to fetch payment methods');
|
|
44
|
+
return {
|
|
45
|
+
blockedReason: 'Unable to verify payment method status.',
|
|
46
|
+
validPaymentMethod: null,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=check-auto-topup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"check-auto-topup.js","sourceRoot":"","sources":["../../src/billing/check-auto-topup.ts"],"names":[],"mappings":";;AAgBA,sDAkDC;AAlED,2CAA6C;AAC7C,2CAAuC;AAEvC,yCAAiC;AAOjC;;;;;GAKG;AACI,KAAK,UAAU,qBAAqB,CACzC,MAAc,EACd,gBAA+B;IAE/B,MAAM,UAAU,GAAG,EAAE,MAAM,EAAE,CAAA;IAE7B,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,OAAO;YACL,aAAa,EAAE,6DAA6D,aAAG,CAAC,mBAAmB,QAAQ;YAC3G,kBAAkB,EAAE,IAAI;SACzB,CAAA;IACH,CAAC;IAED,IAAI,CAAC;QACH,MAAM,cAAc,GAAG,MAAM,qBAAY,CAAC,cAAc,CAAC,IAAI,CAAC;YAC5D,QAAQ,EAAE,gBAAgB;YAC1B,IAAI,EAAE,MAAM;SACb,CAAC,CAAA;QAEF,iCAAiC;QACjC,MAAM,kBAAkB,GAAG,cAAc,CAAC,IAAI,CAAC,IAAI,CACjD,CAAC,EAAE,EAAE,EAAE,CACL,EAAE,CAAC,IAAI,EAAE,QAAQ;YACjB,EAAE,CAAC,IAAI,CAAC,SAAS;YACjB,IAAI,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,IAAI,IAAI,EAAE,CACjE,CAAA;QAED,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACxB,eAAM,CAAC,IAAI,CACT,EAAE,GAAG,UAAU,EAAE,EACjB,gDAAgD,CACjD,CAAA;YACD,OAAO;gBACL,aAAa,EACX,wGAAwG;gBAC1G,kBAAkB,EAAE,IAAI;aACzB,CAAA;QACH,CAAC;QAED,OAAO;YACL,aAAa,EAAE,IAAI;YACnB,kBAAkB;SACnB,CAAA;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,eAAM,CAAC,KAAK,CAAC,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,iCAAiC,CAAC,CAAA;QACzE,OAAO;YACL,aAAa,EAAE,yCAAyC;YACxD,kBAAkB,EAAE,IAAI;SACzB,CAAA;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Determines the cost of one internal credit in USD cents for a given user.
|
|
3
|
+
* TODO: Enhance this function to fetch user's plan and apply plan-specific rates.
|
|
4
|
+
*
|
|
5
|
+
* @param userId - The ID of the user (currently unused, for future enhancement).
|
|
6
|
+
* @returns The cost of one internal credit in cents.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getUserCostPerCredit(userId: string | undefined): Promise<number>;
|
|
9
|
+
export { convertCreditsToUsdCents, convertStripeGrantAmountToCredits } from './credit-conversion';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.convertStripeGrantAmountToCredits = exports.convertCreditsToUsdCents = void 0;
|
|
4
|
+
exports.getUserCostPerCredit = getUserCostPerCredit;
|
|
5
|
+
/**
|
|
6
|
+
* Determines the cost of one internal credit in USD cents for a given user.
|
|
7
|
+
* TODO: Enhance this function to fetch user's plan and apply plan-specific rates.
|
|
8
|
+
*
|
|
9
|
+
* @param userId - The ID of the user (currently unused, for future enhancement).
|
|
10
|
+
* @returns The cost of one internal credit in cents.
|
|
11
|
+
*/
|
|
12
|
+
async function getUserCostPerCredit(userId) {
|
|
13
|
+
// Placeholder: Currently 1 cent per credit for all users. Can adjust in the future based on user
|
|
14
|
+
return 1;
|
|
15
|
+
}
|
|
16
|
+
// Re-export the pure conversion functions
|
|
17
|
+
var credit_conversion_1 = require("./credit-conversion");
|
|
18
|
+
Object.defineProperty(exports, "convertCreditsToUsdCents", { enumerable: true, get: function () { return credit_conversion_1.convertCreditsToUsdCents; } });
|
|
19
|
+
Object.defineProperty(exports, "convertStripeGrantAmountToCredits", { enumerable: true, get: function () { return credit_conversion_1.convertStripeGrantAmountToCredits; } });
|
|
20
|
+
//# sourceMappingURL=conversion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversion.js","sourceRoot":"","sources":["../../src/billing/conversion.ts"],"names":[],"mappings":";;;AAUA,oDAKC;AAZD;;;;;;GAMG;AACI,KAAK,UAAU,oBAAoB,CACxC,MAA0B;IAE1B,iGAAiG;IACjG,OAAO,CAAC,CAAA;AACV,CAAC;AAED,0CAA0C;AAC1C,yDAAiG;AAAxF,6HAAA,wBAAwB,OAAA;AAAE,sIAAA,iCAAiC,OAAA"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { CreditBalance } from './balance-calculator';
|
|
2
|
+
/**
|
|
3
|
+
* Gets the current detailed credit balance for a user.
|
|
4
|
+
* Returns a zero balance for anonymous users.
|
|
5
|
+
* @param userId The ID of the user, or undefined for anonymous.
|
|
6
|
+
* @returns A Promise resolving to the user's CreditBalance.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getCurrentBalanceDetails(userId: string | undefined): Promise<CreditBalance>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getCurrentBalanceDetails = getCurrentBalanceDetails;
|
|
4
|
+
const balance_calculator_1 = require("./balance-calculator");
|
|
5
|
+
const logger_1 = require("../util/logger");
|
|
6
|
+
/**
|
|
7
|
+
* Gets the current detailed credit balance for a user.
|
|
8
|
+
* Returns a zero balance for anonymous users.
|
|
9
|
+
* @param userId The ID of the user, or undefined for anonymous.
|
|
10
|
+
* @returns A Promise resolving to the user's CreditBalance.
|
|
11
|
+
*/
|
|
12
|
+
async function getCurrentBalanceDetails(userId) {
|
|
13
|
+
if (!userId) {
|
|
14
|
+
// Return zero/default balance for anonymous users
|
|
15
|
+
return {
|
|
16
|
+
totalRemaining: 0,
|
|
17
|
+
breakdown: {
|
|
18
|
+
free: 0,
|
|
19
|
+
referral: 0,
|
|
20
|
+
purchase: 0,
|
|
21
|
+
admin: 0,
|
|
22
|
+
rollover: 0,
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
// Use the new balance calculation logic
|
|
28
|
+
return await (0, balance_calculator_1.calculateCurrentBalance)(userId);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
logger_1.logger.error({ userId, error }, 'Error fetching balance details');
|
|
32
|
+
// Return a zero balance on error
|
|
33
|
+
return {
|
|
34
|
+
totalRemaining: 0,
|
|
35
|
+
breakdown: {
|
|
36
|
+
free: 0,
|
|
37
|
+
referral: 0,
|
|
38
|
+
purchase: 0,
|
|
39
|
+
admin: 0,
|
|
40
|
+
rollover: 0,
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=credit-check.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credit-check.js","sourceRoot":"","sources":["../../src/billing/credit-check.ts"],"names":[],"mappings":";;AASA,4DAkCC;AA3CD,6DAA6E;AAC7E,2CAAuC;AAEvC;;;;;GAKG;AACI,KAAK,UAAU,wBAAwB,CAC5C,MAA0B;IAE1B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,kDAAkD;QAClD,OAAO;YACL,cAAc,EAAE,CAAC;YACjB,SAAS,EAAE;gBACT,IAAI,EAAE,CAAC;gBACP,QAAQ,EAAE,CAAC;gBACX,QAAQ,EAAE,CAAC;gBACX,KAAK,EAAE,CAAC;gBACR,QAAQ,EAAE,CAAC;aACZ;SACF,CAAA;IACH,CAAC;IAED,IAAI,CAAC;QACH,wCAAwC;QACxC,OAAO,MAAM,IAAA,4CAAuB,EAAC,MAAM,CAAC,CAAA;IAC9C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,eAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,gCAAgC,CAAC,CAAA;QACjE,iCAAiC;QACjC,OAAO;YACL,cAAc,EAAE,CAAC;YACjB,SAAS,EAAE;gBACT,IAAI,EAAE,CAAC;gBACP,QAAQ,EAAE,CAAC;gBACX,QAAQ,EAAE,CAAC;gBACX,KAAK,EAAE,CAAC;gBACR,QAAQ,EAAE,CAAC;aACZ;SACF,CAAA;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gets the cost per credit for a user. Currently hardcoded to 1 cent per credit,
|
|
3
|
+
* but could be customized per user in the future.
|
|
4
|
+
*/
|
|
5
|
+
export declare function getUserCostPerCredit(userId: string | undefined): Promise<number>;
|
|
6
|
+
/**
|
|
7
|
+
* Converts an internal credit system value to the equivalent monetary amount in USD cents,
|
|
8
|
+
* based on the user's cost per credit.
|
|
9
|
+
* Uses Math.ceil to ensure enough monetary value is calculated if rounding occurs.
|
|
10
|
+
*
|
|
11
|
+
* @param credits - The amount in internal credits.
|
|
12
|
+
* @param centsPerCredit - The user's effective cost per internal credit (in cents).
|
|
13
|
+
* @returns The equivalent amount in USD cents.
|
|
14
|
+
*/
|
|
15
|
+
export declare function convertCreditsToUsdCents(credits: number, centsPerCredit: number): number;
|
|
16
|
+
/**
|
|
17
|
+
* Converts a Stripe grant amount (in the smallest currency unit, e.g., cents for USD)
|
|
18
|
+
* to the application's internal credit system units, based on the user's cost per credit.
|
|
19
|
+
*
|
|
20
|
+
* @param amountInSmallestUnit - The grant amount from Stripe, typically in cents.
|
|
21
|
+
* @param centsPerCredit - The user's effective cost per internal credit (in cents).
|
|
22
|
+
* @returns The equivalent amount in application credits. Uses Math.round for conversion.
|
|
23
|
+
*/
|
|
24
|
+
export declare function convertStripeGrantAmountToCredits(amountInSmallestUnit: number, centsPerCredit: number): number;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUserCostPerCredit = getUserCostPerCredit;
|
|
4
|
+
exports.convertCreditsToUsdCents = convertCreditsToUsdCents;
|
|
5
|
+
exports.convertStripeGrantAmountToCredits = convertStripeGrantAmountToCredits;
|
|
6
|
+
/**
|
|
7
|
+
* Gets the cost per credit for a user. Currently hardcoded to 1 cent per credit,
|
|
8
|
+
* but could be customized per user in the future.
|
|
9
|
+
*/
|
|
10
|
+
async function getUserCostPerCredit(userId) {
|
|
11
|
+
return 1; // 1 cent per credit
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Converts an internal credit system value to the equivalent monetary amount in USD cents,
|
|
15
|
+
* based on the user's cost per credit.
|
|
16
|
+
* Uses Math.ceil to ensure enough monetary value is calculated if rounding occurs.
|
|
17
|
+
*
|
|
18
|
+
* @param credits - The amount in internal credits.
|
|
19
|
+
* @param centsPerCredit - The user's effective cost per internal credit (in cents).
|
|
20
|
+
* @returns The equivalent amount in USD cents.
|
|
21
|
+
*/
|
|
22
|
+
function convertCreditsToUsdCents(credits, centsPerCredit) {
|
|
23
|
+
if (credits <= 0 || centsPerCredit <= 0) {
|
|
24
|
+
return 0;
|
|
25
|
+
}
|
|
26
|
+
// Total Cents = Credits * Cents per Credit
|
|
27
|
+
const cents = credits * centsPerCredit;
|
|
28
|
+
// Use Math.ceil for safety, ensuring we calculate enough monetary value.
|
|
29
|
+
return Math.ceil(cents);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Converts a Stripe grant amount (in the smallest currency unit, e.g., cents for USD)
|
|
33
|
+
* to the application's internal credit system units, based on the user's cost per credit.
|
|
34
|
+
*
|
|
35
|
+
* @param amountInSmallestUnit - The grant amount from Stripe, typically in cents.
|
|
36
|
+
* @param centsPerCredit - The user's effective cost per internal credit (in cents).
|
|
37
|
+
* @returns The equivalent amount in application credits. Uses Math.round for conversion.
|
|
38
|
+
*/
|
|
39
|
+
function convertStripeGrantAmountToCredits(amountInSmallestUnit, centsPerCredit) {
|
|
40
|
+
if (centsPerCredit <= 0) {
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
// Credits = Total Cents / Cents per Credit
|
|
44
|
+
const credits = amountInSmallestUnit / centsPerCredit;
|
|
45
|
+
// Use Math.round for robustness
|
|
46
|
+
return Math.round(credits);
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=credit-conversion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credit-conversion.js","sourceRoot":"","sources":["../../src/billing/credit-conversion.ts"],"names":[],"mappings":";;AAIA,oDAEC;AAWD,4DAWC;AAUD,8EAWC;AAjDD;;;GAGG;AACI,KAAK,UAAU,oBAAoB,CAAC,MAA0B;IACnE,OAAO,CAAC,CAAA,CAAC,oBAAoB;AAC/B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,wBAAwB,CACtC,OAAe,EACf,cAAsB;IAEtB,IAAI,OAAO,IAAI,CAAC,IAAI,cAAc,IAAI,CAAC,EAAE,CAAC;QACxC,OAAO,CAAC,CAAA;IACV,CAAC;IACD,2CAA2C;IAC3C,MAAM,KAAK,GAAG,OAAO,GAAG,cAAc,CAAA;IACtC,yEAAyE;IACzE,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,iCAAiC,CAC/C,oBAA4B,EAC5B,cAAsB;IAEtB,IAAI,cAAc,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,CAAA;IACV,CAAC;IACD,2CAA2C;IAC3C,MAAM,OAAO,GAAG,oBAAoB,GAAG,cAAc,CAAA;IACrD,gCAAgC;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;AAC5B,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { GrantType } from '../db/schema';
|
|
2
|
+
/**
|
|
3
|
+
* Finds the amount of the most recent expired 'free' grant for a user.
|
|
4
|
+
* If no expired 'free' grant is found, returns the default free limit.
|
|
5
|
+
* @param userId The ID of the user.
|
|
6
|
+
* @returns The amount of the last expired free grant or the default.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getPreviousFreeGrantAmount(userId: string): Promise<number>;
|
|
9
|
+
/**
|
|
10
|
+
* Calculates the total referral bonus credits a user should receive based on
|
|
11
|
+
* their referral history (both as referrer and referred).
|
|
12
|
+
* @param userId The ID of the user.
|
|
13
|
+
* @returns The total referral bonus credits earned.
|
|
14
|
+
*/
|
|
15
|
+
export declare function calculateTotalReferralBonus(userId: string): Promise<number>;
|
|
16
|
+
/**
|
|
17
|
+
* Processes a credit grant request with retries and failure logging.
|
|
18
|
+
*/
|
|
19
|
+
export declare function processAndGrantCredit(userId: string, amount: number, type: GrantType, description: string, expiresAt: Date | null, operationId: string): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Revokes credits from a specific grant by operation ID.
|
|
22
|
+
* This sets the balance to 0 and updates the description to indicate a refund.
|
|
23
|
+
*
|
|
24
|
+
* @param operationId The operation ID of the grant to revoke
|
|
25
|
+
* @param reason The reason for revoking the credits (e.g. refund)
|
|
26
|
+
* @returns true if the grant was found and revoked, false otherwise
|
|
27
|
+
*/
|
|
28
|
+
export declare function revokeGrantByOperationId(operationId: string, reason: string): Promise<boolean>;
|