* Init billing tables * Create `IBillingRepository` types * Create billing repositories * Create billingRepositoryFactory * Eslint fix - remove unused organizationOnboarding * internal-team-billing create saveTeamBilling method using repositories * On new teams write to team billing table * On new org write to org billing table * Change fields to organizationId * Add todo comment * Revert "Change fields to organizationId" This reverts commit bbb2e5dfa6b4c20a8a395f5730848a492cd70d68. * test: add comprehensive tests for team billing tables - Fix credit-service.test.ts Prisma mock to export prisma object - Replace any types with proper TypeScript types in credit-service.test.ts - Add unit tests for PrismaTeamBillingRepository covering record creation, enum casting, and error handling - Add unit tests for PrismaOrganizationBillingRepository with same coverage - Add unit tests for BillingRepositoryFactory to verify correct repository selection - Add unit tests for InternalTeamBilling.saveTeamBilling() method testing delegation to correct repositories - All 53 tests pass with TZ=UTC yarn test - Type checking passes with yarn type-check:ci --force Co-Authored-By: [email protected] <[email protected]> * refactor: update saveTeamBilling tests to mock repository interface - Replace prismaMock usage with BillingRepositoryFactory mock - Mock IBillingRepository interface instead of Prisma directly - Follow repository mocking pattern from handleResponse.test.ts - All tests passing (53 total) Co-Authored-By: [email protected] <[email protected]> * Remove log statement * Remove repository tests * Address feedback --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
128 lines
4.2 KiB
TypeScript
128 lines
4.2 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import { Plan, SubscriptionStatus } from "@calcom/features/ee/billing/repository/IBillingRepository";
|
|
import { InternalTeamBilling } from "@calcom/features/ee/billing/teams/internal-team-billing";
|
|
import { createOrganizationFromOnboarding } from "@calcom/features/ee/organizations/lib/server/createOrganizationFromOnboarding";
|
|
import logger from "@calcom/lib/logger";
|
|
import { safeStringify } from "@calcom/lib/safeStringify";
|
|
import { OrganizationOnboardingRepository } from "@calcom/lib/server/repository/organizationOnboarding";
|
|
|
|
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",
|
|
};
|
|
}
|
|
|
|
const { organization } = await createOrganizationFromOnboarding({
|
|
organizationOnboarding,
|
|
paymentSubscriptionId,
|
|
paymentSubscriptionItemId,
|
|
});
|
|
|
|
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,
|
|
});
|
|
|
|
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;
|