rollback_price_changes.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. #!/usr/bin/env node
  2. /**
  3. * Rollback pending price changes for Stripe subscriptions
  4. *
  5. * This script removes pending subscription schedule changes that were created by the
  6. * change_existing_subscription_prices.mjs script. It only removes schedules that
  7. * are purely price changes on an existing plan - if the user has made any other
  8. * modifications (plan change, add-on changes), the pending change is left untouched.
  9. *
  10. * Usage:
  11. * node scripts/stripe/rollback_price_changes.mjs [OPTIONS] [INPUT-FILE]
  12. *
  13. * Options:
  14. * --region REGION Either 'uk' or 'us' (required)
  15. * --output PATH Output file path (default: /tmp/rollback_prices_output_<timestamp>.csv)
  16. * Use '-' to write to stdout
  17. * --commit Apply changes (without this flag, runs in dry-run mode)
  18. * --throttle DURATION Minimum time (in ms) between subscriptions processed (default: 100)
  19. * --help Show a help message
  20. *
  21. * CSV Input Format:
  22. * The CSV must have the following columns (same format as change_existing_subscription_prices.mjs):
  23. * - subscription_id: Stripe subscription id
  24. * - current_lookup_key: Current price lookup key
  25. * - new_lookup_key: New price lookup key
  26. * - current_add_on_lookup_key: Current price lookup key for add-on (optional)
  27. * - new_add_on_lookup_key: New price lookup key for add-on (optional)
  28. *
  29. * Output:
  30. * Writes a CSV with columns:
  31. * - subscription_id: The subscription id processed
  32. * - status: Result status (rolled-back, skipped, validated, not-found, or error)
  33. * - note: Additional information about the status
  34. *
  35. * The script will SKIP (not rollback) a subscription if:
  36. * - There is no active subscription schedule
  37. * - The schedule involves a plan change (user downgrade/upgrade)
  38. * - The schedule involves add-on additions/removals
  39. * - The schedule involves add-on quantity changes
  40. * - The prices don't match what we expect from the CSV
  41. *
  42. * Running on a Pod:
  43. * This script may run for multiple days. When running using `rake run:longpod[ENV,web]`,
  44. * use one of these strategies to preserve output:
  45. *
  46. * 1. Tail the output file from another session:
  47. * kubectl exec -it <pod-name> -- tail -f /tmp/rollback_prices_output_<timestamp>.csv > local_backup.csv
  48. *
  49. * 2. Periodically copy the output file to your laptop:
  50. * kubectl cp <pod-name>:/tmp/rollback_prices_output_<timestamp>.csv ./backup.csv
  51. *
  52. * 3. Write to stdout and capture locally:
  53. * kubectl exec -it <pod-name> -- node scripts/stripe/rollback_price_changes.mjs \
  54. * --region us --commit --output - input.csv > output.csv
  55. *
  56. * Examples:
  57. * # Dry run (preview only)
  58. * node scripts/stripe/rollback_price_changes.mjs --region us input.csv
  59. *
  60. * # Actually perform the rollback
  61. * node scripts/stripe/rollback_price_changes.mjs --region us --commit input.csv
  62. */
  63. import fs from 'node:fs'
  64. import path from 'node:path'
  65. import { setTimeout } from 'node:timers/promises'
  66. import * as csv from 'csv'
  67. import minimist from 'minimist'
  68. import AnalyticsManager from '../../app/src/Features/Analytics/AnalyticsManager.mjs'
  69. import { z } from '../../app/src/infrastructure/Validation.mjs'
  70. import { scriptRunner } from '../lib/ScriptRunner.mjs'
  71. import { getRegionClient } from '../../modules/subscriptions/app/src/StripeClient.mjs'
  72. import { ReportError, getProductIdFromItem } from './helpers.mjs'
  73. /**
  74. * @import { CSVSubscriptionChange, StripeClient } from './helpers.mjs'
  75. * @import Stripe from 'stripe'
  76. * @import { ReadStream } from 'node:fs'
  77. * @import { Parser } from 'csv-parse'
  78. * @import { Stringifier } from 'csv-stringify'
  79. */
  80. // 100 ms corresponds to 10 requests per second (cautious rate within Stripe's 100 req/s limit)
  81. const DEFAULT_THROTTLE = 100
  82. /**
  83. * Print usage information to stderr
  84. */
  85. function usage() {
  86. console.error(`Usage: node scripts/stripe/rollback_price_changes.mjs [OPTIONS] [INPUT-FILE]
  87. Rollback pending price changes for Stripe subscriptions.
  88. This script only removes pending subscription schedules that are purely price changes on an
  89. existing plan. If a user has made any other modifications (plan change, add-on
  90. changes), the subscription is skipped.
  91. Options:
  92. --region REGION Either 'uk' or 'us' (required)
  93. --output PATH Output file path (default: /tmp/rollback_prices_output_<timestamp>.csv)
  94. Use '-' to write to stdout
  95. --commit Apply changes (without this, runs in dry-run mode)
  96. --throttle DURATION Minimum time between requests in ms (default: ${DEFAULT_THROTTLE})
  97. --help Show this help message
  98. See the source file header for detailed documentation on CSV format and pod usage.
  99. `)
  100. }
  101. /**
  102. * Main script entry point
  103. * @param {function(string): Promise<void>} trackProgress - Function to log progress messages
  104. */
  105. async function main(trackProgress) {
  106. const opts = parseArgs()
  107. const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  108. const outputFile =
  109. opts.output ?? `/tmp/rollback_prices_output_${timestamp}.csv`
  110. const stripeClient = getRegionClient(opts.region)
  111. await trackProgress('Starting price rollback script for Stripe')
  112. await trackProgress(`Region: ${opts.region}`)
  113. await trackProgress(`Run mode: ${opts.commit ? 'COMMIT' : 'DRY RUN'}`)
  114. await trackProgress(`Throttle: ${opts.throttle}ms between requests`)
  115. const inputStream = opts.inputFile
  116. ? fs.createReadStream(opts.inputFile)
  117. : process.stdin
  118. const csvReader = getCsvReader(inputStream)
  119. const csvWriter = getCsvWriter(outputFile)
  120. await trackProgress(`Output: ${outputFile === '-' ? 'stdout' : outputFile}`)
  121. let processedCount = 0
  122. let successCount = 0
  123. let skippedCount = 0
  124. let errorCount = 0
  125. let lastLoopTimestamp = 0
  126. for await (const record of csvReader) {
  127. const timeSinceLastLoop = Date.now() - lastLoopTimestamp
  128. if (timeSinceLastLoop < opts.throttle) {
  129. await setTimeout(opts.throttle - timeSinceLastLoop)
  130. }
  131. lastLoopTimestamp = Date.now()
  132. processedCount++
  133. try {
  134. const result = await processRollback(record, stripeClient, opts.commit)
  135. if (opts.commit && result.subscription) {
  136. try {
  137. const userId = result.subscription.customer.metadata?.userId
  138. await AnalyticsManager.recordEventForUser(
  139. userId,
  140. 'script_price_change_reversed',
  141. {
  142. subscriptionId: record.subscription_id,
  143. }
  144. )
  145. } catch (err) {
  146. await trackProgress(
  147. `Warning: failed to record analytics event after successful price rollback for ${record.subscription_id}: ${err.message}`
  148. )
  149. }
  150. }
  151. csvWriter.write({
  152. subscription_id: record.subscription_id,
  153. status: result.status,
  154. note: result.note || '',
  155. })
  156. if (result.status === 'skipped') {
  157. skippedCount++
  158. } else {
  159. successCount++
  160. }
  161. if (processedCount % 10 === 0) {
  162. await trackProgress(
  163. `Processed ${processedCount} subscriptions (${successCount} ${opts.commit ? 'rolled-back' : 'validated'}, ${skippedCount} skipped, ${errorCount} errors)`
  164. )
  165. }
  166. } catch (err) {
  167. errorCount++
  168. if (err instanceof ReportError) {
  169. csvWriter.write({
  170. subscription_id: record.subscription_id,
  171. status: err.status,
  172. note: err.message,
  173. })
  174. } else {
  175. csvWriter.write({
  176. subscription_id: record.subscription_id,
  177. status: 'error',
  178. note: err.message,
  179. })
  180. await trackProgress(
  181. `Error processing ${record.subscription_id}: ${err.message}`
  182. )
  183. }
  184. }
  185. }
  186. await trackProgress('\n✨ FINAL SUMMARY ✨')
  187. await trackProgress(`📊 Total processed: ${processedCount}`)
  188. if (opts.commit) {
  189. await trackProgress(`✅ Successfully rolled back: ${successCount}`)
  190. } else {
  191. await trackProgress(`✅ Successfully validated: ${successCount}`)
  192. await trackProgress('ℹ️ DRY RUN: No changes were applied to Stripe')
  193. }
  194. await trackProgress(`⏭️ Skipped: ${skippedCount}`)
  195. await trackProgress(`❌ Errors: ${errorCount}`)
  196. await trackProgress('🎉 Script completed!')
  197. csvWriter.end()
  198. }
  199. /**
  200. * Get a CSV parser configured for subscription change input
  201. * @param {ReadStream | NodeJS.ReadableStream} inputStream - The input stream to parse
  202. * @returns {Parser} The configured CSV parser
  203. */
  204. function getCsvReader(inputStream) {
  205. const parser = csv.parse({
  206. columns: true,
  207. })
  208. inputStream.pipe(parser)
  209. return parser
  210. }
  211. /**
  212. * Get a CSV stringifier configured for output
  213. * @param {string} outputFile - The output file path to write to, or '-' for stdout
  214. * @returns {Stringifier} The configured CSV stringifier
  215. */
  216. function getCsvWriter(outputFile) {
  217. let outputStream
  218. if (outputFile === '-') {
  219. outputStream = process.stdout
  220. } else {
  221. fs.mkdirSync(path.dirname(outputFile), { recursive: true })
  222. outputStream = fs.createWriteStream(outputFile)
  223. }
  224. const writer = csv.stringify({
  225. columns: ['subscription_id', 'status', 'note'],
  226. header: true,
  227. })
  228. writer.on('error', err => {
  229. console.error(err)
  230. process.exit(1)
  231. })
  232. writer.pipe(outputStream)
  233. return writer
  234. }
  235. /**
  236. * Process a single subscription rollback
  237. * @param {CSVSubscriptionChange} record - The subscription record to process
  238. * @param {StripeClient} stripeClient - The Stripe client for the region
  239. * @param {boolean} commit - Whether to commit changes or run in dry-run mode
  240. * @returns {Promise<{status: string, note: string, subscription?: Stripe.Subscription}>} The result of the rollback
  241. */
  242. async function processRollback(record, stripeClient, commit) {
  243. const subscription = await fetchSubscription(
  244. record.subscription_id,
  245. stripeClient
  246. )
  247. // Validate this is a price-only change that we created
  248. const validation = await validatePriceOnlyChange(
  249. record,
  250. subscription,
  251. stripeClient
  252. )
  253. if (!validation.isPriceOnly) {
  254. return {
  255. status: 'skipped',
  256. note: `${validation.reason}: ${validation.detail || 'N/A'}`,
  257. }
  258. }
  259. if (!commit) {
  260. return {
  261. status: 'validated',
  262. note: `Would release subscription schedule: ${validation.scheduleId}`,
  263. }
  264. }
  265. // Safe to release - this is a price-only change matching our expected values
  266. await stripeClient.stripe.subscriptionSchedules.release(validation.scheduleId)
  267. return {
  268. status: 'rolled-back',
  269. note: `Released subscription schedule: ${validation.scheduleId}`,
  270. subscription,
  271. }
  272. }
  273. /**
  274. * Fetch a subscription from Stripe
  275. * @param {string} subscriptionId - The Stripe subscription id
  276. * @param {StripeClient} stripeClient - The Stripe client for the region
  277. * @returns {Promise<Stripe.Subscription>} The subscription with expanded schedule
  278. * @throws {ReportError} If subscription is not found
  279. */
  280. async function fetchSubscription(subscriptionId, stripeClient) {
  281. try {
  282. const subscription = await stripeClient.stripe.subscriptions.retrieve(
  283. subscriptionId,
  284. {
  285. expand: [
  286. 'schedule',
  287. 'schedule.phases.items.price',
  288. 'items.data.price',
  289. 'customer',
  290. ],
  291. }
  292. )
  293. return subscription
  294. } catch (err) {
  295. if (err.type === 'StripeInvalidRequestError' && err.statusCode === 404) {
  296. throw new ReportError('not-found', 'subscription not found')
  297. }
  298. throw err
  299. }
  300. }
  301. /**
  302. * Validate that the subscription schedule is a price-only change created by our
  303. * price increase script, and not a user-initiated plan change or add-on modification.
  304. *
  305. * @param {CSVSubscriptionChange} record - The CSV record with expected values
  306. * @param {Stripe.Subscription} subscription - The Stripe subscription
  307. * @param {StripeClient} stripeClient - The Stripe client for the region
  308. * @returns {Promise<{ isPriceOnly: boolean, reason?: string, detail?: string, scheduleId?: string }>}
  309. */
  310. async function validatePriceOnlyChange(record, subscription, stripeClient) {
  311. // Must have a subscription schedule
  312. if (!subscription.schedule) {
  313. return {
  314. isPriceOnly: false,
  315. reason: 'no-pending-change',
  316. detail: 'subscription has no schedule to rollback',
  317. }
  318. }
  319. // Subscription must be updatable
  320. const inactiveStatuses = [
  321. 'incomplete',
  322. 'incomplete_expired',
  323. 'canceled',
  324. 'trialing',
  325. ]
  326. if (inactiveStatuses.includes(subscription.status)) {
  327. return {
  328. isPriceOnly: false,
  329. reason: 'inactive',
  330. detail: `subscription status: ${subscription.status}`,
  331. }
  332. }
  333. // Subscription should not be scheduled to be canceled
  334. if (subscription.cancel_at_period_end) {
  335. return {
  336. isPriceOnly: false,
  337. reason: 'inactive',
  338. detail: 'subscription is scheduled to be canceled at period end',
  339. }
  340. }
  341. // Get the schedule (already expanded in subscription fetch)
  342. const schedule =
  343. typeof subscription.schedule === 'string' ? null : subscription.schedule
  344. if (!schedule) {
  345. return {
  346. isPriceOnly: false,
  347. reason: 'no-pending-change',
  348. detail: 'subscription schedule not expanded',
  349. }
  350. }
  351. const scheduleId = schedule.id
  352. // Schedule must not be released already
  353. if (schedule.status === 'released') {
  354. return {
  355. isPriceOnly: false,
  356. reason: 'schedule-released',
  357. detail: 'schedule has already been released',
  358. }
  359. }
  360. // Schedule must have exactly 2 phases (current + future)
  361. if (schedule.phases.length !== 2) {
  362. return {
  363. isPriceOnly: false,
  364. reason: 'unexpected-schedule-structure',
  365. detail: `expected 2 phases, got ${schedule.phases.length}`,
  366. }
  367. }
  368. const currentPhase = schedule.phases[0]
  369. const nextPhase = schedule.phases[1]
  370. // All phases must have same number of items (no add-ons added/removed)
  371. const currentPhaseItemCount = currentPhase.items.length
  372. const subscriptionItemCount = subscription.items.data.length
  373. const nextPhaseItemCount = nextPhase.items.length
  374. if (currentPhaseItemCount !== subscriptionItemCount) {
  375. return {
  376. isPriceOnly: false,
  377. reason: 'item-count-mismatch',
  378. detail: `current phase has ${currentPhaseItemCount} items, subscription has ${subscriptionItemCount}`,
  379. }
  380. }
  381. if (nextPhaseItemCount !== currentPhaseItemCount) {
  382. return {
  383. isPriceOnly: false,
  384. reason: 'addon-change-detected',
  385. detail: `next phase has ${nextPhaseItemCount} items, current has ${currentPhaseItemCount}`,
  386. }
  387. }
  388. // Verify current lookup keys match expected
  389. const currentLookupKeys = new Set(
  390. subscription.items.data.map(item => item.price.lookup_key)
  391. )
  392. if (!currentLookupKeys.has(record.current_lookup_key)) {
  393. return {
  394. isPriceOnly: false,
  395. reason: 'current-price-mismatch',
  396. detail: `expected current_lookup_key ${record.current_lookup_key} not found in subscription`,
  397. }
  398. }
  399. if (
  400. record.current_add_on_lookup_key &&
  401. !currentLookupKeys.has(record.current_add_on_lookup_key)
  402. ) {
  403. return {
  404. isPriceOnly: false,
  405. reason: 'current-addon-price-mismatch',
  406. detail: `expected current_add_on_lookup_key ${record.current_add_on_lookup_key} not found in subscription`,
  407. }
  408. }
  409. // Verify next phase price IDs match expected
  410. const nextPhaseLookupKeys = new Set(
  411. nextPhase.items.map(item => item.price.lookup_key)
  412. )
  413. if (!nextPhaseLookupKeys.has(record.new_lookup_key)) {
  414. return {
  415. isPriceOnly: false,
  416. reason: 'pending-price-mismatch',
  417. detail: `expected new_lookup_key ${record.new_lookup_key} not found in next phase`,
  418. }
  419. }
  420. if (
  421. record.new_add_on_lookup_key &&
  422. !nextPhaseLookupKeys.has(record.new_add_on_lookup_key)
  423. ) {
  424. return {
  425. isPriceOnly: false,
  426. reason: 'pending-addon-price-mismatch',
  427. detail: `expected new_add_on_lookup_key ${record.new_add_on_lookup_key} not found in next phase`,
  428. }
  429. }
  430. // Verify quantities remain the same and products match (no plan/add-on changes)
  431. for (const currentItem of currentPhase.items) {
  432. const currentLookupKey = currentItem.price.lookup_key
  433. const currentProductId = getProductIdFromItem(currentItem)
  434. const nextItem = nextPhase.items.find(item => {
  435. const nextLookupKey = item.price.lookup_key
  436. const nextProductId = getProductIdFromItem(item)
  437. // Match by product ID to handle price changes
  438. return (
  439. nextLookupKey === currentLookupKey || nextProductId === currentProductId
  440. )
  441. })
  442. if (!nextItem) {
  443. return {
  444. isPriceOnly: false,
  445. reason: 'item-mismatch',
  446. detail: `current phase item ${currentLookupKey} not found in next phase`,
  447. }
  448. }
  449. // Verify quantity hasn't changed
  450. if (nextItem.quantity !== currentItem.quantity) {
  451. return {
  452. isPriceOnly: false,
  453. reason: 'quantity-change-detected',
  454. detail: `quantity change: ${currentItem.quantity} -> ${nextItem.quantity}`,
  455. }
  456. }
  457. // Verify product hasn't changed
  458. const nextProductId = getProductIdFromItem(nextItem)
  459. if (
  460. currentProductId &&
  461. nextProductId &&
  462. currentProductId !== nextProductId
  463. ) {
  464. return {
  465. isPriceOnly: false,
  466. reason: 'product-change-detected',
  467. detail: `product change: ${currentProductId} -> ${nextProductId}`,
  468. }
  469. }
  470. }
  471. // All checks passed - this is a price-only change we created
  472. return { isPriceOnly: true, scheduleId }
  473. }
  474. const paramsSchema = z.object({
  475. region: z.enum(['uk', 'us']),
  476. output: z.string().optional(),
  477. commit: z.boolean().default(false),
  478. throttle: z
  479. .string()
  480. .optional()
  481. .transform(val => (val ? parseInt(val, 10) : DEFAULT_THROTTLE)),
  482. _: z.array(z.string()).max(1),
  483. help: z.boolean().optional(),
  484. })
  485. /**
  486. * Parse command line arguments
  487. * @returns {{inputFile: string | undefined, output: string | undefined, commit: boolean, throttle: number, region: 'uk' | 'us'}} Parsed options
  488. */
  489. function parseArgs() {
  490. const argv = minimist(process.argv.slice(2), {
  491. string: ['throttle', 'output', 'region'],
  492. boolean: ['help', 'commit'],
  493. })
  494. if (argv.help) {
  495. usage()
  496. process.exit(0)
  497. }
  498. const parseResult = paramsSchema.safeParse(argv)
  499. if (!parseResult.success) {
  500. console.error(`Invalid parameters: ${parseResult.error.message}`)
  501. usage()
  502. process.exit(1)
  503. }
  504. const { region, output, commit, throttle, _ } = parseResult.data
  505. return {
  506. inputFile: _[0],
  507. output,
  508. commit,
  509. throttle,
  510. region,
  511. }
  512. }
  513. try {
  514. await scriptRunner(main)
  515. process.exit(0)
  516. } catch (error) {
  517. console.error(error)
  518. process.exit(1)
  519. }