From 2474888b140ffbe8fc2b5c21f557355434a251e0 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Sun, 25 Aug 2024 11:36:14 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A8=20Add=20script=20for=20normalizing?= =?UTF-8?q?=20stripe=20subscription=20metadata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/billing/package.json | 3 + .../normalize-subscription-metadata.ts | 65 +++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 packages/billing/src/scripts/normalize-subscription-metadata.ts diff --git a/packages/billing/package.json b/packages/billing/package.json index 1fdcda1d395..6fa32aa1531 100644 --- a/packages/billing/package.json +++ b/packages/billing/package.json @@ -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", diff --git a/packages/billing/src/scripts/normalize-subscription-metadata.ts b/packages/billing/src/scripts/normalize-subscription-metadata.ts new file mode 100644 index 00000000000..8067421c788 --- /dev/null +++ b/packages/billing/src/scripts/normalize-subscription-metadata.ts @@ -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 { + 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();