backfill_user_properties.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const WRITE_CONCURRENCY = parseInt(process.env.WRITE_CONCURRENCY, 10) || 10
  2. const { batchedUpdateWithResultHandling } = require('./helpers/batchedUpdate')
  3. const { promiseMapWithLimit } = require('@overleaf/promise-utils')
  4. const SubscriptionLocator = require('../app/src/Features/Subscription/SubscriptionLocator')
  5. const PlansLocator = require('../app/src/Features/Subscription/PlansLocator')
  6. const FeaturesHelper = require('../app/src/Features/Subscription/FeaturesHelper')
  7. const AnalyticsManager = require('../app/src/Features/Analytics/AnalyticsManager')
  8. async function getGroupSubscriptionPlanCode(userId) {
  9. const subscriptions =
  10. await SubscriptionLocator.promises.getMemberSubscriptions(userId)
  11. let bestPlanCode = null
  12. let bestFeatures = {}
  13. for (const subscription of subscriptions) {
  14. const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode)
  15. if (
  16. plan &&
  17. FeaturesHelper.isFeatureSetBetter(plan.features, bestFeatures)
  18. ) {
  19. bestPlanCode = plan.planCode
  20. bestFeatures = plan.features
  21. }
  22. }
  23. return bestPlanCode
  24. }
  25. async function processUser(user) {
  26. const analyticsId = user.analyticsId || user._id
  27. const groupSubscriptionPlanCode = await getGroupSubscriptionPlanCode(user._id)
  28. if (groupSubscriptionPlanCode) {
  29. await AnalyticsManager.setUserPropertyForAnalyticsId(
  30. analyticsId,
  31. 'group-subscription-plan-code',
  32. groupSubscriptionPlanCode
  33. )
  34. }
  35. const matchedFeatureSet = FeaturesHelper.getMatchedFeatureSet(user.features)
  36. if (matchedFeatureSet !== 'personal') {
  37. await AnalyticsManager.setUserPropertyForAnalyticsId(
  38. analyticsId,
  39. 'feature-set',
  40. matchedFeatureSet
  41. )
  42. }
  43. }
  44. async function processBatch(_, users) {
  45. await promiseMapWithLimit(WRITE_CONCURRENCY, users, async user => {
  46. await processUser(user)
  47. })
  48. }
  49. batchedUpdateWithResultHandling('users', {}, processBatch, {
  50. _id: true,
  51. analyticsId: true,
  52. features: true,
  53. })