2021-09-14 14:18:34 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2022-04-20 12:10:41 +03:00
|
|
|
const logging = require('@tryghost/logging');
|
2021-09-14 14:18:34 +03:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2021-08-25 14:33:13 +03:00
|
|
|
const moment = require('moment');
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
const messages = {
|
|
|
|
stripeNotConnected: 'Missing Stripe connection.',
|
|
|
|
memberAlreadyExists: 'Member already exists.'
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {object} ILabsService
|
|
|
|
* @prop {(key: string) => boolean} isSet
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {object} IEmailService
|
|
|
|
* @prop {(data: {email: string, requestedType: string}) => Promise<any>} sendEmailWithMagicLink
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {object} IStripeService
|
|
|
|
* @prop {boolean} configured
|
|
|
|
*/
|
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
/**
|
|
|
|
* @typedef {import('@tryghost/members-offers/lib/application/OfferMapper').OfferDTO} OfferDTO
|
|
|
|
*/
|
|
|
|
|
2021-08-25 14:30:49 +03:00
|
|
|
module.exports = class MemberBREADService {
|
|
|
|
/**
|
|
|
|
* @param {object} deps
|
|
|
|
* @param {import('../repositories/member')} deps.memberRepository
|
2021-10-20 15:32:41 +03:00
|
|
|
* @param {import('@tryghost/members-offers/lib/application/OffersAPI')} deps.offersAPI
|
2021-09-14 14:18:34 +03:00
|
|
|
* @param {ILabsService} deps.labsService
|
|
|
|
* @param {IEmailService} deps.emailService
|
|
|
|
* @param {IStripeService} deps.stripeService
|
2022-08-19 23:39:18 +03:00
|
|
|
* @param {import('@tryghost/member-attribution/lib/service')} deps.memberAttributionService
|
2022-11-18 12:28:13 +03:00
|
|
|
* @param {import('@tryghost/email-suppression-list/lib/email-suppression-list').IEmailSuppressionList} deps.emailSuppressionList
|
2021-08-25 14:30:49 +03:00
|
|
|
*/
|
2022-11-18 12:28:13 +03:00
|
|
|
constructor({memberRepository, labsService, emailService, stripeService, offersAPI, memberAttributionService, emailSuppressionList}) {
|
2021-10-20 15:32:41 +03:00
|
|
|
this.offersAPI = offersAPI;
|
2021-09-14 14:18:34 +03:00
|
|
|
/** @private */
|
|
|
|
this.memberRepository = memberRepository;
|
|
|
|
/** @private */
|
|
|
|
this.labsService = labsService;
|
|
|
|
/** @private */
|
|
|
|
this.emailService = emailService;
|
|
|
|
/** @private */
|
|
|
|
this.stripeService = stripeService;
|
2022-08-19 23:39:18 +03:00
|
|
|
/** @private */
|
|
|
|
this.memberAttributionService = memberAttributionService;
|
2022-11-18 12:28:13 +03:00
|
|
|
/** @private */
|
|
|
|
this.emailSuppressionList = emailSuppressionList;
|
2021-08-25 14:30:49 +03:00
|
|
|
}
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
/**
|
|
|
|
* @private
|
2022-04-20 12:10:41 +03:00
|
|
|
* Adds missing complimentary subscriptions to a member and makes sure the tier of all subscriptions is set correctly.
|
2021-09-14 14:18:34 +03:00
|
|
|
*/
|
|
|
|
attachSubscriptionsToMember(member) {
|
2021-08-26 13:58:39 +03:00
|
|
|
if (!member.products || !Array.isArray(member.products)) {
|
|
|
|
return member;
|
|
|
|
}
|
|
|
|
|
2022-03-18 13:47:24 +03:00
|
|
|
const subscriptionProducts = (member.subscriptions || [])
|
|
|
|
.filter(sub => sub.status !== 'canceled')
|
|
|
|
.map(sub => sub.price.product.product_id);
|
|
|
|
|
2021-08-25 14:33:13 +03:00
|
|
|
for (const product of member.products) {
|
|
|
|
if (!subscriptionProducts.includes(product.id)) {
|
|
|
|
const productAddEvent = member.productEvents.find(event => event.product_id === product.id);
|
2021-08-26 12:50:16 +03:00
|
|
|
let startDate;
|
2021-08-25 14:33:13 +03:00
|
|
|
if (!productAddEvent || productAddEvent.action !== 'added') {
|
2021-08-26 12:50:16 +03:00
|
|
|
startDate = moment();
|
|
|
|
} else {
|
|
|
|
startDate = moment(productAddEvent.created_at);
|
2021-08-25 14:33:13 +03:00
|
|
|
}
|
|
|
|
member.subscriptions.push({
|
|
|
|
id: '',
|
2022-01-31 14:01:23 +03:00
|
|
|
tier: product,
|
2021-08-25 14:33:13 +03:00
|
|
|
customer: {
|
|
|
|
id: '',
|
|
|
|
name: member.name,
|
|
|
|
email: member.email
|
|
|
|
},
|
|
|
|
plan: {
|
|
|
|
id: '',
|
|
|
|
nickname: 'Complimentary',
|
|
|
|
interval: 'year',
|
|
|
|
currency: 'USD',
|
|
|
|
amount: 0
|
|
|
|
},
|
|
|
|
status: 'active',
|
|
|
|
start_date: startDate,
|
|
|
|
default_payment_card_last4: '****',
|
|
|
|
cancel_at_period_end: false,
|
|
|
|
cancellation_reason: null,
|
|
|
|
current_period_end: moment(startDate).add(1, 'year'),
|
|
|
|
price: {
|
|
|
|
id: '',
|
|
|
|
price_id: '',
|
|
|
|
nickname: 'Complimentary',
|
|
|
|
amount: 0,
|
|
|
|
interval: 'year',
|
|
|
|
type: 'recurring',
|
|
|
|
currency: 'USD',
|
|
|
|
product: {
|
|
|
|
id: '',
|
|
|
|
product_id: product.id
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2022-01-31 14:01:23 +03:00
|
|
|
|
|
|
|
for (const subscription of member.subscriptions) {
|
|
|
|
if (!subscription.tier) {
|
|
|
|
subscription.tier = member.products.find(product => product.id === subscription.price.product.product_id);
|
|
|
|
}
|
|
|
|
}
|
2021-09-14 14:18:34 +03:00
|
|
|
}
|
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
/**
|
|
|
|
* @private Builds a map between subscriptions and their offer representation (from OfferMapper)
|
|
|
|
* @returns {Promise<Map<string, OfferDTO>>}
|
|
|
|
*/
|
|
|
|
async fetchSubscriptionOffers(subscriptions) {
|
|
|
|
const fetchedOffers = new Map();
|
|
|
|
const subscriptionOffers = new Map();
|
|
|
|
|
|
|
|
try {
|
|
|
|
for (const subscriptionModel of subscriptions) {
|
|
|
|
const offerId = subscriptionModel.get('offer_id');
|
2022-07-14 14:54:58 +03:00
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
if (!offerId) {
|
|
|
|
continue;
|
|
|
|
}
|
2022-07-14 14:54:58 +03:00
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
let offer = fetchedOffers.get(offerId);
|
|
|
|
if (!offer) {
|
|
|
|
offer = await this.offersAPI.getOffer({id: offerId});
|
|
|
|
fetchedOffers.set(offerId, offer);
|
|
|
|
}
|
2022-07-14 14:54:58 +03:00
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
subscriptionOffers.set(subscriptionModel.get('subscription_id'), offer);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
logging.error(`Failed to load offers for subscriptions - ${subscriptions.map(s => s.id).join(', ')}.`);
|
|
|
|
logging.error(e);
|
|
|
|
}
|
2022-07-14 14:54:58 +03:00
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
return subscriptionOffers;
|
|
|
|
}
|
|
|
|
|
2021-10-20 15:32:41 +03:00
|
|
|
/**
|
|
|
|
* @private
|
2022-04-20 12:10:41 +03:00
|
|
|
* @param {Object} member JSON serialized member
|
|
|
|
* @param {Map<string, OfferDTO>} subscriptionOffers result from fetchSubscriptionOffers
|
2021-10-20 15:32:41 +03:00
|
|
|
*/
|
|
|
|
attachOffersToSubscriptions(member, subscriptionOffers) {
|
|
|
|
member.subscriptions = member.subscriptions.map((subscription) => {
|
2022-04-20 12:10:41 +03:00
|
|
|
const offer = subscriptionOffers.get(subscription.id);
|
2021-10-20 15:32:41 +03:00
|
|
|
if (offer) {
|
|
|
|
subscription.offer = offer;
|
|
|
|
} else {
|
|
|
|
subscription.offer = null;
|
|
|
|
}
|
|
|
|
return subscription;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-08-19 23:39:18 +03:00
|
|
|
/**
|
|
|
|
* @private
|
|
|
|
* Adds missing complimentary subscriptions to a member and makes sure the tier of all subscriptions is set correctly.
|
|
|
|
*/
|
|
|
|
async attachAttributionsToMember(member, subscriptionIdMap) {
|
|
|
|
// Created attribution
|
|
|
|
member.attribution = await this.memberAttributionService.getMemberCreatedAttribution(member.id);
|
2022-09-29 20:01:48 +03:00
|
|
|
|
2022-08-19 23:39:18 +03:00
|
|
|
// Subscriptions attributions
|
|
|
|
for (const subscription of member.subscriptions) {
|
|
|
|
if (!subscription.id) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert stripe ID to database id
|
|
|
|
const id = subscriptionIdMap.get(subscription.id);
|
|
|
|
if (!id) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
subscription.attribution = await this.memberAttributionService.getSubscriptionCreatedAttribution(id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
async read(data, options = {}) {
|
|
|
|
const defaultWithRelated = [
|
|
|
|
'labels',
|
|
|
|
'stripeSubscriptions',
|
|
|
|
'stripeSubscriptions.customer',
|
|
|
|
'stripeSubscriptions.stripePrice',
|
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct',
|
2022-03-10 11:50:10 +03:00
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct.product',
|
2021-10-20 15:32:41 +03:00
|
|
|
'products',
|
2022-04-04 17:31:58 +03:00
|
|
|
'newsletters'
|
2021-09-14 14:18:34 +03:00
|
|
|
];
|
|
|
|
|
|
|
|
const withRelated = new Set((options.withRelated || []).concat(defaultWithRelated));
|
|
|
|
|
|
|
|
if (!withRelated.has('productEvents')) {
|
|
|
|
withRelated.add('productEvents');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (withRelated.has('email_recipients')) {
|
|
|
|
withRelated.add('email_recipients.email');
|
|
|
|
}
|
|
|
|
|
|
|
|
const model = await this.memberRepository.get(data, {
|
|
|
|
...options,
|
|
|
|
withRelated: Array.from(withRelated)
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!model) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-08-19 23:39:18 +03:00
|
|
|
// We need to know the real IDs for each subscription to fetch the member attribution
|
|
|
|
const subscriptionIdMap = new Map();
|
|
|
|
for (const subscription of model.related('stripeSubscriptions')) {
|
|
|
|
subscriptionIdMap.set(subscription.get('subscription_id'), subscription.id);
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
const member = model.toJSON(options);
|
|
|
|
|
2021-12-01 11:45:50 +03:00
|
|
|
member.subscriptions = member.subscriptions.filter(sub => !!sub.price);
|
2021-09-14 14:18:34 +03:00
|
|
|
this.attachSubscriptionsToMember(member);
|
2022-04-20 12:10:41 +03:00
|
|
|
this.attachOffersToSubscriptions(member, await this.fetchSubscriptionOffers(model.related('stripeSubscriptions')));
|
2021-10-20 15:32:41 +03:00
|
|
|
|
2022-08-19 23:39:18 +03:00
|
|
|
if (this.labsService.isSet('memberAttribution')) {
|
|
|
|
await this.attachAttributionsToMember(member, subscriptionIdMap);
|
|
|
|
}
|
|
|
|
|
2022-11-18 12:28:13 +03:00
|
|
|
if (this.labsService.isSet('suppressionList')) {
|
|
|
|
const suppressionData = await this.emailSuppressionList.getSuppressionData(member.email);
|
|
|
|
member.email_suppression = {
|
|
|
|
suppressed: suppressionData.suppressed,
|
|
|
|
info: suppressionData.info
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-08-25 14:30:49 +03:00
|
|
|
return member;
|
|
|
|
}
|
2021-09-14 14:18:34 +03:00
|
|
|
|
|
|
|
async add(data, options) {
|
|
|
|
if (!this.stripeService.configured && (data.comped || data.stripe_customer_id)) {
|
|
|
|
const property = data.comped ? 'comped' : 'stripe_customer_id';
|
|
|
|
throw new errors.ValidationError({
|
|
|
|
message: tpl(messages.stripeNotConnected),
|
|
|
|
context: 'Attempting to import members with Stripe data when there is no Stripe account connected.',
|
|
|
|
help: 'You need to connect to Stripe to import Stripe customers. ',
|
|
|
|
property
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
let model;
|
|
|
|
|
|
|
|
try {
|
2022-09-29 20:01:48 +03:00
|
|
|
const attribution = await this.memberAttributionService.getAttributionFromContext(options?.context);
|
|
|
|
if (attribution) {
|
|
|
|
data.attribution = attribution;
|
|
|
|
}
|
2021-09-14 14:18:34 +03:00
|
|
|
model = await this.memberRepository.create(data, options);
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) {
|
|
|
|
throw new errors.ValidationError({
|
|
|
|
message: tpl(messages.memberAlreadyExists),
|
2022-09-08 19:29:48 +03:00
|
|
|
context: 'Attempting to add member with existing email address',
|
|
|
|
property: 'email'
|
2021-09-14 14:18:34 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2022-03-31 17:15:53 +03:00
|
|
|
const sharedOptions = options.transacting ? {
|
|
|
|
transacting: options.transacting
|
|
|
|
} : {};
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
try {
|
|
|
|
if (data.stripe_customer_id) {
|
|
|
|
await this.memberRepository.linkStripeCustomer({
|
|
|
|
customer_id: data.stripe_customer_id,
|
|
|
|
member_id: model.id
|
2022-03-31 17:15:53 +03:00
|
|
|
}, sharedOptions);
|
2021-09-14 14:18:34 +03:00
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
const isStripeLinkingError = error.message && (error.message.match(/customer|plan|subscription/g));
|
|
|
|
if (isStripeLinkingError) {
|
|
|
|
if (error.message.indexOf('customer') && error.code === 'resource_missing') {
|
|
|
|
error.message = `Member not imported. ${error.message}`;
|
|
|
|
error.context = 'Missing Stripe Customer';
|
|
|
|
error.help = 'Make sure you\'re connected to the correct Stripe Account';
|
|
|
|
}
|
|
|
|
|
|
|
|
await this.memberRepository.destroy({
|
|
|
|
id: model.id
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.send_email) {
|
|
|
|
await this.emailService.sendEmailWithMagicLink({
|
|
|
|
email: model.get('email'), requestedType: options.email_type
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-07-14 14:54:58 +03:00
|
|
|
if (data.comped) {
|
|
|
|
await this.memberRepository.setComplimentarySubscription(model, options);
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
return this.read({id: model.id}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
async edit(data, options) {
|
2022-05-02 21:09:47 +03:00
|
|
|
delete data.last_seen_at;
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
let model;
|
|
|
|
|
|
|
|
try {
|
|
|
|
model = await this.memberRepository.update(data, options);
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code && error.message.toLowerCase().indexOf('unique') !== -1) {
|
|
|
|
throw new errors.ValidationError({
|
|
|
|
message: tpl(messages.memberAlreadyExists),
|
2022-09-08 19:29:48 +03:00
|
|
|
context: 'Attempting to edit member with existing email address',
|
|
|
|
property: 'email'
|
2021-09-14 14:18:34 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2022-07-14 14:54:58 +03:00
|
|
|
if (this.stripeService.configured) {
|
|
|
|
const hasCompedSubscription = !!model.related('stripeSubscriptions').find(sub => sub.get('plan_nickname') === 'Complimentary' && sub.get('status') === 'active');
|
|
|
|
|
|
|
|
if (typeof data.comped === 'boolean') {
|
|
|
|
if (data.comped && !hasCompedSubscription) {
|
|
|
|
await this.memberRepository.setComplimentarySubscription(model, {
|
|
|
|
context: options.context,
|
|
|
|
transacting: options.transacting
|
|
|
|
});
|
|
|
|
} else if (!(data.comped) && hasCompedSubscription) {
|
|
|
|
await this.memberRepository.cancelComplimentarySubscription(model, {
|
|
|
|
context: options.context,
|
|
|
|
transacting: options.transacting
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
return this.read({id: model.id}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
async browse(options) {
|
|
|
|
const defaultWithRelated = [
|
|
|
|
'labels',
|
|
|
|
'stripeSubscriptions',
|
|
|
|
'stripeSubscriptions.customer',
|
|
|
|
'stripeSubscriptions.stripePrice',
|
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct',
|
2022-04-20 12:10:41 +03:00
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct.product',
|
2022-04-04 17:31:58 +03:00
|
|
|
'products',
|
|
|
|
'newsletters'
|
2021-09-14 14:18:34 +03:00
|
|
|
];
|
|
|
|
|
2021-10-25 14:34:20 +03:00
|
|
|
const originalWithRelated = options.withRelated || [];
|
|
|
|
|
|
|
|
const withRelated = new Set((originalWithRelated).concat(defaultWithRelated));
|
2021-09-14 14:18:34 +03:00
|
|
|
|
|
|
|
if (!withRelated.has('productEvents')) {
|
|
|
|
withRelated.add('productEvents');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (withRelated.has('email_recipients')) {
|
|
|
|
withRelated.add('email_recipients.email');
|
|
|
|
}
|
|
|
|
|
|
|
|
const page = await this.memberRepository.list({
|
|
|
|
...options,
|
|
|
|
withRelated: Array.from(withRelated)
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!page) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-04-20 12:10:41 +03:00
|
|
|
const subscriptions = page.data.flatMap(model => model.related('stripeSubscriptions').slice());
|
|
|
|
const offerMap = await this.fetchSubscriptionOffers(subscriptions);
|
|
|
|
|
2021-09-14 14:18:34 +03:00
|
|
|
const members = page.data.map(model => model.toJSON(options));
|
|
|
|
|
2022-11-18 12:28:13 +03:00
|
|
|
let bulkSuppressionData;
|
|
|
|
if (this.labsService.isSet('suppressionList')) {
|
|
|
|
bulkSuppressionData = await this.emailSuppressionList.getBulkSuppressionData(members.map(member => member.email));
|
|
|
|
}
|
|
|
|
|
|
|
|
const data = members.map((member, index) => {
|
2021-12-01 11:45:50 +03:00
|
|
|
member.subscriptions = member.subscriptions.filter(sub => !!sub.price);
|
2021-09-14 14:18:34 +03:00
|
|
|
this.attachSubscriptionsToMember(member);
|
2022-04-20 12:10:41 +03:00
|
|
|
this.attachOffersToSubscriptions(member, offerMap);
|
2021-10-25 14:34:20 +03:00
|
|
|
if (!originalWithRelated.includes('products')) {
|
|
|
|
delete member.products;
|
|
|
|
}
|
2022-11-18 12:28:13 +03:00
|
|
|
if (this.labsService.isSet('suppressionList')) {
|
|
|
|
member.email_suppression = {
|
|
|
|
suppressed: bulkSuppressionData[index].suppressed,
|
|
|
|
info: bulkSuppressionData[index].info
|
|
|
|
};
|
|
|
|
}
|
2021-09-14 14:18:34 +03:00
|
|
|
return member;
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
data,
|
|
|
|
meta: page.meta
|
|
|
|
};
|
|
|
|
}
|
2021-08-25 14:30:49 +03:00
|
|
|
};
|