sync_group_subscription_memberships.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. const GoogleBigQueryHelper = require('./helpers/GoogleBigQueryHelper')
  2. const { Subscription } = require('../../app/src/models/Subscription')
  3. const { waitForDb } = require('../../app/src/infrastructure/mongodb')
  4. const AnalyticsManager = require('../../app/src/Features/Analytics/AnalyticsManager')
  5. const {
  6. DeletedSubscription,
  7. } = require('../../app/src/models/DeletedSubscription')
  8. const minimist = require('minimist')
  9. const _ = require('lodash')
  10. const { ObjectId } = require('mongodb-legacy')
  11. let FETCH_LIMIT, COMMIT, VERBOSE
  12. async function main() {
  13. await waitForDb()
  14. console.log('## Syncing group subscription memberships...')
  15. const subscriptionsCount = await Subscription.count({ groupPlan: true })
  16. const deletedSubscriptionsCount = await DeletedSubscription.count({
  17. 'subscription.groupPlan': true,
  18. })
  19. console.log(
  20. `## Going to synchronize ${subscriptionsCount} subscriptions and ${deletedSubscriptionsCount} deleted subscriptions`
  21. )
  22. await checkActiveSubscriptions()
  23. await checkDeletedSubscriptions()
  24. }
  25. async function checkActiveSubscriptions() {
  26. let totalSubscriptionsChecked = 0
  27. let subscriptions
  28. const processedSubscriptionIds = new Set()
  29. do {
  30. subscriptions = await Subscription.find(
  31. { groupPlan: true },
  32. { recurlySubscription_id: 1, member_ids: 1 }
  33. )
  34. .sort('_id')
  35. .skip(totalSubscriptionsChecked)
  36. .limit(FETCH_LIMIT)
  37. .lean()
  38. if (subscriptions.length) {
  39. const groupIds = subscriptions.map(sub => sub._id)
  40. const bigQueryGroupMemberships =
  41. await fetchBigQueryMembershipStatuses(groupIds)
  42. const membershipsByGroupId = _.groupBy(
  43. bigQueryGroupMemberships,
  44. 'group_id'
  45. )
  46. for (const subscription of subscriptions) {
  47. const subscriptionId = subscription._id.toString()
  48. if (!processedSubscriptionIds.has(subscriptionId)) {
  49. await checkSubscriptionMemberships(
  50. subscription,
  51. membershipsByGroupId[subscriptionId] || []
  52. )
  53. processedSubscriptionIds.add(subscriptionId)
  54. }
  55. }
  56. totalSubscriptionsChecked += subscriptions.length
  57. }
  58. } while (subscriptions.length > 0)
  59. }
  60. async function checkDeletedSubscriptions() {
  61. let totalDeletedSubscriptionsChecked = 0
  62. let deletedSubscriptions
  63. const processedSubscriptionIds = new Set()
  64. do {
  65. deletedSubscriptions = (
  66. await DeletedSubscription.find(
  67. { 'subscription.groupPlan': true },
  68. { subscription: 1 }
  69. )
  70. .sort('deletedAt')
  71. .skip(totalDeletedSubscriptionsChecked)
  72. .limit(FETCH_LIMIT)
  73. ).map(sub => sub.toObject().subscription)
  74. if (deletedSubscriptions.length) {
  75. const groupIds = deletedSubscriptions.map(sub => sub._id.toString())
  76. const bigQueryGroupMemberships =
  77. await fetchBigQueryMembershipStatuses(groupIds)
  78. const membershipsByGroupId = _.groupBy(
  79. bigQueryGroupMemberships,
  80. 'group_id'
  81. )
  82. for (const deletedSubscription of deletedSubscriptions) {
  83. const subscriptionId = deletedSubscription._id.toString()
  84. if (!processedSubscriptionIds.has(subscriptionId)) {
  85. await checkDeletedSubscriptionMemberships(
  86. deletedSubscription,
  87. membershipsByGroupId[subscriptionId] || []
  88. )
  89. processedSubscriptionIds.add(subscriptionId)
  90. }
  91. }
  92. totalDeletedSubscriptionsChecked += deletedSubscriptions.length
  93. }
  94. } while (deletedSubscriptions.length > 0)
  95. }
  96. async function checkSubscriptionMemberships(subscription, membershipStatuses) {
  97. if (VERBOSE) {
  98. console.log(
  99. '\n###########################################################################################',
  100. '\n# Subscription (mongo): ',
  101. '\n# _id: \t\t\t\t',
  102. subscription._id.toString(),
  103. '\n# member_ids: \t\t\t',
  104. subscription.member_ids.map(_id => _id.toString()),
  105. '\n# recurlySubscription_id: \t',
  106. subscription.recurlySubscription_id
  107. )
  108. console.log('#\n# Membership statuses found in BigQuery: ')
  109. console.table(membershipStatuses)
  110. }
  111. // create missing `joined` events when membership status is missing
  112. for (const memberId of subscription.member_ids) {
  113. if (
  114. !_.find(membershipStatuses, {
  115. user_id: memberId.toString(),
  116. is_member: true,
  117. })
  118. ) {
  119. await sendCorrectiveEvent(
  120. memberId,
  121. 'group-subscription-joined',
  122. subscription
  123. )
  124. }
  125. }
  126. // create missing `left` events if user is not a member of the group anymore
  127. for (const { user_id: userId, is_member: isMember } of membershipStatuses) {
  128. if (
  129. isMember &&
  130. !subscription.member_ids.some(id => id.toString() === userId)
  131. ) {
  132. await sendCorrectiveEvent(userId, 'group-subscription-left', subscription)
  133. }
  134. }
  135. }
  136. async function checkDeletedSubscriptionMemberships(
  137. subscription,
  138. membershipStatuses
  139. ) {
  140. if (VERBOSE) {
  141. console.log(
  142. '\n###########################################################################################',
  143. '\n# Deleted subscription (mongo): ',
  144. '\n# _id: \t\t\t\t',
  145. subscription._id.toString(),
  146. '\n# member_ids: \t\t\t',
  147. subscription.member_ids.map(_id => _id.toString()),
  148. '\n# recurlySubscription_id: \t',
  149. subscription.recurlySubscription_id
  150. )
  151. console.log('#\n# Membership statuses found in BigQuery: ')
  152. console.table(membershipStatuses)
  153. }
  154. const updatedUserIds = new Set()
  155. // create missing `left` events if user was a member of the group in BQ and status is not up-to-date
  156. for (const memberId of subscription.member_ids.map(id => id.toString())) {
  157. if (
  158. _.find(membershipStatuses, {
  159. user_id: memberId,
  160. is_member: true,
  161. })
  162. ) {
  163. await sendCorrectiveEvent(
  164. memberId,
  165. 'group-subscription-left',
  166. subscription
  167. )
  168. updatedUserIds.add(memberId)
  169. }
  170. }
  171. // for cases where the user has been removed from the subscription before it was deleted and status is not up-to-date
  172. for (const { user_id: userId, is_member: isMember } of membershipStatuses) {
  173. if (isMember && !updatedUserIds.has(userId)) {
  174. await sendCorrectiveEvent(userId, 'group-subscription-left', subscription)
  175. updatedUserIds.add(userId)
  176. }
  177. }
  178. }
  179. async function sendCorrectiveEvent(userId, event, subscription) {
  180. if (!ObjectId.isValid(userId)) {
  181. console.warn(`Skipping '${event}' for user ${userId}: invalid user ID`)
  182. return
  183. }
  184. const segmentation = {
  185. groupId: subscription._id.toString(),
  186. subscriptionId: subscription.recurlySubscription_id,
  187. source: 'sync',
  188. }
  189. if (COMMIT) {
  190. console.log(
  191. `Sending event '${event}' for user ${userId} with segmentation: ${JSON.stringify(
  192. segmentation
  193. )}`
  194. )
  195. await AnalyticsManager.recordEventForUser(userId, event, segmentation)
  196. } else {
  197. console.log(
  198. `Dry run - would send event '${event}' for user ${userId} with segmentation: ${JSON.stringify(
  199. segmentation
  200. )}`
  201. )
  202. }
  203. }
  204. async function fetchBigQueryMembershipStatuses(groupIds) {
  205. const joinedGroupIds = groupIds.map(id => `"${id}"`).join(',')
  206. const query = `\
  207. WITH user_memberships AS (
  208. SELECT
  209. group_id,
  210. COALESCE(user_aliases.user_id, ugm.user_id) AS user_id,
  211. is_member,
  212. ugm.created_at
  213. FROM analytics.user_group_memberships ugm
  214. LEFT JOIN analytics.user_aliases ON ugm.user_id = user_aliases.analytics_id
  215. WHERE ugm.group_id IN (${joinedGroupIds})
  216. ),
  217. ordered_status AS (
  218. SELECT *,
  219. ROW_NUMBER() OVER(PARTITION BY group_id, user_id ORDER BY created_at DESC) AS row_number
  220. FROM user_memberships
  221. )
  222. SELECT group_id, user_id, is_member, created_at FROM ordered_status
  223. WHERE row_number = 1;
  224. `
  225. return GoogleBigQueryHelper.query(query)
  226. }
  227. const setup = () => {
  228. const argv = minimist(process.argv.slice(2))
  229. FETCH_LIMIT = argv.fetch ? argv.fetch : 100
  230. COMMIT = argv.commit !== undefined
  231. VERBOSE = argv.debug !== undefined
  232. if (!COMMIT) {
  233. console.warn('Doing dry run without --commit')
  234. }
  235. if (VERBOSE) {
  236. console.log('Running in verbose mode')
  237. }
  238. }
  239. setup()
  240. main()
  241. .then(() => {
  242. console.error('Done.')
  243. process.exit(0)
  244. })
  245. .catch(error => {
  246. console.error({ error })
  247. process.exit(1)
  248. })