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

add sync customer command and drop subscription customer constraint #9131

Merged
merged 3 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
@@ -0,0 +1,19 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class DropSubscriptionCustomerConstraint1734532875877
implements MigrationInterface
{
name = 'DropSubscriptionCustomerConstraint1734532875877';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "core"."billingSubscription" DROP CONSTRAINT "FK_9120b7586c3471463480b58d20a"`,
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: dropping this constraint removes referential integrity - ensure application code properly handles subscription cleanup when customers are deleted

Copy link
Member

Choose a reason for hiding this comment

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

this should be removed from the original migration, otherwise we will apply it first before removing it and end up in the same issue while applying it

);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "core"."billingSubscription" ADD CONSTRAINT "FK_9120b7586c3471463480b58d20a" FOREIGN KEY ("stripeCustomerId") REFERENCES "core"."billingCustomer"("stripeCustomerId") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';

import { BillingController } from 'src/engine/core-modules/billing/billing.controller';
import { BillingResolver } from 'src/engine/core-modules/billing/billing.resolver';
import { BillingSyncCustomerDataCommand } from 'src/engine/core-modules/billing/commands/billing-sync-customer-data.command';
import { BillingCustomer } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingEntitlement } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';
import { BillingMeter } from 'src/engine/core-modules/billing/entities/billing-meter.entity';
Expand Down Expand Up @@ -59,6 +60,7 @@ import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
BillingWebhookProductService,
BillingWebhookPriceService,
BillingRestApiExceptionFilter,
BillingSyncCustomerDataCommand,
],
exports: [
BillingSubscriptionService,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { InjectRepository } from '@nestjs/typeorm';

import chalk from 'chalk';
import { Command } from 'nest-commander';
import { Repository } from 'typeorm';

import {
ActiveWorkspacesCommandOptions,
ActiveWorkspacesCommandRunner,
} from 'src/database/commands/active-workspaces.command';
import { BillingCustomer } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { StripeService } from 'src/engine/core-modules/billing/stripe/stripe.service';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';

interface SyncCustomerDataCommandOptions
extends ActiveWorkspacesCommandOptions {}

@Command({
name: 'billing:sync-customer-data',
description: 'Sync customer data from Stripe for all active workspaces',
})
export class BillingSyncCustomerDataCommand extends ActiveWorkspacesCommandRunner {
constructor(
@InjectRepository(Workspace, 'core')
protected readonly workspaceRepository: Repository<Workspace>,
private readonly stripeService: StripeService,
@InjectRepository(BillingCustomer, 'core')
protected readonly billingCustomerRepository: Repository<BillingCustomer>,
) {
super(workspaceRepository);
}

async executeActiveWorkspacesCommand(
_passedParam: string[],
options: SyncCustomerDataCommandOptions,
workspaceIds: string[],
): Promise<void> {
this.logger.log('Running command to sync customer data');

for (const workspaceId of workspaceIds) {
this.logger.log(`Running command for workspace ${workspaceId}`);

try {
await this.syncCustomerDataForWorkspace(workspaceId, options);
} catch (error) {
this.logger.log(
chalk.red(
`Running command on workspace ${workspaceId} failed with error: ${error}, ${error.stack}`,
),
);
continue;
Comment on lines +45 to +51
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Error is logged but not tracked/reported. Consider adding error metrics or alerting for failed syncs.

} finally {
this.logger.log(
chalk.green(`Finished running command for workspace ${workspaceId}.`),
);
}
}

this.logger.log(chalk.green(`Command completed!`));
}

private async syncCustomerDataForWorkspace(
workspaceId: string,
options: SyncCustomerDataCommandOptions,
): Promise<void> {
const billingCustomer = await this.billingCustomerRepository.findOne({
where: {
workspaceId,
},
});

if (!options.dryRun && !billingCustomer) {
const customerData =
await this.stripeService.getCustomerData(workspaceId);

await this.billingCustomerRepository.upsert(customerData, {
conflictPaths: ['workspaceId'],
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: No validation that customerData exists or is valid before upserting. Could create empty/invalid records if Stripe call fails silently.


if (options.verbose) {
this.logger.log(
chalk.yellow(`Added ${workspaceId} to billingCustomer table`),
);
}
Comment on lines +91 to +95
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Log message indicates addition but this runs even for failed operations. Move inside the if block after successful upsert.

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export class BillingSubscription {
{
nullable: false,
onDelete: 'CASCADE',
createForeignKeyConstraints: false,
},
Comment on lines 82 to 86
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: disabling foreign key constraints removes database-level data integrity checks - ensure application code properly validates customer existence before subscription operations

)
@JoinColumn({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,17 @@ export class StripeService {

return productPrices.sort((a, b) => a.unitAmount - b.unitAmount);
}

async getCustomerData(workspaceId: string) {
const subscription = await this.stripe.subscriptions.search({
query: `metadata['workspaceId']:'${workspaceId}'`,
limit: 1,
});
const stripeCustomerId = String(subscription.data[0].customer);
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: direct array access without length check could throw error - validate subscription.data.length > 0 first


return {
stripeCustomerId,
workspaceId,
};
}
}
Loading