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 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,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 +294,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
@@ -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,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@ import { ActivateWorkspaceInput } from 'src/engine/core-modules/workspace/dtos/a
import { UserWorkspace } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { BillingService } from 'src/engine/core-modules/billing/billing.service';
import { UserService } from 'src/engine/core-modules/user/services/user.service';

export class WorkspaceService extends TypeOrmQueryService<Workspace> {
constructor(
@InjectRepository(Workspace, 'core')
private readonly workspaceRepository: Repository<Workspace>,
@InjectRepository(User, 'core')
private readonly userRepository: Repository<User>,
@InjectRepository(UserWorkspace, 'core')
private readonly userWorkspaceRepository: Repository<UserWorkspace>,
private readonly workspaceManagerService: WorkspaceManagerService,
private readonly userWorkspaceService: UserWorkspaceService,
private readonly billingService: BillingService,
private readonly userService: UserService,
) {
super(workspaceRepository);
}
Expand All @@ -49,7 +49,7 @@ export class WorkspaceService extends TypeOrmQueryService<Workspace> {
return await this.workspaceManagerService.doesDataSourceExist(id);
}

async solfDeleteWorkspace(id: string) {
async softDeleteWorkspace(id: string) {
Weiko marked this conversation as resolved.
Show resolved Hide resolved
const workspace = await this.workspaceRepository.findOneBy({ id });

assert(workspace, 'Workspace not found');
Expand All @@ -67,14 +67,12 @@ export class WorkspaceService extends TypeOrmQueryService<Workspace> {
workspaceId: id,
});

const workspace = await this.solfDeleteWorkspace(id);
const workspace = await this.softDeleteWorkspace(id);

for (const userWorkspace of userWorkspaces) {
await this.userService.handleRemoveWorkspaceMember(
id,
userWorkspace.userId,
);
await this.handleRemoveWorkspaceMember(id, userWorkspace.userId);
}

await this.workspaceRepository.delete(id);

return workspace;
Expand All @@ -85,4 +83,46 @@ export class WorkspaceService extends TypeOrmQueryService<Workspace> {
.find()
.then((workspaces) => workspaces.map((workspace) => workspace.id));
}

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 },
});

if (userWorkspaces.length === 0) {
await this.userRepository.delete({ id: userId });

return;
}

const user = await this.userRepository.findOne({
where: {
id: userId,
},
});

if (!user) {
throw new Error(`User ${userId} not found in workspace ${workspaceId}`);
}

if (user.defaultWorkspaceId === workspaceId) {
await this.userRepository.update(
{ id: userId },
{
defaultWorkspaceId: userWorkspaces[0].workspaceId,
},
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { FileUploadModule } from 'src/engine/core-modules/file/file-upload/file-upload.module';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
import { UserModule } from 'src/engine/core-modules/user/user.module';
import { WorkspaceWorkspaceMemberListener } from 'src/engine/core-modules/workspace/workspace-workspace-member.listener';
import { WorkspaceCacheVersionModule } from 'src/engine/metadata-modules/workspace-cache-version/workspace-cache-version.module';
import { User } from 'src/engine/core-modules/user/user.entity';

import { workspaceAutoResolverOpts } from './workspace.auto-resolver-opts';
import { Workspace } from './workspace.entity';
Expand All @@ -30,14 +30,13 @@ import { WorkspaceService } from './services/workspace.service';
FileUploadModule,
WorkspaceCacheVersionModule,
NestjsQueryTypeOrmModule.forFeature(
[Workspace, UserWorkspace, FeatureFlagEntity],
[User, Workspace, UserWorkspace, FeatureFlagEntity],
'core',
),
UserWorkspaceModule,
WorkspaceManagerModule,
DataSourceModule,
TypeORMModule,
UserModule,
],
services: [WorkspaceService],
resolvers: workspaceAutoResolverOpts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import { MessageChannelMessageAssociationObjectMetadata } from 'src/modules/mess
import { MessageChannelObjectMetadata } from 'src/modules/messaging/standard-objects/message-channel.object-metadata';
import { BlocklistItemDeleteCalendarEventsJob } from 'src/modules/calendar/jobs/blocklist-item-delete-calendar-events.job';
import { BlocklistReimportCalendarEventsJob } from 'src/modules/calendar/jobs/blocklist-reimport-calendar-events.job';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';

@Module({
imports: [
Expand All @@ -81,6 +82,7 @@ import { BlocklistReimportCalendarEventsJob } from 'src/modules/calendar/jobs/bl
TypeOrmModule.forFeature([DataSourceEntity], 'metadata'),
UserModule,
UserWorkspaceModule,
WorkspaceModule,
WorkspaceDataSourceModule,
RecordPositionBackfillModule,
GoogleAPIRefreshAccessTokenModule,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class DeleteIncompleteWorkspacesCommand extends CommandRunner {
} name: '${incompleteWorkspace.displayName}'`,
);
if (!options.dryRun) {
await this.workspaceService.solfDeleteWorkspace(incompleteWorkspace.id);
await this.workspaceService.softDeleteWorkspace(incompleteWorkspace.id);
}
}
}
Expand Down
Loading