@langwatch/server 3.1.0-beta.4 → 3.1.0-beta.5
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/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
- package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
- package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
- package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
- package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
- package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
- package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
- package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
- package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
- package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
- package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
- package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
- package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
- package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
- package/langwatch/ee/admin/impersonation.service.ts +170 -0
- package/langwatch/ee/admin/isAdmin.ts +9 -0
- package/langwatch/ee/admin/routes/admin.ts +531 -0
- package/langwatch/ee/admin/safeSelects.ts +64 -0
- package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
- package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
- package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
- package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
- package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
- package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
- package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
- package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
- package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
- package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
- package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
- package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
- package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
- package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
- package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
- package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
- package/langwatch/ee/billing/currencyRouter.ts +18 -0
- package/langwatch/ee/billing/errors.ts +129 -0
- package/langwatch/ee/billing/index.ts +67 -0
- package/langwatch/ee/billing/middleware.ts +17 -0
- package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
- package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
- package/langwatch/ee/billing/notifications/types.ts +9 -0
- package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
- package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
- package/langwatch/ee/billing/nurturing/types.ts +125 -0
- package/langwatch/ee/billing/planLimits.ts +190 -0
- package/langwatch/ee/billing/planProvider.ts +119 -0
- package/langwatch/ee/billing/planTypes.ts +53 -0
- package/langwatch/ee/billing/pricing.ts +57 -0
- package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
- package/langwatch/ee/billing/services/customerService.ts +90 -0
- package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
- package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
- package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
- package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
- package/langwatch/ee/billing/services/subscription.service.ts +549 -0
- package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
- package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
- package/langwatch/ee/billing/services/webhookService.ts +858 -0
- package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
- package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
- package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
- package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
- package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
- package/langwatch/ee/billing/types.ts +102 -0
- package/langwatch/ee/billing/utils/currency.ts +99 -0
- package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
- package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
- package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
- package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
- package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
- package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
- package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
- package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
- package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
- package/langwatch/ee/licensing/client.ts +29 -0
- package/langwatch/ee/licensing/constants.ts +195 -0
- package/langwatch/ee/licensing/defaults.ts +55 -0
- package/langwatch/ee/licensing/errors.ts +11 -0
- package/langwatch/ee/licensing/index.ts +52 -0
- package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
- package/langwatch/ee/licensing/licenseHandler.ts +308 -0
- package/langwatch/ee/licensing/planInfo.ts +46 -0
- package/langwatch/ee/licensing/planMapping.ts +37 -0
- package/langwatch/ee/licensing/planTemplates.ts +109 -0
- package/langwatch/ee/licensing/server.ts +43 -0
- package/langwatch/ee/licensing/signing.ts +43 -0
- package/langwatch/ee/licensing/types.ts +156 -0
- package/langwatch/ee/licensing/validation.ts +107 -0
- package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
- package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
- package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
- package/langwatch/package.json +1 -1
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +1 -1
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { PLAN_LIMITS } from "../planLimits";
|
|
3
|
+
import { PlanTypes, type PlanTypes as PlanType } from "../planTypes";
|
|
4
|
+
import { isStripePriceName, prices } from "../stripe/stripePriceCatalog";
|
|
5
|
+
|
|
6
|
+
export { prices };
|
|
7
|
+
|
|
8
|
+
type UpdateItem = {
|
|
9
|
+
id?: string;
|
|
10
|
+
price?: string;
|
|
11
|
+
quantity?: number;
|
|
12
|
+
deleted?: boolean;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
type AddOnPlan =
|
|
16
|
+
| typeof PlanTypes.LAUNCH
|
|
17
|
+
| typeof PlanTypes.LAUNCH_ANNUAL
|
|
18
|
+
| typeof PlanTypes.ACCELERATE
|
|
19
|
+
| typeof PlanTypes.ACCELERATE_ANNUAL;
|
|
20
|
+
|
|
21
|
+
type StripePlanPriceConfig = {
|
|
22
|
+
basePriceKey: keyof typeof prices;
|
|
23
|
+
userPriceKey: keyof typeof prices;
|
|
24
|
+
tracesPriceKey: keyof typeof prices;
|
|
25
|
+
tracesUnit: 10_000 | 100_000;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const STRIPE_PLAN_CONFIG: Record<AddOnPlan, StripePlanPriceConfig> = {
|
|
29
|
+
[PlanTypes.LAUNCH]: {
|
|
30
|
+
basePriceKey: "LAUNCH",
|
|
31
|
+
userPriceKey: "LAUNCH_USERS",
|
|
32
|
+
tracesPriceKey: "LAUNCH_TRACES_10K",
|
|
33
|
+
tracesUnit: 10_000,
|
|
34
|
+
},
|
|
35
|
+
[PlanTypes.LAUNCH_ANNUAL]: {
|
|
36
|
+
basePriceKey: "LAUNCH_ANNUAL",
|
|
37
|
+
userPriceKey: "LAUNCH_ANNUAL_USERS",
|
|
38
|
+
tracesPriceKey: "LAUNCH_ANNUAL_TRACES_10K",
|
|
39
|
+
tracesUnit: 10_000,
|
|
40
|
+
},
|
|
41
|
+
[PlanTypes.ACCELERATE]: {
|
|
42
|
+
basePriceKey: "ACCELERATE",
|
|
43
|
+
userPriceKey: "ACCELERATE_USERS",
|
|
44
|
+
tracesPriceKey: "ACCELERATE_TRACES_100K",
|
|
45
|
+
tracesUnit: 100_000,
|
|
46
|
+
},
|
|
47
|
+
[PlanTypes.ACCELERATE_ANNUAL]: {
|
|
48
|
+
basePriceKey: "ACCELERATE_ANNUAL",
|
|
49
|
+
userPriceKey: "ACCELERATE_ANNUAL_USERS",
|
|
50
|
+
tracesPriceKey: "ACCELERATE_ANNUAL_TRACES_100K",
|
|
51
|
+
tracesUnit: 100_000,
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const hasConfigForPlan = (plan: PlanType): plan is AddOnPlan =>
|
|
56
|
+
Object.prototype.hasOwnProperty.call(STRIPE_PLAN_CONFIG, plan);
|
|
57
|
+
|
|
58
|
+
const getPlanConfig = (plan: PlanType) =>
|
|
59
|
+
hasConfigForPlan(plan) ? STRIPE_PLAN_CONFIG[plan] : undefined;
|
|
60
|
+
|
|
61
|
+
const getBasePrice = (plan: PlanType): string | undefined => {
|
|
62
|
+
if (hasConfigForPlan(plan)) {
|
|
63
|
+
return prices[STRIPE_PLAN_CONFIG[plan].basePriceKey];
|
|
64
|
+
}
|
|
65
|
+
return isStripePriceName(plan) ? prices[plan] : undefined;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export const getItemsToUpdate = ({
|
|
69
|
+
currentItems,
|
|
70
|
+
plan,
|
|
71
|
+
tracesToAdd,
|
|
72
|
+
membersToAdd,
|
|
73
|
+
}: {
|
|
74
|
+
currentItems: Stripe.SubscriptionItem[];
|
|
75
|
+
plan: PlanType;
|
|
76
|
+
tracesToAdd: number;
|
|
77
|
+
membersToAdd: number;
|
|
78
|
+
}): UpdateItem[] => {
|
|
79
|
+
const planConfig = getPlanConfig(plan);
|
|
80
|
+
const itemsToUpdate: UpdateItem[] = [];
|
|
81
|
+
|
|
82
|
+
let tracesItem: Stripe.SubscriptionItem | undefined;
|
|
83
|
+
let userItem: Stripe.SubscriptionItem | undefined;
|
|
84
|
+
let planItem: Stripe.SubscriptionItem | undefined;
|
|
85
|
+
let deleteItems: Stripe.SubscriptionItem[] = [];
|
|
86
|
+
|
|
87
|
+
if (planConfig) {
|
|
88
|
+
const keepPriceIds = new Set([
|
|
89
|
+
prices[planConfig.basePriceKey],
|
|
90
|
+
prices[planConfig.userPriceKey],
|
|
91
|
+
prices[planConfig.tracesPriceKey],
|
|
92
|
+
]);
|
|
93
|
+
|
|
94
|
+
const keepItems = currentItems.filter((item) => {
|
|
95
|
+
return keepPriceIds.has(item.price.id);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
deleteItems = currentItems.filter((item) => {
|
|
99
|
+
return !keepItems.includes(item);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
tracesItem = keepItems.find(
|
|
103
|
+
(item) => item.price.id === prices[planConfig.tracesPriceKey],
|
|
104
|
+
);
|
|
105
|
+
userItem = keepItems.find(
|
|
106
|
+
(item) => item.price.id === prices[planConfig.userPriceKey],
|
|
107
|
+
);
|
|
108
|
+
planItem = keepItems.find(
|
|
109
|
+
(item) => item.price.id === prices[planConfig.basePriceKey],
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const planLimits = PLAN_LIMITS[plan];
|
|
114
|
+
if (!planLimits) {
|
|
115
|
+
return [];
|
|
116
|
+
}
|
|
117
|
+
const totalTraces = Math.max(0, tracesToAdd - planLimits.maxMessagesPerMonth);
|
|
118
|
+
const totalMembers = Math.max(0, membersToAdd - planLimits.maxMembers);
|
|
119
|
+
|
|
120
|
+
if (tracesItem && planConfig) {
|
|
121
|
+
itemsToUpdate.push({
|
|
122
|
+
id: tracesItem.id,
|
|
123
|
+
quantity: Math.floor(totalTraces / planConfig.tracesUnit),
|
|
124
|
+
});
|
|
125
|
+
} else if (totalTraces > 0 && planConfig) {
|
|
126
|
+
const tracesQuantity = Math.floor(totalTraces / planConfig.tracesUnit);
|
|
127
|
+
if (tracesQuantity > 0) {
|
|
128
|
+
itemsToUpdate.push({
|
|
129
|
+
price: prices[planConfig.tracesPriceKey],
|
|
130
|
+
quantity: tracesQuantity,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (userItem) {
|
|
136
|
+
itemsToUpdate.push({
|
|
137
|
+
id: userItem.id,
|
|
138
|
+
quantity: totalMembers,
|
|
139
|
+
});
|
|
140
|
+
} else if (totalMembers > 0 && planConfig) {
|
|
141
|
+
itemsToUpdate.push({
|
|
142
|
+
price: prices[planConfig.userPriceKey],
|
|
143
|
+
quantity: totalMembers,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (planItem) {
|
|
148
|
+
itemsToUpdate.push({
|
|
149
|
+
id: planItem.id,
|
|
150
|
+
quantity: 1,
|
|
151
|
+
});
|
|
152
|
+
} else {
|
|
153
|
+
const basePrice = getBasePrice(plan);
|
|
154
|
+
if (basePrice) {
|
|
155
|
+
itemsToUpdate.push({
|
|
156
|
+
price: basePrice,
|
|
157
|
+
quantity: 1,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (deleteItems.length > 0) {
|
|
163
|
+
for (const item of deleteItems) {
|
|
164
|
+
itemsToUpdate.push({
|
|
165
|
+
id: item.id,
|
|
166
|
+
deleted: true,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
for (const item of itemsToUpdate) {
|
|
172
|
+
if (item.quantity === 0) {
|
|
173
|
+
item.deleted = true;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return itemsToUpdate;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export const calculateQuantityForPrice = ({
|
|
181
|
+
priceId,
|
|
182
|
+
quantity,
|
|
183
|
+
plan,
|
|
184
|
+
}: {
|
|
185
|
+
priceId: string;
|
|
186
|
+
quantity: number;
|
|
187
|
+
plan: string | undefined;
|
|
188
|
+
}) => {
|
|
189
|
+
const planLimits = plan ? PLAN_LIMITS[plan as PlanType] : undefined;
|
|
190
|
+
const config = Object.values(STRIPE_PLAN_CONFIG).find((planConfig) => {
|
|
191
|
+
return (
|
|
192
|
+
priceId === prices[planConfig.userPriceKey] ||
|
|
193
|
+
priceId === prices[planConfig.tracesPriceKey]
|
|
194
|
+
);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
if (!config) {
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (priceId === prices[config.userPriceKey]) {
|
|
202
|
+
return (quantity ?? 0) + (planLimits?.maxMembers ?? 0);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return (quantity ?? 0) * config.tracesUnit + (planLimits?.maxMessagesPerMonth ?? 0);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export const createItemsToAdd = (
|
|
209
|
+
planType: PlanType,
|
|
210
|
+
traces: { quantity: number },
|
|
211
|
+
users: { quantity: number },
|
|
212
|
+
): UpdateItem[] => {
|
|
213
|
+
const planConfig = getPlanConfig(planType);
|
|
214
|
+
const itemsToAdd: UpdateItem[] = [];
|
|
215
|
+
|
|
216
|
+
const planLimits = PLAN_LIMITS[planType];
|
|
217
|
+
if (!planLimits) {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const totalTraces = Math.max(
|
|
222
|
+
0,
|
|
223
|
+
traces.quantity - planLimits.maxMessagesPerMonth,
|
|
224
|
+
);
|
|
225
|
+
const totalMembers = Math.max(0, users.quantity - planLimits.maxMembers);
|
|
226
|
+
|
|
227
|
+
if (!planConfig) {
|
|
228
|
+
return itemsToAdd;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (totalMembers > 0) {
|
|
232
|
+
itemsToAdd.push({
|
|
233
|
+
price: prices[planConfig.userPriceKey],
|
|
234
|
+
quantity: totalMembers,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (totalTraces > 0) {
|
|
239
|
+
const tracesQuantity = Math.floor(totalTraces / planConfig.tracesUnit);
|
|
240
|
+
if (tracesQuantity > 0) {
|
|
241
|
+
itemsToAdd.push({
|
|
242
|
+
price: prices[planConfig.tracesPriceKey],
|
|
243
|
+
quantity: tracesQuantity,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return itemsToAdd;
|
|
249
|
+
};
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createLogger } from "../../../src/utils/logger";
|
|
4
|
+
|
|
5
|
+
const logger = createLogger("langwatch:billing:usageReportingService");
|
|
6
|
+
|
|
7
|
+
const meterEventSchema = z.object({
|
|
8
|
+
eventName: z.string().min(1),
|
|
9
|
+
value: z.number().int().nonnegative(),
|
|
10
|
+
/** Unix SECONDS since epoch. NOT milliseconds, NOT ISO string. */
|
|
11
|
+
timestamp: z.number().int().positive(),
|
|
12
|
+
/** Caller-constructed idempotency key. 24-hour rolling uniqueness window in Stripe. */
|
|
13
|
+
identifier: z.string().min(1),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const reportUsageDeltaInputSchema = z.object({
|
|
17
|
+
stripeCustomerId: z.string().startsWith("cus_"),
|
|
18
|
+
organizationId: z.string().min(1),
|
|
19
|
+
events: z.array(meterEventSchema).min(1),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const reportUsageSetInputSchema = z.object({
|
|
23
|
+
stripeCustomerId: z.string().startsWith("cus_"),
|
|
24
|
+
organizationId: z.string().min(1),
|
|
25
|
+
events: z
|
|
26
|
+
.array(
|
|
27
|
+
meterEventSchema.extend({
|
|
28
|
+
previouslyReportedValue: z.number().int().nonnegative(),
|
|
29
|
+
})
|
|
30
|
+
)
|
|
31
|
+
.min(1),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
type ReportUsageDeltaInput = z.infer<typeof reportUsageDeltaInputSchema>;
|
|
35
|
+
type ReportUsageSetInput = z.infer<typeof reportUsageSetInputSchema>;
|
|
36
|
+
|
|
37
|
+
const getUsageSummaryInputSchema = z
|
|
38
|
+
.object({
|
|
39
|
+
stripeCustomerId: z.string().startsWith("cus_"),
|
|
40
|
+
startTime: z.number().int().positive(),
|
|
41
|
+
endTime: z.number().int().positive(),
|
|
42
|
+
})
|
|
43
|
+
.refine((data) => data.endTime > data.startTime, {
|
|
44
|
+
message: "endTime must be after startTime",
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
type GetUsageSummaryInput = z.input<typeof getUsageSummaryInputSchema>;
|
|
48
|
+
|
|
49
|
+
export type MeterEventResult = {
|
|
50
|
+
identifier: string;
|
|
51
|
+
reported: boolean;
|
|
52
|
+
valueSent: number;
|
|
53
|
+
error?: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type UsageSummary = {
|
|
57
|
+
aggregatedValue: number;
|
|
58
|
+
startTime: number;
|
|
59
|
+
endTime: number;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type UsageReportingService = {
|
|
63
|
+
reportUsageDelta(input: ReportUsageDeltaInput): Promise<MeterEventResult[]>;
|
|
64
|
+
reportUsageSet(input: ReportUsageSetInput): Promise<MeterEventResult[]>;
|
|
65
|
+
getUsageSummary(input: GetUsageSummaryInput): Promise<UsageSummary>;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export class StripeUsageReportingService implements UsageReportingService {
|
|
69
|
+
private readonly stripe: Stripe;
|
|
70
|
+
private readonly meterId: string;
|
|
71
|
+
|
|
72
|
+
constructor(deps: { stripe: Stripe; meterId: string }) {
|
|
73
|
+
this.stripe = deps.stripe;
|
|
74
|
+
this.meterId = deps.meterId;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private async sendMeterEvent({
|
|
78
|
+
stripeCustomerId,
|
|
79
|
+
organizationId,
|
|
80
|
+
eventName,
|
|
81
|
+
value,
|
|
82
|
+
timestamp,
|
|
83
|
+
identifier,
|
|
84
|
+
}: {
|
|
85
|
+
stripeCustomerId: string;
|
|
86
|
+
organizationId: string;
|
|
87
|
+
eventName: string;
|
|
88
|
+
value: number;
|
|
89
|
+
timestamp: number;
|
|
90
|
+
identifier: string;
|
|
91
|
+
}): Promise<MeterEventResult> {
|
|
92
|
+
try {
|
|
93
|
+
await this.stripe.billing.meterEvents.create({
|
|
94
|
+
event_name: eventName,
|
|
95
|
+
payload: {
|
|
96
|
+
stripe_customer_id: stripeCustomerId,
|
|
97
|
+
value: String(value),
|
|
98
|
+
},
|
|
99
|
+
identifier,
|
|
100
|
+
timestamp,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
logger.info(
|
|
104
|
+
{ organizationId, identifier, valueSent: value, reported: true },
|
|
105
|
+
"[billing] Meter event sent"
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
return { identifier, reported: true, valueSent: value };
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (isStripeInvalidRequestError(error)) {
|
|
111
|
+
if (error.code === "resource_already_exists") {
|
|
112
|
+
logger.info(
|
|
113
|
+
{ organizationId, identifier, valueSent: value, reported: true },
|
|
114
|
+
"[billing] Meter event already exists (duplicate identifier)"
|
|
115
|
+
);
|
|
116
|
+
return { identifier, reported: true, valueSent: value };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
logger.warn(
|
|
120
|
+
{
|
|
121
|
+
organizationId,
|
|
122
|
+
identifier,
|
|
123
|
+
valueSent: value,
|
|
124
|
+
reported: false,
|
|
125
|
+
error: error.message,
|
|
126
|
+
},
|
|
127
|
+
"[billing] Meter event rejected by Stripe"
|
|
128
|
+
);
|
|
129
|
+
return {
|
|
130
|
+
identifier,
|
|
131
|
+
reported: false,
|
|
132
|
+
valueSent: 0,
|
|
133
|
+
error: error.message,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (isStripeAuthenticationError(error)) {
|
|
138
|
+
logger.warn(
|
|
139
|
+
{
|
|
140
|
+
organizationId,
|
|
141
|
+
identifier,
|
|
142
|
+
valueSent: value,
|
|
143
|
+
reported: false,
|
|
144
|
+
error: error.message,
|
|
145
|
+
},
|
|
146
|
+
"[billing] Stripe authentication error"
|
|
147
|
+
);
|
|
148
|
+
return {
|
|
149
|
+
identifier,
|
|
150
|
+
reported: false,
|
|
151
|
+
valueSent: 0,
|
|
152
|
+
error: error.message,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Retryable errors: re-throw for BullMQ retry
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async reportUsageDelta(input: ReportUsageDeltaInput): Promise<MeterEventResult[]> {
|
|
162
|
+
const validated = reportUsageDeltaInputSchema.parse(input);
|
|
163
|
+
const results: MeterEventResult[] = [];
|
|
164
|
+
|
|
165
|
+
for (const event of validated.events) {
|
|
166
|
+
if (event.value <= 0) {
|
|
167
|
+
logger.info(
|
|
168
|
+
{
|
|
169
|
+
organizationId: validated.organizationId,
|
|
170
|
+
identifier: event.identifier,
|
|
171
|
+
valueSent: 0,
|
|
172
|
+
reported: false,
|
|
173
|
+
},
|
|
174
|
+
"[billing] Skipping zero-value meter event"
|
|
175
|
+
);
|
|
176
|
+
results.push({
|
|
177
|
+
identifier: event.identifier,
|
|
178
|
+
reported: false,
|
|
179
|
+
valueSent: 0,
|
|
180
|
+
});
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const result = await this.sendMeterEvent({
|
|
185
|
+
stripeCustomerId: validated.stripeCustomerId,
|
|
186
|
+
organizationId: validated.organizationId,
|
|
187
|
+
eventName: event.eventName,
|
|
188
|
+
value: event.value,
|
|
189
|
+
timestamp: event.timestamp,
|
|
190
|
+
identifier: event.identifier,
|
|
191
|
+
});
|
|
192
|
+
results.push(result);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return results;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async reportUsageSet(input: ReportUsageSetInput): Promise<MeterEventResult[]> {
|
|
199
|
+
const validated = reportUsageSetInputSchema.parse(input);
|
|
200
|
+
const results: MeterEventResult[] = [];
|
|
201
|
+
|
|
202
|
+
for (const event of validated.events) {
|
|
203
|
+
const delta = event.value - event.previouslyReportedValue;
|
|
204
|
+
|
|
205
|
+
if (delta <= 0) {
|
|
206
|
+
logger.info(
|
|
207
|
+
{
|
|
208
|
+
organizationId: validated.organizationId,
|
|
209
|
+
identifier: event.identifier,
|
|
210
|
+
valueSent: 0,
|
|
211
|
+
reported: false,
|
|
212
|
+
},
|
|
213
|
+
"[billing] Skipping non-positive delta meter event"
|
|
214
|
+
);
|
|
215
|
+
results.push({
|
|
216
|
+
identifier: event.identifier,
|
|
217
|
+
reported: false,
|
|
218
|
+
valueSent: 0,
|
|
219
|
+
});
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const result = await this.sendMeterEvent({
|
|
224
|
+
stripeCustomerId: validated.stripeCustomerId,
|
|
225
|
+
organizationId: validated.organizationId,
|
|
226
|
+
eventName: event.eventName,
|
|
227
|
+
value: delta,
|
|
228
|
+
timestamp: event.timestamp,
|
|
229
|
+
identifier: event.identifier,
|
|
230
|
+
});
|
|
231
|
+
results.push(result);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return results;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async getUsageSummary(input: GetUsageSummaryInput): Promise<UsageSummary> {
|
|
238
|
+
const validated = getUsageSummaryInputSchema.parse(input);
|
|
239
|
+
|
|
240
|
+
const response = await this.stripe.billing.meters.listEventSummaries(
|
|
241
|
+
this.meterId,
|
|
242
|
+
{
|
|
243
|
+
customer: validated.stripeCustomerId,
|
|
244
|
+
start_time: validated.startTime,
|
|
245
|
+
end_time: validated.endTime,
|
|
246
|
+
}
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
if (response.data.length === 0) {
|
|
250
|
+
logger.warn(
|
|
251
|
+
{
|
|
252
|
+
stripeCustomerId: validated.stripeCustomerId,
|
|
253
|
+
meterId: this.meterId,
|
|
254
|
+
startTime: validated.startTime,
|
|
255
|
+
endTime: validated.endTime,
|
|
256
|
+
},
|
|
257
|
+
"[billing] Empty usage summary from Stripe — could mean zero usage or misconfigured meter"
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
aggregatedValue: 0,
|
|
262
|
+
startTime: validated.startTime,
|
|
263
|
+
endTime: validated.endTime,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const aggregatedValue = response.data.reduce(
|
|
268
|
+
(sum, s) => sum + s.aggregated_value,
|
|
269
|
+
0,
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
logger.info(
|
|
273
|
+
{
|
|
274
|
+
stripeCustomerId: validated.stripeCustomerId,
|
|
275
|
+
meterId: this.meterId,
|
|
276
|
+
aggregatedValue,
|
|
277
|
+
startTime: validated.startTime,
|
|
278
|
+
endTime: validated.endTime,
|
|
279
|
+
},
|
|
280
|
+
"[billing] Usage summary retrieved"
|
|
281
|
+
);
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
aggregatedValue,
|
|
285
|
+
startTime: validated.startTime,
|
|
286
|
+
endTime: validated.endTime,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const isStripeInvalidRequestError = (
|
|
292
|
+
error: unknown
|
|
293
|
+
): error is Stripe.errors.StripeInvalidRequestError =>
|
|
294
|
+
error instanceof Error &&
|
|
295
|
+
(error as Stripe.errors.StripeError).type === "StripeInvalidRequestError";
|
|
296
|
+
|
|
297
|
+
const isStripeAuthenticationError = (
|
|
298
|
+
error: unknown
|
|
299
|
+
): error is Stripe.errors.StripeAuthenticationError =>
|
|
300
|
+
error instanceof Error &&
|
|
301
|
+
(error as Stripe.errors.StripeError).type === "StripeAuthenticationError";
|