'use strict'; const debug = require('debug')('agm:stripe-import'), mongoose = require('mongoose'), env = require('../helpers/env'), mongoUtil = require('../helpers/mongo'), { DBConnection } = require('../helpers/db/connect.js'), { stripe } = require('../helpers/subscription_util'), { findApplicatorByCustId, updateCustSubStatus, updateCustSubscriptions, updateSubBillPeriod } = require('../controllers/subscription'); // Configuration const CUSTOMER_ID = process.argv[2]; // Pass Stripe customer ID as an argument const DRY_RUN = process.argv.includes('--dry-run'); // Use --dry-run to test without making changes /** * This script is to import Stripe customer subscriptions into your local database by reusing the updateCustSubStatus() function from subscription.js. This script fetches subscriptions for a specific Stripe customer and updates the local database accordingly. */ /** * Import Stripe subscriptions for a specific customer */ async function importSubscriptions(stripeCustId) { debug(`Starting import for Stripe customer: ${stripeCustId}`); try { // Find the customer in the local database const dbCustomer = await findApplicatorByCustId(stripeCustId); if (!dbCustomer) { debug(`No customer found in the local database for Stripe ID: ${stripeCustId}`); return; } debug(`Found local customer: ${dbCustomer.username}`); // Fetch subscriptions from Stripe const subscriptions = await stripe.subscriptions.list({ customer: stripeCustId, expand: ['data.latest_invoice.payment_intent'] }); if (!subscriptions.data.length) { debug(`No subscriptions found for Stripe customer: ${stripeCustId}`); return; } // // Process each subscription // for (const subscription of subscriptions.data) { // debug(`Processing subscription: ${subscription.id} (${subscription.status})`); // if (DRY_RUN) { // debug(`[DRY RUN] Would update subscription: ${subscription.id}`); // continue; // } // Update the local database using updateCustSubStatus() // Do these updates in a single mongo transaction try { await mongoUtil.runInTransaction(async (session) => { // Update the subscription status in the local database // const updatedCustomer = await updateCustSubStatus(subscription, dbCustomer, session); const updatedCustomer = await updateCustSubscriptions(dbCustomer._id, subscriptions.data, true); if (!updatedCustomer) { debug(`Failed to update subscription: ${subscriptions.data.length} for customer: ${dbCustomer.username}. NOT FOUND!`); return; } for (const subscription of subscriptions.data) { await updateSubBillPeriod(dbCustomer, subscription, session); } debug(`Successfully updated subscription: ${subscriptions.data.length} for customer: ${dbCustomer.username}`); }); } catch (error) { debug(`Error updating subscription: ${subscriptions.data.length} for customer: ${dbCustomer.username}: ${error.message}`); return; // Skip to the next subscription } // } debug(`Import completed for Stripe customer: ${stripeCustId}`); } catch (error) { debug(`Error importing subscriptions for Stripe customer ${stripeCustId}: ${error.message}`); throw error; } } /** * Main function to handle the import process */ async function main() { if (!CUSTOMER_ID) { debug('Usage: node importStripeSubscriptions.js [--dry-run]'); process.exit(1); } if (DRY_RUN) { debug('Running in DRY RUN mode - no changes will be made'); } try { await importSubscriptions(CUSTOMER_ID); debug('Import process completed successfully'); process.exit(0); } catch (error) { debug(`Error: ${error.message}`); process.exit(1); } } // Connect to the database and run the script async function runScript() { const dbConn = new DBConnection('Import Customer Stripe Subscriptions Script'); try { await dbConn.initialize({ setupExitHandlers: false }); debug('Connected to database'); await main(); } catch (error) { debug('Database connection or script execution failed:', error); process.exit(1); } finally { await dbConn.close(); } } // Execute the script runScript(); // Error handling process .on('uncaughtException', function (err) { debug('Uncaught exception:', err); process.exit(1); }) .on('unhandledRejection', (reason, p) => { debug('Unhandled rejection at Promise', p, 'reason:', reason); });