@nordsym/apiclaw 1.8.7 → 1.8.9

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