* feat: redirect to new onboarding flow * Getting started * Brand details * Preview organization brands * Orgs team pages * Invite team steps * Move to global zustand store * Few darkmdoe fixes * Wip onboarding + stripe flow * Default plan state Server Action for gettting slug satus of org * Remove onboardingId * Confirmation prompt * Update old onboarding flow handlers to handle new fields * update onboarding hook * Filter out organization section for none -company emails * Match placeholders to users domain * Drop migration * Wip new onboarding intent * WIP flow for self-hosted. Same service call just split logic * WIP * Add TODO * Use onboarding user type instead of trpc session * WIP * WIP * pass role and team name from onboarding to save in schema * Add test to ensure role + name + team are persisted into onboarding table * migrate roles to enum values * Update ENUM * Fix type error * Redirect if flag is disabled * Remove web * WIP * WIP * Fix migration * Fix calls * User onboarding User types instead of trpc session * Fix factory tests * Fix flow for self hoste * Type error * More type fixes * Fix handler tests * Fix enum return type being different * Use consistant types across the oganization stuff * Fix * Use TEAM_BILLING for e2e test * Refactor is not company email and add tests * Fix * Fix * Refactor flow to submit after form complete * Fix flow with billing disabled * Fix tests * Apply suggestion from @coderabbitai[bot] Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Rename and move test files * WIP * Fix types * Update repo paths + tests * Move to service folder * Fix tests * Fix types * Remove old test files * Restore lock * Fix path * Fix tests with new paths and factory logic * Fix updaetdAt * WIP onboardingID isolation * Fix e2e test * verify test * Code rabbit * Rename SelfHostedOnboardongService -> SelfHostedOrganizationOnboardingService * Fix stores * Fix type error * Fix types * remove tsignore * Apply suggestion from @coderabbitai[bot] Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * NITS * Add the logic to auto complete admin org when billing enabled * Fix store being weird * We need to return the parsed value * fixes * sync from db always * Add onboardingSgtore tests * fix test * remove step and status --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
158 lines
5.6 KiB
TypeScript
158 lines
5.6 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/IBillingRepository";
|
|
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billing-service";
|
|
import { InternalTeamBilling } from "@calcom/features/ee/billing/teams/internal-team-billing";
|
|
import { BillingEnabledOrgOnboardingService } from "@calcom/features/ee/organizations/lib/service/onboarding/BillingEnabledOrgOnboardingService";
|
|
import stripe from "@calcom/features/ee/payments/server/stripe";
|
|
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
|
import logger from "@calcom/lib/logger";
|
|
import { safeStringify } from "@calcom/lib/safeStringify";
|
|
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
|
|
import { prisma } from "@calcom/prisma";
|
|
|
|
import type { SWHMap } from "./__handler";
|
|
|
|
const invoicePaidSchema = z.object({
|
|
object: z.object({
|
|
customer: z.string(),
|
|
subscription: z.string(),
|
|
lines: z.object({
|
|
data: z.array(
|
|
z.object({
|
|
subscription_item: z.string(),
|
|
})
|
|
),
|
|
}),
|
|
}),
|
|
});
|
|
|
|
async function handlePaymentReceivedForOnboarding({
|
|
organizationOnboarding,
|
|
paymentSubscriptionId,
|
|
paymentSubscriptionItemId,
|
|
}: {
|
|
organizationOnboarding: { id: string };
|
|
paymentSubscriptionId: string;
|
|
paymentSubscriptionItemId: string;
|
|
}) {
|
|
await OrganizationOnboardingRepository.update(organizationOnboarding.id, {
|
|
stripeSubscriptionId: paymentSubscriptionId,
|
|
stripeSubscriptionItemId: paymentSubscriptionItemId,
|
|
});
|
|
}
|
|
|
|
const handler = async (data: SWHMap["invoice.paid"]["data"]) => {
|
|
const { object: invoice } = invoicePaidSchema.parse(data);
|
|
const subscriptionItemId = invoice.lines.data[0]?.subscription_item;
|
|
const subscriptionId = invoice.subscription;
|
|
logger.debug(
|
|
`Processing invoice paid webhook for customer ${invoice.customer} and subscription ${invoice.subscription}`
|
|
);
|
|
|
|
const organizationOnboarding = await OrganizationOnboardingRepository.findByStripeCustomerId(
|
|
invoice.customer
|
|
);
|
|
|
|
if (!organizationOnboarding) {
|
|
// Invoice Paid is received for all organizations, even those that were created before Organization Onboarding was introduced.
|
|
logger.info(
|
|
`No onboarding record found for stripe customer id: ${invoice.customer}, Organization created before Organization Onboarding was introduced, so ignoring the webhook`
|
|
);
|
|
|
|
return {
|
|
success: true,
|
|
};
|
|
}
|
|
|
|
const paymentSubscriptionId = subscriptionId;
|
|
const paymentSubscriptionItemId = subscriptionItemId;
|
|
|
|
await handlePaymentReceivedForOnboarding({
|
|
organizationOnboarding,
|
|
paymentSubscriptionId,
|
|
paymentSubscriptionItemId,
|
|
});
|
|
|
|
try {
|
|
logger.info(
|
|
safeStringify({
|
|
orgId: organizationOnboarding.organizationId,
|
|
orgSlug: organizationOnboarding.slug,
|
|
isDomainConfigured: organizationOnboarding.isDomainConfigured,
|
|
createdAt: organizationOnboarding.createdAt,
|
|
stripeSubscriptionId: organizationOnboarding.stripeSubscriptionId,
|
|
})
|
|
);
|
|
|
|
if (organizationOnboarding.isComplete) {
|
|
// If the organization is already complete, there is nothing to do
|
|
// Repeat requests can come for recurring payments
|
|
return {
|
|
success: true,
|
|
message: "Onboarding already completed, skipping",
|
|
};
|
|
}
|
|
|
|
// Get the user who created the onboarding (for service instantiation)
|
|
const userRepo = new UserRepository(prisma);
|
|
const creator = organizationOnboarding.createdById
|
|
? await userRepo.findById({ id: organizationOnboarding.createdById })
|
|
: null;
|
|
|
|
// Create a minimal user context for the service
|
|
// If no creator, use a system user context (webhook is system-initiated)
|
|
const userContext = creator
|
|
? {
|
|
id: creator.id,
|
|
email: creator.email,
|
|
role: "ADMIN" as const,
|
|
name: creator.name || undefined,
|
|
}
|
|
: {
|
|
id: 0, // System user
|
|
email: organizationOnboarding.orgOwnerEmail,
|
|
role: "ADMIN" as const,
|
|
};
|
|
|
|
const onboardingService = new BillingEnabledOrgOnboardingService(userContext);
|
|
const { organization } = await onboardingService.createOrganization(organizationOnboarding, {
|
|
subscriptionId: paymentSubscriptionId,
|
|
subscriptionItemId: paymentSubscriptionItemId,
|
|
});
|
|
|
|
// Get the Stripe subscription object
|
|
const stripeSubscription = await stripe.subscriptions.retrieve(paymentSubscriptionId);
|
|
const { subscriptionStart } = StripeBillingService.extractSubscriptionDates(stripeSubscription);
|
|
|
|
const internalTeamBillingService = new InternalTeamBilling(organization);
|
|
await internalTeamBillingService.saveTeamBilling({
|
|
teamId: organization.id,
|
|
subscriptionId: paymentSubscriptionId,
|
|
subscriptionItemId: paymentSubscriptionItemId,
|
|
customerId: invoice.customer,
|
|
// TODO: Write actual status when webhook events are added
|
|
status: SubscriptionStatus.ACTIVE,
|
|
planName: Plan.ORGANIZATION,
|
|
subscriptionStart,
|
|
});
|
|
|
|
logger.debug(`Marking onboarding as complete for organization ${organization.id}`);
|
|
await OrganizationOnboardingRepository.markAsComplete(organizationOnboarding.id);
|
|
return { success: true };
|
|
} catch (error) {
|
|
if (error instanceof Error) {
|
|
await OrganizationOnboardingRepository.update(organizationOnboarding.id, {
|
|
error: error.message,
|
|
});
|
|
}
|
|
logger.error(
|
|
`Error creating organization from onboarding:${organizationOnboarding.id}`,
|
|
safeStringify({ error: error instanceof Error ? error.message : error })
|
|
);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export default handler;
|