Ghost/ghost/email-service/lib/EmailSegmenter.js
Fabien "egg" O'Carroll 104f84f252 Added eslint rule for file naming convention
As discussed with the product team we want to enforce kebab-case file names for
all files, with the exception of files which export a single class, in which
case they should be PascalCase and reflect the class which they export.

This will help find classes faster, and should push better naming for them too.

Some files and packages have been excluded from this linting, specifically when
a library or framework depends on the naming of a file for the functionality
e.g. Ember, knex-migrator, adapter-manager
2023-05-09 12:34:34 -04:00

75 lines
2.1 KiB
JavaScript

const tpl = require('@tryghost/tpl');
const errors = require('@tryghost/errors');
const messages = {
noneFilterError: 'Cannot send email to "none" recipient filter',
newsletterVisibilityError: 'Unexpected visibility value "{value}". Use one of the valid: "members", "paid".'
};
/**
* @typedef {object} MembersRepository
* @prop {(options) => Promise<any>} list
*/
class EmailSegmenter {
#membersRepository;
/**
*
* @param {object} dependencies
* @param {MembersRepository} dependencies.membersRepository
*/
constructor({
membersRepository
}) {
this.#membersRepository = membersRepository;
}
getMemberFilterForSegment(newsletter, emailRecipientFilter, segment) {
const filter = [`newsletters.id:${newsletter.id}`];
switch (emailRecipientFilter) {
case 'all':
break;
case 'none':
throw new errors.InternalServerError({
message: tpl(messages.noneFilterError)
});
default:
filter.push(`(${emailRecipientFilter})`);
break;
}
const visibility = newsletter.get('visibility');
switch (visibility) {
case 'members':
// No need to add a member status filter as the email is available to all members
break;
case 'paid':
filter.push(`status:-free`);
break;
default:
throw new errors.InternalServerError({
message: tpl(messages.newsletterVisibilityError, {
value: visibility
})
});
}
if (segment) {
filter.push(`(${segment})`);
}
return filter.join('+');
}
async getMembersCount(newsletter, emailRecipientFilter, segment) {
const filter = this.getMemberFilterForSegment(newsletter, emailRecipientFilter, segment);
const {meta: {pagination: {total: membersCount}}} = await this.#membersRepository.list({filter});
return membersCount;
}
}
module.exports = EmailSegmenter;