From effd5af61511644e547698cb5a43a306109c3289 Mon Sep 17 00:00:00 2001 From: Rishabh Date: Thu, 25 Aug 2022 12:54:10 +0530 Subject: [PATCH] Handled fetching staff users for email alerts refs TryGhost/Team#1826 - adds a method on user model which fetches all eligible users for a type of email alert - restricts users to active `Owner` and `Administrators` with setting turned on --- ghost/core/core/server/models/user.js | 26 +++++++++++++++++ .../core/test/unit/server/models/user.test.js | 28 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/ghost/core/core/server/models/user.js b/ghost/core/core/server/models/user.js index 6633bfb74c..d0a1a7f378 100644 --- a/ghost/core/core/server/models/user.js +++ b/ghost/core/core/server/models/user.js @@ -488,6 +488,32 @@ User = ghostBookshelf.Model.extend({ return query.fetch(options); }, + /** + * Returns users who should receive a specific type of alert + * @param {'free-signup'|'paid-started'|'paid-canceled'} type The type of alert to fetch users for + * @param {any} options + * @return {Promise<[Object]>} Array of users + */ + getEmailAlertUsers(type, options) { + options = options || {}; + + let filter = 'status:active'; + if (type === 'free-signup') { + filter += '+free_member_signup_notification:true'; + } else if (type === 'paid-started') { + filter += '+paid_subscription_started_notification:true'; + } else if (type === 'paid-canceled') { + filter += '+paid_subscription_canceled_notification:true'; + } + return this.findAll(_.merge({filter, withRelated: ['roles']}, options)).then((users) => { + return users.toJSON().filter((user) => { + return user?.roles?.some((role) => { + return ['Owner', 'Administrator'].includes(role.name); + }); + }); + }); + }, + /** * ### Edit * diff --git a/ghost/core/test/unit/server/models/user.test.js b/ghost/core/test/unit/server/models/user.test.js index ba0cce4c94..cdc3dbe204 100644 --- a/ghost/core/test/unit/server/models/user.test.js +++ b/ghost/core/test/unit/server/models/user.test.js @@ -534,6 +534,34 @@ describe('Unit: models/user', function () { }); }); + describe('getEmailAlertUsers', function () { + beforeEach(function () { + sinon.stub(models.User, 'findAll'); + }); + + it('can filter out only Admin and Owner users', function () { + const users = sinon.stub(); + + users.toJSON = sinon.stub().returns([ + testUtils.permissions.owner.user, + testUtils.permissions.admin.user, + testUtils.permissions.editor.user, + testUtils.permissions.author.user, + testUtils.permissions.contributor.user + ]); + + models.User + .findAll + .resolves(users); + + return models.User.getEmailAlertUsers('free-signup', {}).then((alertUsers) => { + alertUsers.length.should.eql(2); + alertUsers[0].roles[0].name.should.eql('Owner'); + alertUsers[1].roles[0].name.should.eql('Administrator'); + }); + }); + }); + describe('isSetup', function () { it('active', function () { sinon.stub(models.User, 'getOwnerUser').resolves({get: sinon.stub().returns('active')});