sync_group_subscription_memberships.js 8.2 KB

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