create_prices_from_csv.mjs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. /** @type {any} */
  59. const response = await stripe.prices.list({
  60. limit: 100,
  61. starting_after: startingAfter,
  62. })
  63. for (const price of response.data) {
  64. if (price.lookup_key) {
  65. pricesByLookupKey[price.lookup_key] = price
  66. }
  67. }
  68. startingAfter = response.has_more
  69. ? response.data[response.data.length - 1].id
  70. : undefined
  71. } while (startingAfter)
  72. return pricesByLookupKey
  73. }
  74. /**
  75. * @param {import('stripe').Stripe} stripe
  76. * @return {Promise<Record<string, Product>>}
  77. */
  78. async function getExistingProducts(stripe) {
  79. /** @type {Record<string, Product>} */
  80. const productsById = {}
  81. let startingAfter
  82. do {
  83. /** @type {any} */
  84. const response = await stripe.products.list({
  85. limit: 100,
  86. starting_after: startingAfter,
  87. })
  88. for (const product of response.data) {
  89. productsById[product.id] = product
  90. }
  91. startingAfter = response.has_more
  92. ? response.data[response.data.length - 1].id
  93. : undefined
  94. } while (startingAfter)
  95. return productsById
  96. }
  97. /**
  98. * @param {any} trackProgress
  99. */
  100. export async function main(trackProgress) {
  101. const args = minimist(process.argv.slice(2), {
  102. boolean: ['commit'],
  103. string: ['region', 'f', 'version'],
  104. })
  105. const parseResult = paramsSchema.safeParse(args)
  106. if (!parseResult.success) {
  107. throw new Error(`Invalid parameters: ${parseResult.error.message}`)
  108. }
  109. const { f: inputFile, region, version, commit } = parseResult.data
  110. const mode = commit ? 'COMMIT MODE' : 'DRY RUN MODE'
  111. const log = (message = '') =>
  112. trackProgress(mode === 'DRY RUN MODE' ? `[DRY RUN] ${message}` : message)
  113. await log(`Starting creation script in ${mode} for region: ${region}`)
  114. const stripe = getRegionClient(region).stripe
  115. // Load and Parse CSV
  116. const content = fs.readFileSync(inputFile, 'utf-8')
  117. /** @type {PriceRecord[]} */
  118. const records = csv.parse(content, { columns: true, skip_empty_lines: true })
  119. if (records.length === 0) {
  120. throw new Error('CSV file is empty or invalid.')
  121. }
  122. // Identify currency columns (everything except planCode)
  123. const currencyKeys = Object.keys(records[0]).filter(k => k !== 'planCode')
  124. // Cache existing data to minimize API calls and prevent duplicates
  125. await log('Fetching existing Stripe data...')
  126. const existingPrices = await getExistingPrices(stripe)
  127. const existingProducts = await getExistingProducts(stripe)
  128. const summary = {
  129. productsCreated: 0,
  130. pricesCreated: 0,
  131. skipped: 0,
  132. invalidRows: 0,
  133. errors: 0,
  134. }
  135. let rowNumber = 0 // For logging purposes, starting after header
  136. for (const /** @type {PriceRecord} */ record of records) {
  137. ++rowNumber
  138. const { planCode, productDescription, interval } = record
  139. if (!planCode) {
  140. await log(`✗ No plan code in row ${rowNumber}`)
  141. ++summary.invalidRows
  142. continue
  143. }
  144. if (interval !== 'month' && interval !== 'year') {
  145. await log(
  146. `✗ Invalid interval '${interval}' on row ${rowNumber}. Must be either 'month' or 'year'.`
  147. )
  148. ++summary.invalidRows
  149. continue
  150. }
  151. await log()
  152. await log(`--- Processing Plan: ${planCode} ---`)
  153. // 1. Handle product
  154. if (!existingProducts[planCode]) {
  155. const productName =
  156. record.productName ||
  157. planCode
  158. .split(/[_-]/) // Handle underscores or hyphens
  159. .map(
  160. /** @param {any} word */
  161. word => word.charAt(0).toUpperCase() + word.slice(1)
  162. )
  163. .join(' ')
  164. if (commit) {
  165. try {
  166. await stripe.products.create({
  167. id: planCode,
  168. name: productName,
  169. description: productDescription || undefined, // Don't pass an empty string, Stripe thinks we're trying to unset it and doesn't like it
  170. tax_code: 'txcd_10103000', // "Software as a service (SaaS) - personal use", which is what existing products have
  171. metadata: { planCode },
  172. })
  173. await rateLimitSleep()
  174. } catch (err) {
  175. const errorMessage = err instanceof Error ? err.message : String(err)
  176. await log(`✗ Error creating product ${planCode}: ${errorMessage}`)
  177. summary.errors++
  178. continue // Skip prices if product creation failed
  179. }
  180. }
  181. await log(`✓ Created product: ${planCode} ("${productName}")`)
  182. summary.productsCreated++
  183. } else {
  184. await log(`- Product '${planCode}' already exists.`)
  185. }
  186. // 2. Handle Prices for each currency column
  187. for (const currency of currencyKeys) {
  188. const amountValue = parseFloat(/** @type {any} */ (record)[currency])
  189. if (isNaN(amountValue) || amountValue <= 0) continue
  190. const currencyLower = currency.toLowerCase()
  191. // Standardize lookup key format: {plan}_{interval}_{version}_{currency}
  192. const lookupKey = `${planCode}_${interval}_${version}_${currencyLower}`
  193. if (existingPrices[lookupKey]) {
  194. await log(` - Price '${lookupKey}' already exists. Skipping.`)
  195. summary.skipped++
  196. continue
  197. }
  198. /** @type {PriceCreateParams} */
  199. const priceParams = {
  200. product: planCode,
  201. currency: currencyLower,
  202. unit_amount: convertToMinorUnits(amountValue, currencyLower),
  203. recurring: { interval },
  204. lookup_key: lookupKey,
  205. }
  206. if (commit) {
  207. try {
  208. await stripe.prices.create(priceParams)
  209. await rateLimitSleep()
  210. } catch (err) {
  211. const errorMessage = err instanceof Error ? err.message : String(err)
  212. await log(` ✗ Error creating price ${lookupKey}: ${errorMessage}`)
  213. summary.errors++
  214. continue
  215. }
  216. }
  217. await log(
  218. ` ✓ Created price: ${lookupKey} (${amountValue} ${currencyLower.toUpperCase()})`
  219. )
  220. summary.pricesCreated++
  221. }
  222. }
  223. // Final Summary
  224. await log()
  225. await log('='.repeat(20))
  226. await log()
  227. await log('✨ FINAL SUMMARY ✨')
  228. await log(` ✅ Products created: ${summary.productsCreated}`)
  229. await log(` ✅ Prices created: ${summary.pricesCreated}`)
  230. await log(` ⏭️ Items skipped: ${summary.skipped}`)
  231. await log(` ⏭️ Invalid rows skipped: ${summary.invalidRows}`)
  232. await log(` ❌ Errors encountered: ${summary.errors}`)
  233. if (!commit) {
  234. await log('ℹ️ DRY RUN: No changes were applied to Stripe')
  235. }
  236. await log('🎉 Script completed!')
  237. }
  238. if (import.meta.main) {
  239. try {
  240. await scriptRunner(main)
  241. process.exit(0)
  242. } catch (error) {
  243. console.error(error)
  244. process.exit(1)
  245. }
  246. }