2021-01-18 16:55:40 +03:00
|
|
|
const _ = require('lodash');
|
2021-06-16 13:05:00 +03:00
|
|
|
const errors = require('@tryghost/errors');
|
2021-12-02 17:46:58 +03:00
|
|
|
const logging = require('@tryghost/logging');
|
2021-06-16 13:05:00 +03:00
|
|
|
const tpl = require('@tryghost/tpl');
|
2021-10-18 16:27:17 +03:00
|
|
|
const DomainEvents = require('@tryghost/domain-events');
|
2022-09-09 17:29:06 +03:00
|
|
|
const {MemberCreatedEvent, SubscriptionCreatedEvent, MemberSubscribeEvent, SubscriptionCancelledEvent} = require('@tryghost/member-events');
|
2021-08-16 21:05:48 +03:00
|
|
|
const ObjectId = require('bson-objectid');
|
2022-05-03 17:38:55 +03:00
|
|
|
const {NotFoundError} = require('@tryghost/errors');
|
2021-06-16 13:05:00 +03:00
|
|
|
|
|
|
|
const messages = {
|
|
|
|
noStripeConnection: 'Cannot {action} without a Stripe Connection',
|
|
|
|
moreThanOneProduct: 'A member cannot have more than one Product',
|
2022-08-30 18:36:52 +03:00
|
|
|
addProductWithActiveSubscription: 'Cannot add comped Products to a Member with active Subscriptions',
|
|
|
|
deleteProductWithActiveSubscription: 'Cannot delete a non-comped Product from a Member, because it has an active Subscription for the same product',
|
2022-05-03 17:38:55 +03:00
|
|
|
memberNotFound: 'Could not find Member {id}',
|
2021-06-16 13:05:00 +03:00
|
|
|
subscriptionNotFound: 'Could not find Subscription {id}',
|
2021-08-12 14:45:01 +03:00
|
|
|
productNotFound: 'Could not find Product {id}',
|
2022-01-21 19:24:38 +03:00
|
|
|
bulkActionRequiresFilter: 'Cannot perform {action} without a filter or all=true',
|
|
|
|
tierArchived: 'Cannot use archived Tiers'
|
2021-06-16 13:05:00 +03:00
|
|
|
};
|
2021-05-20 18:56:14 +03:00
|
|
|
|
2021-09-17 12:25:57 +03:00
|
|
|
/**
|
|
|
|
* @typedef {object} ITokenService
|
|
|
|
* @prop {(token: string) => Promise<import('jsonwebtoken').JwtPayload>} decodeToken
|
|
|
|
*/
|
|
|
|
|
2021-01-18 16:55:40 +03:00
|
|
|
module.exports = class MemberRepository {
|
|
|
|
/**
|
|
|
|
* @param {object} deps
|
|
|
|
* @param {any} deps.Member
|
2022-03-12 00:44:28 +03:00
|
|
|
* @param {any} deps.MemberCancelEvent
|
2022-10-03 17:50:28 +03:00
|
|
|
* @param {any} deps.MemberSubscribeEventModel
|
2021-02-15 17:16:58 +03:00
|
|
|
* @param {any} deps.MemberEmailChangeEvent
|
|
|
|
* @param {any} deps.MemberPaidSubscriptionEvent
|
|
|
|
* @param {any} deps.MemberStatusEvent
|
2021-08-23 13:00:19 +03:00
|
|
|
* @param {any} deps.MemberProductEvent
|
2021-01-18 16:55:40 +03:00
|
|
|
* @param {any} deps.StripeCustomer
|
|
|
|
* @param {any} deps.StripeCustomerSubscription
|
2022-04-19 10:15:33 +03:00
|
|
|
* @param {any} deps.OfferRedemption
|
2021-01-18 16:55:40 +03:00
|
|
|
* @param {import('../../services/stripe-api')} deps.stripeAPIService
|
2022-04-19 10:15:33 +03:00
|
|
|
* @param {any} deps.labsService
|
|
|
|
* @param {any} deps.productRepository
|
|
|
|
* @param {any} deps.offerRepository
|
2021-09-17 12:25:57 +03:00
|
|
|
* @param {ITokenService} deps.tokenService
|
2022-04-19 10:15:33 +03:00
|
|
|
* @param {any} deps.newslettersService
|
2021-01-18 16:55:40 +03:00
|
|
|
*/
|
|
|
|
constructor({
|
|
|
|
Member,
|
2022-03-12 00:44:28 +03:00
|
|
|
MemberCancelEvent,
|
2022-10-03 17:50:28 +03:00
|
|
|
MemberSubscribeEventModel,
|
2021-02-15 17:16:58 +03:00
|
|
|
MemberEmailChangeEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberStatusEvent,
|
2021-08-23 13:00:19 +03:00
|
|
|
MemberProductEvent,
|
2021-01-18 16:55:40 +03:00
|
|
|
StripeCustomer,
|
|
|
|
StripeCustomerSubscription,
|
2021-10-18 16:27:17 +03:00
|
|
|
OfferRedemption,
|
2021-01-18 16:55:40 +03:00
|
|
|
stripeAPIService,
|
2022-04-05 20:26:18 +03:00
|
|
|
labsService,
|
2021-04-20 14:51:16 +03:00
|
|
|
productRepository,
|
2022-04-19 10:15:33 +03:00
|
|
|
offerRepository,
|
2022-04-05 20:26:18 +03:00
|
|
|
tokenService,
|
|
|
|
newslettersService
|
2021-01-18 16:55:40 +03:00
|
|
|
}) {
|
|
|
|
this._Member = Member;
|
2022-03-12 00:44:28 +03:00
|
|
|
this._MemberCancelEvent = MemberCancelEvent;
|
2022-10-03 17:50:28 +03:00
|
|
|
this._MemberSubscribeEvent = MemberSubscribeEventModel;
|
2021-02-15 17:16:58 +03:00
|
|
|
this._MemberEmailChangeEvent = MemberEmailChangeEvent;
|
|
|
|
this._MemberPaidSubscriptionEvent = MemberPaidSubscriptionEvent;
|
|
|
|
this._MemberStatusEvent = MemberStatusEvent;
|
2021-08-23 13:00:19 +03:00
|
|
|
this._MemberProductEvent = MemberProductEvent;
|
2021-01-18 16:55:40 +03:00
|
|
|
this._StripeCustomer = StripeCustomer;
|
|
|
|
this._StripeCustomerSubscription = StripeCustomerSubscription;
|
|
|
|
this._stripeAPIService = stripeAPIService;
|
2021-04-20 14:51:16 +03:00
|
|
|
this._productRepository = productRepository;
|
2022-04-19 10:15:33 +03:00
|
|
|
this._offerRepository = offerRepository;
|
2021-09-17 12:25:57 +03:00
|
|
|
this.tokenService = tokenService;
|
2022-04-05 20:26:18 +03:00
|
|
|
this._newslettersService = newslettersService;
|
|
|
|
this._labsService = labsService;
|
2021-10-18 16:27:17 +03:00
|
|
|
|
|
|
|
DomainEvents.subscribe(SubscriptionCreatedEvent, async function (event) {
|
|
|
|
if (!event.data.offerId) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
await OfferRedemption.add({
|
|
|
|
member_id: event.data.memberId,
|
|
|
|
subscription_id: event.data.subscriptionId,
|
|
|
|
offer_id: event.data.offerId
|
|
|
|
});
|
|
|
|
});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2022-10-07 16:45:18 +03:00
|
|
|
dispatchEvent(event, options) {
|
|
|
|
if (options?.transacting) {
|
|
|
|
// Only dispatch the event after the transaction has finished
|
|
|
|
options.transacting.executionPromise.then(async () => {
|
|
|
|
DomainEvents.dispatch(event);
|
|
|
|
}).catch(() => {
|
|
|
|
// catches transaction errors/rollback to not dispatch event
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
DomainEvents.dispatch(event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-25 18:33:23 +03:00
|
|
|
isActiveSubscriptionStatus(status) {
|
|
|
|
return ['active', 'trialing', 'unpaid', 'past_due'].includes(status);
|
|
|
|
}
|
|
|
|
|
2021-08-17 13:09:27 +03:00
|
|
|
isComplimentarySubscription(subscription) {
|
2022-02-09 12:28:26 +03:00
|
|
|
return subscription.plan && subscription.plan.nickname && subscription.plan.nickname.toLowerCase() === 'complimentary';
|
2021-08-17 13:09:27 +03:00
|
|
|
}
|
|
|
|
|
2022-08-25 04:41:19 +03:00
|
|
|
/**
|
|
|
|
* Maps the framework context to members_*.source table record value
|
|
|
|
* @param {Object} context instance of ghost framework context object
|
|
|
|
* @returns {'import' | 'system' | 'api' | 'admin' | 'member'}
|
|
|
|
*/
|
2022-08-23 07:04:43 +03:00
|
|
|
_resolveContextSource(context) {
|
|
|
|
let source;
|
|
|
|
|
|
|
|
if (context.import || context.importer) {
|
|
|
|
source = 'import';
|
|
|
|
} else if (context.internal) {
|
|
|
|
source = 'system';
|
|
|
|
} else if (context.api_key) {
|
|
|
|
source = 'api';
|
2022-08-23 09:38:25 +03:00
|
|
|
} else if (context.user) {
|
|
|
|
source = 'admin';
|
2022-08-23 07:04:43 +03:00
|
|
|
} else {
|
|
|
|
source = 'member';
|
|
|
|
}
|
|
|
|
|
|
|
|
return source;
|
|
|
|
}
|
|
|
|
|
2022-04-13 16:46:43 +03:00
|
|
|
getMRR({interval, amount, status = null, canceled = false, discount = null}) {
|
2022-04-12 12:06:11 +03:00
|
|
|
if (status === 'trialing') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status === 'incomplete') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status === 'incomplete_expired') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status === 'canceled') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-05-25 11:29:44 +03:00
|
|
|
if (canceled) {
|
2022-04-12 12:06:11 +03:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-04-13 16:46:43 +03:00
|
|
|
let amountWithDiscount = amount;
|
|
|
|
|
2022-05-25 11:29:44 +03:00
|
|
|
if (discount && discount.end === null && discount.coupon && discount.coupon.duration === 'forever') {
|
2022-04-13 16:46:43 +03:00
|
|
|
// Discounts should only get applied when they are 'forever' discounts / they don't have an end date
|
|
|
|
if (discount.coupon.amount_off !== null) {
|
|
|
|
amountWithDiscount = Math.max(0, amountWithDiscount - discount.coupon.amount_off);
|
|
|
|
} else {
|
|
|
|
amountWithDiscount = Math.round((amountWithDiscount * (100 - discount.coupon.percent_off)) / 100);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-12 12:06:11 +03:00
|
|
|
if (interval === 'year') {
|
2022-04-13 16:46:43 +03:00
|
|
|
return Math.floor(amountWithDiscount / 12);
|
2022-04-12 12:06:11 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (interval === 'month') {
|
2022-04-13 16:46:43 +03:00
|
|
|
return amountWithDiscount;
|
2022-04-12 12:06:11 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (interval === 'week') {
|
2022-04-13 16:46:43 +03:00
|
|
|
return amountWithDiscount * 4;
|
2022-04-12 12:06:11 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (interval === 'day') {
|
2022-04-13 16:46:43 +03:00
|
|
|
return amountWithDiscount * 30;
|
2022-04-12 12:06:11 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-18 16:55:40 +03:00
|
|
|
async get(data, options) {
|
|
|
|
if (data.customer_id) {
|
|
|
|
const customer = await this._StripeCustomer.findOne({
|
|
|
|
customer_id: data.customer_id
|
|
|
|
}, {
|
|
|
|
withRelated: ['member']
|
|
|
|
});
|
|
|
|
if (customer) {
|
|
|
|
return customer.related('member');
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return this._Member.findOne(data, options);
|
|
|
|
}
|
|
|
|
|
2021-09-17 12:25:57 +03:00
|
|
|
async getByToken(token, options) {
|
|
|
|
const data = await this.tokenService.decodeToken(token);
|
|
|
|
|
|
|
|
return this.get({
|
|
|
|
email: data.sub
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2022-08-18 18:38:42 +03:00
|
|
|
/**
|
|
|
|
* Create a member
|
2022-08-17 12:11:14 +03:00
|
|
|
* @param {Object} data
|
2022-08-18 18:38:42 +03:00
|
|
|
* @param {string} data.email
|
|
|
|
* @param {string} [data.name]
|
|
|
|
* @param {string} [data.note]
|
|
|
|
* @param {(string|Object)[]} [data.labels]
|
|
|
|
* @param {boolean} [data.subscribed] (deprecated)
|
2022-08-17 12:11:14 +03:00
|
|
|
* @param {string} [data.geolocation]
|
2022-08-18 18:38:42 +03:00
|
|
|
* @param {Date} [data.created_at]
|
|
|
|
* @param {Object[]} [data.products]
|
|
|
|
* @param {Object[]} [data.newsletters]
|
2022-09-09 17:29:06 +03:00
|
|
|
* @param {Object} [data.stripeCustomer]
|
|
|
|
* @param {string} [data.offerId]
|
2022-09-29 20:01:48 +03:00
|
|
|
* @param {import('@tryghost/member-attribution/lib/attribution').AttributionResource} [data.attribution]
|
2022-08-17 12:11:14 +03:00
|
|
|
* @param {*} options
|
|
|
|
* @returns
|
2022-08-18 18:38:42 +03:00
|
|
|
*/
|
2021-01-18 16:55:40 +03:00
|
|
|
async create(data, options) {
|
2022-05-02 21:07:30 +03:00
|
|
|
if (!options) {
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
|
2022-09-09 17:29:06 +03:00
|
|
|
const {labels, stripeCustomer, offerId, attribution} = data;
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
if (labels) {
|
|
|
|
labels.forEach((label, index) => {
|
|
|
|
if (typeof label === 'string') {
|
|
|
|
labels[index] = {name: label};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-04-05 20:26:18 +03:00
|
|
|
const memberData = _.pick(data, ['email', 'name', 'note', 'subscribed', 'geolocation', 'created_at', 'products', 'newsletters']);
|
2021-01-22 18:15:31 +03:00
|
|
|
|
2021-06-16 13:33:21 +03:00
|
|
|
if (memberData.products && memberData.products.length > 1) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.moreThanOneProduct)});
|
2021-06-16 13:33:21 +03:00
|
|
|
}
|
|
|
|
|
2022-01-21 19:24:38 +03:00
|
|
|
if (memberData.products) {
|
|
|
|
for (const productData of memberData.products) {
|
|
|
|
const product = await this._productRepository.get(productData);
|
|
|
|
if (product.get('active') !== true) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.tierArchived)});
|
2022-01-21 19:24:38 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
const memberStatusData = {
|
|
|
|
status: 'free'
|
|
|
|
};
|
|
|
|
|
2021-07-06 13:52:08 +03:00
|
|
|
if (memberData.products && memberData.products.length === 1) {
|
2021-07-01 21:51:54 +03:00
|
|
|
memberStatusData.status = 'comped';
|
|
|
|
}
|
|
|
|
|
2022-04-14 18:40:14 +03:00
|
|
|
// Subscribe member to default newsletters
|
2022-04-26 20:28:05 +03:00
|
|
|
if (memberData.subscribed !== false && !memberData.newsletters) {
|
2022-04-14 18:40:14 +03:00
|
|
|
const browseOptions = _.pick(options, 'transacting');
|
2022-04-26 20:28:05 +03:00
|
|
|
memberData.newsletters = await this.getSubscribeOnSignupNewsletters(browseOptions);
|
2022-04-05 20:26:18 +03:00
|
|
|
}
|
|
|
|
|
2022-05-02 21:07:30 +03:00
|
|
|
const withRelated = options.withRelated ? options.withRelated : [];
|
|
|
|
if (!withRelated.includes('labels')) {
|
|
|
|
withRelated.push('labels');
|
|
|
|
}
|
|
|
|
if (!withRelated.includes('newsletters')) {
|
|
|
|
withRelated.push('newsletters');
|
|
|
|
}
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
const member = await this._Member.add({
|
2021-01-22 18:15:31 +03:00
|
|
|
...memberData,
|
2021-07-01 21:51:54 +03:00
|
|
|
...memberStatusData,
|
2021-01-22 18:15:31 +03:00
|
|
|
labels
|
2022-05-02 21:07:30 +03:00
|
|
|
}, {...options, withRelated});
|
2021-02-15 17:16:58 +03:00
|
|
|
|
2021-08-23 13:00:19 +03:00
|
|
|
for (const product of member.related('products').models) {
|
|
|
|
await this._MemberProductEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
product_id: product.id,
|
|
|
|
action: 'added'
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
const context = options && options.context || {};
|
2022-08-23 07:04:43 +03:00
|
|
|
const source = this._resolveContextSource(context);
|
2021-02-15 17:16:58 +03:00
|
|
|
|
2021-07-15 12:25:41 +03:00
|
|
|
const eventData = _.pick(data, ['created_at']);
|
|
|
|
|
2022-04-28 10:29:41 +03:00
|
|
|
if (!eventData.created_at) {
|
|
|
|
eventData.created_at = member.get('created_at');
|
|
|
|
}
|
|
|
|
|
2021-03-05 15:39:30 +03:00
|
|
|
await this._MemberStatusEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_status: null,
|
2021-07-15 12:25:41 +03:00
|
|
|
to_status: member.get('status'),
|
|
|
|
...eventData
|
2021-03-05 15:39:30 +03:00
|
|
|
}, options);
|
|
|
|
|
2022-04-26 09:40:19 +03:00
|
|
|
const newsletters = member.related('newsletters').models;
|
|
|
|
|
|
|
|
for (const newsletter of newsletters) {
|
2021-02-15 17:16:58 +03:00
|
|
|
await this._MemberSubscribeEvent.add({
|
|
|
|
member_id: member.id,
|
2022-04-26 09:40:19 +03:00
|
|
|
newsletter_id: newsletter.id,
|
2021-02-15 17:16:58 +03:00
|
|
|
subscribed: true,
|
2021-07-15 12:25:41 +03:00
|
|
|
source,
|
|
|
|
...eventData
|
2021-02-15 17:16:58 +03:00
|
|
|
}, options);
|
2022-04-26 09:40:19 +03:00
|
|
|
}
|
2022-01-27 13:57:51 +03:00
|
|
|
|
2022-04-26 09:40:19 +03:00
|
|
|
if (newsletters && newsletters.length > 0) {
|
2022-10-07 16:45:18 +03:00
|
|
|
this.dispatchEvent(MemberSubscribeEvent.create({
|
2022-01-27 13:57:51 +03:00
|
|
|
memberId: member.id,
|
|
|
|
source: source
|
2022-10-07 16:45:18 +03:00
|
|
|
}, eventData.created_at), options);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
2022-09-09 17:29:06 +03:00
|
|
|
// For paid members created via stripe checkout webhook event, link subscription
|
|
|
|
if (stripeCustomer) {
|
|
|
|
await this.upsertCustomer({
|
|
|
|
member_id: member.id,
|
|
|
|
customer_id: stripeCustomer.id,
|
|
|
|
name: stripeCustomer.name,
|
|
|
|
email: stripeCustomer.email
|
|
|
|
});
|
|
|
|
|
|
|
|
for (const subscription of stripeCustomer.subscriptions.data) {
|
|
|
|
try {
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription,
|
|
|
|
offerId,
|
|
|
|
attribution
|
|
|
|
});
|
|
|
|
} catch (err) {
|
|
|
|
if (err.code !== 'ER_DUP_ENTRY' && err.code !== 'SQLITE_CONSTRAINT') {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
throw new errors.ConflictError({
|
|
|
|
err
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-10-07 16:45:18 +03:00
|
|
|
this.dispatchEvent(MemberCreatedEvent.create({
|
2022-08-18 18:38:42 +03:00
|
|
|
memberId: member.id,
|
|
|
|
attribution: data.attribution,
|
|
|
|
source
|
2022-10-07 16:45:18 +03:00
|
|
|
}, eventData.created_at), options);
|
2022-08-18 18:38:42 +03:00
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
return member;
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2022-04-26 20:28:05 +03:00
|
|
|
async getSubscribeOnSignupNewsletters(browseOptions) {
|
|
|
|
// By default subscribe to all active auto opt-in newsletters with members visibility
|
|
|
|
//TODO: Will mostly need to be updated later for paid-only newsletters
|
|
|
|
browseOptions.filter = 'status:active+subscribe_on_signup:true+visibility:members';
|
|
|
|
const newsletters = await this._newslettersService.browse(browseOptions);
|
|
|
|
return newsletters || [];
|
|
|
|
}
|
|
|
|
|
2021-01-18 16:55:40 +03:00
|
|
|
async update(data, options) {
|
2021-06-10 19:48:15 +03:00
|
|
|
const sharedOptions = {
|
|
|
|
transacting: options.transacting
|
|
|
|
};
|
|
|
|
|
2022-05-02 21:07:30 +03:00
|
|
|
if (!options) {
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
const withRelated = options.withRelated ? options.withRelated : [];
|
|
|
|
if (!withRelated.includes('labels')) {
|
|
|
|
withRelated.push('labels');
|
|
|
|
}
|
|
|
|
if (!withRelated.includes('newsletters')) {
|
|
|
|
withRelated.push('newsletters');
|
|
|
|
}
|
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
const memberData = _.pick(data, [
|
|
|
|
'email',
|
|
|
|
'name',
|
|
|
|
'note',
|
|
|
|
'subscribed',
|
|
|
|
'labels',
|
|
|
|
'geolocation',
|
2022-04-04 17:37:26 +03:00
|
|
|
'products',
|
2022-05-02 21:07:30 +03:00
|
|
|
'newsletters',
|
2022-07-07 15:12:54 +03:00
|
|
|
'enable_comment_notifications',
|
2022-07-25 18:35:46 +03:00
|
|
|
'last_seen_at',
|
2022-08-04 16:51:23 +03:00
|
|
|
'last_commented_at',
|
2022-09-09 11:14:49 +03:00
|
|
|
'expertise'
|
2021-07-01 21:51:54 +03:00
|
|
|
]);
|
|
|
|
|
2022-09-09 11:14:49 +03:00
|
|
|
// Trim whitespaces from expertise
|
|
|
|
if (memberData.expertise) {
|
|
|
|
memberData.expertise = memberData.expertise.trim();
|
2022-08-05 18:09:48 +03:00
|
|
|
}
|
2022-08-10 15:30:11 +03:00
|
|
|
|
2022-05-03 17:38:55 +03:00
|
|
|
// Determine if we need to fetch the initial member with relations
|
|
|
|
const needsProducts = this._stripeAPIService.configured && data.products;
|
|
|
|
const needsNewsletters = memberData.newsletters || typeof memberData.subscribed === 'boolean';
|
|
|
|
|
|
|
|
// Build list for withRelated
|
|
|
|
const requiredRelations = [];
|
|
|
|
if (needsProducts) {
|
|
|
|
requiredRelations.push('products');
|
|
|
|
}
|
|
|
|
if (needsNewsletters) {
|
|
|
|
requiredRelations.push('newsletters');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch the member with relations if required
|
|
|
|
let initialMember = null;
|
|
|
|
if (requiredRelations.length > 0) {
|
|
|
|
initialMember = await this._Member.findOne({
|
|
|
|
id: options.id
|
|
|
|
}, {...sharedOptions, withRelated: requiredRelations});
|
|
|
|
|
|
|
|
// Make sure we throw the right error if it doesn't exist
|
|
|
|
if (!initialMember) {
|
|
|
|
throw new NotFoundError({message: tpl(messages.memberNotFound, {id: options.id})});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
const memberStatusData = {};
|
|
|
|
|
2021-08-23 13:00:19 +03:00
|
|
|
let productsToAdd = [];
|
|
|
|
let productsToRemove = [];
|
2022-05-03 17:38:55 +03:00
|
|
|
if (needsProducts) {
|
|
|
|
const existingProducts = initialMember.related('products').models;
|
2021-06-10 19:48:15 +03:00
|
|
|
const existingProductIds = existingProducts.map(product => product.id);
|
|
|
|
const incomingProductIds = data.products.map(product => product.id);
|
|
|
|
|
2021-06-16 13:33:21 +03:00
|
|
|
if (incomingProductIds.length > 1 && incomingProductIds.length > existingProductIds.length) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.moreThanOneProduct)});
|
2021-06-16 13:33:21 +03:00
|
|
|
}
|
|
|
|
|
2021-08-23 13:00:19 +03:00
|
|
|
productsToAdd = _.differenceWith(incomingProductIds, existingProductIds);
|
|
|
|
productsToRemove = _.differenceWith(existingProductIds, incomingProductIds);
|
2021-06-10 19:48:15 +03:00
|
|
|
const productsToModify = productsToAdd.concat(productsToRemove);
|
2022-09-01 17:30:37 +03:00
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
if (productsToModify.length !== 0) {
|
2022-08-30 18:36:52 +03:00
|
|
|
// Load active subscriptions information
|
|
|
|
await initialMember.load(
|
|
|
|
[
|
|
|
|
'stripeSubscriptions',
|
|
|
|
'stripeSubscriptions.stripePrice',
|
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct',
|
|
|
|
'stripeSubscriptions.stripePrice.stripeProduct.product'
|
|
|
|
], sharedOptions);
|
2022-09-01 17:30:37 +03:00
|
|
|
|
2022-08-30 18:36:52 +03:00
|
|
|
const exisitingSubscriptions = initialMember.related('stripeSubscriptions')?.models ?? [];
|
2022-09-01 17:30:37 +03:00
|
|
|
|
2022-08-30 18:36:52 +03:00
|
|
|
if (productsToRemove.length > 0) {
|
|
|
|
// Only allow to delete comped products without a subscription attached to them
|
|
|
|
// Other products should be removed by canceling them via the related stripe subscription
|
|
|
|
const dontAllowToRemoveProductsIds = exisitingSubscriptions
|
|
|
|
.filter(sub => this.isActiveSubscriptionStatus(sub.get('status')))
|
|
|
|
.map(sub => sub.related('stripePrice')?.related('stripeProduct')?.get('product_id'));
|
|
|
|
|
|
|
|
for (const deleteId of productsToRemove) {
|
|
|
|
if (dontAllowToRemoveProductsIds.includes(deleteId)) {
|
|
|
|
throw new errors.BadRequestError({message: tpl(messages.deleteProductWithActiveSubscription)});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (incomingProductIds.length === 0) {
|
|
|
|
// CASE: We are removing all (comped) products from a member & there were no active subscriptions - the member is "free"
|
|
|
|
memberStatusData.status = 'free';
|
|
|
|
}
|
2021-06-10 19:48:15 +03:00
|
|
|
}
|
2021-07-01 21:51:54 +03:00
|
|
|
|
2022-08-30 18:36:52 +03:00
|
|
|
if (productsToAdd.length > 0) {
|
|
|
|
// Don't allow to add complimentary subscriptions (= creating a new product) when the member already has an active
|
|
|
|
// subscription
|
|
|
|
const existingActiveSubscriptions = exisitingSubscriptions.filter((subscription) => {
|
|
|
|
return this.isActiveSubscriptionStatus(subscription.get('status'));
|
|
|
|
});
|
2022-09-01 17:30:37 +03:00
|
|
|
|
2022-08-30 18:36:52 +03:00
|
|
|
if (existingActiveSubscriptions.length) {
|
|
|
|
throw new errors.BadRequestError({message: tpl(messages.addProductWithActiveSubscription)});
|
|
|
|
}
|
|
|
|
|
|
|
|
// CASE: We are changing products & there were not active stripe subscriptions - the member is "comped"
|
2021-07-01 21:51:54 +03:00
|
|
|
memberStatusData.status = 'comped';
|
|
|
|
}
|
|
|
|
}
|
2021-06-10 19:48:15 +03:00
|
|
|
}
|
|
|
|
|
2022-01-21 19:24:38 +03:00
|
|
|
for (const productId of productsToAdd) {
|
|
|
|
const product = await this._productRepository.get({id: productId}, sharedOptions);
|
|
|
|
if (product.get('active') !== true) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.tierArchived)});
|
2022-01-21 19:24:38 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-26 09:40:19 +03:00
|
|
|
// Keep track of the newsletters that were added and removed of a member so we can generate the corresponding events
|
|
|
|
let newslettersToAdd = [];
|
|
|
|
let newslettersToRemove = [];
|
|
|
|
|
2022-05-03 17:38:55 +03:00
|
|
|
if (needsNewsletters) {
|
|
|
|
const existingNewsletters = initialMember.related('newsletters').models;
|
|
|
|
|
2022-07-14 14:10:18 +03:00
|
|
|
// This maps the old subscribed property to the new newsletters field
|
2022-05-03 17:38:55 +03:00
|
|
|
if (!memberData.newsletters) {
|
|
|
|
if (memberData.subscribed === false) {
|
|
|
|
memberData.newsletters = [];
|
|
|
|
} else if (memberData.subscribed === true && !existingNewsletters.find(n => n.status === 'active')) {
|
|
|
|
const browseOptions = _.pick(options, 'transacting');
|
|
|
|
memberData.newsletters = await this.getSubscribeOnSignupNewsletters(browseOptions);
|
|
|
|
}
|
|
|
|
}
|
2022-05-10 17:53:19 +03:00
|
|
|
|
2022-05-03 17:38:55 +03:00
|
|
|
if (memberData.newsletters) {
|
|
|
|
const existingNewsletterIds = existingNewsletters.map(newsletter => newsletter.id);
|
|
|
|
const incomingNewsletterIds = memberData.newsletters.map(newsletter => newsletter.id);
|
|
|
|
|
|
|
|
newslettersToAdd = _.differenceWith(incomingNewsletterIds, existingNewsletterIds);
|
|
|
|
newslettersToRemove = _.differenceWith(existingNewsletterIds, incomingNewsletterIds);
|
|
|
|
}
|
2022-04-26 09:40:19 +03:00
|
|
|
}
|
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
const member = await this._Member.edit({
|
|
|
|
...memberData,
|
|
|
|
...memberStatusData
|
2022-05-02 21:07:30 +03:00
|
|
|
}, {...options, withRelated});
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-08-23 13:00:19 +03:00
|
|
|
for (const productToAdd of productsToAdd) {
|
|
|
|
await this._MemberProductEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
product_id: productToAdd,
|
|
|
|
action: 'added'
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const productToRemove of productsToRemove) {
|
|
|
|
await this._MemberProductEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
product_id: productToRemove,
|
|
|
|
action: 'removed'
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2022-04-26 09:40:19 +03:00
|
|
|
// Add subscribe events for all (un)subscribed newsletters
|
|
|
|
const context = options && options.context || {};
|
2022-08-23 07:29:55 +03:00
|
|
|
const source = this._resolveContextSource(context);
|
2022-04-26 09:40:19 +03:00
|
|
|
|
|
|
|
for (const newsletterToAdd of newslettersToAdd) {
|
2021-02-15 17:16:58 +03:00
|
|
|
await this._MemberSubscribeEvent.add({
|
|
|
|
member_id: member.id,
|
2022-04-26 09:40:19 +03:00
|
|
|
newsletter_id: newsletterToAdd,
|
|
|
|
subscribed: true,
|
2021-02-15 17:16:58 +03:00
|
|
|
source
|
2021-06-10 19:57:06 +03:00
|
|
|
}, sharedOptions);
|
2022-04-26 09:40:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for (const newsletterToRemove of newslettersToRemove) {
|
|
|
|
await this._MemberSubscribeEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
newsletter_id: newsletterToRemove,
|
|
|
|
subscribed: false,
|
|
|
|
source
|
|
|
|
}, sharedOptions);
|
|
|
|
}
|
2022-01-27 13:57:51 +03:00
|
|
|
|
2022-04-26 09:40:19 +03:00
|
|
|
if (newslettersToAdd.length > 0 || newslettersToRemove.length > 0) {
|
2022-10-07 16:45:18 +03:00
|
|
|
this.dispatchEvent(MemberSubscribeEvent.create({
|
2022-01-27 13:57:51 +03:00
|
|
|
memberId: member.id,
|
|
|
|
source: source
|
2022-10-07 16:45:18 +03:00
|
|
|
}, member.updated_at), sharedOptions);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (member.attributes.email !== member._previousAttributes.email) {
|
|
|
|
await this._MemberEmailChangeEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_email: member._previousAttributes.email,
|
|
|
|
to_email: member.get('email')
|
2021-06-10 19:57:06 +03:00
|
|
|
}, sharedOptions);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
2021-07-01 21:51:54 +03:00
|
|
|
if (member.attributes.status !== member._previousAttributes.status) {
|
|
|
|
await this._MemberStatusEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_status: member._previousAttributes.status,
|
|
|
|
to_status: member.get('status')
|
|
|
|
}, sharedOptions);
|
|
|
|
}
|
|
|
|
|
2021-04-19 17:09:28 +03:00
|
|
|
if (this._stripeAPIService.configured && member._changed.email) {
|
2021-01-18 16:55:40 +03:00
|
|
|
await member.related('stripeCustomers').fetch();
|
|
|
|
const customers = member.related('stripeCustomers');
|
|
|
|
for (const customer of customers.models) {
|
|
|
|
await this._stripeAPIService.updateCustomerEmail(
|
|
|
|
customer.get('customer_id'),
|
|
|
|
member.get('email')
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return member;
|
|
|
|
}
|
|
|
|
|
|
|
|
async list(options) {
|
|
|
|
return this._Member.findPage(options);
|
|
|
|
}
|
|
|
|
|
|
|
|
async destroy(data, options) {
|
|
|
|
const member = await this._Member.findOne(data, options);
|
|
|
|
|
|
|
|
if (!member) {
|
|
|
|
// throw error?
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-04-19 17:09:28 +03:00
|
|
|
if (this._stripeAPIService.configured && options.cancelStripeSubscriptions) {
|
2021-03-01 14:23:58 +03:00
|
|
|
await member.related('stripeSubscriptions').fetch();
|
2021-01-18 16:55:40 +03:00
|
|
|
const subscriptions = member.related('stripeSubscriptions');
|
|
|
|
for (const subscription of subscriptions.models) {
|
|
|
|
if (subscription.get('status') !== 'canceled') {
|
|
|
|
const updatedSubscription = await this._stripeAPIService.cancelSubscription(
|
|
|
|
subscription.get('subscription_id')
|
|
|
|
);
|
2021-03-01 14:23:58 +03:00
|
|
|
|
|
|
|
await this._StripeCustomerSubscription.upsert({
|
2022-04-13 16:46:43 +03:00
|
|
|
status: updatedSubscription.status,
|
|
|
|
mrr: 0
|
2021-03-01 14:23:58 +03:00
|
|
|
}, {
|
|
|
|
subscription_id: updatedSubscription.id
|
|
|
|
});
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
await this._MemberPaidSubscriptionEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
source: 'stripe',
|
2022-04-12 12:06:11 +03:00
|
|
|
subscription_id: subscription.id,
|
2021-02-15 17:16:58 +03:00
|
|
|
from_plan: subscription.get('plan_id'),
|
|
|
|
to_plan: null,
|
|
|
|
currency: subscription.get('plan_currency'),
|
2022-04-13 16:46:43 +03:00
|
|
|
mrr_delta: -1 * subscription.get('mrr')
|
2021-02-15 17:16:58 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return this._Member.destroy({
|
|
|
|
id: data.id
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2021-08-12 14:45:01 +03:00
|
|
|
async bulkDestroy(options) {
|
|
|
|
const {all, filter, search} = options;
|
|
|
|
|
|
|
|
if (!filter && !search && (!all || all !== true)) {
|
|
|
|
throw new errors.IncorrectUsageError({
|
|
|
|
message: tpl(messages.bulkActionRequiresFilter, {action: 'bulk delete'})
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-05-11 17:17:41 +03:00
|
|
|
const filterOptions = _.pick(options, ['transacting', 'context']);
|
2021-08-13 14:23:01 +03:00
|
|
|
|
2021-08-12 14:45:01 +03:00
|
|
|
if (all !== true) {
|
2022-05-11 17:17:41 +03:00
|
|
|
// Include mongoTransformer to apply subscribed:{true|false} => newsletter relation mapping
|
|
|
|
Object.assign(filterOptions, _.pick(options, ['filter', 'search', 'mongoTransformer']));
|
2021-08-12 14:45:01 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const memberRows = await this._Member.getFilteredCollectionQuery(filterOptions)
|
|
|
|
.select('members.id')
|
|
|
|
.distinct();
|
|
|
|
|
|
|
|
const memberIds = memberRows.map(row => row.id);
|
|
|
|
|
2021-08-13 14:23:01 +03:00
|
|
|
const bulkDestroyResult = await this._Member.bulkDestroy(memberIds);
|
|
|
|
|
|
|
|
bulkDestroyResult.unsuccessfulIds = bulkDestroyResult.unsuccessfulData;
|
|
|
|
|
|
|
|
delete bulkDestroyResult.unsuccessfulData;
|
|
|
|
|
|
|
|
return bulkDestroyResult;
|
2021-08-12 14:45:01 +03:00
|
|
|
}
|
|
|
|
|
2021-08-16 21:05:48 +03:00
|
|
|
async bulkEdit(data, options) {
|
|
|
|
const {all, filter, search} = options;
|
|
|
|
|
|
|
|
if (!['unsubscribe', 'addLabel', 'removeLabel'].includes(data.action)) {
|
|
|
|
throw new errors.IncorrectUsageError({
|
|
|
|
message: 'Unsupported bulk action'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!filter && !search && (!all || all !== true)) {
|
|
|
|
throw new errors.IncorrectUsageError({
|
|
|
|
message: tpl(messages.bulkActionRequiresFilter, {action: 'bulk edit'})
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-05-11 17:17:41 +03:00
|
|
|
const filterOptions = _.pick(options, ['transacting', 'context']);
|
2021-08-16 21:05:48 +03:00
|
|
|
|
|
|
|
if (all !== true) {
|
2022-05-11 17:17:41 +03:00
|
|
|
// Include mongoTransformer to apply subscribed:{true|false} => newsletter relation mapping
|
|
|
|
Object.assign(filterOptions, _.pick(options, ['filter', 'search', 'mongoTransformer']));
|
2021-08-16 21:05:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const memberRows = await this._Member.getFilteredCollectionQuery(filterOptions)
|
|
|
|
.select('members.id')
|
|
|
|
.distinct();
|
|
|
|
|
|
|
|
const memberIds = memberRows.map(row => row.id);
|
|
|
|
|
|
|
|
if (data.action === 'unsubscribe') {
|
2022-05-20 13:25:58 +03:00
|
|
|
return await this._Member.bulkDestroy(memberIds, 'members_newsletters', {column: 'member_id'});
|
2021-08-16 21:05:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (data.action === 'removeLabel') {
|
|
|
|
const membersLabelsRows = await this._Member.getLabelRelations({
|
|
|
|
labelId: data.meta.label.id,
|
|
|
|
memberIds
|
|
|
|
});
|
|
|
|
|
|
|
|
const membersLabelsIds = membersLabelsRows.map(row => row.id);
|
|
|
|
|
|
|
|
return this._Member.bulkDestroy(membersLabelsIds, 'members_labels');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (data.action === 'addLabel') {
|
|
|
|
const relations = memberIds.map((id) => {
|
|
|
|
return {
|
|
|
|
member_id: id,
|
|
|
|
label_id: data.meta.label.id,
|
2021-08-23 15:46:53 +03:00
|
|
|
id: ObjectId().toHexString()
|
2021-08-16 21:05:48 +03:00
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
return this._Member.bulkAdd(relations, 'members_labels');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-12 14:17:26 +03:00
|
|
|
async upsertCustomer(data) {
|
|
|
|
return await this._StripeCustomer.upsert({
|
|
|
|
customer_id: data.customer_id,
|
|
|
|
member_id: data.member_id,
|
|
|
|
name: data.name,
|
|
|
|
email: data.email
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
async linkStripeCustomer(data, options) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'link Stripe Customer'})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
2021-04-22 19:21:01 +03:00
|
|
|
const customer = await this._stripeAPIService.getCustomer(data.customer_id);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
if (!customer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add instead of upsert ensures that we do not link existing customer
|
|
|
|
await this._StripeCustomer.add({
|
|
|
|
customer_id: data.customer_id,
|
|
|
|
member_id: data.member_id,
|
|
|
|
name: customer.name,
|
|
|
|
email: customer.email
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
for (const subscription of customer.subscriptions.data) {
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: data.member_id,
|
|
|
|
subscription
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-18 16:27:17 +03:00
|
|
|
async getSubscriptionByStripeID(id, options) {
|
|
|
|
const subscription = await this._StripeCustomerSubscription.findOne({
|
|
|
|
subscription_id: id
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
return subscription;
|
|
|
|
}
|
|
|
|
|
2022-07-14 14:54:58 +03:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {Object} data
|
|
|
|
* @param {String} data.id - member ID
|
|
|
|
* @param {Object} data.subscription
|
2022-08-10 15:30:11 +03:00
|
|
|
* @param {String} data.offerId
|
2022-09-29 20:01:48 +03:00
|
|
|
* @param {import('@tryghost/member-attribution/lib/attribution').AttributionResource} [data.attribution]
|
2022-07-14 14:54:58 +03:00
|
|
|
* @param {*} options
|
|
|
|
* @returns
|
|
|
|
*/
|
2021-10-18 16:27:17 +03:00
|
|
|
async linkSubscription(data, options = {}) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'link Stripe Subscription'})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
2021-10-18 17:36:56 +03:00
|
|
|
|
|
|
|
if (!options.transacting) {
|
|
|
|
return this._Member.transaction((transacting) => {
|
|
|
|
return this.linkSubscription(data, {
|
|
|
|
...options,
|
|
|
|
transacting
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
const member = await this._Member.findOne({
|
|
|
|
id: data.id
|
2022-04-07 17:12:55 +03:00
|
|
|
}, {...options, forUpdate: true});
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
const customer = await member.related('stripeCustomers').query({
|
|
|
|
where: {
|
|
|
|
customer_id: data.subscription.customer
|
|
|
|
}
|
2021-01-22 18:15:31 +03:00
|
|
|
}).fetchOne(options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
if (!customer) {
|
|
|
|
// Maybe just link the customer?
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound)});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-02-11 20:43:36 +03:00
|
|
|
const subscription = await this._stripeAPIService.getSubscription(data.subscription.id);
|
2021-01-18 16:55:40 +03:00
|
|
|
let paymentMethodId;
|
|
|
|
if (!subscription.default_payment_method) {
|
|
|
|
paymentMethodId = null;
|
|
|
|
} else if (typeof subscription.default_payment_method === 'string') {
|
|
|
|
paymentMethodId = subscription.default_payment_method;
|
|
|
|
} else {
|
|
|
|
paymentMethodId = subscription.default_payment_method.id;
|
|
|
|
}
|
|
|
|
const paymentMethod = paymentMethodId ? await this._stripeAPIService.getCardPaymentMethod(paymentMethodId) : null;
|
2021-02-15 17:16:58 +03:00
|
|
|
|
2022-04-07 17:12:55 +03:00
|
|
|
const model = await this.getSubscriptionByStripeID(subscription.id, {...options, forUpdate: true});
|
2021-10-18 16:27:17 +03:00
|
|
|
|
2021-04-20 14:51:16 +03:00
|
|
|
const subscriptionPriceData = _.get(subscription, 'items.data[0].price');
|
|
|
|
let ghostProduct;
|
|
|
|
try {
|
2022-04-07 17:12:55 +03:00
|
|
|
ghostProduct = await this._productRepository.get({stripe_product_id: subscriptionPriceData.product}, {...options, forUpdate: true});
|
2021-04-20 14:51:16 +03:00
|
|
|
// Use first Ghost product as default product in case of missing link
|
|
|
|
if (!ghostProduct) {
|
2022-01-17 20:32:02 +03:00
|
|
|
let {data: pageData} = await this._productRepository.list({
|
|
|
|
limit: 1,
|
2022-02-01 18:05:22 +03:00
|
|
|
filter: 'type:paid',
|
2022-04-07 17:12:55 +03:00
|
|
|
...options,
|
|
|
|
forUpdate: true
|
2022-01-17 20:32:02 +03:00
|
|
|
});
|
2021-04-20 14:51:16 +03:00
|
|
|
ghostProduct = (pageData && pageData[0]) || null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Link Stripe Product & Price to Ghost Product
|
|
|
|
if (ghostProduct) {
|
|
|
|
await this._productRepository.update({
|
|
|
|
id: ghostProduct.get('id'),
|
|
|
|
name: ghostProduct.get('name'),
|
|
|
|
stripe_prices: [
|
|
|
|
{
|
|
|
|
stripe_price_id: subscriptionPriceData.id,
|
|
|
|
stripe_product_id: subscriptionPriceData.product,
|
|
|
|
active: subscriptionPriceData.active,
|
|
|
|
nickname: subscriptionPriceData.nickname,
|
|
|
|
currency: subscriptionPriceData.currency,
|
|
|
|
amount: subscriptionPriceData.unit_amount,
|
|
|
|
type: subscriptionPriceData.type,
|
|
|
|
interval: (subscriptionPriceData.recurring && subscriptionPriceData.recurring.interval) || null
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}, options);
|
|
|
|
} else {
|
|
|
|
// Log error if no Ghost products found
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`There was an error linking subscription - ${subscription.id}, no Products exist.`);
|
2021-04-20 14:51:16 +03:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`Failed to handle prices and product for - ${subscription.id}.`);
|
|
|
|
logging.error(e);
|
2021-04-20 14:51:16 +03:00
|
|
|
}
|
2021-02-15 17:16:58 +03:00
|
|
|
|
2022-04-19 12:21:48 +03:00
|
|
|
let stripeCouponId = subscription.discount && subscription.discount.coupon ? subscription.discount.coupon.id : null;
|
2022-08-10 15:30:11 +03:00
|
|
|
|
|
|
|
// For trial offers, offer id is passed from metadata as there is no stripe coupon
|
|
|
|
let offerId = data.offerId || null;
|
2022-08-25 10:30:27 +03:00
|
|
|
let offer = null;
|
2022-04-19 12:21:48 +03:00
|
|
|
|
|
|
|
if (stripeCouponId) {
|
|
|
|
// Get the offer from our database
|
2022-08-25 10:30:27 +03:00
|
|
|
offer = await this._offerRepository.getByStripeCouponId(stripeCouponId, {transacting: options.transacting});
|
2022-04-19 12:21:48 +03:00
|
|
|
if (offer) {
|
|
|
|
offerId = offer.id;
|
|
|
|
} else {
|
|
|
|
logging.error(`Received an unknown stripe coupon id (${stripeCouponId}) for subscription - ${subscription.id}.`);
|
2022-04-19 10:15:33 +03:00
|
|
|
}
|
2022-08-25 10:30:27 +03:00
|
|
|
} else if (offerId) {
|
|
|
|
offer = await this._offerRepository.getById(offerId, {transacting: options.transacting});
|
2022-04-19 10:15:33 +03:00
|
|
|
}
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
const subscriptionData = {
|
2021-01-18 16:55:40 +03:00
|
|
|
customer_id: subscription.customer,
|
|
|
|
subscription_id: subscription.id,
|
|
|
|
status: subscription.status,
|
|
|
|
cancel_at_period_end: subscription.cancel_at_period_end,
|
|
|
|
cancellation_reason: subscription.metadata && subscription.metadata.cancellation_reason || null,
|
|
|
|
current_period_end: new Date(subscription.current_period_end * 1000),
|
|
|
|
start_date: new Date(subscription.start_date * 1000),
|
|
|
|
default_payment_card_last4: paymentMethod && paymentMethod.card && paymentMethod.card.last4 || null,
|
2021-04-20 14:51:16 +03:00
|
|
|
stripe_price_id: subscriptionPriceData.id,
|
|
|
|
plan_id: subscriptionPriceData.id,
|
2022-08-05 15:20:40 +03:00
|
|
|
// trial start and end are returned as Stripe timestamps and need coversion
|
|
|
|
trial_start_at: subscription.trial_start ? new Date(subscription.trial_start * 1000) : null,
|
|
|
|
trial_end_at: subscription.trial_end ? new Date(subscription.trial_end * 1000) : null,
|
2021-01-18 16:55:40 +03:00
|
|
|
// NOTE: Defaulting to interval as migration to nullable field
|
|
|
|
// turned out to be much bigger problem.
|
|
|
|
// Ideally, would need nickname field to be nullable on the DB level
|
|
|
|
// condition can be simplified once this is done
|
2021-04-20 14:51:16 +03:00
|
|
|
plan_nickname: subscriptionPriceData.nickname || _.get(subscriptionPriceData, 'recurring.interval'),
|
|
|
|
plan_interval: _.get(subscriptionPriceData, 'recurring.interval', ''),
|
|
|
|
plan_amount: subscriptionPriceData.unit_amount,
|
2022-04-12 12:19:09 +03:00
|
|
|
plan_currency: subscriptionPriceData.currency,
|
|
|
|
mrr: this.getMRR({
|
2022-04-14 18:40:14 +03:00
|
|
|
interval: _.get(subscriptionPriceData, 'recurring.interval', ''),
|
|
|
|
amount: subscriptionPriceData.unit_amount,
|
|
|
|
status: subscription.status,
|
2022-04-13 16:46:43 +03:00
|
|
|
canceled: subscription.cancel_at_period_end,
|
|
|
|
discount: subscription.discount
|
2022-04-19 10:15:33 +03:00
|
|
|
}),
|
|
|
|
offer_id: offerId
|
2021-02-15 17:16:58 +03:00
|
|
|
};
|
2022-04-19 10:15:33 +03:00
|
|
|
|
2021-07-15 12:25:41 +03:00
|
|
|
let eventData = {};
|
2021-02-15 17:16:58 +03:00
|
|
|
if (model) {
|
2022-08-10 15:30:11 +03:00
|
|
|
// CASE: Offer is already mapped against sub, don't overwrite it with NULL
|
|
|
|
// Needed for trial offers, which don't have a stripe coupon/discount attached to sub
|
|
|
|
if (!subscriptionData.offer_id) {
|
|
|
|
delete subscriptionData.offer_id;
|
|
|
|
}
|
2021-02-15 17:16:58 +03:00
|
|
|
const updated = await this._StripeCustomerSubscription.edit(subscriptionData, {
|
|
|
|
...options,
|
|
|
|
id: model.id
|
|
|
|
});
|
2021-01-25 18:33:49 +03:00
|
|
|
|
2022-04-13 16:46:43 +03:00
|
|
|
if (model.get('mrr') !== updated.get('mrr') || model.get('plan_id') !== updated.get('plan_id') || model.get('status') !== updated.get('status') || model.get('cancel_at_period_end') !== updated.get('cancel_at_period_end')) {
|
|
|
|
const originalMrrDelta = model.get('mrr');
|
|
|
|
const updatedMrrDelta = updated.get('mrr');
|
2022-04-12 12:06:11 +03:00
|
|
|
|
2022-10-03 17:50:28 +03:00
|
|
|
const getStatus = (modelToCheck) => {
|
|
|
|
const status = modelToCheck.get('status');
|
|
|
|
const canceled = modelToCheck.get('cancel_at_period_end');
|
2022-04-12 12:06:11 +03:00
|
|
|
|
|
|
|
if (status === 'canceled') {
|
|
|
|
return 'expired';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (canceled) {
|
|
|
|
return 'canceled';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.isActiveSubscriptionStatus(status)) {
|
|
|
|
return 'active';
|
|
|
|
}
|
|
|
|
|
|
|
|
return 'inactive';
|
|
|
|
};
|
|
|
|
|
|
|
|
const getEventName = (originalStatus, updatedStatus) => {
|
|
|
|
if (originalStatus === updatedStatus) {
|
|
|
|
return 'updated';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (originalStatus === 'canceled' && updatedStatus === 'active') {
|
|
|
|
return 'reactivated';
|
|
|
|
}
|
|
|
|
|
|
|
|
return updatedStatus;
|
|
|
|
};
|
|
|
|
|
|
|
|
const originalStatus = getStatus(model);
|
|
|
|
const updatedStatus = getStatus(updated);
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
const mrrDelta = updatedMrrDelta - originalMrrDelta;
|
|
|
|
await this._MemberPaidSubscriptionEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
source: 'stripe',
|
2022-04-12 13:17:39 +03:00
|
|
|
type: getEventName(originalStatus, updatedStatus),
|
2022-04-12 12:06:11 +03:00
|
|
|
subscription_id: updated.id,
|
2021-02-15 17:16:58 +03:00
|
|
|
from_plan: model.get('plan_id'),
|
2022-04-12 12:06:11 +03:00
|
|
|
to_plan: updated.get('status') === 'canceled' ? null : updated.get('plan_id'),
|
2021-04-20 14:51:16 +03:00
|
|
|
currency: subscriptionPriceData.currency,
|
2021-02-15 17:16:58 +03:00
|
|
|
mrr_delta: mrrDelta
|
2021-03-10 18:24:43 +03:00
|
|
|
}, options);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
} else {
|
2021-07-15 12:25:41 +03:00
|
|
|
eventData.created_at = new Date(subscription.start_date * 1000);
|
2022-10-03 17:50:28 +03:00
|
|
|
const subscriptionModel = await this._StripeCustomerSubscription.add(subscriptionData, options);
|
2021-02-15 17:16:58 +03:00
|
|
|
await this._MemberPaidSubscriptionEvent.add({
|
|
|
|
member_id: member.id,
|
2022-10-03 17:50:28 +03:00
|
|
|
subscription_id: subscriptionModel.id,
|
2022-04-12 13:17:39 +03:00
|
|
|
type: 'created',
|
2021-02-15 17:16:58 +03:00
|
|
|
source: 'stripe',
|
|
|
|
from_plan: null,
|
2021-04-20 14:51:16 +03:00
|
|
|
to_plan: subscriptionPriceData.id,
|
|
|
|
currency: subscriptionPriceData.currency,
|
2022-10-03 17:50:28 +03:00
|
|
|
mrr_delta: subscriptionModel.get('mrr'),
|
2021-07-15 12:25:41 +03:00
|
|
|
...eventData
|
2021-03-10 18:24:43 +03:00
|
|
|
}, options);
|
2022-08-25 10:30:27 +03:00
|
|
|
|
2022-09-01 17:30:37 +03:00
|
|
|
const context = options?.context || {};
|
|
|
|
const source = this._resolveContextSource(context);
|
|
|
|
|
2022-09-09 17:30:05 +03:00
|
|
|
const event = SubscriptionCreatedEvent.create({
|
|
|
|
source,
|
|
|
|
tierId: ghostProduct?.get('id'),
|
|
|
|
memberId: member.id,
|
2022-10-03 17:50:28 +03:00
|
|
|
subscriptionId: subscriptionModel.get('id'),
|
2022-09-09 17:30:05 +03:00
|
|
|
offerId: data.offerId,
|
|
|
|
attribution: data.attribution
|
|
|
|
});
|
2022-10-07 16:45:18 +03:00
|
|
|
this.dispatchEvent(event, options);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
2021-06-10 20:33:22 +03:00
|
|
|
let memberProducts = (await member.related('products').fetch(options)).toJSON();
|
2021-08-23 13:00:19 +03:00
|
|
|
const oldMemberProducts = member.related('products').toJSON();
|
2021-07-01 22:19:56 +03:00
|
|
|
let status = memberProducts.length === 0 ? 'free' : 'comped';
|
2021-01-25 18:33:49 +03:00
|
|
|
if (this.isActiveSubscriptionStatus(subscription.status)) {
|
2021-08-17 13:09:27 +03:00
|
|
|
if (this.isComplimentarySubscription(subscription)) {
|
|
|
|
status = 'comped';
|
|
|
|
} else {
|
|
|
|
status = 'paid';
|
|
|
|
}
|
2022-08-17 12:11:14 +03:00
|
|
|
if (this._labsService.isSet('compExpiring')) {
|
|
|
|
// This is an active subscription! Update member to have only this product
|
|
|
|
if (ghostProduct) {
|
|
|
|
memberProducts = [ghostProduct.toJSON()];
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// This is an active subscription! Add the product
|
|
|
|
if (ghostProduct) {
|
|
|
|
memberProducts.push(ghostProduct.toJSON());
|
|
|
|
}
|
|
|
|
if (model) {
|
|
|
|
if (model.get('stripe_price_id') !== subscriptionData.stripe_price_id) {
|
|
|
|
// The subscription has changed plan - we may need to update the products
|
|
|
|
|
|
|
|
const subscriptions = await member.related('stripeSubscriptions').fetch(options);
|
|
|
|
const changedProduct = await this._productRepository.get({
|
|
|
|
stripe_price_id: model.get('stripe_price_id')
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
let activeSubscriptionForChangedProduct = false;
|
|
|
|
|
2022-10-03 17:50:28 +03:00
|
|
|
for (const subscriptionModel of subscriptions.models) {
|
|
|
|
if (this.isActiveSubscriptionStatus(subscriptionModel.get('status'))) {
|
2022-08-17 12:11:14 +03:00
|
|
|
try {
|
2022-10-03 17:50:28 +03:00
|
|
|
const subscriptionProduct = await this._productRepository.get({stripe_price_id: subscriptionModel.get('stripe_price_id')}, options);
|
2022-08-17 12:11:14 +03:00
|
|
|
if (subscriptionProduct && changedProduct && subscriptionProduct.id === changedProduct.id) {
|
|
|
|
activeSubscriptionForChangedProduct = true;
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
logging.error(`Failed to attach products to member - ${data.id}`);
|
|
|
|
logging.error(e);
|
2021-08-26 14:00:56 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-17 12:11:14 +03:00
|
|
|
if (!activeSubscriptionForChangedProduct) {
|
|
|
|
memberProducts = memberProducts.filter((product) => {
|
|
|
|
return product.id !== changedProduct.id;
|
|
|
|
});
|
|
|
|
}
|
2021-08-26 14:00:56 +03:00
|
|
|
}
|
|
|
|
}
|
2021-04-20 14:51:16 +03:00
|
|
|
}
|
2021-01-25 18:33:49 +03:00
|
|
|
} else {
|
|
|
|
const subscriptions = await member.related('stripeSubscriptions').fetch(options);
|
2021-06-10 20:33:22 +03:00
|
|
|
let activeSubscriptionForGhostProduct = false;
|
2022-10-03 17:50:28 +03:00
|
|
|
for (const subscriptionModel of subscriptions.models) {
|
|
|
|
if (this.isActiveSubscriptionStatus(subscriptionModel.get('status'))) {
|
2021-06-10 20:33:22 +03:00
|
|
|
status = 'paid';
|
2021-04-20 14:51:16 +03:00
|
|
|
try {
|
2022-10-03 17:50:28 +03:00
|
|
|
const subscriptionProduct = await this._productRepository.get({stripe_price_id: subscriptionModel.get('stripe_price_id')}, options);
|
2021-06-10 20:33:22 +03:00
|
|
|
if (subscriptionProduct && ghostProduct && subscriptionProduct.id === ghostProduct.id) {
|
|
|
|
activeSubscriptionForGhostProduct = true;
|
2021-04-20 14:51:16 +03:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`Failed to attach products to member - ${data.id}`);
|
|
|
|
logging.error(e);
|
2021-04-20 14:51:16 +03:00
|
|
|
}
|
2021-01-25 18:33:49 +03:00
|
|
|
}
|
|
|
|
}
|
2021-06-10 20:33:22 +03:00
|
|
|
|
|
|
|
if (!activeSubscriptionForGhostProduct) {
|
|
|
|
memberProducts = memberProducts.filter((product) => {
|
|
|
|
return product.id !== ghostProduct.id;
|
|
|
|
});
|
|
|
|
}
|
2021-08-11 13:40:27 +03:00
|
|
|
|
|
|
|
if (memberProducts.length === 0) {
|
|
|
|
status = 'free';
|
|
|
|
}
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
2021-08-23 13:00:19 +03:00
|
|
|
|
2021-04-20 14:51:16 +03:00
|
|
|
let updatedMember;
|
|
|
|
try {
|
|
|
|
// Remove duplicate products from the list
|
|
|
|
memberProducts = _.uniqBy(memberProducts, function (e) {
|
|
|
|
return e.id;
|
|
|
|
});
|
|
|
|
// Edit member with updated products assoicated
|
|
|
|
updatedMember = await this._Member.edit({status: status, products: memberProducts}, {...options, id: data.id});
|
|
|
|
} catch (e) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`Failed to update member - ${data.id} - with related products`);
|
|
|
|
logging.error(e);
|
2021-04-20 14:51:16 +03:00
|
|
|
updatedMember = await this._Member.edit({status: status}, {...options, id: data.id});
|
|
|
|
}
|
2021-08-23 13:00:19 +03:00
|
|
|
|
|
|
|
const newMemberProductIds = memberProducts.map(product => product.id);
|
|
|
|
const oldMemberProductIds = oldMemberProducts.map(product => product.id);
|
|
|
|
|
|
|
|
const productsToAdd = _.differenceWith(newMemberProductIds, oldMemberProductIds);
|
|
|
|
const productsToRemove = _.differenceWith(oldMemberProductIds, newMemberProductIds);
|
|
|
|
|
|
|
|
for (const productToAdd of productsToAdd) {
|
|
|
|
await this._MemberProductEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
product_id: productToAdd,
|
|
|
|
action: 'added'
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const productToRemove of productsToRemove) {
|
|
|
|
await this._MemberProductEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
product_id: productToRemove,
|
|
|
|
action: 'removed'
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
if (updatedMember.attributes.status !== updatedMember._previousAttributes.status) {
|
|
|
|
await this._MemberStatusEvent.add({
|
|
|
|
member_id: data.id,
|
|
|
|
from_status: updatedMember._previousAttributes.status,
|
2021-07-15 12:25:41 +03:00
|
|
|
to_status: updatedMember.get('status'),
|
|
|
|
...eventData
|
2021-02-15 17:16:58 +03:00
|
|
|
}, options);
|
2021-01-25 18:33:49 +03:00
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-03-25 15:47:45 +03:00
|
|
|
async getSubscription(data, options) {
|
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'get Stripe Subscription'})});
|
2021-03-25 15:47:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne({
|
|
|
|
email: data.email
|
|
|
|
});
|
|
|
|
|
|
|
|
const subscription = await member.related('stripeSubscriptions').query({
|
|
|
|
where: {
|
|
|
|
subscription_id: data.subscription.subscription_id
|
|
|
|
}
|
|
|
|
}).fetchOne(options);
|
|
|
|
|
|
|
|
if (!subscription) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound, {id: data.subscription.subscription_id})});
|
2021-03-25 15:47:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return subscription.toJSON();
|
|
|
|
}
|
|
|
|
|
|
|
|
async cancelSubscription(data, options) {
|
2022-03-12 00:44:28 +03:00
|
|
|
const sharedOptions = {
|
|
|
|
transacting: options ? options.transacting : null
|
|
|
|
};
|
2021-03-25 15:47:45 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'update Stripe Subscription'})});
|
2021-03-25 15:47:45 +03:00
|
|
|
}
|
|
|
|
|
2021-06-10 15:27:44 +03:00
|
|
|
let findQuery = null;
|
|
|
|
if (data.id) {
|
|
|
|
findQuery = {id: data.id};
|
|
|
|
} else if (data.email) {
|
|
|
|
findQuery = {email: data.email};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!findQuery) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound)});
|
2021-06-10 15:27:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne(findQuery);
|
2021-03-25 15:47:45 +03:00
|
|
|
|
|
|
|
const subscription = await member.related('stripeSubscriptions').query({
|
|
|
|
where: {
|
|
|
|
subscription_id: data.subscription.subscription_id
|
|
|
|
}
|
|
|
|
}).fetchOne(options);
|
|
|
|
|
|
|
|
if (!subscription) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound, {id: data.subscription.subscription_id})});
|
2021-03-25 15:47:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const updatedSubscription = await this._stripeAPIService.cancelSubscription(data.subscription.subscription_id);
|
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription: updatedSubscription
|
|
|
|
}, options);
|
2022-03-12 00:44:28 +03:00
|
|
|
|
|
|
|
await this._MemberCancelEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_plan: subscription.get('plan_id')
|
|
|
|
}, sharedOptions);
|
2021-03-25 15:47:45 +03:00
|
|
|
}
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
async updateSubscription(data, options) {
|
2022-03-12 00:44:28 +03:00
|
|
|
const sharedOptions = {
|
|
|
|
transacting: options ? options.transacting : null
|
|
|
|
};
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'update Stripe Subscription'})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
2021-03-25 15:19:01 +03:00
|
|
|
|
2021-03-30 13:00:39 +03:00
|
|
|
let findQuery = null;
|
|
|
|
if (data.id) {
|
|
|
|
findQuery = {id: data.id};
|
|
|
|
} else if (data.email) {
|
|
|
|
findQuery = {email: data.email};
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!findQuery) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound)});
|
2021-03-30 13:00:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne(findQuery);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-04 18:57:58 +03:00
|
|
|
const subscriptionModel = await member.related('stripeSubscriptions').query({
|
2021-01-18 16:55:40 +03:00
|
|
|
where: {
|
|
|
|
subscription_id: data.subscription.subscription_id
|
|
|
|
}
|
2021-01-22 18:15:31 +03:00
|
|
|
}).fetchOne(options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-04 18:57:58 +03:00
|
|
|
if (!subscriptionModel) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.subscriptionNotFound, {id: data.subscription.subscription_id})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-03-25 15:19:01 +03:00
|
|
|
let updatedSubscription;
|
2021-05-04 18:57:58 +03:00
|
|
|
if (data.subscription.price) {
|
|
|
|
const subscription = await this._stripeAPIService.getSubscription(
|
|
|
|
data.subscription.subscription_id
|
|
|
|
);
|
|
|
|
|
|
|
|
const subscriptionItem = subscription.items.data[0];
|
|
|
|
|
2021-11-09 12:12:13 +03:00
|
|
|
if (data.subscription.price !== subscription.price) {
|
|
|
|
updatedSubscription = await this._stripeAPIService.updateSubscriptionItemPrice(
|
|
|
|
subscription.id,
|
|
|
|
subscriptionItem.id,
|
|
|
|
data.subscription.price
|
|
|
|
);
|
|
|
|
updatedSubscription = await this._stripeAPIService.removeCouponFromSubscription(subscription.id);
|
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-03-25 15:19:01 +03:00
|
|
|
if (data.subscription.cancel_at_period_end !== undefined) {
|
|
|
|
if (data.subscription.cancel_at_period_end) {
|
|
|
|
updatedSubscription = await this._stripeAPIService.cancelSubscriptionAtPeriodEnd(
|
|
|
|
data.subscription.subscription_id,
|
|
|
|
data.subscription.cancellationReason
|
|
|
|
);
|
2022-03-12 00:44:28 +03:00
|
|
|
|
|
|
|
await this._MemberCancelEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_plan: subscriptionModel.get('plan_id')
|
|
|
|
}, sharedOptions);
|
2021-03-25 15:19:01 +03:00
|
|
|
} else {
|
|
|
|
updatedSubscription = await this._stripeAPIService.continueSubscriptionAtPeriodEnd(
|
|
|
|
data.subscription.subscription_id
|
|
|
|
);
|
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-03-25 15:19:01 +03:00
|
|
|
if (updatedSubscription) {
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription: updatedSubscription
|
2021-03-25 15:47:45 +03:00
|
|
|
}, options);
|
2022-09-09 17:30:05 +03:00
|
|
|
|
|
|
|
// Dispatch cancellation event
|
|
|
|
if (data.subscription.cancel_at_period_end) {
|
|
|
|
const stripeProductId = _.get(updatedSubscription, 'items.data[0].price.product');
|
|
|
|
|
|
|
|
let ghostProduct;
|
|
|
|
try {
|
|
|
|
ghostProduct = await this._productRepository.get(
|
|
|
|
{stripe_product_id: stripeProductId},
|
|
|
|
{...sharedOptions, forUpdate: true}
|
|
|
|
);
|
|
|
|
} catch (e) {
|
|
|
|
ghostProduct = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const context = options?.context || {};
|
|
|
|
const source = this._resolveContextSource(context);
|
|
|
|
const cancellationTimestamp = updatedSubscription.canceled_at
|
|
|
|
? new Date(updatedSubscription.canceled_at * 1000)
|
|
|
|
: new Date();
|
|
|
|
const cancelEventData = {
|
|
|
|
source,
|
|
|
|
memberId: member.id,
|
|
|
|
subscriptionId: subscriptionModel.get('id'),
|
|
|
|
tierId: ghostProduct?.get('id')
|
|
|
|
};
|
2022-10-07 16:45:18 +03:00
|
|
|
this.dispatchEvent(SubscriptionCancelledEvent.create(cancelEventData, cancellationTimestamp), options);
|
2022-09-09 17:30:05 +03:00
|
|
|
}
|
2021-03-25 15:19:01 +03:00
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-04-23 18:53:32 +03:00
|
|
|
async createSubscription(data, options) {
|
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'create Stripe Subscription'})});
|
2021-04-23 18:53:32 +03:00
|
|
|
}
|
|
|
|
const member = await this._Member.findOne({
|
|
|
|
id: data.id
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
let stripeCustomer;
|
|
|
|
|
|
|
|
await member.related('stripeCustomers').fetch(options);
|
|
|
|
|
|
|
|
for (const customer of member.related('stripeCustomers').models) {
|
|
|
|
try {
|
|
|
|
const fetchedCustomer = await this._stripeAPIService.getCustomer(customer.get('customer_id'));
|
|
|
|
stripeCustomer = fetchedCustomer;
|
|
|
|
} catch (err) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.info('Ignoring error for fetching customer for checkout');
|
2021-04-23 18:53:32 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!stripeCustomer) {
|
|
|
|
stripeCustomer = await this._stripeAPIService.createCustomer({
|
|
|
|
email: member.get('email')
|
|
|
|
});
|
|
|
|
|
|
|
|
await this._StripeCustomer.add({
|
|
|
|
customer_id: stripeCustomer.id,
|
|
|
|
member_id: data.id,
|
|
|
|
email: stripeCustomer.email,
|
|
|
|
name: stripeCustomer.name
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
const subscription = await this._stripeAPIService.createSubscription(stripeCustomer.id, data.subscription.stripe_price_id);
|
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2022-07-14 14:54:58 +03:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {Object} data
|
|
|
|
* @param {String} data.id - member ID
|
|
|
|
* @param {Object} options
|
|
|
|
* @param {Object} [options.transacting]
|
|
|
|
*/
|
2022-02-01 18:05:22 +03:00
|
|
|
async setComplimentarySubscription(data, options = {}) {
|
|
|
|
if (!options.transacting) {
|
|
|
|
return this._Member.transaction((transacting) => {
|
|
|
|
return this.setComplimentarySubscription(data, {
|
|
|
|
...options,
|
|
|
|
transacting
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'create Complimentary Subscription'})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
const member = await this._Member.findOne({
|
|
|
|
id: data.id
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
const subscriptions = await member.related('stripeSubscriptions').fetch(options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
const activeSubscriptions = subscriptions.models.filter((subscription) => {
|
2021-01-25 18:33:23 +03:00
|
|
|
return this.isActiveSubscriptionStatus(subscription.get('status'));
|
2021-01-18 16:55:40 +03:00
|
|
|
});
|
|
|
|
|
2022-01-17 20:32:02 +03:00
|
|
|
const productPage = await this._productRepository.list({
|
|
|
|
limit: 1,
|
|
|
|
withRelated: ['stripePrices'],
|
|
|
|
filter: 'type:paid',
|
|
|
|
...options
|
|
|
|
});
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
const defaultProduct = productPage && productPage.data && productPage.data[0] && productPage.data[0].toJSON();
|
|
|
|
|
|
|
|
if (!defaultProduct) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.NotFoundError({message: tpl(messages.productNotFound)});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
const zeroValuePrices = defaultProduct.stripePrices.filter((price) => {
|
|
|
|
return price.amount === 0;
|
|
|
|
});
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
if (activeSubscriptions.length) {
|
|
|
|
for (const subscription of activeSubscriptions) {
|
|
|
|
const price = await subscription.related('stripePrice').fetch(options);
|
|
|
|
|
|
|
|
let zeroValuePrice = zeroValuePrices.find((p) => {
|
|
|
|
return p.currency.toLowerCase() === price.get('currency').toLowerCase();
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!zeroValuePrice) {
|
|
|
|
const product = (await this._productRepository.update({
|
|
|
|
id: defaultProduct.id,
|
|
|
|
name: defaultProduct.name,
|
|
|
|
description: defaultProduct.description,
|
|
|
|
stripe_prices: [{
|
|
|
|
nickname: 'Complimentary',
|
|
|
|
currency: price.get('currency'),
|
|
|
|
type: 'recurring',
|
|
|
|
interval: 'year',
|
|
|
|
amount: 0
|
|
|
|
}]
|
|
|
|
}, options)).toJSON();
|
2021-05-11 12:56:40 +03:00
|
|
|
zeroValuePrice = product.stripePrices.find((p) => {
|
|
|
|
return p.currency.toLowerCase() === price.get('currency').toLowerCase() && p.amount === 0;
|
2021-05-10 17:39:44 +03:00
|
|
|
});
|
|
|
|
zeroValuePrices.push(zeroValuePrice);
|
|
|
|
}
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
const stripeSubscription = await this._stripeAPIService.getSubscription(
|
|
|
|
subscription.get('subscription_id')
|
|
|
|
);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
const subscriptionItem = stripeSubscription.items.data[0];
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
const updatedSubscription = await this._stripeAPIService.updateSubscriptionItemPrice(
|
|
|
|
stripeSubscription.id,
|
|
|
|
subscriptionItem.id,
|
|
|
|
zeroValuePrice.stripe_price_id
|
|
|
|
);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription: updatedSubscription
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
const stripeCustomer = await this._stripeAPIService.createCustomer({
|
2021-01-18 16:55:40 +03:00
|
|
|
email: member.get('email')
|
|
|
|
});
|
|
|
|
|
|
|
|
await this._StripeCustomer.upsert({
|
|
|
|
customer_id: stripeCustomer.id,
|
|
|
|
member_id: data.id,
|
|
|
|
email: stripeCustomer.email,
|
|
|
|
name: stripeCustomer.name
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
2021-05-10 17:39:44 +03:00
|
|
|
let zeroValuePrice = zeroValuePrices[0];
|
|
|
|
|
|
|
|
if (!zeroValuePrice) {
|
|
|
|
const product = (await this._productRepository.update({
|
|
|
|
id: defaultProduct.id,
|
|
|
|
name: defaultProduct.name,
|
|
|
|
description: defaultProduct.description,
|
|
|
|
stripe_prices: [{
|
|
|
|
nickname: 'Complimentary',
|
|
|
|
currency: 'USD',
|
|
|
|
type: 'recurring',
|
|
|
|
interval: 'year',
|
|
|
|
amount: 0
|
|
|
|
}]
|
|
|
|
}, options)).toJSON();
|
|
|
|
zeroValuePrice = product.stripePrices.find((price) => {
|
|
|
|
return price.currency.toLowerCase() === 'usd' && price.amount === 0;
|
|
|
|
});
|
|
|
|
zeroValuePrices.push(zeroValuePrice);
|
|
|
|
}
|
|
|
|
|
|
|
|
const subscription = await this._stripeAPIService.createSubscription(
|
|
|
|
stripeCustomer.id,
|
|
|
|
zeroValuePrice.stripe_price_id
|
|
|
|
);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-14 14:54:58 +03:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {Object} data
|
|
|
|
* @param {String} data.id - member ID
|
2022-07-14 14:54:58 +03:00
|
|
|
* @param {Object} options
|
|
|
|
* @param {Object} [options.transacting]
|
2022-07-14 14:54:58 +03:00
|
|
|
*/
|
2022-07-14 14:54:58 +03:00
|
|
|
async cancelComplimentarySubscription({id}, options) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
2022-02-15 15:27:22 +03:00
|
|
|
throw new errors.BadRequestError({message: tpl(messages.noStripeConnection, {action: 'cancel Complimentary Subscription'})});
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne({
|
2022-07-14 14:54:58 +03:00
|
|
|
id: id
|
2021-01-18 16:55:40 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
const subscriptions = await member.related('stripeSubscriptions').fetch();
|
|
|
|
|
|
|
|
for (const subscription of subscriptions.models) {
|
|
|
|
if (subscription.get('status') !== 'canceled') {
|
|
|
|
try {
|
|
|
|
const updatedSubscription = await this._stripeAPIService.cancelSubscription(
|
|
|
|
subscription.get('subscription_id')
|
|
|
|
);
|
|
|
|
// Only needs to update `status`
|
|
|
|
await this.linkSubscription({
|
2022-07-14 14:54:58 +03:00
|
|
|
id: id,
|
2021-01-18 16:55:40 +03:00
|
|
|
subscription: updatedSubscription
|
2022-07-14 14:54:58 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
} catch (err) {
|
2021-12-02 17:46:58 +03:00
|
|
|
logging.error(`There was an error cancelling subscription ${subscription.get('subscription_id')}`);
|
|
|
|
logging.error(err);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
};
|