Skip to content

Commit

Permalink
🔨 Add script for normalizing stripe subscription metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
lukevella committed Aug 25, 2024
1 parent 88c746b commit 2474888
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/billing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"./next": "./src/next/index.ts",
".": "./src/index.ts"
},
"scripts": {
"normalize-subscription-metadata": "dotenv -e ../../.env -- tsx ./src/scripts/normalize-metadata.ts"
},
"dependencies": {
"@rallly/ui": "*",
"stripe": "^13.2.0",
Expand Down
65 changes: 65 additions & 0 deletions packages/billing/src/scripts/normalize-subscription-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* This script will go through all subscriptions and add the userId to the metadata.
*/
import { stripe } from "../lib/stripe";
import { prisma } from "@rallly/database";

async function getSubscriptionsWithMissingMetadata(
starting_after?: string,
): Promise<string[]> {
const res: string[] = [];

const subscriptions = await stripe.subscriptions.list({
limit: 100,
starting_after,
});
subscriptions.data.forEach((subscription) => {
if (!subscription.metadata.userId) {
res.push(subscription.id);
}
});
if (subscriptions.has_more) {
return [
...res,
...(await getSubscriptionsWithMissingMetadata(
subscriptions.data[subscriptions.data.length - 1].id,
)),
];
} else {
return res;
}
}

async function normalizeSubscriptionMetadata() {
const subscriptions = await getSubscriptionsWithMissingMetadata();

console.log(
`Found ${subscriptions.length} subscriptions with missing metadata`,
);

for (const subscriptionId of subscriptions) {
const user = await prisma.user.findFirst({
select: {
id: true,
},
where: {
subscriptionId: subscriptionId,
},
});

if (!user) {
console.log("User not found for subscription", subscriptionId);
continue;
}

await stripe.subscriptions.update(subscriptionId, {
metadata: {
userId: user.id,
},
});

console.log("Updated subscription", subscriptionId);
}
}

normalizeSubscriptionMetadata();

0 comments on commit 2474888

Please sign in to comment.