@langwatch/server 3.1.0-beta.3 → 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/langwatch_nlp/uv.lock +179 -5
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +192 -142
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { PrismaClient } from "@prisma/client";
|
|
2
|
+
import type Stripe from "stripe";
|
|
3
|
+
import { createLogger } from "../../../src/utils/logger";
|
|
4
|
+
import {
|
|
5
|
+
CustomerCreationRaceError,
|
|
6
|
+
OrganizationNotFoundError,
|
|
7
|
+
UserEmailRequiredError,
|
|
8
|
+
} from "../errors";
|
|
9
|
+
|
|
10
|
+
const logger = createLogger("langwatch:billing:customerService");
|
|
11
|
+
|
|
12
|
+
const maskCustomerId = (id: string) => `${id.slice(0, 7)}...${id.slice(-4)}`;
|
|
13
|
+
|
|
14
|
+
export type CustomerService = {
|
|
15
|
+
getOrCreateCustomerId(params: {
|
|
16
|
+
user: { email?: string | null };
|
|
17
|
+
organizationId: string;
|
|
18
|
+
}): Promise<string>;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const createCustomerService = ({
|
|
22
|
+
stripe,
|
|
23
|
+
db,
|
|
24
|
+
}: {
|
|
25
|
+
stripe: Stripe;
|
|
26
|
+
db: PrismaClient;
|
|
27
|
+
}): CustomerService => {
|
|
28
|
+
return {
|
|
29
|
+
async getOrCreateCustomerId({ user, organizationId }) {
|
|
30
|
+
const organization = await db.organization.findUnique({
|
|
31
|
+
where: { id: organizationId },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!organization) {
|
|
35
|
+
throw new OrganizationNotFoundError();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (organization.stripeCustomerId) {
|
|
39
|
+
return organization.stripeCustomerId;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!user.email) {
|
|
43
|
+
throw new UserEmailRequiredError();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const customer = await stripe.customers.create({
|
|
47
|
+
email: user.email,
|
|
48
|
+
name: organization.name,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const updated = await db.organization.updateMany({
|
|
52
|
+
where: { id: organizationId, stripeCustomerId: null },
|
|
53
|
+
data: { stripeCustomerId: customer.id },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (updated.count === 0) {
|
|
57
|
+
// Another request won the race — clean up orphan and use existing
|
|
58
|
+
logger.warn(
|
|
59
|
+
{
|
|
60
|
+
organizationId,
|
|
61
|
+
orphanedCustomerId: maskCustomerId(customer.id),
|
|
62
|
+
},
|
|
63
|
+
"[billing] Stripe customer race detected, cleaning up orphan",
|
|
64
|
+
);
|
|
65
|
+
try {
|
|
66
|
+
await stripe.customers.del(customer.id);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
logger.warn(
|
|
69
|
+
{
|
|
70
|
+
organizationId,
|
|
71
|
+
orphanedCustomerId: maskCustomerId(customer.id),
|
|
72
|
+
error: (error as Error).message,
|
|
73
|
+
},
|
|
74
|
+
"[billing] Failed to clean up orphaned Stripe customer",
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const refreshed = await db.organization.findUniqueOrThrow({
|
|
79
|
+
where: { id: organizationId },
|
|
80
|
+
});
|
|
81
|
+
if (!refreshed.stripeCustomerId) {
|
|
82
|
+
throw new CustomerCreationRaceError();
|
|
83
|
+
}
|
|
84
|
+
return refreshed.stripeCustomerId;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return customer.id;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { generateLicenseKey } from "../../licensing/licenseGenerationService";
|
|
3
|
+
import { sendLicenseEmail } from "../../../src/server/mailer/licenseEmail";
|
|
4
|
+
import { getApp } from "../../../src/server/app-layer/app";
|
|
5
|
+
import { createLogger } from "../../../src/utils/logger";
|
|
6
|
+
|
|
7
|
+
const logger = createLogger("langwatch:billing:licensePurchaseHandler");
|
|
8
|
+
|
|
9
|
+
interface HandleLicensePurchaseParams {
|
|
10
|
+
checkoutSession: Stripe.Checkout.Session;
|
|
11
|
+
stripe: Stripe;
|
|
12
|
+
privateKey: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function handleLicensePurchase({
|
|
16
|
+
checkoutSession,
|
|
17
|
+
stripe,
|
|
18
|
+
privateKey,
|
|
19
|
+
}: HandleLicensePurchaseParams): Promise<void> {
|
|
20
|
+
const email = checkoutSession.customer_details?.email;
|
|
21
|
+
if (!email) {
|
|
22
|
+
throw new Error("No email found in checkout session customer_details");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const businessName = checkoutSession.customer_details?.name ?? "";
|
|
26
|
+
|
|
27
|
+
// Line items are not included in the webhook payload — must fetch separately
|
|
28
|
+
const lineItems = await stripe.checkout.sessions.listLineItems(
|
|
29
|
+
checkoutSession.id,
|
|
30
|
+
);
|
|
31
|
+
const quantity = lineItems.data[0]?.quantity ?? 1;
|
|
32
|
+
|
|
33
|
+
const { licenseKey, licenseData } = generateLicenseKey({
|
|
34
|
+
organizationName: businessName,
|
|
35
|
+
email,
|
|
36
|
+
planType: "GROWTH",
|
|
37
|
+
maxMembers: quantity,
|
|
38
|
+
privateKey,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
logger.info(
|
|
42
|
+
{
|
|
43
|
+
licenseId: licenseData.licenseId,
|
|
44
|
+
email,
|
|
45
|
+
seats: quantity,
|
|
46
|
+
expiresAt: licenseData.expiresAt,
|
|
47
|
+
},
|
|
48
|
+
"[licensePurchaseHandler] License generated",
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
await sendLicenseEmail({
|
|
52
|
+
email,
|
|
53
|
+
licenseKey,
|
|
54
|
+
planType: licenseData.plan.type,
|
|
55
|
+
maxMembers: quantity,
|
|
56
|
+
expiresAt: licenseData.expiresAt,
|
|
57
|
+
organizationName: licenseData.organizationName,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
logger.info(
|
|
61
|
+
{ email, licenseId: licenseData.licenseId },
|
|
62
|
+
"[licensePurchaseHandler] License email sent",
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
// Slack notification -- fire and forget, errors swallowed by NotificationService
|
|
66
|
+
await getApp().notifications.sendSlackLicensePurchase({
|
|
67
|
+
buyerEmail: email,
|
|
68
|
+
planType: licenseData.plan.type,
|
|
69
|
+
seats: quantity,
|
|
70
|
+
amountPaid: checkoutSession.amount_total ?? 0,
|
|
71
|
+
currency: checkoutSession.currency ?? "usd",
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { Currency, type OrganizationUserRole, type PrismaClient } from "@prisma/client";
|
|
2
|
+
import { nanoid } from "nanoid";
|
|
3
|
+
import type Stripe from "stripe";
|
|
4
|
+
import { SubscriptionStatus } from "../planTypes";
|
|
5
|
+
import {
|
|
6
|
+
createCheckoutLineItems,
|
|
7
|
+
GROWTH_SEAT_PLAN_TYPES,
|
|
8
|
+
isGrowthSeatPrice,
|
|
9
|
+
resolveGrowthSeatPlanType,
|
|
10
|
+
} from "../utils/growthSeatEvent";
|
|
11
|
+
import {
|
|
12
|
+
NoActiveSubscriptionError,
|
|
13
|
+
SubscriptionItemNotFoundError,
|
|
14
|
+
} from "../errors";
|
|
15
|
+
import type { BillingInterval } from "../utils/growthSeatEvent";
|
|
16
|
+
|
|
17
|
+
type InviteInput = {
|
|
18
|
+
email: string;
|
|
19
|
+
role: OrganizationUserRole;
|
|
20
|
+
teamIds: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type SeatEventSubscriptionFns = ReturnType<
|
|
24
|
+
typeof createSeatEventSubscriptionFns
|
|
25
|
+
>;
|
|
26
|
+
|
|
27
|
+
export const createSeatEventSubscriptionFns = ({
|
|
28
|
+
stripe,
|
|
29
|
+
db,
|
|
30
|
+
}: {
|
|
31
|
+
stripe: Stripe;
|
|
32
|
+
db: PrismaClient;
|
|
33
|
+
}) => ({
|
|
34
|
+
async createSeatEventCheckout({
|
|
35
|
+
organizationId,
|
|
36
|
+
customerId,
|
|
37
|
+
baseUrl,
|
|
38
|
+
currency,
|
|
39
|
+
billingInterval,
|
|
40
|
+
membersToAdd,
|
|
41
|
+
isUpgradeFromTiered = false,
|
|
42
|
+
invites,
|
|
43
|
+
}: {
|
|
44
|
+
organizationId: string;
|
|
45
|
+
customerId: string;
|
|
46
|
+
baseUrl: string;
|
|
47
|
+
currency: Currency;
|
|
48
|
+
billingInterval: BillingInterval;
|
|
49
|
+
membersToAdd: number;
|
|
50
|
+
isUpgradeFromTiered?: boolean;
|
|
51
|
+
invites?: InviteInput[];
|
|
52
|
+
}) {
|
|
53
|
+
// Find stale PENDING subs so we can clean up their PAYMENT_PENDING invites too
|
|
54
|
+
const staleSubs = await db.subscription.findMany({
|
|
55
|
+
where: {
|
|
56
|
+
organizationId,
|
|
57
|
+
plan: { in: [...GROWTH_SEAT_PLAN_TYPES] },
|
|
58
|
+
status: SubscriptionStatus.PENDING,
|
|
59
|
+
},
|
|
60
|
+
select: { id: true },
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const staleSubIds = staleSubs.map((s) => s.id);
|
|
64
|
+
|
|
65
|
+
// Cancel stale PENDING subs from abandoned checkouts
|
|
66
|
+
await db.subscription.updateMany({
|
|
67
|
+
where: {
|
|
68
|
+
organizationId,
|
|
69
|
+
plan: { in: [...GROWTH_SEAT_PLAN_TYPES] },
|
|
70
|
+
status: SubscriptionStatus.PENDING,
|
|
71
|
+
},
|
|
72
|
+
data: {
|
|
73
|
+
status: SubscriptionStatus.CANCELLED,
|
|
74
|
+
endDate: new Date(),
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// Clean up orphaned PAYMENT_PENDING invites from stale subs
|
|
79
|
+
if (staleSubIds.length > 0) {
|
|
80
|
+
await db.organizationInvite.deleteMany({
|
|
81
|
+
where: {
|
|
82
|
+
organizationId,
|
|
83
|
+
status: "PAYMENT_PENDING",
|
|
84
|
+
subscriptionId: { in: staleSubIds },
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Build line items BEFORE persisting anything so a validation failure
|
|
90
|
+
// doesn't leave orphaned pending records in the database.
|
|
91
|
+
const lineItems = createCheckoutLineItems({
|
|
92
|
+
coreMembers: membersToAdd,
|
|
93
|
+
currency,
|
|
94
|
+
interval: billingInterval,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// Create subscription + invites in a transaction
|
|
98
|
+
const subscription = await db.$transaction(async (tx) => {
|
|
99
|
+
const sub = await tx.subscription.create({
|
|
100
|
+
data: {
|
|
101
|
+
organizationId,
|
|
102
|
+
status: SubscriptionStatus.PENDING,
|
|
103
|
+
plan: resolveGrowthSeatPlanType({ currency, interval: billingInterval }),
|
|
104
|
+
maxMembers: membersToAdd,
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
if (invites && invites.length > 0) {
|
|
109
|
+
for (const invite of invites) {
|
|
110
|
+
// Skip duplicates (existing PENDING or PAYMENT_PENDING invites)
|
|
111
|
+
const existing = await tx.organizationInvite.findFirst({
|
|
112
|
+
where: {
|
|
113
|
+
email: invite.email,
|
|
114
|
+
organizationId,
|
|
115
|
+
status: { in: ["PENDING", "PAYMENT_PENDING"] },
|
|
116
|
+
OR: [{ expiration: { gt: new Date() } }, { expiration: null }],
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (existing) continue;
|
|
121
|
+
|
|
122
|
+
await tx.organizationInvite.create({
|
|
123
|
+
data: {
|
|
124
|
+
email: invite.email,
|
|
125
|
+
inviteCode: nanoid(),
|
|
126
|
+
expiration: null,
|
|
127
|
+
organizationId,
|
|
128
|
+
teamIds: invite.teamIds,
|
|
129
|
+
role: invite.role,
|
|
130
|
+
status: "PAYMENT_PENDING",
|
|
131
|
+
subscriptionId: sub.id,
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return sub;
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const selectedOptionsMetadata = {
|
|
141
|
+
selectedCurrency: currency,
|
|
142
|
+
selectedBillingInterval: billingInterval,
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// Anchor billing cycle to the 1st of next month for all plans.
|
|
146
|
+
// Customer pays prorated amount for the partial period (checkout → anchor),
|
|
147
|
+
// then full price (monthly or annual) starting on the 1st.
|
|
148
|
+
const now = new Date();
|
|
149
|
+
const billingCycleAnchor = new Date(
|
|
150
|
+
Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1),
|
|
151
|
+
);
|
|
152
|
+
const subscriptionData: Stripe.Checkout.SessionCreateParams["subscription_data"] =
|
|
153
|
+
{
|
|
154
|
+
metadata: selectedOptionsMetadata,
|
|
155
|
+
billing_cycle_anchor: Math.floor(
|
|
156
|
+
billingCycleAnchor.getTime() / 1000,
|
|
157
|
+
),
|
|
158
|
+
proration_behavior:
|
|
159
|
+
"create_prorations" as Stripe.Checkout.SessionCreateParams.SubscriptionData.ProrationBehavior,
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const session = await stripe.checkout.sessions.create({
|
|
163
|
+
mode: "subscription",
|
|
164
|
+
currency: currency.toLowerCase(),
|
|
165
|
+
...({ adaptive_pricing: { enabled: false } } as Record<string, unknown>),
|
|
166
|
+
customer: customerId,
|
|
167
|
+
customer_update: {
|
|
168
|
+
address: "auto",
|
|
169
|
+
name: "auto",
|
|
170
|
+
},
|
|
171
|
+
automatic_tax: { enabled: true },
|
|
172
|
+
billing_address_collection: "required",
|
|
173
|
+
tax_id_collection: { enabled: true },
|
|
174
|
+
line_items: lineItems,
|
|
175
|
+
metadata: selectedOptionsMetadata,
|
|
176
|
+
subscription_data: subscriptionData,
|
|
177
|
+
success_url: `${baseUrl}/settings/subscription?success${isUpgradeFromTiered ? "&upgraded_from=tiered" : ""}`,
|
|
178
|
+
cancel_url: `${baseUrl}/settings/subscription`,
|
|
179
|
+
client_reference_id: `subscription_setup_${subscription.id}`,
|
|
180
|
+
allow_promotion_codes: true,
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
return { url: session.url };
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
async updateSeatEventItems({
|
|
187
|
+
organizationId,
|
|
188
|
+
totalMembers,
|
|
189
|
+
}: {
|
|
190
|
+
organizationId: string;
|
|
191
|
+
totalMembers: number;
|
|
192
|
+
}) {
|
|
193
|
+
// Find the most recent subscription with a Stripe ID (ACTIVE or CANCELLED-but-still-active-in-Stripe)
|
|
194
|
+
const lastSubscription = await db.subscription.findFirst({
|
|
195
|
+
where: {
|
|
196
|
+
organizationId,
|
|
197
|
+
status: { in: [SubscriptionStatus.ACTIVE, SubscriptionStatus.CANCELLED] },
|
|
198
|
+
stripeSubscriptionId: { not: null },
|
|
199
|
+
},
|
|
200
|
+
orderBy: { createdAt: "desc" },
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
if (!lastSubscription?.stripeSubscriptionId) {
|
|
204
|
+
return { success: false };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const stripeSubscription = await stripe.subscriptions.retrieve(
|
|
208
|
+
lastSubscription.stripeSubscriptionId,
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
// Stripe sub must still be active (even if scheduled for cancellation)
|
|
212
|
+
if (stripeSubscription.status !== "active") {
|
|
213
|
+
return { success: false };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const seatItem = stripeSubscription.items.data.find((item) =>
|
|
217
|
+
isGrowthSeatPrice(item.price.id),
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
if (!seatItem) {
|
|
221
|
+
return { success: false };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Update seats (and reactivate if scheduled for cancellation — the user
|
|
225
|
+
// is choosing to keep their subscription by updating seats).
|
|
226
|
+
await stripe.subscriptions.update(lastSubscription.stripeSubscriptionId, {
|
|
227
|
+
...(stripeSubscription.canceled_at
|
|
228
|
+
? { cancel_at_period_end: false }
|
|
229
|
+
: {}),
|
|
230
|
+
items: [{ id: seatItem.id, quantity: totalMembers }],
|
|
231
|
+
proration_behavior: "always_invoice",
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// Restore DB record to ACTIVE with updated seat count
|
|
235
|
+
await db.subscription.update({
|
|
236
|
+
where: { id: lastSubscription.id },
|
|
237
|
+
data: {
|
|
238
|
+
status: SubscriptionStatus.ACTIVE,
|
|
239
|
+
maxMembers: totalMembers,
|
|
240
|
+
endDate: null,
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
return { success: true };
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
async previewProration({
|
|
248
|
+
organizationId,
|
|
249
|
+
newTotalSeats,
|
|
250
|
+
}: {
|
|
251
|
+
organizationId: string;
|
|
252
|
+
newTotalSeats: number;
|
|
253
|
+
}) {
|
|
254
|
+
// Find the most recent subscription with a Stripe ID (ACTIVE or CANCELLED-but-still-active-in-Stripe)
|
|
255
|
+
const lastSubscription = await db.subscription.findFirst({
|
|
256
|
+
where: {
|
|
257
|
+
organizationId,
|
|
258
|
+
status: { in: [SubscriptionStatus.ACTIVE, SubscriptionStatus.CANCELLED] },
|
|
259
|
+
stripeSubscriptionId: { not: null },
|
|
260
|
+
},
|
|
261
|
+
orderBy: { createdAt: "desc" },
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
if (!lastSubscription?.stripeSubscriptionId) {
|
|
265
|
+
throw new NoActiveSubscriptionError();
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const stripeSubscription = await stripe.subscriptions.retrieve(
|
|
269
|
+
lastSubscription.stripeSubscriptionId,
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
// Guard: Stripe sub must still be active (even if scheduled for cancellation)
|
|
273
|
+
if (stripeSubscription.status !== "active") {
|
|
274
|
+
throw new NoActiveSubscriptionError();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const seatItem = stripeSubscription.items.data.find((item) =>
|
|
278
|
+
isGrowthSeatPrice(item.price.id),
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
if (!seatItem) {
|
|
282
|
+
throw new SubscriptionItemNotFoundError("seat");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Fetch upcoming invoice WITH the proposed seat change
|
|
286
|
+
const upcomingWithChange = await stripe.invoices.retrieveUpcoming({
|
|
287
|
+
subscription: lastSubscription.stripeSubscriptionId,
|
|
288
|
+
subscription_items: [
|
|
289
|
+
{ id: seatItem.id, quantity: newTotalSeats },
|
|
290
|
+
],
|
|
291
|
+
subscription_proration_behavior: "create_prorations",
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
// Fetch current upcoming invoice WITHOUT changes to isolate pre-existing
|
|
295
|
+
// prorations (e.g. from mid-month signup with billing_cycle_anchor)
|
|
296
|
+
const upcomingCurrent = await stripe.invoices.retrieveUpcoming({
|
|
297
|
+
subscription: lastSubscription.stripeSubscriptionId,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
const currency = (upcomingWithChange.currency?.toUpperCase() ?? Currency.USD) as Currency;
|
|
301
|
+
const billingInterval = seatItem.price.recurring?.interval ?? "month";
|
|
302
|
+
|
|
303
|
+
// Subtract existing prorations from changed prorations to get ONLY
|
|
304
|
+
// the incremental cost of adding/removing seats.
|
|
305
|
+
const sumProrations = (lines: { proration: boolean; amount: number }[]) => {
|
|
306
|
+
let total = 0;
|
|
307
|
+
for (const line of lines) {
|
|
308
|
+
if (line.proration) total += line.amount;
|
|
309
|
+
}
|
|
310
|
+
return total;
|
|
311
|
+
};
|
|
312
|
+
const prorationCents =
|
|
313
|
+
sumProrations(upcomingWithChange.lines.data) -
|
|
314
|
+
sumProrations(upcomingCurrent.lines.data);
|
|
315
|
+
|
|
316
|
+
// Recurring total: new seat count × per-seat price
|
|
317
|
+
const unitAmountCents = seatItem.price.unit_amount ?? 0;
|
|
318
|
+
const recurringTotalCents = newTotalSeats * unitAmountCents;
|
|
319
|
+
|
|
320
|
+
const format = (cents: number) => {
|
|
321
|
+
const amount = cents / 100;
|
|
322
|
+
return new Intl.NumberFormat(currency === Currency.EUR ? "en-IE" : "en-US", {
|
|
323
|
+
style: "currency",
|
|
324
|
+
currency,
|
|
325
|
+
minimumFractionDigits: Number.isInteger(amount) ? 0 : 2,
|
|
326
|
+
maximumFractionDigits: 2,
|
|
327
|
+
}).format(amount);
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
formattedAmountDue: format(prorationCents),
|
|
332
|
+
formattedRecurringTotal: format(recurringTotalCents),
|
|
333
|
+
billingInterval,
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
|
|
337
|
+
async seatEventBillingPortalUrl({
|
|
338
|
+
customerId,
|
|
339
|
+
baseUrl,
|
|
340
|
+
}: {
|
|
341
|
+
customerId: string;
|
|
342
|
+
baseUrl: string;
|
|
343
|
+
}) {
|
|
344
|
+
const session = await stripe.billingPortal.sessions.create({
|
|
345
|
+
customer: customerId,
|
|
346
|
+
return_url: `${baseUrl}/settings/subscription`,
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
return { url: session.url };
|
|
350
|
+
},
|
|
351
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { PricingModel, type PrismaClient } from "@prisma/client";
|
|
2
|
+
import type { SeatEventSubscriptionFns } from "./seatEventSubscription";
|
|
3
|
+
|
|
4
|
+
export const createSeatSyncService = ({
|
|
5
|
+
seatEventFns,
|
|
6
|
+
db,
|
|
7
|
+
}: {
|
|
8
|
+
seatEventFns: SeatEventSubscriptionFns;
|
|
9
|
+
db: PrismaClient;
|
|
10
|
+
}) => ({
|
|
11
|
+
async syncSeatsToStripe({
|
|
12
|
+
organizationId,
|
|
13
|
+
newTotalSeats,
|
|
14
|
+
}: {
|
|
15
|
+
organizationId: string;
|
|
16
|
+
newTotalSeats: number;
|
|
17
|
+
}): Promise<boolean> {
|
|
18
|
+
const org = await db.organization.findUnique({
|
|
19
|
+
where: { id: organizationId },
|
|
20
|
+
select: { pricingModel: true },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (org?.pricingModel !== PricingModel.SEAT_EVENT) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const result = await seatEventFns.updateSeatEventItems({
|
|
28
|
+
organizationId,
|
|
29
|
+
totalMembers: newTotalSeats,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
return result.success;
|
|
33
|
+
},
|
|
34
|
+
});
|