From 852bb15eb943b55454b3aa2f8bdfe135adf6638c Mon Sep 17 00:00:00 2001 From: Matic Jurglic Date: Thu, 21 Nov 2024 12:01:46 +0100 Subject: [PATCH] Add script to sync plans with stripe product ids --- .../scripts/sync-stripe-products.ts | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100755 packages/realm-server/scripts/sync-stripe-products.ts diff --git a/packages/realm-server/scripts/sync-stripe-products.ts b/packages/realm-server/scripts/sync-stripe-products.ts new file mode 100755 index 0000000000..0e2658487f --- /dev/null +++ b/packages/realm-server/scripts/sync-stripe-products.ts @@ -0,0 +1,49 @@ +import '../setup-logger'; +import { PgAdapter } from '@cardstack/postgres'; + +async function fetchStripeProducts() { + const response = await fetch( + 'https://api.stripe.com/v1/products?active=true', + { + method: 'GET', + headers: { + Authorization: `Bearer ${process.env.STRIPE_API_KEY}`, + 'Content-Type': 'application/json', + }, + }, + ); + return response.json(); +} + +async function main() { + let pgAdapter = new PgAdapter(); + let products = await fetchStripeProducts(); + if (products.error) { + throw new Error(products.error.message); + } + let planQuery = await pgAdapter.execute(`SELECT name FROM plans`); + let planNames = planQuery.map((row) => row.name); + + let planStripeIds = products.data.reduce( + (acc: Record, product: any) => { + acc[product.name] = product.id; + return acc; + }, + {}, + ) as Record; + + let updateQueries = planNames.map((planName) => { + let planStripeId = planStripeIds[planName as string]; + if (!planStripeId) { + throw new Error(`Plan ${planName} not found in Stripe`); + } + return `UPDATE plans SET stripe_plan_id = '${planStripeId}' WHERE name = '${planName}';`; + }); + + await pgAdapter.execute(updateQueries.join('\n')); + + console.log('Plans were updated using the following queries:'); + console.log(updateQueries.join('\n')); +} + +main();