5748 Create contacts for emails sent and received by email aliases (#5855)
Closes #5748 - Create feature flag - Add scope `https://www.googleapis.com/auth/profile.emails.read` when connecting an account - Get email aliases with google people API, store them in connectedAccount and refresh them before each message-import - Update the contact creation logic accordingly - Refactor --------- Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
@ -11,9 +11,9 @@ import {
|
||||
import { Response } from 'express';
|
||||
|
||||
import {
|
||||
BillingService,
|
||||
BillingWorkspaceService,
|
||||
WebhookEvent,
|
||||
} from 'src/engine/core-modules/billing/billing.service';
|
||||
} from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
import { StripeService } from 'src/engine/core-modules/billing/stripe/stripe.service';
|
||||
|
||||
@Controller('billing')
|
||||
@ -22,7 +22,7 @@ export class BillingController {
|
||||
|
||||
constructor(
|
||||
private readonly stripeService: StripeService,
|
||||
private readonly billingService: BillingService,
|
||||
private readonly billingWorkspaceService: BillingWorkspaceService,
|
||||
) {}
|
||||
|
||||
@Post('/webhooks')
|
||||
@ -42,7 +42,7 @@ export class BillingController {
|
||||
);
|
||||
|
||||
if (event.type === WebhookEvent.SETUP_INTENT_SUCCEEDED) {
|
||||
await this.billingService.handleUnpaidInvoices(event.data);
|
||||
await this.billingWorkspaceService.handleUnpaidInvoices(event.data);
|
||||
}
|
||||
|
||||
if (
|
||||
@ -58,7 +58,7 @@ export class BillingController {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.billingService.upsertBillingSubscription(
|
||||
await this.billingWorkspaceService.upsertBillingSubscription(
|
||||
workspaceId,
|
||||
event.data,
|
||||
);
|
||||
|
||||
@ -11,6 +11,7 @@ import { BillingResolver } from 'src/engine/core-modules/billing/billing.resolve
|
||||
import { BillingWorkspaceMemberListener } from 'src/engine/core-modules/billing/listeners/billing-workspace-member.listener';
|
||||
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
|
||||
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
|
||||
import { BillingWorkspaceService } from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -27,7 +28,12 @@ import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-
|
||||
),
|
||||
],
|
||||
controllers: [BillingController],
|
||||
providers: [BillingService, BillingResolver, BillingWorkspaceMemberListener],
|
||||
exports: [BillingService],
|
||||
providers: [
|
||||
BillingService,
|
||||
BillingWorkspaceService,
|
||||
BillingResolver,
|
||||
BillingWorkspaceMemberListener,
|
||||
],
|
||||
exports: [BillingService, BillingWorkspaceService],
|
||||
})
|
||||
export class BillingModule {}
|
||||
|
||||
@ -3,8 +3,8 @@ import { UseGuards } from '@nestjs/common';
|
||||
|
||||
import {
|
||||
AvailableProduct,
|
||||
BillingService,
|
||||
} from 'src/engine/core-modules/billing/billing.service';
|
||||
BillingWorkspaceService,
|
||||
} from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
import { ProductInput } from 'src/engine/core-modules/billing/dto/product.input';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { ProductPricesEntity } from 'src/engine/core-modules/billing/dto/product-prices.entity';
|
||||
@ -18,11 +18,14 @@ import { UpdateBillingEntity } from 'src/engine/core-modules/billing/dto/update-
|
||||
|
||||
@Resolver()
|
||||
export class BillingResolver {
|
||||
constructor(private readonly billingService: BillingService) {}
|
||||
constructor(
|
||||
private readonly billingWorkspaceService: BillingWorkspaceService,
|
||||
) {}
|
||||
|
||||
@Query(() => ProductPricesEntity)
|
||||
async getProductPrices(@Args() { product }: ProductInput) {
|
||||
const stripeProductId = this.billingService.getProductStripeId(product);
|
||||
const stripeProductId =
|
||||
this.billingWorkspaceService.getProductStripeId(product);
|
||||
|
||||
assert(
|
||||
stripeProductId,
|
||||
@ -32,7 +35,7 @@ export class BillingResolver {
|
||||
);
|
||||
|
||||
const productPrices =
|
||||
await this.billingService.getProductPrices(stripeProductId);
|
||||
await this.billingWorkspaceService.getProductPrices(stripeProductId);
|
||||
|
||||
return {
|
||||
totalNumberOfPrices: productPrices.length,
|
||||
@ -47,7 +50,7 @@ export class BillingResolver {
|
||||
@Args() { returnUrlPath }: BillingSessionInput,
|
||||
) {
|
||||
return {
|
||||
url: await this.billingService.computeBillingPortalSessionURL(
|
||||
url: await this.billingWorkspaceService.computeBillingPortalSessionURL(
|
||||
user.defaultWorkspaceId,
|
||||
returnUrlPath,
|
||||
),
|
||||
@ -60,7 +63,7 @@ export class BillingResolver {
|
||||
@AuthUser() user: User,
|
||||
@Args() { recurringInterval, successUrlPath }: CheckoutSessionInput,
|
||||
) {
|
||||
const stripeProductId = this.billingService.getProductStripeId(
|
||||
const stripeProductId = this.billingWorkspaceService.getProductStripeId(
|
||||
AvailableProduct.BasePlan,
|
||||
);
|
||||
|
||||
@ -70,7 +73,7 @@ export class BillingResolver {
|
||||
);
|
||||
|
||||
const productPrices =
|
||||
await this.billingService.getProductPrices(stripeProductId);
|
||||
await this.billingWorkspaceService.getProductPrices(stripeProductId);
|
||||
|
||||
const stripePriceId = productPrices.filter(
|
||||
(price) => price.recurringInterval === recurringInterval,
|
||||
@ -82,7 +85,7 @@ export class BillingResolver {
|
||||
);
|
||||
|
||||
return {
|
||||
url: await this.billingService.computeCheckoutSessionURL(
|
||||
url: await this.billingWorkspaceService.computeCheckoutSessionURL(
|
||||
user,
|
||||
stripePriceId,
|
||||
successUrlPath,
|
||||
@ -93,7 +96,7 @@ export class BillingResolver {
|
||||
@Mutation(() => UpdateBillingEntity)
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async updateBillingSubscription(@AuthUser() user: User) {
|
||||
await this.billingService.updateBillingSubscription(user);
|
||||
await this.billingWorkspaceService.updateBillingSubscription(user);
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@ -1,51 +1,21 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import Stripe from 'stripe';
|
||||
import { In, Not, Repository } from 'typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
|
||||
import { EnvironmentService } from 'src/engine/integrations/environment/environment.service';
|
||||
import { StripeService } from 'src/engine/core-modules/billing/stripe/stripe.service';
|
||||
import {
|
||||
BillingSubscription,
|
||||
SubscriptionInterval,
|
||||
SubscriptionStatus,
|
||||
} from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
|
||||
import { BillingSubscriptionItem } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
|
||||
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { ProductPriceEntity } from 'src/engine/core-modules/billing/dto/product-price.entity';
|
||||
import { User } from 'src/engine/core-modules/user/user.entity';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import {
|
||||
FeatureFlagEntity,
|
||||
FeatureFlagKeys,
|
||||
} from 'src/engine/core-modules/feature-flag/feature-flag.entity';
|
||||
|
||||
export enum AvailableProduct {
|
||||
BasePlan = 'base-plan',
|
||||
}
|
||||
|
||||
export enum WebhookEvent {
|
||||
CUSTOMER_SUBSCRIPTION_CREATED = 'customer.subscription.created',
|
||||
CUSTOMER_SUBSCRIPTION_UPDATED = 'customer.subscription.updated',
|
||||
CUSTOMER_SUBSCRIPTION_DELETED = 'customer.subscription.deleted',
|
||||
SETUP_INTENT_SUCCEEDED = 'setup_intent.succeeded',
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BillingService {
|
||||
protected readonly logger = new Logger(BillingService.name);
|
||||
constructor(
|
||||
private readonly stripeService: StripeService,
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
@InjectRepository(BillingSubscription, 'core')
|
||||
private readonly billingSubscriptionRepository: Repository<BillingSubscription>,
|
||||
@InjectRepository(FeatureFlagEntity, 'core')
|
||||
private readonly featureFlagRepository: Repository<FeatureFlagEntity>,
|
||||
@InjectRepository(BillingSubscriptionItem, 'core')
|
||||
private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItem>,
|
||||
@InjectRepository(Workspace, 'core')
|
||||
private readonly workspaceRepository: Repository<Workspace>,
|
||||
) {}
|
||||
@ -68,283 +38,4 @@ export class BillingService {
|
||||
})
|
||||
).map((workspace) => workspace.id);
|
||||
}
|
||||
|
||||
async isBillingEnabledForWorkspace(workspaceId: string) {
|
||||
const isFreeAccessEnabled = await this.featureFlagRepository.findOneBy({
|
||||
workspaceId,
|
||||
key: FeatureFlagKeys.IsFreeAccessEnabled,
|
||||
value: true,
|
||||
});
|
||||
|
||||
return (
|
||||
!isFreeAccessEnabled && this.environmentService.get('IS_BILLING_ENABLED')
|
||||
);
|
||||
}
|
||||
|
||||
getProductStripeId(product: AvailableProduct) {
|
||||
if (product === AvailableProduct.BasePlan) {
|
||||
return this.environmentService.get('BILLING_STRIPE_BASE_PLAN_PRODUCT_ID');
|
||||
}
|
||||
}
|
||||
|
||||
async getProductPrices(stripeProductId: string) {
|
||||
const productPrices =
|
||||
await this.stripeService.getProductPrices(stripeProductId);
|
||||
|
||||
return this.formatProductPrices(productPrices.data);
|
||||
}
|
||||
|
||||
formatProductPrices(prices: Stripe.Price[]) {
|
||||
const result: Record<string, ProductPriceEntity> = {};
|
||||
|
||||
prices.forEach((item) => {
|
||||
const interval = item.recurring?.interval;
|
||||
|
||||
if (!interval || !item.unit_amount) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!result[interval] ||
|
||||
item.created > (result[interval]?.created || 0)
|
||||
) {
|
||||
result[interval] = {
|
||||
unitAmount: item.unit_amount,
|
||||
recurringInterval: interval,
|
||||
created: item.created,
|
||||
stripePriceId: item.id,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return Object.values(result).sort((a, b) => a.unitAmount - b.unitAmount);
|
||||
}
|
||||
|
||||
async getCurrentBillingSubscription(criteria: {
|
||||
workspaceId?: string;
|
||||
stripeCustomerId?: string;
|
||||
}) {
|
||||
const notCanceledSubscriptions =
|
||||
await this.billingSubscriptionRepository.find({
|
||||
where: { ...criteria, status: Not(SubscriptionStatus.Canceled) },
|
||||
relations: ['billingSubscriptionItems'],
|
||||
});
|
||||
|
||||
assert(
|
||||
notCanceledSubscriptions.length <= 1,
|
||||
`More than one not canceled subscription for workspace ${criteria.workspaceId}`,
|
||||
);
|
||||
|
||||
return notCanceledSubscriptions?.[0];
|
||||
}
|
||||
|
||||
async getBillingSubscription(stripeSubscriptionId: string) {
|
||||
return this.billingSubscriptionRepository.findOneOrFail({
|
||||
where: { stripeSubscriptionId },
|
||||
});
|
||||
}
|
||||
|
||||
async getStripeCustomerId(workspaceId: string) {
|
||||
const subscriptions = await this.billingSubscriptionRepository.find({
|
||||
where: { workspaceId },
|
||||
});
|
||||
|
||||
return subscriptions?.[0]?.stripeCustomerId;
|
||||
}
|
||||
|
||||
async getBillingSubscriptionItem(
|
||||
workspaceId: string,
|
||||
stripeProductId = this.environmentService.get(
|
||||
'BILLING_STRIPE_BASE_PLAN_PRODUCT_ID',
|
||||
),
|
||||
) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
if (!billingSubscription) {
|
||||
throw new Error(
|
||||
`Cannot find billingSubscriptionItem for product ${stripeProductId} for workspace ${workspaceId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const billingSubscriptionItem =
|
||||
billingSubscription.billingSubscriptionItems.filter(
|
||||
(billingSubscriptionItem) =>
|
||||
billingSubscriptionItem.stripeProductId === stripeProductId,
|
||||
)?.[0];
|
||||
|
||||
if (!billingSubscriptionItem) {
|
||||
throw new Error(
|
||||
`Cannot find billingSubscriptionItem for product ${stripeProductId} for workspace ${workspaceId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return billingSubscriptionItem;
|
||||
}
|
||||
|
||||
async computeBillingPortalSessionURL(
|
||||
workspaceId: string,
|
||||
returnUrlPath?: string,
|
||||
) {
|
||||
const stripeCustomerId = await this.getStripeCustomerId(workspaceId);
|
||||
|
||||
if (!stripeCustomerId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const frontBaseUrl = this.environmentService.get('FRONT_BASE_URL');
|
||||
const returnUrl = returnUrlPath
|
||||
? frontBaseUrl + returnUrlPath
|
||||
: frontBaseUrl;
|
||||
|
||||
const session = await this.stripeService.createBillingPortalSession(
|
||||
stripeCustomerId,
|
||||
returnUrl,
|
||||
);
|
||||
|
||||
assert(session.url, 'Error: missing billingPortal.session.url');
|
||||
|
||||
return session.url;
|
||||
}
|
||||
|
||||
async updateBillingSubscription(user: User) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
workspaceId: user.defaultWorkspaceId,
|
||||
});
|
||||
const newInterval =
|
||||
billingSubscription?.interval === SubscriptionInterval.Year
|
||||
? SubscriptionInterval.Month
|
||||
: SubscriptionInterval.Year;
|
||||
const billingSubscriptionItem = await this.getBillingSubscriptionItem(
|
||||
user.defaultWorkspaceId,
|
||||
);
|
||||
const stripeProductId = this.getProductStripeId(AvailableProduct.BasePlan);
|
||||
|
||||
if (!stripeProductId) {
|
||||
throw new Error('Stripe product id not found for basePlan');
|
||||
}
|
||||
const productPrices = await this.getProductPrices(stripeProductId);
|
||||
|
||||
const stripePriceId = productPrices.filter(
|
||||
(price) => price.recurringInterval === newInterval,
|
||||
)?.[0]?.stripePriceId;
|
||||
|
||||
await this.stripeService.updateBillingSubscriptionItem(
|
||||
billingSubscriptionItem,
|
||||
stripePriceId,
|
||||
);
|
||||
}
|
||||
|
||||
async computeCheckoutSessionURL(
|
||||
user: User,
|
||||
priceId: string,
|
||||
successUrlPath?: string,
|
||||
): Promise<string> {
|
||||
const frontBaseUrl = this.environmentService.get('FRONT_BASE_URL');
|
||||
const successUrl = successUrlPath
|
||||
? frontBaseUrl + successUrlPath
|
||||
: frontBaseUrl;
|
||||
|
||||
const quantity =
|
||||
(await this.userWorkspaceService.getWorkspaceMemberCount()) || 1;
|
||||
|
||||
const stripeCustomerId = (
|
||||
await this.billingSubscriptionRepository.findOneBy({
|
||||
workspaceId: user.defaultWorkspaceId,
|
||||
})
|
||||
)?.stripeCustomerId;
|
||||
|
||||
const session = await this.stripeService.createCheckoutSession(
|
||||
user,
|
||||
priceId,
|
||||
quantity,
|
||||
successUrl,
|
||||
frontBaseUrl,
|
||||
stripeCustomerId,
|
||||
);
|
||||
|
||||
assert(session.url, 'Error: missing checkout.session.url');
|
||||
|
||||
return session.url;
|
||||
}
|
||||
|
||||
async deleteSubscription(workspaceId: string) {
|
||||
const subscriptionToCancel = await this.getCurrentBillingSubscription({
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
if (subscriptionToCancel) {
|
||||
await this.stripeService.cancelSubscription(
|
||||
subscriptionToCancel.stripeSubscriptionId,
|
||||
);
|
||||
await this.billingSubscriptionRepository.delete(subscriptionToCancel.id);
|
||||
}
|
||||
}
|
||||
|
||||
async handleUnpaidInvoices(data: Stripe.SetupIntentSucceededEvent.Data) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
stripeCustomerId: data.object.customer as string,
|
||||
});
|
||||
|
||||
if (billingSubscription?.status === 'unpaid') {
|
||||
await this.stripeService.collectLastInvoice(
|
||||
billingSubscription.stripeSubscriptionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async upsertBillingSubscription(
|
||||
workspaceId: string,
|
||||
data:
|
||||
| Stripe.CustomerSubscriptionUpdatedEvent.Data
|
||||
| Stripe.CustomerSubscriptionCreatedEvent.Data
|
||||
| Stripe.CustomerSubscriptionDeletedEvent.Data,
|
||||
) {
|
||||
const workspace = this.workspaceRepository.find({
|
||||
where: { id: workspaceId },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.billingSubscriptionRepository.upsert(
|
||||
{
|
||||
workspaceId: workspaceId,
|
||||
stripeCustomerId: data.object.customer as string,
|
||||
stripeSubscriptionId: data.object.id,
|
||||
status: data.object.status,
|
||||
interval: data.object.items.data[0].plan.interval,
|
||||
},
|
||||
{
|
||||
conflictPaths: ['stripeSubscriptionId'],
|
||||
skipUpdateIfNoValuesChanged: true,
|
||||
},
|
||||
);
|
||||
|
||||
const billingSubscription = await this.getBillingSubscription(
|
||||
data.object.id,
|
||||
);
|
||||
|
||||
await this.billingSubscriptionItemRepository.upsert(
|
||||
data.object.items.data.map((item) => {
|
||||
return {
|
||||
billingSubscriptionId: billingSubscription.id,
|
||||
stripeProductId: item.price.product as string,
|
||||
stripePriceId: item.price.id,
|
||||
stripeSubscriptionItemId: item.id,
|
||||
quantity: item.quantity,
|
||||
};
|
||||
}),
|
||||
{
|
||||
conflictPaths: ['billingSubscriptionId', 'stripeProductId'],
|
||||
skipUpdateIfNoValuesChanged: true,
|
||||
},
|
||||
);
|
||||
|
||||
await this.featureFlagRepository.delete({
|
||||
workspaceId,
|
||||
key: FeatureFlagKeys.IsFreeAccessEnabled,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,332 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
|
||||
import Stripe from 'stripe';
|
||||
import { Not, Repository } from 'typeorm';
|
||||
|
||||
import { EnvironmentService } from 'src/engine/integrations/environment/environment.service';
|
||||
import { StripeService } from 'src/engine/core-modules/billing/stripe/stripe.service';
|
||||
import {
|
||||
BillingSubscription,
|
||||
SubscriptionInterval,
|
||||
SubscriptionStatus,
|
||||
} from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
|
||||
import { BillingSubscriptionItem } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
|
||||
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { ProductPriceEntity } from 'src/engine/core-modules/billing/dto/product-price.entity';
|
||||
import { User } from 'src/engine/core-modules/user/user.entity';
|
||||
import { assert } from 'src/utils/assert';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import {
|
||||
FeatureFlagEntity,
|
||||
FeatureFlagKeys,
|
||||
} from 'src/engine/core-modules/feature-flag/feature-flag.entity';
|
||||
import { BillingService } from 'src/engine/core-modules/billing/billing.service';
|
||||
|
||||
export enum AvailableProduct {
|
||||
BasePlan = 'base-plan',
|
||||
}
|
||||
|
||||
export enum WebhookEvent {
|
||||
CUSTOMER_SUBSCRIPTION_CREATED = 'customer.subscription.created',
|
||||
CUSTOMER_SUBSCRIPTION_UPDATED = 'customer.subscription.updated',
|
||||
CUSTOMER_SUBSCRIPTION_DELETED = 'customer.subscription.deleted',
|
||||
SETUP_INTENT_SUCCEEDED = 'setup_intent.succeeded',
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BillingWorkspaceService {
|
||||
protected readonly logger = new Logger(BillingService.name);
|
||||
constructor(
|
||||
private readonly stripeService: StripeService,
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
@InjectRepository(BillingSubscription, 'core')
|
||||
private readonly billingSubscriptionRepository: Repository<BillingSubscription>,
|
||||
@InjectRepository(FeatureFlagEntity, 'core')
|
||||
private readonly featureFlagRepository: Repository<FeatureFlagEntity>,
|
||||
@InjectRepository(BillingSubscriptionItem, 'core')
|
||||
private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItem>,
|
||||
@InjectRepository(Workspace, 'core')
|
||||
private readonly workspaceRepository: Repository<Workspace>,
|
||||
) {}
|
||||
|
||||
async isBillingEnabledForWorkspace(workspaceId: string) {
|
||||
const isFreeAccessEnabled = await this.featureFlagRepository.findOneBy({
|
||||
workspaceId,
|
||||
key: FeatureFlagKeys.IsFreeAccessEnabled,
|
||||
value: true,
|
||||
});
|
||||
|
||||
return (
|
||||
!isFreeAccessEnabled && this.environmentService.get('IS_BILLING_ENABLED')
|
||||
);
|
||||
}
|
||||
|
||||
getProductStripeId(product: AvailableProduct) {
|
||||
if (product === AvailableProduct.BasePlan) {
|
||||
return this.environmentService.get('BILLING_STRIPE_BASE_PLAN_PRODUCT_ID');
|
||||
}
|
||||
}
|
||||
|
||||
async getProductPrices(stripeProductId: string) {
|
||||
const productPrices =
|
||||
await this.stripeService.getProductPrices(stripeProductId);
|
||||
|
||||
return this.formatProductPrices(productPrices.data);
|
||||
}
|
||||
|
||||
formatProductPrices(prices: Stripe.Price[]) {
|
||||
const result: Record<string, ProductPriceEntity> = {};
|
||||
|
||||
prices.forEach((item) => {
|
||||
const interval = item.recurring?.interval;
|
||||
|
||||
if (!interval || !item.unit_amount) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!result[interval] ||
|
||||
item.created > (result[interval]?.created || 0)
|
||||
) {
|
||||
result[interval] = {
|
||||
unitAmount: item.unit_amount,
|
||||
recurringInterval: interval,
|
||||
created: item.created,
|
||||
stripePriceId: item.id,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return Object.values(result).sort((a, b) => a.unitAmount - b.unitAmount);
|
||||
}
|
||||
|
||||
async getCurrentBillingSubscription(criteria: {
|
||||
workspaceId?: string;
|
||||
stripeCustomerId?: string;
|
||||
}) {
|
||||
const notCanceledSubscriptions =
|
||||
await this.billingSubscriptionRepository.find({
|
||||
where: { ...criteria, status: Not(SubscriptionStatus.Canceled) },
|
||||
relations: ['billingSubscriptionItems'],
|
||||
});
|
||||
|
||||
assert(
|
||||
notCanceledSubscriptions.length <= 1,
|
||||
`More than one not canceled subscription for workspace ${criteria.workspaceId}`,
|
||||
);
|
||||
|
||||
return notCanceledSubscriptions?.[0];
|
||||
}
|
||||
|
||||
async getBillingSubscription(stripeSubscriptionId: string) {
|
||||
return this.billingSubscriptionRepository.findOneOrFail({
|
||||
where: { stripeSubscriptionId },
|
||||
});
|
||||
}
|
||||
|
||||
async getStripeCustomerId(workspaceId: string) {
|
||||
const subscriptions = await this.billingSubscriptionRepository.find({
|
||||
where: { workspaceId },
|
||||
});
|
||||
|
||||
return subscriptions?.[0]?.stripeCustomerId;
|
||||
}
|
||||
|
||||
async getBillingSubscriptionItem(
|
||||
workspaceId: string,
|
||||
stripeProductId = this.environmentService.get(
|
||||
'BILLING_STRIPE_BASE_PLAN_PRODUCT_ID',
|
||||
),
|
||||
) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
if (!billingSubscription) {
|
||||
throw new Error(
|
||||
`Cannot find billingSubscriptionItem for product ${stripeProductId} for workspace ${workspaceId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const billingSubscriptionItem =
|
||||
billingSubscription.billingSubscriptionItems.filter(
|
||||
(billingSubscriptionItem) =>
|
||||
billingSubscriptionItem.stripeProductId === stripeProductId,
|
||||
)?.[0];
|
||||
|
||||
if (!billingSubscriptionItem) {
|
||||
throw new Error(
|
||||
`Cannot find billingSubscriptionItem for product ${stripeProductId} for workspace ${workspaceId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return billingSubscriptionItem;
|
||||
}
|
||||
|
||||
async computeBillingPortalSessionURL(
|
||||
workspaceId: string,
|
||||
returnUrlPath?: string,
|
||||
) {
|
||||
const stripeCustomerId = await this.getStripeCustomerId(workspaceId);
|
||||
|
||||
if (!stripeCustomerId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const frontBaseUrl = this.environmentService.get('FRONT_BASE_URL');
|
||||
const returnUrl = returnUrlPath
|
||||
? frontBaseUrl + returnUrlPath
|
||||
: frontBaseUrl;
|
||||
|
||||
const session = await this.stripeService.createBillingPortalSession(
|
||||
stripeCustomerId,
|
||||
returnUrl,
|
||||
);
|
||||
|
||||
assert(session.url, 'Error: missing billingPortal.session.url');
|
||||
|
||||
return session.url;
|
||||
}
|
||||
|
||||
async updateBillingSubscription(user: User) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
workspaceId: user.defaultWorkspaceId,
|
||||
});
|
||||
const newInterval =
|
||||
billingSubscription?.interval === SubscriptionInterval.Year
|
||||
? SubscriptionInterval.Month
|
||||
: SubscriptionInterval.Year;
|
||||
const billingSubscriptionItem = await this.getBillingSubscriptionItem(
|
||||
user.defaultWorkspaceId,
|
||||
);
|
||||
const stripeProductId = this.getProductStripeId(AvailableProduct.BasePlan);
|
||||
|
||||
if (!stripeProductId) {
|
||||
throw new Error('Stripe product id not found for basePlan');
|
||||
}
|
||||
const productPrices = await this.getProductPrices(stripeProductId);
|
||||
|
||||
const stripePriceId = productPrices.filter(
|
||||
(price) => price.recurringInterval === newInterval,
|
||||
)?.[0]?.stripePriceId;
|
||||
|
||||
await this.stripeService.updateBillingSubscriptionItem(
|
||||
billingSubscriptionItem,
|
||||
stripePriceId,
|
||||
);
|
||||
}
|
||||
|
||||
async computeCheckoutSessionURL(
|
||||
user: User,
|
||||
priceId: string,
|
||||
successUrlPath?: string,
|
||||
): Promise<string> {
|
||||
const frontBaseUrl = this.environmentService.get('FRONT_BASE_URL');
|
||||
const successUrl = successUrlPath
|
||||
? frontBaseUrl + successUrlPath
|
||||
: frontBaseUrl;
|
||||
|
||||
const quantity =
|
||||
(await this.userWorkspaceService.getWorkspaceMemberCount()) || 1;
|
||||
|
||||
const stripeCustomerId = (
|
||||
await this.billingSubscriptionRepository.findOneBy({
|
||||
workspaceId: user.defaultWorkspaceId,
|
||||
})
|
||||
)?.stripeCustomerId;
|
||||
|
||||
const session = await this.stripeService.createCheckoutSession(
|
||||
user,
|
||||
priceId,
|
||||
quantity,
|
||||
successUrl,
|
||||
frontBaseUrl,
|
||||
stripeCustomerId,
|
||||
);
|
||||
|
||||
assert(session.url, 'Error: missing checkout.session.url');
|
||||
|
||||
return session.url;
|
||||
}
|
||||
|
||||
async deleteSubscription(workspaceId: string) {
|
||||
const subscriptionToCancel = await this.getCurrentBillingSubscription({
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
if (subscriptionToCancel) {
|
||||
await this.stripeService.cancelSubscription(
|
||||
subscriptionToCancel.stripeSubscriptionId,
|
||||
);
|
||||
await this.billingSubscriptionRepository.delete(subscriptionToCancel.id);
|
||||
}
|
||||
}
|
||||
|
||||
async handleUnpaidInvoices(data: Stripe.SetupIntentSucceededEvent.Data) {
|
||||
const billingSubscription = await this.getCurrentBillingSubscription({
|
||||
stripeCustomerId: data.object.customer as string,
|
||||
});
|
||||
|
||||
if (billingSubscription?.status === 'unpaid') {
|
||||
await this.stripeService.collectLastInvoice(
|
||||
billingSubscription.stripeSubscriptionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async upsertBillingSubscription(
|
||||
workspaceId: string,
|
||||
data:
|
||||
| Stripe.CustomerSubscriptionUpdatedEvent.Data
|
||||
| Stripe.CustomerSubscriptionCreatedEvent.Data
|
||||
| Stripe.CustomerSubscriptionDeletedEvent.Data,
|
||||
) {
|
||||
const workspace = this.workspaceRepository.find({
|
||||
where: { id: workspaceId },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.billingSubscriptionRepository.upsert(
|
||||
{
|
||||
workspaceId: workspaceId,
|
||||
stripeCustomerId: data.object.customer as string,
|
||||
stripeSubscriptionId: data.object.id,
|
||||
status: data.object.status,
|
||||
interval: data.object.items.data[0].plan.interval,
|
||||
},
|
||||
{
|
||||
conflictPaths: ['stripeSubscriptionId'],
|
||||
skipUpdateIfNoValuesChanged: true,
|
||||
},
|
||||
);
|
||||
|
||||
const billingSubscription = await this.getBillingSubscription(
|
||||
data.object.id,
|
||||
);
|
||||
|
||||
await this.billingSubscriptionItemRepository.upsert(
|
||||
data.object.items.data.map((item) => {
|
||||
return {
|
||||
billingSubscriptionId: billingSubscription.id,
|
||||
stripeProductId: item.price.product as string,
|
||||
stripePriceId: item.price.id,
|
||||
stripeSubscriptionItemId: item.id,
|
||||
quantity: item.quantity,
|
||||
};
|
||||
}),
|
||||
{
|
||||
conflictPaths: ['billingSubscriptionId', 'stripeProductId'],
|
||||
skipUpdateIfNoValuesChanged: true,
|
||||
},
|
||||
);
|
||||
|
||||
await this.featureFlagRepository.delete({
|
||||
workspaceId,
|
||||
key: FeatureFlagKeys.IsFreeAccessEnabled,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -2,7 +2,7 @@ import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
import { AvailableProduct } from 'src/engine/core-modules/billing/billing.service';
|
||||
import { AvailableProduct } from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
|
||||
@ArgsType()
|
||||
export class ProductInput {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { Logger, Scope } from '@nestjs/common';
|
||||
|
||||
import { BillingService } from 'src/engine/core-modules/billing/billing.service';
|
||||
import { BillingWorkspaceService } from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import { StripeService } from 'src/engine/core-modules/billing/stripe/stripe.service';
|
||||
import { Processor } from 'src/engine/integrations/message-queue/decorators/processor.decorator';
|
||||
@ -16,7 +16,7 @@ export class UpdateSubscriptionJob {
|
||||
protected readonly logger = new Logger(UpdateSubscriptionJob.name);
|
||||
|
||||
constructor(
|
||||
private readonly billingService: BillingService,
|
||||
private readonly billingWorkspaceService: BillingWorkspaceService,
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
private readonly stripeService: StripeService,
|
||||
) {}
|
||||
@ -32,7 +32,9 @@ export class UpdateSubscriptionJob {
|
||||
|
||||
try {
|
||||
const billingSubscriptionItem =
|
||||
await this.billingService.getBillingSubscriptionItem(data.workspaceId);
|
||||
await this.billingWorkspaceService.getBillingSubscriptionItem(
|
||||
data.workspaceId,
|
||||
);
|
||||
|
||||
await this.stripeService.updateSubscriptionItem(
|
||||
billingSubscriptionItem.stripeSubscriptionItemId,
|
||||
|
||||
@ -10,14 +10,14 @@ import {
|
||||
UpdateSubscriptionJobData,
|
||||
} from 'src/engine/core-modules/billing/jobs/update-subscription.job';
|
||||
import { InjectMessageQueue } from 'src/engine/integrations/message-queue/decorators/message-queue.decorator';
|
||||
import { BillingService } from 'src/engine/core-modules/billing/billing.service';
|
||||
import { BillingWorkspaceService } from 'src/engine/core-modules/billing/billing.workspace-service';
|
||||
|
||||
@Injectable()
|
||||
export class BillingWorkspaceMemberListener {
|
||||
constructor(
|
||||
@InjectMessageQueue(MessageQueue.billingQueue)
|
||||
private readonly messageQueueService: MessageQueueService,
|
||||
private readonly billingService: BillingService,
|
||||
private readonly billingWorkspaceService: BillingWorkspaceService,
|
||||
) {}
|
||||
|
||||
@OnEvent('workspaceMember.created')
|
||||
@ -26,7 +26,7 @@ export class BillingWorkspaceMemberListener {
|
||||
payload: ObjectRecordCreateEvent<WorkspaceMemberWorkspaceEntity>,
|
||||
) {
|
||||
const isBillingEnabledForWorkspace =
|
||||
await this.billingService.isBillingEnabledForWorkspace(
|
||||
await this.billingWorkspaceService.isBillingEnabledForWorkspace(
|
||||
payload.workspaceId,
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user