Ghost/core/server/models/email.js
Thibaut Patel ed29c7addf Filtered member email recipients based on the newsletter subscriptions (#14489)
refs https://github.com/TryGhost/Team/issues/1524

- We need to fetch the post newsletter to grab the slug as it's needed for the member NQL filter.
- We can then use the newsletter slug and append it in the existing member NQL filter.
- Removed `subscribed:true` when an email is sent to a newsletter and replaced it with the newsletter id
- Added `status:-free` when an email is sent to a newsletter with `visibility` set to `paid`
- Added tests what happens when you publish without newsletter_id
- Added tests what happens when you publish with newsletter_id

Co-authored-by: Simon Backx <simon@ghost.org>
2022-04-26 12:31:34 +01:00

97 lines
2.5 KiB
JavaScript

const uuid = require('uuid');
const ghostBookshelf = require('./base');
const Email = ghostBookshelf.Model.extend({
tableName: 'emails',
defaults: function defaults() {
return {
uuid: uuid.v4(),
status: 'pending',
recipient_filter: 'status:-free',
track_opens: false,
delivered_count: 0,
opened_count: 0,
failed_count: 0
};
},
parse() {
const attrs = ghostBookshelf.Model.prototype.parse.apply(this, arguments);
// update legacy recipient_filter values to proper NQL
if (attrs.recipient_filter === 'free') {
attrs.recipient_filter = 'status:free';
}
if (attrs.recipient_filter === 'paid') {
attrs.recipient_filter = 'status:-free';
}
return attrs;
},
formatOnWrite(attrs) {
// update legacy recipient_filter values to proper NQL
if (attrs.recipient_filter === 'free') {
attrs.recipient_filter = 'status:free';
}
if (attrs.recipient_filter === 'paid') {
attrs.recipient_filter = 'status:-free';
}
return attrs;
},
post() {
return this.belongsTo('Post', 'post_id');
},
emailBatches() {
return this.hasMany('EmailBatch', 'email_id');
},
recipients() {
return this.hasMany('EmailRecipient', 'email_id');
},
newsletter() {
return this.belongsTo('Newsletter', 'newsletter_id');
},
emitChange: function emitChange(event, options) {
const eventToTrigger = 'email' + '.' + event;
ghostBookshelf.Model.prototype.emitChange.bind(this)(this, eventToTrigger, options);
},
onCreated: function onCreated(model, options) {
ghostBookshelf.Model.prototype.onCreated.apply(this, arguments);
model.emitChange('added', options);
},
onUpdated: function onUpdated(model, options) {
ghostBookshelf.Model.prototype.onUpdated.apply(this, arguments);
model.emitChange('edited', options);
},
onDestroyed: function onDestroyed(model, options) {
ghostBookshelf.Model.prototype.onDestroyed.apply(this, arguments);
model.emitChange('deleted', options);
}
}, {
post() {
return this.belongsTo('Post');
}
});
const Emails = ghostBookshelf.Collection.extend({
model: Email
});
module.exports = {
Email: ghostBookshelf.model('Email', Email),
Emails: ghostBookshelf.collection('Emails', Emails)
};