@nordsym/apiclaw 1.7.11 → 1.7.13

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 (153) hide show
  1. package/convex/adminActivate.d.ts +3 -0
  2. package/convex/adminActivate.d.ts.map +1 -0
  3. package/convex/adminActivate.js +47 -0
  4. package/convex/adminActivate.js.map +1 -0
  5. package/convex/adminStats.d.ts +4 -0
  6. package/convex/adminStats.d.ts.map +1 -0
  7. package/convex/adminStats.js +101 -0
  8. package/convex/adminStats.js.map +1 -0
  9. package/convex/agents.d.ts +76 -0
  10. package/convex/agents.d.ts.map +1 -0
  11. package/convex/agents.js +699 -0
  12. package/convex/agents.js.map +1 -0
  13. package/convex/analytics.d.ts +5 -0
  14. package/convex/analytics.d.ts.map +1 -0
  15. package/convex/analytics.js +166 -0
  16. package/convex/analytics.js.map +1 -0
  17. package/convex/billing.d.ts +88 -0
  18. package/convex/billing.d.ts.map +1 -0
  19. package/convex/billing.js +655 -0
  20. package/convex/billing.js.map +1 -0
  21. package/convex/capabilities.d.ts +9 -0
  22. package/convex/capabilities.d.ts.map +1 -0
  23. package/convex/capabilities.js +145 -0
  24. package/convex/capabilities.js.map +1 -0
  25. package/convex/chains.d.ts +68 -0
  26. package/convex/chains.d.ts.map +1 -0
  27. package/convex/chains.js +1105 -0
  28. package/convex/chains.js.map +1 -0
  29. package/convex/credits.d.ts +25 -0
  30. package/convex/credits.d.ts.map +1 -0
  31. package/convex/credits.js +186 -0
  32. package/convex/credits.js.map +1 -0
  33. package/convex/crons.d.ts +3 -0
  34. package/convex/crons.d.ts.map +1 -0
  35. package/convex/crons.js +17 -0
  36. package/convex/crons.js.map +1 -0
  37. package/convex/directCall.d.ts +72 -0
  38. package/convex/directCall.d.ts.map +1 -0
  39. package/convex/directCall.js +627 -0
  40. package/convex/directCall.js.map +1 -0
  41. package/convex/earnProgress.d.ts +58 -0
  42. package/convex/earnProgress.d.ts.map +1 -0
  43. package/convex/earnProgress.js +649 -0
  44. package/convex/earnProgress.js.map +1 -0
  45. package/convex/email.d.ts +14 -0
  46. package/convex/email.d.ts.map +1 -0
  47. package/convex/email.js +300 -0
  48. package/convex/email.js.map +1 -0
  49. package/convex/feedback.d.ts +7 -0
  50. package/convex/feedback.d.ts.map +1 -0
  51. package/convex/feedback.js +227 -0
  52. package/convex/feedback.js.map +1 -0
  53. package/convex/http.d.ts +3 -0
  54. package/convex/http.d.ts.map +1 -0
  55. package/convex/http.js +1405 -0
  56. package/convex/http.js.map +1 -0
  57. package/convex/inbound.d.ts +2 -0
  58. package/convex/inbound.d.ts.map +1 -0
  59. package/convex/inbound.js +32 -0
  60. package/convex/inbound.js.map +1 -0
  61. package/convex/logs.d.ts +48 -0
  62. package/convex/logs.d.ts.map +1 -0
  63. package/convex/logs.js +605 -0
  64. package/convex/logs.js.map +1 -0
  65. package/convex/mou.d.ts +6 -0
  66. package/convex/mou.d.ts.map +1 -0
  67. package/convex/mou.js +82 -0
  68. package/convex/mou.js.map +1 -0
  69. package/convex/providerKeys.d.ts +31 -0
  70. package/convex/providerKeys.d.ts.map +1 -0
  71. package/convex/providerKeys.js +257 -0
  72. package/convex/providerKeys.js.map +1 -0
  73. package/convex/providers.d.ts +34 -0
  74. package/convex/providers.d.ts.map +1 -0
  75. package/convex/providers.js +898 -0
  76. package/convex/providers.js.map +1 -0
  77. package/convex/providers.ts +57 -2
  78. package/convex/purchases.d.ts +7 -0
  79. package/convex/purchases.d.ts.map +1 -0
  80. package/convex/purchases.js +157 -0
  81. package/convex/purchases.js.map +1 -0
  82. package/convex/ratelimit.d.ts +4 -0
  83. package/convex/ratelimit.d.ts.map +1 -0
  84. package/convex/ratelimit.js +91 -0
  85. package/convex/ratelimit.js.map +1 -0
  86. package/convex/searchLogs.d.ts +4 -0
  87. package/convex/searchLogs.d.ts.map +1 -0
  88. package/convex/searchLogs.js +129 -0
  89. package/convex/searchLogs.js.map +1 -0
  90. package/convex/seedAPILayerAPIs.d.ts +7 -0
  91. package/convex/seedAPILayerAPIs.d.ts.map +1 -0
  92. package/convex/seedAPILayerAPIs.js +177 -0
  93. package/convex/seedAPILayerAPIs.js.map +1 -0
  94. package/convex/seedDirectCallConfigs.d.ts +2 -0
  95. package/convex/seedDirectCallConfigs.d.ts.map +1 -0
  96. package/convex/seedDirectCallConfigs.js +324 -0
  97. package/convex/seedDirectCallConfigs.js.map +1 -0
  98. package/convex/seedPratham.d.ts +6 -0
  99. package/convex/seedPratham.d.ts.map +1 -0
  100. package/convex/seedPratham.js +150 -0
  101. package/convex/seedPratham.js.map +1 -0
  102. package/convex/spendAlerts.d.ts +36 -0
  103. package/convex/spendAlerts.d.ts.map +1 -0
  104. package/convex/spendAlerts.js +380 -0
  105. package/convex/spendAlerts.js.map +1 -0
  106. package/convex/stripeActions.d.ts +19 -0
  107. package/convex/stripeActions.d.ts.map +1 -0
  108. package/convex/stripeActions.js +411 -0
  109. package/convex/stripeActions.js.map +1 -0
  110. package/convex/teams.d.ts +21 -0
  111. package/convex/teams.d.ts.map +1 -0
  112. package/convex/teams.js +215 -0
  113. package/convex/teams.js.map +1 -0
  114. package/convex/telemetry.d.ts +4 -0
  115. package/convex/telemetry.d.ts.map +1 -0
  116. package/convex/telemetry.js +74 -0
  117. package/convex/telemetry.js.map +1 -0
  118. package/convex/updateAPIStatus.d.ts +6 -0
  119. package/convex/updateAPIStatus.d.ts.map +1 -0
  120. package/convex/updateAPIStatus.js +40 -0
  121. package/convex/updateAPIStatus.js.map +1 -0
  122. package/convex/usage.d.ts +27 -0
  123. package/convex/usage.d.ts.map +1 -0
  124. package/convex/usage.js +229 -0
  125. package/convex/usage.js.map +1 -0
  126. package/convex/waitlist.d.ts +4 -0
  127. package/convex/waitlist.d.ts.map +1 -0
  128. package/convex/waitlist.js +49 -0
  129. package/convex/waitlist.js.map +1 -0
  130. package/convex/webhooks.d.ts +12 -0
  131. package/convex/webhooks.d.ts.map +1 -0
  132. package/convex/webhooks.js +410 -0
  133. package/convex/webhooks.js.map +1 -0
  134. package/convex/workspaces.d.ts +31 -0
  135. package/convex/workspaces.d.ts.map +1 -0
  136. package/convex/workspaces.js +975 -0
  137. package/convex/workspaces.js.map +1 -0
  138. package/dist/capability-router.js +1 -1
  139. package/dist/capability-router.js.map +1 -1
  140. package/dist/cli.js +1 -1
  141. package/dist/cli.js.map +1 -1
  142. package/dist/hivr-whitelist.js +1 -1
  143. package/dist/hivr-whitelist.js.map +1 -1
  144. package/dist/index.js +53 -30
  145. package/dist/index.js.map +1 -1
  146. package/dist/product-whitelist.js +1 -1
  147. package/dist/product-whitelist.js.map +1 -1
  148. package/dist/proxy.js +1 -1
  149. package/dist/proxy.js.map +1 -1
  150. package/dist/telemetry.js +1 -1
  151. package/dist/telemetry.js.map +1 -1
  152. package/package.json +1 -1
  153. package/src/index.ts +5 -18
@@ -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