archive_prices_by_version_key.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #!/usr/bin/env node
  2. /**
  3. * This script archives or unarchives all prices with a matching version key in their lookup key
  4. *
  5. * Usage:
  6. * node scripts/stripe/archive_prices_by_version_key.mjs --region us --version versionKey [options]
  7. * node scripts/stripe/archive_prices_by_version_key.mjs --region uk --version versionKey [options]
  8. *
  9. * Options:
  10. * --region Required. Stripe region to process (us or uk)
  11. * --version Required. Version key to match in lookup keys (e.g., 'jul2025')
  12. * --action Required. Action to perform: 'archive' or 'unarchive'
  13. * --commit Actually perform the updates (default: dry-run mode)
  14. *
  15. * Examples:
  16. * # Dry run archive prices with version 'jul2025' in US region
  17. * node scripts/stripe/archive_prices_by_version_key.mjs --region us --version jul2025 --action archive
  18. *
  19. * # Commit archive prices with version 'jul2025' in UK region
  20. * node scripts/stripe/archive_prices_by_version_key.mjs --region uk --version jul2025 --action archive --commit
  21. *
  22. * # Unarchive prices with version 'jul2025'
  23. * node scripts/stripe/archive_prices_by_version_key.mjs --region us --version jul2025 --action unarchive --commit
  24. */
  25. import minimist from 'minimist'
  26. import { z } from '../../app/src/infrastructure/Validation.mjs'
  27. import { scriptRunner } from '../lib/ScriptRunner.mjs'
  28. import { getRegionClient } from '../../modules/subscriptions/app/src/StripeClient.mjs'
  29. /**
  30. * @import Stripe from 'stripe'
  31. */
  32. const paramsSchema = z.object({
  33. region: z.enum(['us', 'uk']),
  34. version: z.string(),
  35. action: z.enum(['archive', 'unarchive']),
  36. commit: z.boolean().default(false),
  37. })
  38. /**
  39. * Sleep function to respect Stripe rate limits (100 requests per second)
  40. */
  41. async function rateLimitSleep() {
  42. return new Promise(resolve => setTimeout(resolve, 50))
  43. }
  44. /**
  45. * Fetch all prices matching the version key from Stripe
  46. *
  47. * @param {Stripe} stripe
  48. * @param {string} version
  49. * @param {function} trackProgress
  50. * @returns {Promise<Stripe.Price[]>}
  51. */
  52. async function fetchPricesByVersion(stripe, version, trackProgress) {
  53. const matchingPrices = []
  54. let hasMore = true
  55. let startingAfter
  56. await trackProgress('Fetching prices from Stripe...')
  57. while (hasMore) {
  58. const pricesResult = await stripe.prices.list({
  59. limit: 100,
  60. starting_after: startingAfter,
  61. })
  62. // Filter prices that have the version in their lookup key
  63. const filtered = pricesResult.data.filter(
  64. price => price.lookup_key && price.lookup_key.includes(version)
  65. )
  66. matchingPrices.push(...filtered)
  67. hasMore = pricesResult.has_more
  68. if (hasMore) {
  69. startingAfter = pricesResult.data[pricesResult.data.length - 1].id
  70. }
  71. await rateLimitSleep()
  72. }
  73. await trackProgress(`Found ${matchingPrices.length} matching prices...`)
  74. return matchingPrices
  75. }
  76. /**
  77. * Archive or unarchive prices in Stripe
  78. *
  79. * @param {Stripe.Price[]} prices
  80. * @param {Stripe} stripe
  81. * @param {string} action
  82. * @param {boolean} commit
  83. * @param {function} trackProgress
  84. * @returns {Promise<object>}
  85. */
  86. async function processPrices(prices, stripe, action, commit, trackProgress) {
  87. const targetActiveStatus = action === 'unarchive'
  88. const results = {
  89. processed: 0,
  90. skipped: 0,
  91. errored: 0,
  92. }
  93. for (const price of prices) {
  94. try {
  95. // Skip if already in the desired state
  96. if (price.active === targetActiveStatus) {
  97. await trackProgress(
  98. `Skipping price ${price.id} (${price.lookup_key}) - already ${price.active ? 'active' : 'archived'}`
  99. )
  100. results.skipped++
  101. continue
  102. }
  103. if (commit) {
  104. await stripe.prices.update(price.id, { active: targetActiveStatus })
  105. await trackProgress(
  106. `${action === 'archive' ? 'Archived' : 'Unarchived'} price: ${price.id} (${price.lookup_key})`
  107. )
  108. await rateLimitSleep()
  109. } else {
  110. await trackProgress(
  111. `[DRY RUN] Would ${action} price: ${price.id} (${price.lookup_key})`
  112. )
  113. }
  114. results.processed++
  115. } catch (error) {
  116. await trackProgress(
  117. `ERROR processing price ${price.id}: ${error.message}`
  118. )
  119. results.errored++
  120. }
  121. }
  122. return results
  123. }
  124. async function main(trackProgress) {
  125. const parseResult = paramsSchema.safeParse(
  126. minimist(process.argv.slice(2), {
  127. boolean: ['commit'],
  128. string: ['region', 'version', 'action'],
  129. })
  130. )
  131. if (!parseResult.success) {
  132. throw new Error(`Invalid parameters: ${parseResult.error.message}`)
  133. }
  134. const { region, version, action, commit } = parseResult.data
  135. const mode = commit ? 'COMMIT MODE' : 'DRY RUN MODE'
  136. await trackProgress(`Starting ${action} in ${mode} for region: ${region}`)
  137. await trackProgress(`Target version: ${version}`)
  138. const stripe = getRegionClient(region).stripe
  139. const prices = await fetchPricesByVersion(stripe, version, trackProgress)
  140. if (prices.length === 0) {
  141. await trackProgress('No prices found. Exiting.')
  142. return
  143. }
  144. await trackProgress(`Processing ${action} operation...`)
  145. const results = await processPrices(
  146. prices,
  147. stripe,
  148. action,
  149. commit,
  150. trackProgress
  151. )
  152. await trackProgress('OPERATION SUMMARY')
  153. await trackProgress(
  154. `Prices ${commit ? 'processed' : 'would be processed'}: ${results.processed}`
  155. )
  156. await trackProgress(
  157. `Prices skipped (already in desired state): ${results.skipped}`
  158. )
  159. await trackProgress(`Prices errored: ${results.errored}`)
  160. if (results.errored > 0) {
  161. await trackProgress(
  162. 'WARNING: Some prices failed to process. Check the logs above.'
  163. )
  164. }
  165. if (!commit) {
  166. await trackProgress(
  167. 'This was a dry run. Use --commit to actually perform the operation.'
  168. )
  169. }
  170. await trackProgress(`Script completed in ${mode}`)
  171. }
  172. try {
  173. await scriptRunner(main)
  174. process.exit(0)
  175. } catch (error) {
  176. console.error('Script failed:', error.message)
  177. process.exit(1)
  178. }