Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5188 bug some canceled subscriptions are billed #5254

Merged
merged 7 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -196,24 +196,17 @@ export class BillingService {
? frontBaseUrl + successUrlPath
: frontBaseUrl;

let quantity = 1;
const quantity =
(await this.userWorkspaceService.getWorkspaceMemberCount(
user.defaultWorkspaceId,
)) || 1;

const stripeCustomerId = (
await this.billingSubscriptionRepository.findOneBy({
workspaceId: user.defaultWorkspaceId,
})
)?.stripeCustomerId;

try {
quantity = await this.userWorkspaceService.getWorkspaceMemberCount(
user.defaultWorkspaceId,
);
} catch (e) {
this.logger.error(
`Failed to get workspace member count for workspace ${user.defaultWorkspaceId}`,
);
}

const session = await this.stripeService.createCheckoutSession(
user,
priceId,
Expand Down Expand Up @@ -260,6 +253,26 @@ export class BillingService {
| Stripe.CustomerSubscriptionCreatedEvent.Data
| Stripe.CustomerSubscriptionDeletedEvent.Data,
) {
const workspace = this.workspaceRepository.find({
where: { id: workspaceId },
});

if (!workspace) {
return;
}

await this.workspaceRepository.update(workspaceId, {
subscriptionStatus: data.object.status,
});

const billingSubscription = await this.getCurrentBillingSubscription({
workspaceId,
});

if (!billingSubscription) {
return;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this a valid business case? should we expect a workspace without billingSubscription? If not, we should throw

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, we can activate a workspace without a valid subscription. It is the case for old early users ' workspaces

}

await this.billingSubscriptionRepository.upsert(
{
workspaceId: workspaceId,
Expand All @@ -274,18 +287,6 @@ export class BillingService {
},
);

await this.workspaceRepository.update(workspaceId, {
subscriptionStatus: data.object.status,
});

const billingSubscription = await this.getCurrentBillingSubscription({
workspaceId,
});

if (!billingSubscription) {
return;
}

await this.billingSubscriptionItemRepository.upsert(
data.object.items.data.map((item) => {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class UpdateSubscriptionJob
const workspaceMembersCount =
await this.userWorkspaceService.getWorkspaceMemberCount(data.workspaceId);

if (workspaceMembersCount <= 0) {
if (!workspaceMembersCount || workspaceMembersCount <= 0) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,23 @@ export class UserWorkspaceService extends TypeOrmQueryService<UserWorkspace> {
this.eventEmitter.emit('workspaceMember.created', payload);
}

public async getWorkspaceMemberCount(workspaceId: string): Promise<number> {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
public async getWorkspaceMemberCount(
workspaceId: string,
): Promise<number | undefined> {
try {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);

return (
await this.workspaceDataSourceService.executeRawQuery(
`SELECT * FROM ${dataSourceSchema}."workspaceMember"`,
[],
workspaceId,
)
).length;
return (
await this.workspaceDataSourceService.executeRawQuery(
`SELECT * FROM ${dataSourceSchema}."workspaceMember"`,
[],
workspaceId,
)
).length;
} catch {
return undefined;
}
}

async checkUserWorkspaceExists(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { EventEmitter2 } from '@nestjs/event-emitter';

import { User } from 'src/engine/core-modules/user/user.entity';
import { DataSourceService } from 'src/engine/metadata-modules/data-source/data-source.service';
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
import { UserWorkspace } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';

import { UserService } from './user.service';

Expand All @@ -31,6 +33,14 @@ describe('UserService', () => {
provide: TypeORMService,
useValue: {},
},
{
provide: EventEmitter2,
useValue: {},
},
{
provide: WorkspaceService,
useValue: {},
},
],
}).compile();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { InjectRepository } from '@nestjs/typeorm';
import { EventEmitter2 } from '@nestjs/event-emitter';

import { TypeOrmQueryService } from '@ptc-org/nestjs-query-typeorm';
import { Repository } from 'typeorm';
Expand All @@ -8,17 +9,20 @@ import { User } from 'src/engine/core-modules/user/user.entity';
import { WorkspaceMember } from 'src/engine/core-modules/user/dtos/workspace-member.dto';
import { DataSourceService } from 'src/engine/metadata-modules/data-source/data-source.service';
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
import { UserWorkspace } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { DataSourceEntity } from 'src/engine/metadata-modules/data-source/data-source.entity';
import { WorkspaceMemberObjectMetadata } from 'src/modules/workspace-member/standard-objects/workspace-member.object-metadata';
import { ObjectRecordDeleteEvent } from 'src/engine/integrations/event-emitter/types/object-record-delete.event';
import { ObjectRecord } from 'src/engine/workspace-manager/workspace-sync-metadata/types/object-record';
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';

export class UserService extends TypeOrmQueryService<User> {
constructor(
@InjectRepository(User, 'core')
private readonly userRepository: Repository<User>,
@InjectRepository(UserWorkspace, 'core')
private readonly userWorkspaceRepository: Repository<UserWorkspace>,
private readonly dataSourceService: DataSourceService,
private readonly typeORMService: TypeORMService,
private readonly eventEmitter: EventEmitter2,
private readonly workspaceService: WorkspaceService,
) {
super(userRepository);
}
Expand Down Expand Up @@ -95,64 +99,46 @@ export class UserService extends TypeOrmQueryService<User> {

assert(user, 'User not found');

const workspaceId = user.defaultWorkspaceId;

const dataSourceMetadata =
await this.dataSourceService.getLastDataSourceMetadataFromWorkspaceIdOrFail(
user.defaultWorkspace.id,
workspaceId,
);

const workspaceDataSource =
await this.typeORMService.connectToDataSource(dataSourceMetadata);

await workspaceDataSource?.query(
`DELETE FROM ${dataSourceMetadata.schema}."workspaceMember" WHERE "userId" = '${userId}'`,
const workspaceMembers = await workspaceDataSource?.query(
`SELECT * FROM ${dataSourceMetadata.schema}."workspaceMember"`,
);
const workspaceMember = workspaceMembers.filter(
(member: ObjectRecord<WorkspaceMemberObjectMetadata>) =>
member.userId === userId,
)?.[0];

await this.userWorkspaceRepository.delete({ userId });

await this.userRepository.delete(user.id);

return user;
}

async handleRemoveWorkspaceMember(workspaceId: string, userId: string) {
await this.userWorkspaceRepository.delete({
userId,
workspaceId,
});
await this.reassignOrRemoveUserDefaultWorkspace(workspaceId, userId);
}

private async reassignOrRemoveUserDefaultWorkspace(
workspaceId: string,
userId: string,
) {
const userWorkspaces = await this.userWorkspaceRepository.find({
where: { userId: userId },
});
assert(workspaceMember, 'WorkspaceMember not found');

if (userWorkspaces.length === 0) {
await this.userRepository.delete({ id: userId });
if (workspaceMembers.length === 1) {
await this.workspaceService.deleteWorkspace(workspaceId);

return;
return user;
}

const user = await this.userRepository.findOne({
where: {
id: userId,
},
});
await workspaceDataSource?.query(
`DELETE FROM ${dataSourceMetadata.schema}."workspaceMember" WHERE "userId" = '${userId}'`,
);
const payload =
new ObjectRecordDeleteEvent<WorkspaceMemberObjectMetadata>();

if (!user) {
throw new Error(`User ${userId} not found in workspace ${workspaceId}`);
}
payload.workspaceId = workspaceId;
payload.properties = {
before: workspaceMember,
};
payload.recordId = workspaceMember.id;

if (user.defaultWorkspaceId === workspaceId) {
await this.userRepository.update(
{ id: userId },
{
defaultWorkspaceId: userWorkspaces[0].workspaceId,
},
);
}
this.eventEmitter.emit('workspaceMember.deleted', payload);

return user;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import { UserResolver } from 'src/engine/core-modules/user/user.resolver';
import { TypeORMService } from 'src/database/typeorm/typeorm.service';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { UserWorkspace } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { FileUploadModule } from 'src/engine/core-modules/file/file-upload/file-upload.module';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';

import { userAutoResolverOpts } from './user.auto-resolver-opts';

Expand All @@ -21,14 +20,14 @@ import { UserService } from './services/user.service';
imports: [
NestjsQueryGraphQLModule.forFeature({
imports: [
NestjsQueryTypeOrmModule.forFeature([User, UserWorkspace], 'core'),
NestjsQueryTypeOrmModule.forFeature([User], 'core'),
TypeORMModule,
],
resolvers: userAutoResolverOpts,
}),
DataSourceModule,
FileUploadModule,
UserWorkspaceModule,
WorkspaceModule,
],
exports: [UserService],
providers: [UserService, UserResolver, TypeORMService],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';

import { MessageQueueJob } from 'src/engine/integrations/message-queue/interfaces/message-queue-job.interface';

import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';

export type HandleWorkspaceMemberDeletedJobData = {
workspaceId: string;
Expand All @@ -12,11 +12,14 @@ export type HandleWorkspaceMemberDeletedJobData = {
export class HandleWorkspaceMemberDeletedJob
implements MessageQueueJob<HandleWorkspaceMemberDeletedJobData>
{
constructor(private readonly userService: UserService) {}
constructor(private readonly workspaceService: WorkspaceService) {}

async handle(data: HandleWorkspaceMemberDeletedJobData): Promise<void> {
const { workspaceId, userId } = data;

await this.userService.handleRemoveWorkspaceMember(workspaceId, userId);
await this.workspaceService.handleRemoveWorkspaceMember(
workspaceId,
userId,
);
}
}