SubscriptionUpdater.test.mjs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. import { beforeEach, describe, it, vi, assert, expect } from 'vitest'
  2. import sinon from 'sinon'
  3. import mongodb from 'mongodb-legacy'
  4. const modulePath =
  5. '../../../../app/src/Features/Subscription/SubscriptionUpdater'
  6. const { ObjectId } = mongodb
  7. describe('SubscriptionUpdater', function () {
  8. beforeEach(async function (ctx) {
  9. ctx.recurlyPlan = { planCode: 'recurly-plan' }
  10. ctx.recurlySubscription = {
  11. uuid: '1238uoijdasjhd',
  12. plan: {
  13. plan_code: ctx.recurlyPlan.planCode,
  14. },
  15. }
  16. ctx.adminUser = { _id: (ctx.adminuser_id = '5208dd34438843e2db000007') }
  17. ctx.otherUserId = '5208dd34438842e2db000005'
  18. ctx.allUserIds = ['13213', 'dsadas', 'djsaiud89']
  19. ctx.subscription = {
  20. _id: '111111111111111111111111',
  21. admin_id: ctx.adminUser._id,
  22. manager_ids: [ctx.adminUser._id],
  23. member_ids: [],
  24. save: sinon.stub().resolves(),
  25. planCode: 'student_or_something',
  26. recurlySubscription_id: 'abc123def456fab789',
  27. }
  28. ctx.user_id = ctx.adminuser_id
  29. ctx.groupSubscription = {
  30. _id: '222222222222222222222222',
  31. admin_id: ctx.adminUser._id,
  32. manager_ids: [ctx.adminUser._id],
  33. member_ids: ctx.allUserIds,
  34. save: sinon.stub().resolves(),
  35. groupPlan: true,
  36. planCode: 'group_subscription',
  37. recurlySubscription_id: '456fab789abc123def',
  38. }
  39. ctx.betterGroupSubscription = {
  40. _id: '999999999999999999999999',
  41. admin_id: ctx.adminUser._id,
  42. manager_ids: [ctx.adminUser._id],
  43. member_ids: [ctx.otherUserId],
  44. save: sinon.stub().resolves(),
  45. groupPlan: true,
  46. planCode: 'better_group_subscription',
  47. recurlySubscription_id: '123def456fab789abc',
  48. }
  49. const subscription = ctx.subscription
  50. ctx.SubscriptionModel = class {
  51. constructor(opts) {
  52. // Always return our mock subscription when creating a new one
  53. subscription.admin_id = opts.admin_id
  54. subscription.manager_ids = [opts.admin_id]
  55. return subscription
  56. }
  57. save() {
  58. return Promise.resolve(subscription)
  59. }
  60. }
  61. ctx.SubscriptionModel.deleteOne = sinon
  62. .stub()
  63. .returns({ exec: sinon.stub().resolves() })
  64. ctx.SubscriptionModel.updateOne = sinon
  65. .stub()
  66. .returns({ exec: sinon.stub().resolves() })
  67. ctx.SubscriptionModel.findOne = sinon.stub().resolves()
  68. ctx.SubscriptionModel.findById = sinon.stub().resolves()
  69. ctx.SubscriptionModel.updateMany = sinon
  70. .stub()
  71. .returns({ exec: sinon.stub().resolves() })
  72. ctx.SubscriptionModel.findOneAndUpdate = sinon.stub().returns({
  73. exec: sinon.stub().resolves(ctx.subscription),
  74. })
  75. ctx.SSOConfigModel = class {}
  76. ctx.SSOConfigModel.findOne = sinon.stub().returns({
  77. lean: sinon.stub().returns({
  78. exec: sinon.stub().resolves({ enabled: true }),
  79. }),
  80. })
  81. ctx.SubscriptionLocator = {
  82. promises: {
  83. getUsersSubscription: sinon.stub(),
  84. getGroupSubscriptionMemberOf: sinon.stub(),
  85. getMemberSubscriptions: sinon.stub().resolves([]),
  86. getSubscription: sinon.stub(),
  87. },
  88. }
  89. ctx.SubscriptionLocator.promises.getSubscription
  90. .withArgs(ctx.subscription._id)
  91. .resolves(ctx.subscription)
  92. ctx.Settings = {
  93. defaultPlanCode: 'personal',
  94. defaultFeatures: { default: 'features' },
  95. plans: [
  96. ctx.recurlyPlan,
  97. { planCode: ctx.subscription.planCode, features: {} },
  98. {
  99. planCode: ctx.groupSubscription.planCode,
  100. features: {
  101. collaborators: 10,
  102. compileTimeout: 60,
  103. dropbox: true,
  104. },
  105. },
  106. {
  107. planCode: ctx.betterGroupSubscription.planCode,
  108. features: {
  109. collaborators: -1,
  110. compileTimeout: 240,
  111. dropbox: true,
  112. },
  113. },
  114. ],
  115. mongo: {
  116. options: {
  117. appname: 'web',
  118. maxPoolSize: 100,
  119. serverSelectionTimeoutMS: 60000,
  120. socketTimeoutMS: 60000,
  121. monitorCommands: true,
  122. family: 4,
  123. },
  124. url: 'mongodb://mongo/test-overleaf',
  125. hasSecondaries: false,
  126. },
  127. }
  128. ctx.UserFeaturesUpdater = {
  129. promises: {
  130. updateFeatures: sinon.stub().resolves(),
  131. },
  132. }
  133. ctx.ReferalFeatures = {
  134. promises: {
  135. getBonusFeatures: sinon.stub().resolves(),
  136. },
  137. }
  138. ctx.FeaturesUpdater = {
  139. promises: {
  140. scheduleRefreshFeatures: sinon.stub().resolves(),
  141. refreshFeatures: sinon.stub().resolves({}),
  142. },
  143. }
  144. ctx.DeletedSubscription = {
  145. findOneAndUpdate: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  146. }
  147. ctx.AnalyticsManager = {
  148. recordEventForUserInBackground: sinon.stub().resolves(),
  149. setUserPropertyForUserInBackground: sinon.stub(),
  150. registerAccountMapping: sinon.stub(),
  151. }
  152. ctx.Features = {
  153. hasFeature: sinon.stub().returns(false),
  154. }
  155. ctx.UserAuditLogHandler = {
  156. promises: {
  157. addEntry: sinon.stub().resolves(),
  158. },
  159. }
  160. ctx.UserUpdater = {
  161. promises: {
  162. updateUser: sinon.stub().resolves(),
  163. },
  164. }
  165. vi.doMock('../../../../app/src/models/Subscription', () => ({
  166. Subscription: ctx.SubscriptionModel,
  167. }))
  168. vi.doMock('../../../../app/src/models/SSOConfig', () => ({
  169. SSOConfig: ctx.SSOConfigModel,
  170. }))
  171. vi.doMock(
  172. '../../../../app/src/Features/Subscription/UserFeaturesUpdater',
  173. () => ({
  174. default: ctx.UserFeaturesUpdater,
  175. })
  176. )
  177. vi.doMock(
  178. '../../../../app/src/Features/Subscription/SubscriptionLocator',
  179. () => ({
  180. default: ctx.SubscriptionLocator,
  181. })
  182. )
  183. vi.doMock('@overleaf/settings', () => ({
  184. default: ctx.Settings,
  185. }))
  186. vi.doMock('../../../../app/src/infrastructure/mongodb', () => ({
  187. db: {},
  188. ObjectId,
  189. }))
  190. vi.doMock(
  191. '../../../../app/src/Features/Subscription/FeaturesUpdater',
  192. () => ({
  193. default: ctx.FeaturesUpdater,
  194. })
  195. )
  196. vi.doMock('../../../../app/src/models/DeletedSubscription', () => ({
  197. DeletedSubscription: ctx.DeletedSubscription,
  198. }))
  199. vi.doMock(
  200. '../../../../app/src/Features/Analytics/AnalyticsManager',
  201. () => ({
  202. default: ctx.AnalyticsManager,
  203. })
  204. )
  205. vi.doMock(
  206. '../../../../app/src/Features/Analytics/AccountMappingHelper',
  207. () => ({
  208. default: (ctx.AccountMappingHelper = {
  209. generateSubscriptionToRecurlyMapping: sinon.stub(),
  210. }),
  211. })
  212. )
  213. vi.doMock('../../../../app/src/infrastructure/Features', () => ({
  214. default: ctx.Features,
  215. }))
  216. vi.doMock('../../../../app/src/Features/User/UserAuditLogHandler', () => ({
  217. default: ctx.UserAuditLogHandler,
  218. }))
  219. vi.doMock('../../../../app/src/Features/User/UserUpdater', () => ({
  220. default: ctx.UserUpdater,
  221. }))
  222. vi.doMock('../../../../app/src/infrastructure/Modules', () => ({
  223. default: (ctx.Modules = {
  224. promises: {
  225. hooks: {
  226. fire: sinon.stub().resolves(),
  227. },
  228. },
  229. }),
  230. }))
  231. ctx.SubscriptionUpdater = (await import(modulePath)).default
  232. })
  233. describe('updateAdmin', function () {
  234. it('should update the subscription admin', async function (ctx) {
  235. ctx.subscription.groupPlan = true
  236. await ctx.SubscriptionUpdater.promises.updateAdmin(
  237. ctx.subscription,
  238. ctx.otherUserId
  239. )
  240. const query = {
  241. _id: new ObjectId(ctx.subscription._id),
  242. customAccount: true,
  243. }
  244. const update = {
  245. $set: { admin_id: new ObjectId(ctx.otherUserId) },
  246. $addToSet: { manager_ids: new ObjectId(ctx.otherUserId) },
  247. }
  248. ctx.SubscriptionModel.updateOne.should.have.been.calledOnce
  249. ctx.SubscriptionModel.updateOne.should.have.been.calledWith(query, update)
  250. })
  251. it('should remove the manager for non-group subscriptions', async function (ctx) {
  252. await ctx.SubscriptionUpdater.promises.updateAdmin(
  253. ctx.subscription,
  254. ctx.otherUserId
  255. )
  256. const query = {
  257. _id: new ObjectId(ctx.subscription._id),
  258. customAccount: true,
  259. }
  260. const update = {
  261. $set: {
  262. admin_id: new ObjectId(ctx.otherUserId),
  263. manager_ids: [new ObjectId(ctx.otherUserId)],
  264. },
  265. }
  266. ctx.SubscriptionModel.updateOne.should.have.been.calledOnce
  267. ctx.SubscriptionModel.updateOne.should.have.been.calledWith(query, update)
  268. })
  269. })
  270. describe('syncSubscription', function () {
  271. beforeEach(function (ctx) {
  272. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  273. ctx.subscription
  274. )
  275. })
  276. it('should update the subscription if the user already is admin of one', async function (ctx) {
  277. await ctx.SubscriptionUpdater.promises.syncSubscription(
  278. ctx.recurlySubscription,
  279. ctx.adminUser._id
  280. )
  281. ctx.SubscriptionLocator.promises.getUsersSubscription
  282. .calledWith(ctx.adminUser._id)
  283. .should.equal(true)
  284. })
  285. it('should not call updateFeatures with group subscription if recurly subscription is not expired', async function (ctx) {
  286. await ctx.SubscriptionUpdater.promises.syncSubscription(
  287. ctx.recurlySubscription,
  288. ctx.adminUser._id
  289. )
  290. ctx.SubscriptionLocator.promises.getUsersSubscription
  291. .calledWith(ctx.adminUser._id)
  292. .should.equal(true)
  293. ctx.UserFeaturesUpdater.promises.updateFeatures.called.should.equal(false)
  294. })
  295. })
  296. describe('updateSubscriptionFromRecurly', function () {
  297. afterEach(function (ctx) {
  298. ctx.subscription.member_ids = []
  299. })
  300. it('should update the subscription with token etc when not expired', async function (ctx) {
  301. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  302. ctx.recurlySubscription,
  303. ctx.subscription,
  304. {}
  305. )
  306. ctx.subscription.recurlySubscription_id.should.equal(
  307. ctx.recurlySubscription.uuid
  308. )
  309. ctx.subscription.planCode.should.equal(
  310. ctx.recurlySubscription.plan.plan_code
  311. )
  312. ctx.subscription.save.called.should.equal(true)
  313. expect(
  314. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  315. ).to.have.been.calledWith(ctx.adminUser._id)
  316. })
  317. it('should send a recurly account mapping event', async function (ctx) {
  318. const createdAt = new Date().toISOString()
  319. ctx.AccountMappingHelper.generateSubscriptionToRecurlyMapping.returns({
  320. source: 'recurly',
  321. sourceEntity: 'subscription',
  322. sourceEntityId: ctx.recurlySubscription.uuid,
  323. target: 'v2',
  324. targetEntity: 'subscription',
  325. targetEntityId: ctx.subscription._id,
  326. createdAt,
  327. })
  328. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  329. ctx.recurlySubscription,
  330. ctx.subscription,
  331. {}
  332. )
  333. expect(
  334. ctx.AccountMappingHelper.generateSubscriptionToRecurlyMapping
  335. ).to.have.been.calledWith(
  336. ctx.subscription._id,
  337. ctx.recurlySubscription.uuid
  338. )
  339. expect(
  340. ctx.AnalyticsManager.registerAccountMapping
  341. ).to.have.been.calledWith({
  342. source: 'recurly',
  343. sourceEntity: 'subscription',
  344. sourceEntityId: ctx.recurlySubscription.uuid,
  345. target: 'v2',
  346. targetEntity: 'subscription',
  347. targetEntityId: ctx.subscription._id,
  348. createdAt,
  349. })
  350. })
  351. it('should remove the subscription when expired', async function (ctx) {
  352. ctx.recurlySubscription.state = 'expired'
  353. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  354. ctx.recurlySubscription,
  355. ctx.subscription,
  356. {}
  357. )
  358. ctx.SubscriptionModel.deleteOne.should.have.been.calledWith({
  359. _id: ctx.subscription._id,
  360. })
  361. })
  362. it('should not remove the subscription when expired if it has Managed Users enabled', async function (ctx) {
  363. ctx.Features.hasFeature.withArgs('saas').returns(true)
  364. ctx.subscription.managedUsersEnabled = true
  365. ctx.recurlySubscription.state = 'expired'
  366. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  367. ctx.recurlySubscription,
  368. ctx.subscription,
  369. {}
  370. )
  371. ctx.SubscriptionModel.deleteOne.should.not.have.been.called
  372. })
  373. it('should not remove the subscription when expired if it has Group SSO enabled', async function (ctx) {
  374. ctx.Features.hasFeature.withArgs('saas').returns(true)
  375. ctx.subscription.ssoConfig = new ObjectId('abc123abc123abc123abc123')
  376. ctx.recurlySubscription.state = 'expired'
  377. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  378. ctx.recurlySubscription,
  379. ctx.subscription,
  380. {}
  381. )
  382. ctx.SubscriptionModel.deleteOne.should.not.have.been.called
  383. })
  384. it('should update all the users features', async function (ctx) {
  385. ctx.subscription.member_ids = ctx.allUserIds
  386. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  387. ctx.recurlySubscription,
  388. ctx.subscription,
  389. {}
  390. )
  391. expect(
  392. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  393. ).to.have.been.calledWith(ctx.adminUser._id)
  394. expect(
  395. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  396. ).to.have.been.calledWith(ctx.allUserIds[0])
  397. expect(
  398. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  399. ).to.have.been.calledWith(ctx.allUserIds[1])
  400. expect(
  401. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  402. ).to.have.been.calledWith(ctx.allUserIds[2])
  403. })
  404. it('should set group to true and save how many members can be added to group', async function (ctx) {
  405. ctx.recurlyPlan.groupPlan = true
  406. ctx.recurlyPlan.membersLimit = 5
  407. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  408. ctx.recurlySubscription,
  409. ctx.subscription,
  410. {}
  411. )
  412. ctx.subscription.membersLimit.should.equal(5)
  413. ctx.subscription.groupPlan.should.equal(true)
  414. ctx.subscription.member_ids.should.deep.equal([ctx.subscription.admin_id])
  415. })
  416. it('should delete and replace subscription when downgrading from group to individual plan', async function (ctx) {
  417. ctx.recurlyPlan.groupPlan = false
  418. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  419. ctx.recurlySubscription,
  420. ctx.groupSubscription,
  421. {}
  422. )
  423. })
  424. it('should not set group to true or set groupPlan', async function (ctx) {
  425. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  426. ctx.recurlySubscription,
  427. ctx.subscription,
  428. {}
  429. )
  430. assert.notEqual(ctx.subscription.membersLimit, 5)
  431. assert.notEqual(ctx.subscription.groupPlan, true)
  432. })
  433. describe('when the plan allows adding more seats', function () {
  434. beforeEach(function (ctx) {
  435. ctx.membersLimitAddOn = 'add_on1'
  436. ctx.recurlyPlan.groupPlan = true
  437. ctx.recurlyPlan.membersLimit = 5
  438. ctx.recurlyPlan.membersLimitAddOn = ctx.membersLimitAddOn
  439. })
  440. function expectMembersLimit(limit) {
  441. it('should set the membersLimit accordingly', async function (ctx) {
  442. await ctx.SubscriptionUpdater.promises.updateSubscriptionFromRecurly(
  443. ctx.recurlySubscription,
  444. ctx.subscription,
  445. {}
  446. )
  447. expect(ctx.subscription.membersLimit).to.equal(limit)
  448. })
  449. }
  450. describe('when the recurlySubscription does not have add ons', function () {
  451. beforeEach(function (ctx) {
  452. delete ctx.recurlySubscription.subscription_add_ons
  453. })
  454. expectMembersLimit(5)
  455. })
  456. describe('when the recurlySubscription has non-matching add ons', function () {
  457. beforeEach(function (ctx) {
  458. ctx.recurlySubscription.subscription_add_ons = [
  459. { add_on_code: 'add_on_99', quantity: 3 },
  460. ]
  461. })
  462. expectMembersLimit(5)
  463. })
  464. describe('when the recurlySubscription has a matching add on', function () {
  465. beforeEach(function (ctx) {
  466. ctx.recurlySubscription.subscription_add_ons = [
  467. { add_on_code: ctx.membersLimitAddOn, quantity: 10 },
  468. ]
  469. })
  470. expectMembersLimit(15)
  471. })
  472. // NOTE: This is unexpected, but we are going to support it anyways.
  473. describe('when the recurlySubscription has multiple matching add ons', function () {
  474. beforeEach(function (ctx) {
  475. ctx.recurlySubscription.subscription_add_ons = [
  476. { add_on_code: ctx.membersLimitAddOn, quantity: 10 },
  477. { add_on_code: ctx.membersLimitAddOn, quantity: 3 },
  478. ]
  479. })
  480. expectMembersLimit(18)
  481. })
  482. })
  483. })
  484. describe('addUserToGroup', function () {
  485. it('should add the user ids to the group as a set', async function (ctx) {
  486. ctx.SubscriptionModel.findOne = sinon
  487. .stub()
  488. .resolves(ctx.groupSubscription)
  489. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  490. ctx.groupSubscription._id,
  491. ctx.otherUserId
  492. )
  493. const searchOps = { _id: ctx.groupSubscription._id }
  494. const insertOperation = {
  495. $addToSet: { member_ids: ctx.otherUserId },
  496. }
  497. ctx.SubscriptionModel.updateOne
  498. .calledWith(searchOps, insertOperation)
  499. .should.equal(true)
  500. expect(ctx.SubscriptionModel.updateOne.lastCall.args[2].session).to.exist
  501. sinon.assert.calledWith(
  502. ctx.AnalyticsManager.recordEventForUserInBackground,
  503. ctx.otherUserId,
  504. 'group-subscription-joined',
  505. {
  506. groupId: ctx.groupSubscription._id,
  507. subscriptionId: ctx.groupSubscription.recurlySubscription_id,
  508. }
  509. )
  510. })
  511. it('should update the users features', async function (ctx) {
  512. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  513. ctx.subscription._id,
  514. ctx.otherUserId
  515. )
  516. ctx.FeaturesUpdater.promises.refreshFeatures
  517. .calledWith(ctx.otherUserId)
  518. .should.equal(true)
  519. })
  520. it('should set the group plan code user property to the best plan with 1 group subscription', async function (ctx) {
  521. ctx.SubscriptionLocator.promises.getMemberSubscriptions
  522. .withArgs(ctx.otherUserId)
  523. .resolves([ctx.groupSubscription])
  524. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  525. ctx.groupSubscription._id,
  526. ctx.otherUserId
  527. )
  528. sinon.assert.calledWith(
  529. ctx.AnalyticsManager.setUserPropertyForUserInBackground,
  530. ctx.otherUserId,
  531. 'group-subscription-plan-code',
  532. 'group_subscription'
  533. )
  534. })
  535. it('should set the group plan code user property to the best plan with 2 group subscriptions', async function (ctx) {
  536. ctx.SubscriptionLocator.promises.getMemberSubscriptions
  537. .withArgs(ctx.otherUserId)
  538. .resolves([ctx.groupSubscription, ctx.betterGroupSubscription])
  539. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  540. ctx.betterGroupSubscription._id,
  541. ctx.otherUserId
  542. )
  543. sinon.assert.calledWith(
  544. ctx.AnalyticsManager.setUserPropertyForUserInBackground,
  545. ctx.otherUserId,
  546. 'group-subscription-plan-code',
  547. 'better_group_subscription'
  548. )
  549. })
  550. it('should set the group plan code user property to the best plan with 2 group subscriptions in reverse order', async function (ctx) {
  551. ctx.SubscriptionLocator.promises.getMemberSubscriptions
  552. .withArgs(ctx.otherUserId)
  553. .resolves([ctx.betterGroupSubscription, ctx.groupSubscription])
  554. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  555. ctx.betterGroupSubscription._id,
  556. ctx.otherUserId
  557. )
  558. sinon.assert.calledWith(
  559. ctx.AnalyticsManager.setUserPropertyForUserInBackground,
  560. ctx.otherUserId,
  561. 'group-subscription-plan-code',
  562. 'better_group_subscription'
  563. )
  564. })
  565. it('should add an entry to the user audit log when joining a group', async function (ctx) {
  566. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  567. ctx.subscription._id,
  568. ctx.otherUserId
  569. )
  570. sinon.assert.calledWith(
  571. ctx.UserAuditLogHandler.promises.addEntry,
  572. ctx.otherUserId,
  573. 'join-group-subscription',
  574. undefined,
  575. undefined,
  576. {
  577. subscriptionId: ctx.subscription._id,
  578. }
  579. )
  580. })
  581. it('should add an entry to the group audit log when joining a group', async function (ctx) {
  582. await ctx.SubscriptionUpdater.promises.addUserToGroup(
  583. ctx.subscription._id,
  584. ctx.otherUserId,
  585. { ipAddress: '0:0:0:0', initiatorId: 'user123' }
  586. )
  587. expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
  588. 'addGroupAuditLogEntry',
  589. {
  590. groupId: ctx.subscription._id,
  591. initiatorId: 'user123',
  592. ipAddress: '0:0:0:0',
  593. operation: 'join-group',
  594. }
  595. )
  596. })
  597. })
  598. describe('removeUserFromGroup', function () {
  599. beforeEach(function (ctx) {
  600. ctx.fakeSubscriptions = [
  601. {
  602. _id: 'fake-id-1',
  603. },
  604. {
  605. _id: 'fake-id-2',
  606. },
  607. ]
  608. ctx.SubscriptionModel.findOne.resolves(ctx.groupSubscription)
  609. ctx.SubscriptionModel.findById = sinon
  610. .stub()
  611. .resolves(ctx.groupSubscription)
  612. ctx.SubscriptionLocator.promises.getMemberSubscriptions.resolves(
  613. ctx.fakeSubscriptions
  614. )
  615. })
  616. it('should pull the users id from the group', async function (ctx) {
  617. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  618. ctx.subscription._id,
  619. ctx.otherUserId
  620. )
  621. const removeOperation = { $pull: { member_ids: ctx.otherUserId } }
  622. ctx.SubscriptionModel.updateOne
  623. .calledWith({ _id: ctx.subscription._id }, removeOperation)
  624. .should.equal(true)
  625. })
  626. it('should remove user enrollment if the group is managed', async function (ctx) {
  627. ctx.SubscriptionModel.findById.resolves({
  628. ...ctx.groupSubscription,
  629. managedUsersEnabled: true,
  630. })
  631. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  632. ctx.groupSubscription._id,
  633. ctx.otherUserId
  634. )
  635. ctx.UserUpdater.promises.updateUser
  636. .calledWith(
  637. { _id: ctx.otherUserId },
  638. {
  639. $unset: {
  640. 'enrollment.managedBy': 1,
  641. 'enrollment.enrolledAt': 1,
  642. },
  643. }
  644. )
  645. .should.equal(true)
  646. })
  647. it('should send a group-subscription-left event', async function (ctx) {
  648. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  649. ctx.groupSubscription._id,
  650. ctx.otherUserId
  651. )
  652. sinon.assert.calledWith(
  653. ctx.AnalyticsManager.recordEventForUserInBackground,
  654. ctx.otherUserId,
  655. 'group-subscription-left',
  656. {
  657. groupId: ctx.groupSubscription._id,
  658. subscriptionId: ctx.groupSubscription.recurlySubscription_id,
  659. }
  660. )
  661. })
  662. it('should set the group plan code user property when removing user from group', async function (ctx) {
  663. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  664. ctx.subscription._id,
  665. ctx.otherUserId
  666. )
  667. sinon.assert.calledWith(
  668. ctx.AnalyticsManager.setUserPropertyForUserInBackground,
  669. ctx.otherUserId,
  670. 'group-subscription-plan-code',
  671. null
  672. )
  673. })
  674. it('should update the users features', async function (ctx) {
  675. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  676. ctx.subscription._id,
  677. ctx.otherUserId
  678. )
  679. ctx.FeaturesUpdater.promises.refreshFeatures
  680. .calledWith(ctx.otherUserId)
  681. .should.equal(true)
  682. })
  683. it('should add an audit log when a user leaves a group', async function (ctx) {
  684. await ctx.SubscriptionUpdater.promises.removeUserFromGroup(
  685. ctx.subscription._id,
  686. ctx.otherUserId
  687. )
  688. sinon.assert.calledWith(
  689. ctx.UserAuditLogHandler.promises.addEntry,
  690. ctx.otherUserId,
  691. 'leave-group-subscription',
  692. undefined,
  693. undefined,
  694. {
  695. subscriptionId: ctx.subscription._id,
  696. }
  697. )
  698. })
  699. })
  700. describe('removeUserFromAllGroups', function () {
  701. beforeEach(function (ctx) {
  702. ctx.SubscriptionLocator.promises.getMemberSubscriptions.resolves([
  703. {
  704. _id: 'fake-id-1',
  705. },
  706. {
  707. _id: 'fake-id-2',
  708. },
  709. ])
  710. })
  711. it('should set the group plan code user property when removing user from all groups', async function (ctx) {
  712. await ctx.SubscriptionUpdater.promises.removeUserFromAllGroups(
  713. ctx.otherUserId
  714. )
  715. sinon.assert.calledWith(
  716. ctx.AnalyticsManager.setUserPropertyForUserInBackground,
  717. ctx.otherUserId,
  718. 'group-subscription-plan-code',
  719. null
  720. )
  721. })
  722. it('should pull the users id from all groups', async function (ctx) {
  723. await ctx.SubscriptionUpdater.promises.removeUserFromAllGroups(
  724. ctx.otherUserId
  725. )
  726. const filter = { _id: ['fake-id-1', 'fake-id-2'] }
  727. const removeOperation = { $pull: { member_ids: ctx.otherUserId } }
  728. sinon.assert.calledWith(
  729. ctx.SubscriptionModel.updateMany,
  730. filter,
  731. removeOperation
  732. )
  733. })
  734. it('should send a group-subscription-left event for each group', async function (ctx) {
  735. ctx.fakeSub1 = {
  736. _id: 'fake-id-1',
  737. groupPlan: true,
  738. recurlySubscription_id: 'fake-sub-1',
  739. }
  740. ctx.fakeSub2 = {
  741. _id: 'fake-id-2',
  742. groupPlan: true,
  743. recurlySubscription_id: 'fake-sub-2',
  744. }
  745. ctx.SubscriptionModel.findOne
  746. .withArgs(
  747. { _id: 'fake-id-1' },
  748. { recurlySubscription_id: 1, groupPlan: 1 }
  749. )
  750. .resolves(ctx.fakeSub1)
  751. .withArgs(
  752. { _id: 'fake-id-2' },
  753. { recurlySubscription_id: 1, groupPlan: 1 }
  754. )
  755. .resolves(ctx.fakeSub2)
  756. await ctx.SubscriptionUpdater.promises.removeUserFromAllGroups(
  757. ctx.otherUserId
  758. )
  759. sinon.assert.calledWith(
  760. ctx.AnalyticsManager.recordEventForUserInBackground,
  761. ctx.otherUserId,
  762. 'group-subscription-left',
  763. {
  764. groupId: 'fake-id-1',
  765. subscriptionId: 'fake-sub-1',
  766. }
  767. )
  768. sinon.assert.calledWith(
  769. ctx.AnalyticsManager.recordEventForUserInBackground,
  770. ctx.otherUserId,
  771. 'group-subscription-left',
  772. {
  773. groupId: 'fake-id-2',
  774. subscriptionId: 'fake-sub-2',
  775. }
  776. )
  777. })
  778. it('should add an audit log entry for each group the user leaves', async function (ctx) {
  779. await ctx.SubscriptionUpdater.promises.removeUserFromAllGroups(
  780. ctx.otherUserId
  781. )
  782. sinon.assert.calledWith(
  783. ctx.UserAuditLogHandler.promises.addEntry,
  784. ctx.otherUserId,
  785. 'leave-group-subscription',
  786. undefined,
  787. undefined,
  788. {
  789. subscriptionId: 'fake-id-1',
  790. }
  791. )
  792. sinon.assert.calledWith(
  793. ctx.UserAuditLogHandler.promises.addEntry,
  794. ctx.otherUserId,
  795. 'leave-group-subscription',
  796. undefined,
  797. undefined,
  798. {
  799. subscriptionId: 'fake-id-2',
  800. }
  801. )
  802. })
  803. })
  804. describe('deleteSubscription', function () {
  805. beforeEach(async function (ctx) {
  806. ctx.subscription = {
  807. _id: new ObjectId().toString(),
  808. mock: 'subscription',
  809. admin_id: new ObjectId(),
  810. member_ids: [new ObjectId(), new ObjectId(), new ObjectId()],
  811. }
  812. await ctx.SubscriptionUpdater.promises.deleteSubscription(
  813. ctx.subscription,
  814. {}
  815. )
  816. })
  817. it('should remove the subscription', function (ctx) {
  818. ctx.SubscriptionModel.deleteOne
  819. .calledWith({ _id: ctx.subscription._id })
  820. .should.equal(true)
  821. })
  822. it('should downgrade the admin_id', function (ctx) {
  823. expect(
  824. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  825. ).to.have.been.calledWith(ctx.subscription.admin_id)
  826. })
  827. it('should downgrade all of the members', function (ctx) {
  828. for (const userId of ctx.subscription.member_ids) {
  829. expect(
  830. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  831. ).to.have.been.calledWith(userId)
  832. }
  833. })
  834. })
  835. describe('scheduleRefreshFeatures', function () {
  836. it('should call upgrades feature for personal subscription from admin_id', async function (ctx) {
  837. ctx.subscription = {
  838. _id: new ObjectId().toString(),
  839. mock: 'subscription',
  840. admin_id: new ObjectId(),
  841. }
  842. await ctx.SubscriptionUpdater.promises.scheduleRefreshFeatures(
  843. ctx.subscription
  844. )
  845. expect(
  846. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures
  847. ).to.have.been.calledOnceWith(ctx.subscription.admin_id)
  848. })
  849. it('should call upgrades feature for group subscription from admin_id and member_ids', async function (ctx) {
  850. ctx.subscription = {
  851. _id: new ObjectId().toString(),
  852. mock: 'subscription',
  853. admin_id: new ObjectId(),
  854. member_ids: [new ObjectId(), new ObjectId(), new ObjectId()],
  855. }
  856. await ctx.SubscriptionUpdater.promises.scheduleRefreshFeatures(
  857. ctx.subscription
  858. )
  859. expect(
  860. ctx.FeaturesUpdater.promises.scheduleRefreshFeatures.callCount
  861. ).to.equal(4)
  862. })
  863. })
  864. describe('setRestorePoint', function () {
  865. it('should set the restore point with the given plan code and add-ons', async function (ctx) {
  866. const subscriptionId = new ObjectId()
  867. const planCode = 'gold-plan'
  868. const addOns = [
  869. { addOnCode: 'addon-1', quantity: 2, unitAmountInCents: 500 },
  870. { addOnCode: 'addon-2', quantity: 1, unitAmountInCents: 1000 },
  871. ]
  872. const consumed = false
  873. await ctx.SubscriptionUpdater.promises.setRestorePoint(
  874. subscriptionId,
  875. planCode,
  876. addOns,
  877. consumed
  878. )
  879. sinon.assert.calledWith(
  880. ctx.SubscriptionModel.updateOne,
  881. { _id: subscriptionId },
  882. {
  883. $set: {
  884. 'lastSuccesfulSubscription.planCode': planCode,
  885. 'lastSuccesfulSubscription.addOns': addOns,
  886. },
  887. }
  888. )
  889. })
  890. it('should increment revertedDueToFailedPayment if consumed is true', async function (ctx) {
  891. const consumed = true
  892. const subscriptionId = new ObjectId()
  893. await ctx.SubscriptionUpdater.promises.setRestorePoint(
  894. subscriptionId,
  895. null,
  896. null,
  897. consumed
  898. )
  899. sinon.assert.calledWith(
  900. ctx.SubscriptionModel.updateOne,
  901. { _id: subscriptionId },
  902. {
  903. $set: {
  904. 'lastSuccesfulSubscription.planCode': null,
  905. 'lastSuccesfulSubscription.addOns': null,
  906. },
  907. $inc: { timesRevertedDueToFailedPayment: 1 },
  908. }
  909. )
  910. })
  911. })
  912. describe('setSubscriptionWasReverted', function () {
  913. it('should clear the restore point and mark the subscription as reverted', async function (ctx) {
  914. const subscriptionId = new ObjectId().toString()
  915. await ctx.SubscriptionUpdater.promises.setSubscriptionWasReverted(
  916. subscriptionId
  917. )
  918. ctx.SubscriptionModel.updateOne.should.have.been.calledWith(
  919. { _id: subscriptionId },
  920. {
  921. $set: {
  922. 'lastSuccesfulSubscription.planCode': null,
  923. 'lastSuccesfulSubscription.addOns': null,
  924. },
  925. $inc: { timesRevertedDueToFailedPayment: 1 },
  926. }
  927. )
  928. })
  929. })
  930. describe('voidRestorePoint', function () {
  931. it('should clear the restore point without marking the subscription as reverted', async function (ctx) {
  932. const subscriptionId = new ObjectId().toString()
  933. await ctx.SubscriptionUpdater.promises.voidRestorePoint(subscriptionId)
  934. sinon.assert.calledWith(
  935. ctx.SubscriptionModel.updateOne,
  936. { _id: subscriptionId },
  937. {
  938. $set: {
  939. 'lastSuccesfulSubscription.planCode': null,
  940. 'lastSuccesfulSubscription.addOns': null,
  941. },
  942. }
  943. )
  944. })
  945. })
  946. })