create_prices_from_csv.mjs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // @ts-check
  2. /**
  3. * This script creates new Products and Prices in Stripe from a CSV file.
  4. * Use this when adding entirely new plans that don't exist in Stripe yet.
  5. *
  6. * Usage:
  7. * node scripts/stripe/create_prices_from_csv.mjs -f <file> --region <us|uk> --version <v> [options]
  8. *
  9. * Options:
  10. * -f Path to the prices CSV file.
  11. * --region Stripe region (us or uk).
  12. * --version Version string for the lookup_key (e.g., 'v1', 'jan2026').
  13. * --commit Apply changes to Stripe (default is dry-run).
  14. *
  15. * CSV Format:
  16. * planCode,productName,productDescription,interval,USD,GBP,EUR
  17. * essentials,Essentials Monthly,"Editable project limit 10, collaborators 5",month,21,17,19
  18. * essentials-annual,Essentials Annual,"Editable project limit 10, collaborators 5",year,199,159,179
  19. */
  20. import minimist from 'minimist'
  21. import fs from 'node:fs'
  22. // https://github.com/import-js/eslint-plugin-import/issues/1810
  23. // eslint-disable-next-line import/no-unresolved
  24. import * as csv from 'csv/sync'
  25. import { scriptRunner } from '../lib/ScriptRunner.mjs'
  26. import { getRegionClient } from '../../modules/subscriptions/app/src/StripeClient.mjs'
  27. import { z } from '@overleaf/validation-tools'
  28. import { convertToMinorUnits, rateLimitSleep } from './helpers.mjs'
  29. /**
  30. * @typedef {object} PriceRecord
  31. * @property {string} planCode
  32. * @property {string} productName - Optional, can be derived from planCode if not provided
  33. * @property {string} productDescription - Optional
  34. * @property {string} interval - 'month' or 'year'
  35. * @property {Record<string, string | number>} currencies - Dynamic currency columns
  36. */
  37. /**
  38. * @typedef {import('stripe').Stripe} Stripe
  39. * @typedef {import('stripe').Stripe.Price} Price
  40. * @typedef {import('stripe').Stripe.PriceCreateParams} PriceCreateParams
  41. * @typedef {import('stripe').Stripe.Product} Product
  42. */
  43. const paramsSchema = z.object({
  44. f: z.string(),
  45. region: z.enum(['us', 'uk']),
  46. version: z.string(),
  47. commit: z.boolean().default(false),
  48. })
  49. /**
  50. * @param {import('stripe').Stripe} stripe
  51. * @returns {Promise<Record<string, Price>>}
  52. */
  53. async function getExistingPrices(stripe) {
  54. /** @type {Record<string, Price>} */
  55. const pricesByLookupKey = {}
  56. let startingAfter
  57. do {
  58. const response = await stripe.prices.list({
  59. limit: 100,
  60. starting_after: startingAfter,
  61. })
  62. for (const price of response.data) {
  63. if (price.lookup_key) {
  64. pricesByLookupKey[price.lookup_key] = price
  65. }
  66. }
  67. startingAfter = response.has_more
  68. ? response.data[response.data.length - 1].id
  69. : undefined
  70. } while (startingAfter)
  71. return pricesByLookupKey
  72. }
  73. /**
  74. * @param {import('stripe').Stripe} stripe
  75. * @return {Promise<Record<string, Product>>}
  76. */
  77. async function getExistingProducts(stripe) {
  78. /** @type {Record<string, Product>} */
  79. const productsById = {}
  80. let startingAfter
  81. do {
  82. const response = await stripe.products.list({
  83. limit: 100,
  84. starting_after: startingAfter,
  85. })
  86. for (const product of response.data) {
  87. productsById[product.id] = product
  88. }
  89. startingAfter = response.has_more
  90. ? response.data[response.data.length - 1].id
  91. : undefined
  92. } while (startingAfter)
  93. return productsById
  94. }
  95. export async function main(trackProgress) {
  96. const args = minimist(process.argv.slice(2), {
  97. boolean: ['commit'],
  98. string: ['region', 'f', 'version'],
  99. })
  100. const parseResult = paramsSchema.safeParse(args)
  101. if (!parseResult.success) {
  102. throw new Error(`Invalid parameters: ${parseResult.error.message}`)
  103. }
  104. const { f: inputFile, region, version, commit } = parseResult.data
  105. const mode = commit ? 'COMMIT MODE' : 'DRY RUN MODE'
  106. const log = (message = '') =>
  107. trackProgress(mode === 'DRY RUN MODE' ? `[DRY RUN] ${message}` : message)
  108. await log(`Starting creation script in ${mode} for region: ${region}`)
  109. const stripe = getRegionClient(region).stripe
  110. // Load and Parse CSV
  111. const content = fs.readFileSync(inputFile, 'utf-8')
  112. const records = csv.parse(content, { columns: true, skip_empty_lines: true })
  113. if (records.length === 0) {
  114. throw new Error('CSV file is empty or invalid.')
  115. }
  116. // Identify currency columns (everything except planCode)
  117. const currencyKeys = Object.keys(records[0]).filter(k => k !== 'planCode')
  118. // Cache existing data to minimize API calls and prevent duplicates
  119. await log('Fetching existing Stripe data...')
  120. const existingPrices = await getExistingPrices(stripe)
  121. const existingProducts = await getExistingProducts(stripe)
  122. const summary = {
  123. productsCreated: 0,
  124. pricesCreated: 0,
  125. skipped: 0,
  126. invalidRows: 0,
  127. errors: 0,
  128. }
  129. let rowNumber = 0 // For logging purposes, starting after header
  130. for (const /** @type {PriceRecord} */ record of records) {
  131. ++rowNumber
  132. const { planCode, productDescription, interval } = record
  133. if (!planCode) {
  134. await log(`✗ No plan code in row ${rowNumber}`)
  135. ++summary.invalidRows
  136. continue
  137. }
  138. if (interval !== 'month' && interval !== 'year') {
  139. await log(
  140. `✗ Invalid interval '${interval}' on row ${rowNumber}. Must be either 'month' or 'year'.`
  141. )
  142. ++summary.invalidRows
  143. continue
  144. }
  145. await log()
  146. await log(`--- Processing Plan: ${planCode} ---`)
  147. // 1. Handle product
  148. if (!existingProducts[planCode]) {
  149. const productName =
  150. record.productName ||
  151. planCode
  152. .split(/[_-]/) // Handle underscores or hyphens
  153. .map(word => word.charAt(0).toUpperCase() + word.slice(1))
  154. .join(' ')
  155. if (commit) {
  156. try {
  157. await stripe.products.create({
  158. id: planCode,
  159. name: productName,
  160. description: productDescription || undefined, // Don't pass an empty string, Stripe thinks we're trying to unset it and doesn't like it
  161. tax_code: 'txcd_10103000', // "Software as a service (SaaS) - personal use", which is what existing products have
  162. metadata: { planCode },
  163. })
  164. await rateLimitSleep()
  165. } catch (err) {
  166. const errorMessage = err instanceof Error ? err.message : String(err)
  167. await log(`✗ Error creating product ${planCode}: ${errorMessage}`)
  168. summary.errors++
  169. continue // Skip prices if product creation failed
  170. }
  171. }
  172. await log(`✓ Created product: ${planCode} ("${productName}")`)
  173. summary.productsCreated++
  174. } else {
  175. await log(`- Product '${planCode}' already exists.`)
  176. }
  177. // 2. Handle Prices for each currency column
  178. for (const currency of currencyKeys) {
  179. const amountValue = parseFloat(record[currency])
  180. if (isNaN(amountValue) || amountValue <= 0) continue
  181. const currencyLower = currency.toLowerCase()
  182. // Standardize lookup key format: {plan}_{interval}_{version}_{currency}
  183. const lookupKey = `${planCode}_${interval}_${version}_${currencyLower}`
  184. if (existingPrices[lookupKey]) {
  185. await log(` - Price '${lookupKey}' already exists. Skipping.`)
  186. summary.skipped++
  187. continue
  188. }
  189. /** @type {PriceCreateParams} */
  190. const priceParams = {
  191. product: planCode,
  192. currency: currencyLower,
  193. unit_amount: convertToMinorUnits(amountValue, currencyLower),
  194. recurring: { interval },
  195. lookup_key: lookupKey,
  196. }
  197. if (commit) {
  198. try {
  199. await stripe.prices.create(priceParams)
  200. await rateLimitSleep()
  201. } catch (err) {
  202. const errorMessage = err instanceof Error ? err.message : String(err)
  203. await log(` ✗ Error creating price ${lookupKey}: ${errorMessage}`)
  204. summary.errors++
  205. continue
  206. }
  207. }
  208. await log(
  209. ` ✓ Created price: ${lookupKey} (${amountValue} ${currencyLower.toUpperCase()})`
  210. )
  211. summary.pricesCreated++
  212. }
  213. }
  214. // Final Summary
  215. await log()
  216. await log('='.repeat(20))
  217. await log()
  218. await log('✨ FINAL SUMMARY ✨')
  219. await log(` ✅ Products created: ${summary.productsCreated}`)
  220. await log(` ✅ Prices created: ${summary.pricesCreated}`)
  221. await log(` ⏭️ Items skipped: ${summary.skipped}`)
  222. await log(` ⏭️ Invalid rows skipped: ${summary.invalidRows}`)
  223. await log(` ❌ Errors encountered: ${summary.errors}`)
  224. if (!commit) {
  225. await log('ℹ️ DRY RUN: No changes were applied to Stripe')
  226. }
  227. await log('🎉 Script completed!')
  228. }
  229. if (import.meta.main) {
  230. try {
  231. await scriptRunner(main)
  232. process.exit(0)
  233. } catch (error) {
  234. console.error(error)
  235. process.exit(1)
  236. }
  237. }