backfill_stripe_to_subscription_mapping.mjs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /**
  2. * This script backfills the account mapping for subscriptions that are active and backed by Stripe.
  3. *
  4. * The mapping joins a Stripe subscription ID to a subscription _id in BigQuery.
  5. *
  6. * This script has an assumption that it is being run in a clean slate condition, it will create some
  7. * duplicate mappings if run multiple times. The Analytics team will have the expectation
  8. * that this table may need to be deduplicated as it is an event sourcing record.
  9. *
  10. * Call it with `--commit` to actually register the mappings.
  11. * Call it with `--verbose` to see debug logs.
  12. * Call it with `--endDate=<EndDate>` to stop processing at a certain date, for example `--endDate=2024-01-01`
  13. */
  14. import logger from '@overleaf/logger'
  15. import minimist from 'minimist'
  16. import { batchedUpdate } from '@overleaf/mongo-utils/batchedUpdate.js'
  17. import { db } from '../../app/src/infrastructure/mongodb.js'
  18. import AccountMappingHelper from '../../app/src/Features/Analytics/AccountMappingHelper.js'
  19. import { registerAccountMapping } from '../../app/src/Features/Analytics/AnalyticsManager.js'
  20. import { triggerGracefulShutdown } from '../../app/src/infrastructure/GracefulShutdown.js'
  21. import Validation from '../../app/src/infrastructure/Validation.js'
  22. import { scriptRunner } from '../lib/ScriptRunner.mjs'
  23. const paramsSchema = Validation.Joi.object({
  24. endDate: Validation.Joi.string().isoDate(),
  25. commit: Validation.Joi.boolean().default(false),
  26. verbose: Validation.Joi.boolean().default(false),
  27. }).unknown(true)
  28. let mapped = 0
  29. let subscriptionCount = 0
  30. const now = new Date().toISOString() // use the same timestamp for all mappings
  31. const seenSubscriptions = new Set()
  32. function registerMapping(subscription) {
  33. if (seenSubscriptions.has(subscription._id)) {
  34. logger.warn({ subscription }, 'duplicate subscription found, skipping')
  35. return
  36. }
  37. seenSubscriptions.add(subscription._id)
  38. subscriptionCount++
  39. const mapping = AccountMappingHelper.generateSubscriptionToStripeMapping(
  40. subscription._id,
  41. subscription.paymentProvider.subscriptionId,
  42. subscription.paymentProvider.service,
  43. now
  44. )
  45. logger.debug(
  46. {
  47. stripe: subscription.paymentProvider.subscriptionId,
  48. stripeService: subscription.paymentProvider.service,
  49. mapping,
  50. },
  51. `processing subscription ${subscription._id}`
  52. )
  53. if (commit) {
  54. registerAccountMapping(mapping)
  55. mapped++
  56. }
  57. }
  58. async function main(trackProgress) {
  59. const additionalBatchedUpdateOptions = {}
  60. if (endDate) {
  61. additionalBatchedUpdateOptions.BATCH_RANGE_END = endDate
  62. }
  63. await batchedUpdate(
  64. db.subscriptions,
  65. {
  66. 'paymentProvider.service': { $in: ['stripe-us', 'stripe-uk'] },
  67. },
  68. subscriptions => subscriptions.forEach(registerMapping),
  69. {
  70. _id: 1,
  71. 'paymentProvider.subscriptionId': 1,
  72. 'paymentProvider.service': 1,
  73. },
  74. {
  75. readPreference: 'secondaryPreferred',
  76. },
  77. {
  78. verboseLogging: verbose,
  79. ...additionalBatchedUpdateOptions,
  80. trackProgress,
  81. }
  82. )
  83. logger.debug({}, `${subscriptionCount} subscriptions processed`)
  84. if (commit) {
  85. logger.debug({}, `${mapped} mappings registered`)
  86. }
  87. }
  88. const {
  89. error,
  90. value: { commit, endDate, verbose },
  91. } = paramsSchema.validate(
  92. minimist(process.argv.slice(2), {
  93. boolean: ['commit', 'verbose'],
  94. string: ['endDate'],
  95. })
  96. )
  97. logger.logger.level(verbose ? 'debug' : 'info')
  98. if (error) {
  99. logger.error({ error }, 'error with parameters')
  100. triggerGracefulShutdown({
  101. close(done) {
  102. logger.info({}, 'shutting down')
  103. done(1)
  104. },
  105. })
  106. } else {
  107. logger.info({ verbose, commit, endDate }, commit ? 'COMMITTING' : 'DRY RUN')
  108. await scriptRunner(main)
  109. triggerGracefulShutdown({
  110. close(done) {
  111. logger.info({}, 'shutting down')
  112. done()
  113. },
  114. })
  115. }