@nordsym/apiclaw 1.7.2 → 1.7.4
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/convex/_generated/api.d.ts +115 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +143 -0
- package/convex/_generated/server.js +93 -0
- package/convex/adminActivate.d.ts +3 -0
- package/convex/adminActivate.d.ts.map +1 -0
- package/convex/adminActivate.js +47 -0
- package/convex/adminActivate.js.map +1 -0
- package/convex/adminActivate.ts +54 -0
- package/convex/adminStats.d.ts +3 -0
- package/convex/adminStats.d.ts.map +1 -0
- package/convex/adminStats.js +42 -0
- package/convex/adminStats.js.map +1 -0
- package/convex/adminStats.ts +44 -0
- package/convex/agents.d.ts +76 -0
- package/convex/agents.d.ts.map +1 -0
- package/convex/agents.js +699 -0
- package/convex/agents.js.map +1 -0
- package/convex/agents.ts +814 -0
- package/convex/analytics.d.ts +5 -0
- package/convex/analytics.d.ts.map +1 -0
- package/convex/analytics.js +166 -0
- package/convex/analytics.js.map +1 -0
- package/convex/analytics.ts +186 -0
- package/convex/billing.d.ts +88 -0
- package/convex/billing.d.ts.map +1 -0
- package/convex/billing.js +655 -0
- package/convex/billing.js.map +1 -0
- package/convex/billing.ts +791 -0
- package/convex/capabilities.d.ts +9 -0
- package/convex/capabilities.d.ts.map +1 -0
- package/convex/capabilities.js +145 -0
- package/convex/capabilities.js.map +1 -0
- package/convex/capabilities.ts +157 -0
- package/convex/chains.d.ts +68 -0
- package/convex/chains.d.ts.map +1 -0
- package/convex/chains.js +1105 -0
- package/convex/chains.js.map +1 -0
- package/convex/chains.ts +1318 -0
- package/convex/credits.d.ts +25 -0
- package/convex/credits.d.ts.map +1 -0
- package/convex/credits.js +186 -0
- package/convex/credits.js.map +1 -0
- package/convex/credits.ts +211 -0
- package/convex/crons.d.ts +3 -0
- package/convex/crons.d.ts.map +1 -0
- package/convex/crons.js +17 -0
- package/convex/crons.js.map +1 -0
- package/convex/crons.ts +28 -0
- package/convex/directCall.d.ts +72 -0
- package/convex/directCall.d.ts.map +1 -0
- package/convex/directCall.js +627 -0
- package/convex/directCall.js.map +1 -0
- package/convex/directCall.ts +678 -0
- package/convex/earnProgress.d.ts +58 -0
- package/convex/earnProgress.d.ts.map +1 -0
- package/convex/earnProgress.js +649 -0
- package/convex/earnProgress.js.map +1 -0
- package/convex/earnProgress.ts +753 -0
- package/convex/email.d.ts +14 -0
- package/convex/email.d.ts.map +1 -0
- package/convex/email.js +300 -0
- package/convex/email.js.map +1 -0
- package/convex/email.ts +329 -0
- package/convex/feedback.d.ts +7 -0
- package/convex/feedback.d.ts.map +1 -0
- package/convex/feedback.js +227 -0
- package/convex/feedback.js.map +1 -0
- package/convex/feedback.ts +265 -0
- package/convex/http.d.ts +3 -0
- package/convex/http.d.ts.map +1 -0
- package/convex/http.js +1405 -0
- package/convex/http.js.map +1 -0
- package/convex/http.ts +1577 -0
- package/convex/inbound.d.ts +2 -0
- package/convex/inbound.d.ts.map +1 -0
- package/convex/inbound.js +32 -0
- package/convex/inbound.js.map +1 -0
- package/convex/inbound.ts +32 -0
- package/convex/logs.d.ts +38 -0
- package/convex/logs.d.ts.map +1 -0
- package/convex/logs.js +487 -0
- package/convex/logs.js.map +1 -0
- package/convex/logs.ts +550 -0
- package/convex/mou.d.ts +6 -0
- package/convex/mou.d.ts.map +1 -0
- package/convex/mou.js +82 -0
- package/convex/mou.js.map +1 -0
- package/convex/mou.ts +91 -0
- package/convex/providerKeys.d.ts +31 -0
- package/convex/providerKeys.d.ts.map +1 -0
- package/convex/providerKeys.js +257 -0
- package/convex/providerKeys.js.map +1 -0
- package/convex/providerKeys.ts +289 -0
- package/convex/providers.d.ts +32 -0
- package/convex/providers.d.ts.map +1 -0
- package/convex/providers.js +814 -0
- package/convex/providers.js.map +1 -0
- package/convex/providers.ts +909 -0
- package/convex/purchases.d.ts +7 -0
- package/convex/purchases.d.ts.map +1 -0
- package/convex/purchases.js +157 -0
- package/convex/purchases.js.map +1 -0
- package/convex/purchases.ts +183 -0
- package/convex/ratelimit.d.ts +4 -0
- package/convex/ratelimit.d.ts.map +1 -0
- package/convex/ratelimit.js +91 -0
- package/convex/ratelimit.js.map +1 -0
- package/convex/ratelimit.ts +104 -0
- package/convex/schema.ts +802 -0
- package/convex/searchLogs.d.ts +4 -0
- package/convex/searchLogs.d.ts.map +1 -0
- package/convex/searchLogs.js +129 -0
- package/convex/searchLogs.js.map +1 -0
- package/convex/searchLogs.ts +146 -0
- package/convex/seedAPILayerAPIs.d.ts +7 -0
- package/convex/seedAPILayerAPIs.d.ts.map +1 -0
- package/convex/seedAPILayerAPIs.js +177 -0
- package/convex/seedAPILayerAPIs.js.map +1 -0
- package/convex/seedAPILayerAPIs.ts +191 -0
- package/convex/seedDirectCallConfigs.d.ts +2 -0
- package/convex/seedDirectCallConfigs.d.ts.map +1 -0
- package/convex/seedDirectCallConfigs.js +324 -0
- package/convex/seedDirectCallConfigs.js.map +1 -0
- package/convex/seedDirectCallConfigs.ts +336 -0
- package/convex/seedPratham.d.ts +6 -0
- package/convex/seedPratham.d.ts.map +1 -0
- package/convex/seedPratham.js +150 -0
- package/convex/seedPratham.js.map +1 -0
- package/convex/seedPratham.ts +161 -0
- package/convex/spendAlerts.d.ts +36 -0
- package/convex/spendAlerts.d.ts.map +1 -0
- package/convex/spendAlerts.js +380 -0
- package/convex/spendAlerts.js.map +1 -0
- package/convex/spendAlerts.ts +442 -0
- package/convex/stripeActions.d.ts +19 -0
- package/convex/stripeActions.d.ts.map +1 -0
- package/convex/stripeActions.js +411 -0
- package/convex/stripeActions.js.map +1 -0
- package/convex/stripeActions.ts +512 -0
- package/convex/teams.d.ts +21 -0
- package/convex/teams.d.ts.map +1 -0
- package/convex/teams.js +215 -0
- package/convex/teams.js.map +1 -0
- package/convex/teams.ts +243 -0
- package/convex/telemetry.d.ts +4 -0
- package/convex/telemetry.d.ts.map +1 -0
- package/convex/telemetry.js +74 -0
- package/convex/telemetry.js.map +1 -0
- package/convex/telemetry.ts +81 -0
- package/convex/tsconfig.json +25 -0
- package/convex/updateAPIStatus.d.ts +6 -0
- package/convex/updateAPIStatus.d.ts.map +1 -0
- package/convex/updateAPIStatus.js +40 -0
- package/convex/updateAPIStatus.js.map +1 -0
- package/convex/updateAPIStatus.ts +45 -0
- package/convex/usage.d.ts +27 -0
- package/convex/usage.d.ts.map +1 -0
- package/convex/usage.js +229 -0
- package/convex/usage.js.map +1 -0
- package/convex/usage.ts +260 -0
- package/convex/waitlist.d.ts +4 -0
- package/convex/waitlist.d.ts.map +1 -0
- package/convex/waitlist.js +49 -0
- package/convex/waitlist.js.map +1 -0
- package/convex/waitlist.ts +55 -0
- package/convex/webhooks.d.ts +12 -0
- package/convex/webhooks.d.ts.map +1 -0
- package/convex/webhooks.js +410 -0
- package/convex/webhooks.js.map +1 -0
- package/convex/webhooks.ts +494 -0
- package/convex/workspaces.d.ts +31 -0
- package/convex/workspaces.d.ts.map +1 -0
- package/convex/workspaces.js +975 -0
- package/convex/workspaces.js.map +1 -0
- package/convex/workspaces.ts +1130 -0
- package/dist/bin.js +0 -0
- package/dist/capability-router.js +1 -1
- package/dist/capability-router.js.map +1 -1
- package/dist/execute.d.ts +2 -0
- package/dist/execute.d.ts.map +1 -1
- package/dist/execute.js +18 -4
- package/dist/execute.js.map +1 -1
- package/dist/http-api.js +1 -1
- package/dist/http-api.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp-analytics.d.ts +32 -0
- package/dist/mcp-analytics.d.ts.map +1 -0
- package/dist/mcp-analytics.js +130 -0
- package/dist/mcp-analytics.js.map +1 -0
- package/package.json +1 -1
- package/dist/chain-types.d.ts +0 -187
- package/dist/chain-types.d.ts.map +0 -1
- package/dist/chain-types.js +0 -33
- package/dist/chain-types.js.map +0 -1
- package/dist/registry/apis.json.bak +0 -248811
- package/dist/src/bin.js +0 -17
- package/dist/src/capability-router.js +0 -240
- package/dist/src/chainExecutor.js +0 -451
- package/dist/src/chainResolver.js +0 -518
- package/dist/src/cli/commands/doctor.js +0 -324
- package/dist/src/cli/commands/mcp-install.js +0 -255
- package/dist/src/cli/commands/restore.js +0 -259
- package/dist/src/cli/commands/setup.js +0 -205
- package/dist/src/cli/commands/uninstall.js +0 -188
- package/dist/src/cli/index.js +0 -111
- package/dist/src/cli.js +0 -302
- package/dist/src/confirmation.js +0 -240
- package/dist/src/credentials.js +0 -357
- package/dist/src/credits.js +0 -260
- package/dist/src/crypto.js +0 -66
- package/dist/src/discovery.js +0 -504
- package/dist/src/enterprise/env.js +0 -123
- package/dist/src/enterprise/script-generator.js +0 -460
- package/dist/src/execute-dynamic.js +0 -473
- package/dist/src/execute.js +0 -1727
- package/dist/src/index.js +0 -2062
- package/dist/src/metered.js +0 -80
- package/dist/src/open-apis.js +0 -276
- package/dist/src/proxy.js +0 -28
- package/dist/src/session.js +0 -86
- package/dist/src/stripe.js +0 -407
- package/dist/src/telemetry.js +0 -49
- package/dist/src/types.js +0 -2
- package/dist/src/utils/backup.js +0 -181
- package/dist/src/utils/config.js +0 -220
- package/dist/src/utils/os.js +0 -105
- package/dist/src/utils/paths.js +0 -159
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { mutation, query, internalMutation, internalAction, internalQuery } from "./_generated/server";
|
|
3
|
+
import { internal } from "./_generated/api";
|
|
4
|
+
import Stripe from "stripe";
|
|
5
|
+
// Initialize Stripe
|
|
6
|
+
function getStripe() {
|
|
7
|
+
const key = process.env.STRIPE_SECRET_KEY;
|
|
8
|
+
if (!key) {
|
|
9
|
+
throw new Error("STRIPE_SECRET_KEY not configured");
|
|
10
|
+
}
|
|
11
|
+
return new Stripe(key);
|
|
12
|
+
}
|
|
13
|
+
// ============================================
|
|
14
|
+
// MUTATIONS
|
|
15
|
+
// ============================================
|
|
16
|
+
/**
|
|
17
|
+
* Link a Stripe customer to a workspace
|
|
18
|
+
*/
|
|
19
|
+
export const linkCustomer = mutation({
|
|
20
|
+
args: {
|
|
21
|
+
workspaceId: v.id("workspaces"),
|
|
22
|
+
stripeCustomerId: v.string(),
|
|
23
|
+
},
|
|
24
|
+
handler: async (ctx, args) => {
|
|
25
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
26
|
+
if (!workspace) {
|
|
27
|
+
throw new Error("Workspace not found");
|
|
28
|
+
}
|
|
29
|
+
await ctx.db.patch(args.workspaceId, {
|
|
30
|
+
stripeCustomerId: args.stripeCustomerId,
|
|
31
|
+
updatedAt: Date.now(),
|
|
32
|
+
});
|
|
33
|
+
return { success: true };
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* Update subscription status for a workspace
|
|
38
|
+
*/
|
|
39
|
+
export const updateSubscription = mutation({
|
|
40
|
+
args: {
|
|
41
|
+
workspaceId: v.id("workspaces"),
|
|
42
|
+
stripeSubscriptionId: v.optional(v.string()),
|
|
43
|
+
billingPlan: v.string(),
|
|
44
|
+
},
|
|
45
|
+
handler: async (ctx, args) => {
|
|
46
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
47
|
+
if (!workspace) {
|
|
48
|
+
throw new Error("Workspace not found");
|
|
49
|
+
}
|
|
50
|
+
// Update tier and usage limit based on plan
|
|
51
|
+
const planLimits = {
|
|
52
|
+
free: 50,
|
|
53
|
+
usage_based: 999999999, // Effectively unlimited
|
|
54
|
+
starter: 1000,
|
|
55
|
+
pro: 10000,
|
|
56
|
+
scale: 100000,
|
|
57
|
+
backer: 999999999, // Founding Backer - unlimited until end of 2026
|
|
58
|
+
};
|
|
59
|
+
const newLimit = planLimits[args.billingPlan] || 50;
|
|
60
|
+
// Determine tier
|
|
61
|
+
let newTier = "free";
|
|
62
|
+
if (args.billingPlan === "backer") {
|
|
63
|
+
newTier = "backer";
|
|
64
|
+
}
|
|
65
|
+
else if (args.billingPlan !== "free") {
|
|
66
|
+
newTier = "pro";
|
|
67
|
+
}
|
|
68
|
+
// For Backer: set expiry to end of 2026
|
|
69
|
+
const backerUntil = args.billingPlan === "backer"
|
|
70
|
+
? new Date("2026-12-31T23:59:59Z").getTime()
|
|
71
|
+
: undefined;
|
|
72
|
+
await ctx.db.patch(args.workspaceId, {
|
|
73
|
+
stripeSubscriptionId: args.stripeSubscriptionId,
|
|
74
|
+
billingPlan: args.billingPlan,
|
|
75
|
+
tier: newTier,
|
|
76
|
+
usageLimit: newLimit,
|
|
77
|
+
...(backerUntil && { backerUntil }),
|
|
78
|
+
updatedAt: Date.now(),
|
|
79
|
+
});
|
|
80
|
+
return { success: true, newLimit };
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
/**
|
|
84
|
+
* Record daily usage for billing
|
|
85
|
+
*/
|
|
86
|
+
export const recordUsage = mutation({
|
|
87
|
+
args: {
|
|
88
|
+
workspaceId: v.id("workspaces"),
|
|
89
|
+
callCount: v.number(),
|
|
90
|
+
date: v.string(), // "2026-02-28" format
|
|
91
|
+
},
|
|
92
|
+
handler: async (ctx, args) => {
|
|
93
|
+
// Check if record exists for this date
|
|
94
|
+
const existing = await ctx.db
|
|
95
|
+
.query("usageRecords")
|
|
96
|
+
.withIndex("by_workspaceId_date", (q) => q.eq("workspaceId", args.workspaceId).eq("date", args.date))
|
|
97
|
+
.unique();
|
|
98
|
+
if (existing) {
|
|
99
|
+
// Update existing record
|
|
100
|
+
await ctx.db.patch(existing._id, {
|
|
101
|
+
callCount: existing.callCount + args.callCount,
|
|
102
|
+
updatedAt: Date.now(),
|
|
103
|
+
});
|
|
104
|
+
return { id: existing._id, callCount: existing.callCount + args.callCount };
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
// Create new record
|
|
108
|
+
const id = await ctx.db.insert("usageRecords", {
|
|
109
|
+
workspaceId: args.workspaceId,
|
|
110
|
+
date: args.date,
|
|
111
|
+
callCount: args.callCount,
|
|
112
|
+
reportedToStripe: false,
|
|
113
|
+
createdAt: Date.now(),
|
|
114
|
+
updatedAt: Date.now(),
|
|
115
|
+
});
|
|
116
|
+
return { id, callCount: args.callCount };
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
/**
|
|
121
|
+
* Process a successful payment (from webhook)
|
|
122
|
+
*/
|
|
123
|
+
export const processPayment = mutation({
|
|
124
|
+
args: {
|
|
125
|
+
stripeInvoiceId: v.string(),
|
|
126
|
+
workspaceId: v.id("workspaces"),
|
|
127
|
+
amount: v.number(), // in cents
|
|
128
|
+
periodStart: v.number(),
|
|
129
|
+
periodEnd: v.number(),
|
|
130
|
+
callCount: v.number(),
|
|
131
|
+
pdfUrl: v.optional(v.string()),
|
|
132
|
+
},
|
|
133
|
+
handler: async (ctx, args) => {
|
|
134
|
+
// Check for idempotency - don't process same invoice twice
|
|
135
|
+
const existing = await ctx.db
|
|
136
|
+
.query("invoices")
|
|
137
|
+
.withIndex("by_stripeInvoiceId", (q) => q.eq("stripeInvoiceId", args.stripeInvoiceId))
|
|
138
|
+
.unique();
|
|
139
|
+
if (existing) {
|
|
140
|
+
// Already processed, return existing
|
|
141
|
+
return { id: existing._id, alreadyProcessed: true };
|
|
142
|
+
}
|
|
143
|
+
// Create invoice record
|
|
144
|
+
const id = await ctx.db.insert("invoices", {
|
|
145
|
+
workspaceId: args.workspaceId,
|
|
146
|
+
stripeInvoiceId: args.stripeInvoiceId,
|
|
147
|
+
amount: args.amount,
|
|
148
|
+
status: "paid",
|
|
149
|
+
periodStart: args.periodStart,
|
|
150
|
+
periodEnd: args.periodEnd,
|
|
151
|
+
callCount: args.callCount,
|
|
152
|
+
pdfUrl: args.pdfUrl,
|
|
153
|
+
createdAt: Date.now(),
|
|
154
|
+
});
|
|
155
|
+
// Update workspace last billing date
|
|
156
|
+
await ctx.db.patch(args.workspaceId, {
|
|
157
|
+
lastBillingDate: Date.now(),
|
|
158
|
+
updatedAt: Date.now(),
|
|
159
|
+
});
|
|
160
|
+
return { id, alreadyProcessed: false };
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
/**
|
|
164
|
+
* Increment credit balance (for prepaid credits)
|
|
165
|
+
*/
|
|
166
|
+
export const incrementCredits = mutation({
|
|
167
|
+
args: {
|
|
168
|
+
workspaceId: v.id("workspaces"),
|
|
169
|
+
amount: v.number(), // in cents
|
|
170
|
+
},
|
|
171
|
+
handler: async (ctx, args) => {
|
|
172
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
173
|
+
if (!workspace) {
|
|
174
|
+
throw new Error("Workspace not found");
|
|
175
|
+
}
|
|
176
|
+
const currentBalance = workspace.creditBalance || 0;
|
|
177
|
+
const newBalance = currentBalance + args.amount;
|
|
178
|
+
await ctx.db.patch(args.workspaceId, {
|
|
179
|
+
creditBalance: newBalance,
|
|
180
|
+
updatedAt: Date.now(),
|
|
181
|
+
});
|
|
182
|
+
return { previousBalance: currentBalance, newBalance };
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* Decrement credit balance (when using prepaid credits)
|
|
187
|
+
*/
|
|
188
|
+
export const decrementCredits = mutation({
|
|
189
|
+
args: {
|
|
190
|
+
workspaceId: v.id("workspaces"),
|
|
191
|
+
amount: v.number(), // in cents
|
|
192
|
+
},
|
|
193
|
+
handler: async (ctx, args) => {
|
|
194
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
195
|
+
if (!workspace) {
|
|
196
|
+
throw new Error("Workspace not found");
|
|
197
|
+
}
|
|
198
|
+
const currentBalance = workspace.creditBalance || 0;
|
|
199
|
+
if (currentBalance < args.amount) {
|
|
200
|
+
throw new Error("Insufficient credit balance");
|
|
201
|
+
}
|
|
202
|
+
const newBalance = currentBalance - args.amount;
|
|
203
|
+
await ctx.db.patch(args.workspaceId, {
|
|
204
|
+
creditBalance: newBalance,
|
|
205
|
+
updatedAt: Date.now(),
|
|
206
|
+
});
|
|
207
|
+
return { previousBalance: currentBalance, newBalance };
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
/**
|
|
211
|
+
* Mark usage as reported to Stripe
|
|
212
|
+
*/
|
|
213
|
+
export const markUsageReported = internalMutation({
|
|
214
|
+
args: {
|
|
215
|
+
usageRecordId: v.id("usageRecords"),
|
|
216
|
+
stripeUsageRecordId: v.string(),
|
|
217
|
+
},
|
|
218
|
+
handler: async (ctx, args) => {
|
|
219
|
+
await ctx.db.patch(args.usageRecordId, {
|
|
220
|
+
reportedToStripe: true,
|
|
221
|
+
stripeUsageRecordId: args.stripeUsageRecordId,
|
|
222
|
+
updatedAt: Date.now(),
|
|
223
|
+
});
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
/**
|
|
227
|
+
* Update invoice status (from webhook)
|
|
228
|
+
*/
|
|
229
|
+
export const updateInvoiceStatus = mutation({
|
|
230
|
+
args: {
|
|
231
|
+
stripeInvoiceId: v.string(),
|
|
232
|
+
status: v.string(),
|
|
233
|
+
},
|
|
234
|
+
handler: async (ctx, args) => {
|
|
235
|
+
const invoice = await ctx.db
|
|
236
|
+
.query("invoices")
|
|
237
|
+
.withIndex("by_stripeInvoiceId", (q) => q.eq("stripeInvoiceId", args.stripeInvoiceId))
|
|
238
|
+
.unique();
|
|
239
|
+
if (!invoice) {
|
|
240
|
+
return { found: false };
|
|
241
|
+
}
|
|
242
|
+
await ctx.db.patch(invoice._id, {
|
|
243
|
+
status: args.status,
|
|
244
|
+
});
|
|
245
|
+
return { found: true, id: invoice._id };
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
/**
|
|
249
|
+
* Reset usage count on subscription cancellation
|
|
250
|
+
* Gives user a clean slate when downgrading to free
|
|
251
|
+
*/
|
|
252
|
+
export const resetUsageOnCancellation = mutation({
|
|
253
|
+
args: {
|
|
254
|
+
workspaceId: v.id("workspaces"),
|
|
255
|
+
},
|
|
256
|
+
handler: async (ctx, args) => {
|
|
257
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
258
|
+
if (!workspace) {
|
|
259
|
+
throw new Error("Workspace not found");
|
|
260
|
+
}
|
|
261
|
+
await ctx.db.patch(args.workspaceId, {
|
|
262
|
+
usageCount: 0,
|
|
263
|
+
updatedAt: Date.now(),
|
|
264
|
+
});
|
|
265
|
+
return { success: true, previousUsage: workspace.usageCount };
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
/**
|
|
269
|
+
* Update payment method info (from webhook)
|
|
270
|
+
*/
|
|
271
|
+
export const updatePaymentMethodInfo = mutation({
|
|
272
|
+
args: {
|
|
273
|
+
workspaceId: v.id("workspaces"),
|
|
274
|
+
hasPaymentMethod: v.boolean(),
|
|
275
|
+
paymentMethodType: v.optional(v.string()),
|
|
276
|
+
cardBrand: v.optional(v.string()),
|
|
277
|
+
cardLast4: v.optional(v.string()),
|
|
278
|
+
},
|
|
279
|
+
handler: async (ctx, args) => {
|
|
280
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
281
|
+
if (!workspace) {
|
|
282
|
+
throw new Error("Workspace not found");
|
|
283
|
+
}
|
|
284
|
+
await ctx.db.patch(args.workspaceId, {
|
|
285
|
+
hasPaymentMethod: args.hasPaymentMethod,
|
|
286
|
+
paymentMethodType: args.paymentMethodType,
|
|
287
|
+
cardBrand: args.cardBrand,
|
|
288
|
+
cardLast4: args.cardLast4,
|
|
289
|
+
updatedAt: Date.now(),
|
|
290
|
+
});
|
|
291
|
+
return { success: true };
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
// ============================================
|
|
295
|
+
// QUERIES
|
|
296
|
+
// ============================================
|
|
297
|
+
/**
|
|
298
|
+
* Get billing info for a workspace
|
|
299
|
+
*/
|
|
300
|
+
export const getInfo = query({
|
|
301
|
+
args: {
|
|
302
|
+
workspaceId: v.id("workspaces"),
|
|
303
|
+
},
|
|
304
|
+
handler: async (ctx, args) => {
|
|
305
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
306
|
+
if (!workspace) {
|
|
307
|
+
throw new Error("Workspace not found");
|
|
308
|
+
}
|
|
309
|
+
// Get recent invoices
|
|
310
|
+
const invoices = await ctx.db
|
|
311
|
+
.query("invoices")
|
|
312
|
+
.withIndex("by_workspaceId_createdAt", (q) => q.eq("workspaceId", args.workspaceId))
|
|
313
|
+
.order("desc")
|
|
314
|
+
.take(10);
|
|
315
|
+
// Calculate current period usage
|
|
316
|
+
const now = new Date();
|
|
317
|
+
const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
318
|
+
const periodStartStr = periodStart.toISOString().split("T")[0];
|
|
319
|
+
const usageRecords = await ctx.db
|
|
320
|
+
.query("usageRecords")
|
|
321
|
+
.withIndex("by_workspaceId", (q) => q.eq("workspaceId", args.workspaceId))
|
|
322
|
+
.collect();
|
|
323
|
+
const currentPeriodUsage = usageRecords
|
|
324
|
+
.filter((r) => r.date >= periodStartStr)
|
|
325
|
+
.reduce((sum, r) => sum + r.callCount, 0);
|
|
326
|
+
// Determine plan limits
|
|
327
|
+
const plan = workspace.billingPlan || "free";
|
|
328
|
+
const planLimits = {
|
|
329
|
+
free: 100,
|
|
330
|
+
usage_based: 999999999,
|
|
331
|
+
starter: 1000,
|
|
332
|
+
pro: 10000,
|
|
333
|
+
scale: 100000,
|
|
334
|
+
};
|
|
335
|
+
return {
|
|
336
|
+
plan,
|
|
337
|
+
tier: workspace.tier,
|
|
338
|
+
usage: workspace.usageCount,
|
|
339
|
+
currentPeriodUsage,
|
|
340
|
+
limit: workspace.usageLimit,
|
|
341
|
+
creditBalance: workspace.creditBalance || 0,
|
|
342
|
+
stripeCustomerId: workspace.stripeCustomerId,
|
|
343
|
+
stripeSubscriptionId: workspace.stripeSubscriptionId,
|
|
344
|
+
lastBillingDate: workspace.lastBillingDate,
|
|
345
|
+
invoices: invoices.map((inv) => ({
|
|
346
|
+
id: inv._id,
|
|
347
|
+
stripeInvoiceId: inv.stripeInvoiceId,
|
|
348
|
+
amount: inv.amount,
|
|
349
|
+
status: inv.status,
|
|
350
|
+
periodStart: inv.periodStart,
|
|
351
|
+
periodEnd: inv.periodEnd,
|
|
352
|
+
callCount: inv.callCount,
|
|
353
|
+
pdfUrl: inv.pdfUrl,
|
|
354
|
+
createdAt: inv.createdAt,
|
|
355
|
+
})),
|
|
356
|
+
// Check if payment method needed
|
|
357
|
+
needsPaymentMethod: plan === "free" && workspace.usageCount >= workspace.usageLimit,
|
|
358
|
+
};
|
|
359
|
+
},
|
|
360
|
+
});
|
|
361
|
+
/**
|
|
362
|
+
* Get current period usage
|
|
363
|
+
*/
|
|
364
|
+
export const getCurrentUsage = query({
|
|
365
|
+
args: {
|
|
366
|
+
workspaceId: v.id("workspaces"),
|
|
367
|
+
},
|
|
368
|
+
handler: async (ctx, args) => {
|
|
369
|
+
const workspace = await ctx.db.get(args.workspaceId);
|
|
370
|
+
if (!workspace) {
|
|
371
|
+
throw new Error("Workspace not found");
|
|
372
|
+
}
|
|
373
|
+
// Current billing period (month)
|
|
374
|
+
const now = new Date();
|
|
375
|
+
const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
376
|
+
const periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
|
|
377
|
+
const periodStartStr = periodStart.toISOString().split("T")[0];
|
|
378
|
+
// Get usage records for this period
|
|
379
|
+
const usageRecords = await ctx.db
|
|
380
|
+
.query("usageRecords")
|
|
381
|
+
.withIndex("by_workspaceId", (q) => q.eq("workspaceId", args.workspaceId))
|
|
382
|
+
.collect();
|
|
383
|
+
const periodRecords = usageRecords.filter((r) => r.date >= periodStartStr);
|
|
384
|
+
const callCount = periodRecords.reduce((sum, r) => sum + r.callCount, 0);
|
|
385
|
+
// Calculate estimated cost (for usage-based billing)
|
|
386
|
+
const FREE_CALLS = 100;
|
|
387
|
+
const COST_PER_CALL = 1; // 1 cent = $0.01
|
|
388
|
+
const billableCalls = Math.max(0, callCount - FREE_CALLS);
|
|
389
|
+
const estimatedCost = billableCalls * COST_PER_CALL;
|
|
390
|
+
return {
|
|
391
|
+
callCount,
|
|
392
|
+
periodStart: periodStart.getTime(),
|
|
393
|
+
periodEnd: periodEnd.getTime(),
|
|
394
|
+
limit: workspace.usageLimit,
|
|
395
|
+
remaining: Math.max(0, workspace.usageLimit - workspace.usageCount),
|
|
396
|
+
percentUsed: Math.round((workspace.usageCount / workspace.usageLimit) * 100),
|
|
397
|
+
billableCalls,
|
|
398
|
+
estimatedCostCents: estimatedCost,
|
|
399
|
+
dailyBreakdown: periodRecords.map((r) => ({
|
|
400
|
+
date: r.date,
|
|
401
|
+
calls: r.callCount,
|
|
402
|
+
reportedToStripe: r.reportedToStripe,
|
|
403
|
+
})),
|
|
404
|
+
};
|
|
405
|
+
},
|
|
406
|
+
});
|
|
407
|
+
/**
|
|
408
|
+
* Get invoices for a workspace
|
|
409
|
+
*/
|
|
410
|
+
export const getInvoices = query({
|
|
411
|
+
args: {
|
|
412
|
+
workspaceId: v.id("workspaces"),
|
|
413
|
+
limit: v.optional(v.number()),
|
|
414
|
+
},
|
|
415
|
+
handler: async (ctx, args) => {
|
|
416
|
+
const limit = args.limit || 20;
|
|
417
|
+
const invoices = await ctx.db
|
|
418
|
+
.query("invoices")
|
|
419
|
+
.withIndex("by_workspaceId_createdAt", (q) => q.eq("workspaceId", args.workspaceId))
|
|
420
|
+
.order("desc")
|
|
421
|
+
.take(limit);
|
|
422
|
+
return invoices.map((inv) => ({
|
|
423
|
+
id: inv._id,
|
|
424
|
+
stripeInvoiceId: inv.stripeInvoiceId,
|
|
425
|
+
amount: inv.amount,
|
|
426
|
+
amountFormatted: `$${(inv.amount / 100).toFixed(2)}`,
|
|
427
|
+
status: inv.status,
|
|
428
|
+
periodStart: inv.periodStart,
|
|
429
|
+
periodEnd: inv.periodEnd,
|
|
430
|
+
callCount: inv.callCount,
|
|
431
|
+
pdfUrl: inv.pdfUrl,
|
|
432
|
+
createdAt: inv.createdAt,
|
|
433
|
+
}));
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
/**
|
|
437
|
+
* Get unreported usage records (for cron job)
|
|
438
|
+
*/
|
|
439
|
+
export const getUnreportedUsage = query({
|
|
440
|
+
args: {},
|
|
441
|
+
handler: async (ctx) => {
|
|
442
|
+
const unreported = await ctx.db
|
|
443
|
+
.query("usageRecords")
|
|
444
|
+
.withIndex("by_reportedToStripe", (q) => q.eq("reportedToStripe", false))
|
|
445
|
+
.collect();
|
|
446
|
+
return unreported;
|
|
447
|
+
},
|
|
448
|
+
});
|
|
449
|
+
/**
|
|
450
|
+
* Get workspace by Stripe customer ID
|
|
451
|
+
*/
|
|
452
|
+
export const getByStripeCustomerId = query({
|
|
453
|
+
args: {
|
|
454
|
+
stripeCustomerId: v.string(),
|
|
455
|
+
},
|
|
456
|
+
handler: async (ctx, args) => {
|
|
457
|
+
return await ctx.db
|
|
458
|
+
.query("workspaces")
|
|
459
|
+
.withIndex("by_stripeCustomerId", (q) => q.eq("stripeCustomerId", args.stripeCustomerId))
|
|
460
|
+
.unique();
|
|
461
|
+
},
|
|
462
|
+
});
|
|
463
|
+
/**
|
|
464
|
+
* Get workspace by ID
|
|
465
|
+
*/
|
|
466
|
+
export const getWorkspace = query({
|
|
467
|
+
args: {
|
|
468
|
+
id: v.id("workspaces"),
|
|
469
|
+
},
|
|
470
|
+
handler: async (ctx, args) => {
|
|
471
|
+
return await ctx.db.get(args.id);
|
|
472
|
+
},
|
|
473
|
+
});
|
|
474
|
+
// ============================================
|
|
475
|
+
// STRIPE USAGE REPORTING (Internal Actions)
|
|
476
|
+
// ============================================
|
|
477
|
+
/**
|
|
478
|
+
* Get all workspaces with active Stripe subscriptions (internal)
|
|
479
|
+
*/
|
|
480
|
+
export const getActiveSubscriptions = internalQuery({
|
|
481
|
+
args: {},
|
|
482
|
+
handler: async (ctx) => {
|
|
483
|
+
// Get all workspaces with a subscription ID
|
|
484
|
+
const workspaces = await ctx.db
|
|
485
|
+
.query("workspaces")
|
|
486
|
+
.filter((q) => q.neq(q.field("stripeSubscriptionId"), undefined))
|
|
487
|
+
.collect();
|
|
488
|
+
// Filter to only those with billing plan that requires reporting
|
|
489
|
+
return workspaces.filter((w) => w.billingPlan === "usage_based" && w.stripeSubscriptionId);
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
/**
|
|
493
|
+
* Get unreported usage records for a specific workspace (internal)
|
|
494
|
+
*/
|
|
495
|
+
export const getUnreportedUsageForWorkspace = internalQuery({
|
|
496
|
+
args: {
|
|
497
|
+
workspaceId: v.id("workspaces"),
|
|
498
|
+
},
|
|
499
|
+
handler: async (ctx, args) => {
|
|
500
|
+
return await ctx.db
|
|
501
|
+
.query("usageRecords")
|
|
502
|
+
.withIndex("by_workspaceId", (q) => q.eq("workspaceId", args.workspaceId))
|
|
503
|
+
.filter((q) => q.eq(q.field("reportedToStripe"), false))
|
|
504
|
+
.collect();
|
|
505
|
+
},
|
|
506
|
+
});
|
|
507
|
+
/**
|
|
508
|
+
* Mark multiple usage records as reported (internal)
|
|
509
|
+
*/
|
|
510
|
+
export const markUsageRecordsReported = internalMutation({
|
|
511
|
+
args: {
|
|
512
|
+
usageRecordIds: v.array(v.id("usageRecords")),
|
|
513
|
+
stripeUsageRecordId: v.string(),
|
|
514
|
+
},
|
|
515
|
+
handler: async (ctx, args) => {
|
|
516
|
+
const now = Date.now();
|
|
517
|
+
for (const recordId of args.usageRecordIds) {
|
|
518
|
+
await ctx.db.patch(recordId, {
|
|
519
|
+
reportedToStripe: true,
|
|
520
|
+
stripeUsageRecordId: args.stripeUsageRecordId,
|
|
521
|
+
updatedAt: now,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
},
|
|
525
|
+
});
|
|
526
|
+
/**
|
|
527
|
+
* Report usage to Stripe for a single workspace
|
|
528
|
+
* Internal action - called by the daily cron
|
|
529
|
+
*/
|
|
530
|
+
export const reportUsageToStripe = internalAction({
|
|
531
|
+
args: {
|
|
532
|
+
workspaceId: v.id("workspaces"),
|
|
533
|
+
stripeSubscriptionId: v.string(),
|
|
534
|
+
},
|
|
535
|
+
handler: async (ctx, args) => {
|
|
536
|
+
try {
|
|
537
|
+
// Get unreported usage records
|
|
538
|
+
const usageRecords = await ctx.runQuery(internal.billing.getUnreportedUsageForWorkspace, { workspaceId: args.workspaceId });
|
|
539
|
+
if (usageRecords.length === 0) {
|
|
540
|
+
return { success: true, callCount: 0 };
|
|
541
|
+
}
|
|
542
|
+
// Sum up all unreported calls
|
|
543
|
+
const totalCalls = usageRecords.reduce((sum, r) => sum + r.callCount, 0);
|
|
544
|
+
if (totalCalls === 0) {
|
|
545
|
+
// Mark as reported even if 0 calls (to prevent re-processing)
|
|
546
|
+
await ctx.runMutation(internal.billing.markUsageRecordsReported, {
|
|
547
|
+
usageRecordIds: usageRecords.map((r) => r._id),
|
|
548
|
+
stripeUsageRecordId: "zero_usage",
|
|
549
|
+
});
|
|
550
|
+
return { success: true, callCount: 0 };
|
|
551
|
+
}
|
|
552
|
+
const stripe = getStripe();
|
|
553
|
+
// Get subscription to find the metered subscription item
|
|
554
|
+
const subscription = await stripe.subscriptions.retrieve(args.stripeSubscriptionId);
|
|
555
|
+
// Find the metered price item (usage_based price)
|
|
556
|
+
const meteredItem = subscription.items.data.find((item) => {
|
|
557
|
+
return item.price.recurring?.usage_type === "metered";
|
|
558
|
+
});
|
|
559
|
+
if (!meteredItem) {
|
|
560
|
+
console.error(`No metered subscription item found for subscription ${args.stripeSubscriptionId}`);
|
|
561
|
+
return {
|
|
562
|
+
success: false,
|
|
563
|
+
callCount: totalCalls,
|
|
564
|
+
error: "No metered subscription item found",
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
// Report usage to Stripe using usage records API
|
|
568
|
+
// Using raw fetch since SDK method varies by version
|
|
569
|
+
const stripeKey = process.env.STRIPE_SECRET_KEY;
|
|
570
|
+
const usageRecordResponse = await fetch(`https://api.stripe.com/v1/subscription_items/${meteredItem.id}/usage_records`, {
|
|
571
|
+
method: "POST",
|
|
572
|
+
headers: {
|
|
573
|
+
"Authorization": `Bearer ${stripeKey}`,
|
|
574
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
575
|
+
},
|
|
576
|
+
body: new URLSearchParams({
|
|
577
|
+
quantity: String(totalCalls),
|
|
578
|
+
timestamp: String(Math.floor(Date.now() / 1000)),
|
|
579
|
+
action: "increment",
|
|
580
|
+
}),
|
|
581
|
+
});
|
|
582
|
+
if (!usageRecordResponse.ok) {
|
|
583
|
+
const errorData = await usageRecordResponse.text();
|
|
584
|
+
throw new Error(`Stripe API error: ${usageRecordResponse.status} - ${errorData}`);
|
|
585
|
+
}
|
|
586
|
+
const usageRecord = await usageRecordResponse.json();
|
|
587
|
+
// Mark records as reported
|
|
588
|
+
await ctx.runMutation(internal.billing.markUsageRecordsReported, {
|
|
589
|
+
usageRecordIds: usageRecords.map((r) => r._id),
|
|
590
|
+
stripeUsageRecordId: usageRecord.id,
|
|
591
|
+
});
|
|
592
|
+
console.log(`Reported ${totalCalls} calls for workspace ${args.workspaceId} to Stripe`);
|
|
593
|
+
return { success: true, callCount: totalCalls };
|
|
594
|
+
}
|
|
595
|
+
catch (error) {
|
|
596
|
+
console.error(`Failed to report usage for workspace ${args.workspaceId}:`, error);
|
|
597
|
+
return {
|
|
598
|
+
success: false,
|
|
599
|
+
callCount: 0,
|
|
600
|
+
error: error.message || "Unknown error",
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
/**
|
|
606
|
+
* Daily cron job: Report all unreported usage to Stripe
|
|
607
|
+
* Runs at 00:05 UTC
|
|
608
|
+
*/
|
|
609
|
+
export const reportAllUsageToStripe = internalAction({
|
|
610
|
+
args: {},
|
|
611
|
+
handler: async (ctx) => {
|
|
612
|
+
console.log("[Cron] Starting daily usage reporting to Stripe...");
|
|
613
|
+
// Get all workspaces with active subscriptions
|
|
614
|
+
const workspaces = await ctx.runQuery(internal.billing.getActiveSubscriptions, {});
|
|
615
|
+
console.log(`[Cron] Found ${workspaces.length} workspaces with active subscriptions`);
|
|
616
|
+
const results = {
|
|
617
|
+
total: workspaces.length,
|
|
618
|
+
success: 0,
|
|
619
|
+
failed: 0,
|
|
620
|
+
skipped: 0,
|
|
621
|
+
totalCallsReported: 0,
|
|
622
|
+
errors: [],
|
|
623
|
+
};
|
|
624
|
+
// Process each workspace
|
|
625
|
+
for (const workspace of workspaces) {
|
|
626
|
+
if (!workspace.stripeSubscriptionId) {
|
|
627
|
+
results.skipped++;
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
try {
|
|
631
|
+
const result = await ctx.runAction(internal.billing.reportUsageToStripe, {
|
|
632
|
+
workspaceId: workspace._id,
|
|
633
|
+
stripeSubscriptionId: workspace.stripeSubscriptionId,
|
|
634
|
+
});
|
|
635
|
+
if (result.success) {
|
|
636
|
+
results.success++;
|
|
637
|
+
results.totalCallsReported += result.callCount;
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
results.failed++;
|
|
641
|
+
results.errors.push(`${workspace.email}: ${result.error || "Unknown error"}`);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
results.failed++;
|
|
646
|
+
results.errors.push(`${workspace.email}: ${error.message || "Unknown error"}`);
|
|
647
|
+
console.error(`[Cron] Error processing workspace ${workspace._id}:`, error);
|
|
648
|
+
// Continue with next workspace
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
console.log("[Cron] Daily usage reporting complete:", JSON.stringify(results));
|
|
652
|
+
return results;
|
|
653
|
+
},
|
|
654
|
+
});
|
|
655
|
+
//# sourceMappingURL=billing.js.map
|