create_custom_prices_from_csv.mjs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // @ts-check
  2. /**
  3. * This script creates custom Prices in Stripe from a CSV file.
  4. * It does not create products; each row must include an existing Stripe productId.
  5. *
  6. * Usage:
  7. * node scripts/stripe/create_custom_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,productId,productName,priceDescription,interval,USD,GBP,EUR
  17. * essentials,prod_123,Essentials Monthly,"Historical custom price",month,21,17,19
  18. * essentials-annual,prod_456,Essentials Annual,"Historical custom price",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} productId - Optional expected Stripe Product ID to validate against
  33. * @property {string} productName - Optional, can be derived from planCode if not provided
  34. * @property {string} priceDescription - Optional
  35. * @property {string} interval - 'month' or 'year'
  36. * @property {Record<string, string | number>} currencies - Dynamic currency columns
  37. */
  38. /**
  39. * @typedef {import('stripe').Stripe} Stripe
  40. * @typedef {import('stripe').Stripe.Price} Price
  41. * @typedef {import('stripe').Stripe.PriceCreateParams} PriceCreateParams
  42. * @typedef {import('stripe').Stripe.Product} Product
  43. */
  44. const paramsSchema = z.object({
  45. f: z.string(),
  46. region: z.enum(['us', 'uk']),
  47. version: z.string(),
  48. commit: z.boolean().default(false),
  49. })
  50. /**
  51. * @param {import('stripe').Stripe} stripe
  52. * @returns {Promise<Record<string, Price>>}
  53. */
  54. async function getExistingPrices(stripe) {
  55. /** @type {Record<string, Price>} */
  56. const pricesByLookupKey = {}
  57. let startingAfter
  58. do {
  59. /** @type {any} */
  60. const response = await stripe.prices.list({
  61. limit: 100,
  62. starting_after: startingAfter,
  63. })
  64. for (const price of response.data) {
  65. if (price.lookup_key) {
  66. pricesByLookupKey[price.lookup_key] = price
  67. }
  68. }
  69. startingAfter = response.has_more
  70. ? response.data[response.data.length - 1].id
  71. : undefined
  72. } while (startingAfter)
  73. return pricesByLookupKey
  74. }
  75. /**
  76. * @param {import('stripe').Stripe} stripe
  77. * @return {Promise<Record<string, Product>>}
  78. */
  79. async function getExistingProducts(stripe) {
  80. /** @type {Record<string, Product>} */
  81. const productsById = {}
  82. let startingAfter
  83. do {
  84. /** @type {any} */
  85. const response = await stripe.products.list({
  86. limit: 100,
  87. starting_after: startingAfter,
  88. })
  89. for (const product of response.data) {
  90. productsById[product.metadata.planCode] = product
  91. }
  92. startingAfter = response.has_more
  93. ? response.data[response.data.length - 1].id
  94. : undefined
  95. } while (startingAfter)
  96. return productsById
  97. }
  98. /**
  99. * @param {any} trackProgress
  100. */
  101. export async function main(trackProgress) {
  102. const args = minimist(process.argv.slice(2), {
  103. boolean: ['commit'],
  104. string: ['region', 'f', 'version'],
  105. })
  106. const parseResult = paramsSchema.safeParse(args)
  107. if (!parseResult.success) {
  108. throw new Error(`Invalid parameters: ${parseResult.error.message}`)
  109. }
  110. const { f: inputFile, region, version, commit } = parseResult.data
  111. const mode = commit ? 'COMMIT MODE' : 'DRY RUN MODE'
  112. const log = (message = '') =>
  113. trackProgress(mode === 'DRY RUN MODE' ? `[DRY RUN] ${message}` : message)
  114. await log(`Starting creation script in ${mode} for region: ${region}`)
  115. const stripe = getRegionClient(region).stripe
  116. // Load and Parse CSV
  117. const content = fs.readFileSync(inputFile, 'utf-8')
  118. /** @type {PriceRecord[]} */
  119. const records = csv.parse(content, { columns: true, skip_empty_lines: true })
  120. if (records.length === 0) {
  121. throw new Error('CSV file is empty or invalid.')
  122. }
  123. // Identify currency columns (everything except the known non-currency columns)
  124. const nonCurrencyKeys = new Set([
  125. 'planCode',
  126. 'productId',
  127. 'productName',
  128. 'priceDescription',
  129. 'interval',
  130. ])
  131. const currencyKeys = Object.keys(records[0]).filter(
  132. k => !nonCurrencyKeys.has(k)
  133. )
  134. // Cache existing data to minimize API calls and prevent duplicates
  135. await log('Fetching existing Stripe data...')
  136. const existingPrices = await getExistingPrices(stripe)
  137. const existingProducts = await getExistingProducts(stripe)
  138. /** @type {Record<string, Product>} */
  139. const existingProductsById = {}
  140. for (const product of Object.values(existingProducts)) {
  141. existingProductsById[product.id] = product
  142. }
  143. const summary = {
  144. productsCreated: 0,
  145. pricesCreated: 0,
  146. skipped: 0,
  147. invalidRows: 0,
  148. errors: 0,
  149. }
  150. let rowNumber = 0 // For logging purposes, starting after header
  151. for (const /** @type {PriceRecord} */ record of records) {
  152. ++rowNumber
  153. const { planCode, productId, priceDescription, interval } = record
  154. const expectedProductId = String(productId || '').trim()
  155. if (!planCode) {
  156. await log(`✗ No plan code in row ${rowNumber}`)
  157. ++summary.invalidRows
  158. continue
  159. }
  160. if (interval !== 'month' && interval !== 'year') {
  161. await log(
  162. `✗ Invalid interval '${interval}' on row ${rowNumber}. Must be either 'month' or 'year'.`
  163. )
  164. ++summary.invalidRows
  165. continue
  166. }
  167. // If productId is provided, treat it as an assertion that the product already
  168. // exists and matches the planCode mapping. Skip the row before product-create.
  169. if (expectedProductId) {
  170. const existingProduct = existingProducts[planCode]
  171. if (!existingProduct) {
  172. await log(
  173. `✗ CSV productId '${expectedProductId}' provided for plan '${planCode}', but no existing product was found for that planCode. Skipping row.`
  174. )
  175. summary.errors++
  176. continue
  177. }
  178. if (existingProduct.id !== expectedProductId) {
  179. await log(
  180. `✗ CSV productId '${expectedProductId}' does not match existing product id '${existingProduct.id}' for plan '${planCode}'. Skipping row.`
  181. )
  182. summary.errors++
  183. continue
  184. }
  185. }
  186. await log()
  187. await log(`--- Processing Plan: ${planCode} ---`)
  188. // 1. Validate required existing productId from CSV.
  189. const productIdForPrice = String(productId || '').trim()
  190. if (!productIdForPrice) {
  191. await log(`✗ No productId in row ${rowNumber}. Skipping row.`)
  192. summary.invalidRows++
  193. continue
  194. }
  195. if (!existingProductsById[productIdForPrice]) {
  196. await log(
  197. `✗ Product '${productIdForPrice}' from CSV row ${rowNumber} was not found in Stripe. Skipping row.`
  198. )
  199. summary.errors++
  200. continue
  201. }
  202. if (
  203. existingProducts[planCode]?.id &&
  204. existingProducts[planCode].id !== productIdForPrice
  205. ) {
  206. await log(
  207. ` ✗ productId mismatch for plan '${planCode}': CSV has '${productIdForPrice}', planCode resolves to '${existingProducts[planCode].id}'. Skipping row.`
  208. )
  209. summary.errors++
  210. continue
  211. }
  212. // 2. Handle Prices for each currency column
  213. for (const currency of currencyKeys) {
  214. const amountValue = parseFloat(/** @type {any} */ (record)[currency])
  215. if (isNaN(amountValue) || amountValue <= 0) continue
  216. const currencyLower = currency.toLowerCase()
  217. const unitAmount = convertToMinorUnits(amountValue, currencyLower)
  218. const lookupKeyInterval = interval === 'month' ? 'monthly' : 'annual'
  219. // For custom prices, lookup keys always include the minor-unit amount.
  220. const lookupKeyBase = `${planCode}_${lookupKeyInterval}_${version}_${currencyLower}`
  221. const lookupKey = `${lookupKeyBase}_${unitAmount}`
  222. if (existingPrices[lookupKey]) {
  223. await log(` - Price '${lookupKey}' already exists. Skipping.`)
  224. summary.skipped++
  225. continue
  226. }
  227. /** @type {PriceCreateParams} */
  228. const priceParams = {
  229. product: productIdForPrice,
  230. currency: currencyLower,
  231. unit_amount: unitAmount,
  232. recurring: { interval },
  233. lookup_key: lookupKey,
  234. nickname: priceDescription || undefined,
  235. }
  236. if (commit) {
  237. try {
  238. await stripe.prices.create(priceParams)
  239. await rateLimitSleep()
  240. } catch (err) {
  241. const errorMessage = err instanceof Error ? err.message : String(err)
  242. await log(` ✗ Error creating price ${lookupKey}: ${errorMessage}`)
  243. summary.errors++
  244. continue
  245. }
  246. }
  247. // Keep in-memory cache in sync so duplicates in the same run are skipped.
  248. existingPrices[lookupKey] = /** @type {any} */ ({
  249. lookup_key: lookupKey,
  250. })
  251. await log(
  252. ` ✓ Created price: ${lookupKey} (${amountValue} ${currencyLower.toUpperCase()})`
  253. )
  254. summary.pricesCreated++
  255. }
  256. }
  257. // Final Summary
  258. await log()
  259. await log('='.repeat(20))
  260. await log()
  261. await log('✨ FINAL SUMMARY ✨')
  262. await log(` ✅ Products created: ${summary.productsCreated}`)
  263. await log(` ✅ Prices created: ${summary.pricesCreated}`)
  264. await log(` ⏭️ Items skipped: ${summary.skipped}`)
  265. await log(` ⏭️ Invalid rows skipped: ${summary.invalidRows}`)
  266. await log(` ❌ Errors encountered: ${summary.errors}`)
  267. if (!commit) {
  268. await log('ℹ️ DRY RUN: No changes were applied to Stripe')
  269. }
  270. await log('🎉 Script completed!')
  271. }
  272. if (import.meta.main) {
  273. try {
  274. await scriptRunner(main)
  275. process.exit(0)
  276. } catch (error) {
  277. console.error(error)
  278. process.exit(1)
  279. }
  280. }