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
This commit is contained in:
Rishabh 2022-08-25 12:54:10 +05:30 committed by Rishabh Garg
parent 59e796d321
commit effd5af615
2 changed files with 54 additions and 0 deletions

View File

@ -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
*

View File

@ -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')});