2021-01-18 16:55:40 +03:00
|
|
|
const _ = require('lodash');
|
|
|
|
module.exports = class MemberRepository {
|
|
|
|
/**
|
|
|
|
* @param {object} deps
|
|
|
|
* @param {any} deps.Member
|
2021-02-15 17:16:58 +03:00
|
|
|
* @param {any} deps.MemberSubscribeEvent
|
|
|
|
* @param {any} deps.MemberEmailChangeEvent
|
|
|
|
* @param {any} deps.MemberPaidSubscriptionEvent
|
|
|
|
* @param {any} deps.MemberStatusEvent
|
2021-01-18 16:55:40 +03:00
|
|
|
* @param {any} deps.StripeCustomer
|
|
|
|
* @param {any} deps.StripeCustomerSubscription
|
2021-04-20 14:51:16 +03:00
|
|
|
* @param {any} deps.productRepository
|
2021-01-18 16:55:40 +03:00
|
|
|
* @param {import('../../services/stripe-api')} deps.stripeAPIService
|
|
|
|
* @param {import('../../services/stripe-plans')} deps.stripePlansService
|
|
|
|
* @param {any} deps.logger
|
|
|
|
*/
|
|
|
|
constructor({
|
|
|
|
Member,
|
2021-02-15 17:16:58 +03:00
|
|
|
MemberSubscribeEvent,
|
|
|
|
MemberEmailChangeEvent,
|
|
|
|
MemberPaidSubscriptionEvent,
|
|
|
|
MemberStatusEvent,
|
2021-01-18 16:55:40 +03:00
|
|
|
StripeCustomer,
|
|
|
|
StripeCustomerSubscription,
|
|
|
|
stripeAPIService,
|
|
|
|
stripePlansService,
|
2021-04-20 14:51:16 +03:00
|
|
|
productRepository,
|
2021-01-18 16:55:40 +03:00
|
|
|
logger
|
|
|
|
}) {
|
|
|
|
this._Member = Member;
|
2021-02-15 17:16:58 +03:00
|
|
|
this._MemberSubscribeEvent = MemberSubscribeEvent;
|
|
|
|
this._MemberEmailChangeEvent = MemberEmailChangeEvent;
|
|
|
|
this._MemberPaidSubscriptionEvent = MemberPaidSubscriptionEvent;
|
|
|
|
this._MemberStatusEvent = MemberStatusEvent;
|
2021-01-18 16:55:40 +03:00
|
|
|
this._StripeCustomer = StripeCustomer;
|
|
|
|
this._StripeCustomerSubscription = StripeCustomerSubscription;
|
|
|
|
this._stripeAPIService = stripeAPIService;
|
|
|
|
this._stripePlansService = stripePlansService;
|
2021-04-20 14:51:16 +03:00
|
|
|
this._productRepository = productRepository;
|
2021-01-18 16:55:40 +03:00
|
|
|
this._logging = logger;
|
|
|
|
}
|
|
|
|
|
2021-01-25 18:33:23 +03:00
|
|
|
isActiveSubscriptionStatus(status) {
|
|
|
|
return ['active', 'trialing', 'unpaid', 'past_due'].includes(status);
|
|
|
|
}
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
isComplimentarySubscription(subscription) {
|
2021-03-10 19:07:43 +03:00
|
|
|
return subscription.plan.nickname && subscription.plan.nickname.toLowerCase() === 'complimentary';
|
2021-02-15 17:16:58 +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);
|
|
|
|
}
|
|
|
|
|
|
|
|
async create(data, options) {
|
|
|
|
const {labels} = data;
|
|
|
|
|
|
|
|
if (labels) {
|
|
|
|
labels.forEach((label, index) => {
|
|
|
|
if (typeof label === 'string') {
|
|
|
|
labels[index] = {name: label};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
const memberData = _.pick(data, ['email', 'name', 'note', 'subscribed', 'geolocation', 'created_at']);
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
const member = await this._Member.add({
|
2021-01-22 18:15:31 +03:00
|
|
|
...memberData,
|
|
|
|
labels
|
2021-01-18 16:55:40 +03:00
|
|
|
}, options);
|
2021-02-15 17:16:58 +03:00
|
|
|
|
|
|
|
const context = options && options.context || {};
|
|
|
|
let source;
|
|
|
|
|
|
|
|
if (context.internal) {
|
|
|
|
source = 'system';
|
|
|
|
} else if (context.user) {
|
|
|
|
source = 'admin';
|
|
|
|
} else {
|
|
|
|
source = 'member';
|
|
|
|
}
|
|
|
|
|
2021-03-05 15:39:30 +03:00
|
|
|
await this._MemberStatusEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
from_status: null,
|
|
|
|
to_status: member.get('status')
|
|
|
|
}, options);
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
if (member.get('subscribed')) {
|
|
|
|
await this._MemberSubscribeEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
subscribed: true,
|
|
|
|
source
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
return member;
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
async update(data, options) {
|
|
|
|
const member = await this._Member.edit(_.pick(data, [
|
|
|
|
'email',
|
|
|
|
'name',
|
|
|
|
'note',
|
|
|
|
'subscribed',
|
|
|
|
'labels',
|
|
|
|
'geolocation'
|
|
|
|
]), options);
|
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
// member._changed.subscribed has a value if the `subscribed` attribute is passed in the update call, regardless of the previous value
|
|
|
|
if (member.attributes.subscribed !== member._previousAttributes.subscribed) {
|
|
|
|
const context = options && options.context || {};
|
|
|
|
let source;
|
|
|
|
if (context.internal) {
|
|
|
|
source = 'system';
|
|
|
|
} else if (context.user) {
|
|
|
|
source = 'admin';
|
|
|
|
} else {
|
|
|
|
source = 'member';
|
|
|
|
}
|
|
|
|
await this._MemberSubscribeEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
subscribed: member.get('subscribed'),
|
|
|
|
source
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
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-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({
|
2021-01-18 16:55:40 +03:00
|
|
|
status: updatedSubscription.status
|
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',
|
|
|
|
from_plan: subscription.get('plan_id'),
|
|
|
|
to_plan: null,
|
|
|
|
currency: subscription.get('plan_currency'),
|
|
|
|
mrr_delta: -1 * (subscription.get('plan_interval') === 'month' ? subscription.get('plan_amount') : Math.floor(subscription.get('plan_amount') / 12))
|
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return this._Member.destroy({
|
|
|
|
id: data.id
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
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) {
|
|
|
|
throw new Error('Cannot link Stripe Customer with no Stripe Connection');
|
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-01-22 18:15:31 +03:00
|
|
|
async linkSubscription(data, options) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
|
|
|
throw new Error('Cannot link Stripe Subscription with no Stripe Connection');
|
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
|
|
|
|
|
|
|
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?
|
|
|
|
throw new Error('Subscription is not associated with a customer for the member');
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
|
|
|
const model = await this._StripeCustomerSubscription.findOne({
|
|
|
|
subscription_id: subscription.id
|
|
|
|
}, options);
|
2021-04-20 14:51:16 +03:00
|
|
|
const subscriptionPriceData = _.get(subscription, 'items.data[0].price');
|
|
|
|
let ghostProduct;
|
|
|
|
try {
|
|
|
|
ghostProduct = await this._productRepository.get({stripe_product_id: subscriptionPriceData.product}, options);
|
|
|
|
// Use first Ghost product as default product in case of missing link
|
|
|
|
if (!ghostProduct) {
|
|
|
|
let {data: pageData} = await this._productRepository.list({limit: 1});
|
|
|
|
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
|
|
|
|
this._logging.error(`There was an error linking subscription - ${subscription.id}, no Products exist.`);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
this._logging.error(`Failed to handle prices and product for - ${subscription.id}.`);
|
|
|
|
this._logging.error(e);
|
|
|
|
}
|
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,
|
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,
|
|
|
|
plan_currency: subscriptionPriceData.currency
|
2021-02-15 17:16:58 +03:00
|
|
|
};
|
|
|
|
function getMRRDelta({interval, amount, status}) {
|
|
|
|
if (status === 'trialing') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status === 'incomplete') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
if (status === 'incomplete_expired') {
|
|
|
|
return 0;
|
|
|
|
}
|
2021-04-06 07:46:28 +03:00
|
|
|
if (status === 'canceled') {
|
|
|
|
return 0;
|
|
|
|
}
|
2021-02-15 17:16:58 +03:00
|
|
|
|
|
|
|
if (interval === 'year') {
|
2021-04-06 07:46:28 +03:00
|
|
|
return Math.floor(amount / 12);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (interval === 'month') {
|
2021-04-06 07:46:28 +03:00
|
|
|
return amount;
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (model) {
|
|
|
|
const updated = await this._StripeCustomerSubscription.edit(subscriptionData, {
|
|
|
|
...options,
|
|
|
|
id: model.id
|
|
|
|
});
|
2021-01-25 18:33:49 +03:00
|
|
|
|
2021-02-15 17:16:58 +03:00
|
|
|
if (model.get('plan_id') !== updated.get('plan_id') || model.get('status') !== updated.get('status')) {
|
|
|
|
const originalMrrDelta = getMRRDelta({interval: model.get('plan_interval'), amount: model.get('plan_amount'), status: model.get('status')});
|
|
|
|
const updatedMrrDelta = getMRRDelta({interval: updated.get('plan_interval'), amount: updated.get('plan_amount'), status: updated.get('status')});
|
|
|
|
const mrrDelta = updatedMrrDelta - originalMrrDelta;
|
|
|
|
await this._MemberPaidSubscriptionEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
source: 'stripe',
|
|
|
|
from_plan: model.get('plan_id'),
|
|
|
|
to_plan: 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 {
|
|
|
|
await this._StripeCustomerSubscription.add(subscriptionData, options);
|
|
|
|
await this._MemberPaidSubscriptionEvent.add({
|
|
|
|
member_id: member.id,
|
|
|
|
source: 'stripe',
|
|
|
|
from_plan: null,
|
2021-04-20 14:51:16 +03:00
|
|
|
to_plan: subscriptionPriceData.id,
|
|
|
|
currency: subscriptionPriceData.currency,
|
|
|
|
mrr_delta: getMRRDelta({interval: _.get(subscriptionPriceData, 'recurring.interval'), amount: subscriptionPriceData.unit_amount, status: subscriptionPriceData.status})
|
2021-03-10 18:24:43 +03:00
|
|
|
}, options);
|
2021-02-15 17:16:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
let status = 'free';
|
2021-04-20 14:51:16 +03:00
|
|
|
let memberProducts = [];
|
2021-01-25 18:33:49 +03:00
|
|
|
if (this.isActiveSubscriptionStatus(subscription.status)) {
|
2021-02-15 17:16:58 +03:00
|
|
|
if (this.isComplimentarySubscription(subscription)) {
|
|
|
|
status = 'comped';
|
|
|
|
} else {
|
|
|
|
status = 'paid';
|
|
|
|
}
|
2021-04-20 14:51:16 +03:00
|
|
|
try {
|
|
|
|
if (ghostProduct) {
|
|
|
|
memberProducts.push(ghostProduct.toJSON());
|
|
|
|
}
|
|
|
|
const existingProducts = await member.related('products').fetch(options);
|
|
|
|
for (const productModel of existingProducts.models) {
|
|
|
|
memberProducts.push(productModel.toJSON());
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
this._logging.error(`Failed to attach products to member - ${data.id}`);
|
|
|
|
}
|
2021-01-25 18:33:49 +03:00
|
|
|
} else {
|
|
|
|
const subscriptions = await member.related('stripeSubscriptions').fetch(options);
|
|
|
|
for (const subscription of subscriptions.models) {
|
|
|
|
if (this.isActiveSubscriptionStatus(subscription.get('status'))) {
|
2021-04-20 14:51:16 +03:00
|
|
|
try {
|
|
|
|
const subscriptionProduct = await this._productRepository.get({stripe_price_id: subscription.get('stripe_price_id')});
|
|
|
|
if (subscriptionProduct) {
|
|
|
|
memberProducts.push(subscriptionProduct.toJSON());
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
this._logging.error(`Failed to attach products to member - ${data.id}`);
|
|
|
|
this._logging.error(e);
|
|
|
|
}
|
|
|
|
const isComplimentary = subscription.get('plan_nickname') && subscription.get('plan_nickname').toLowerCase() === 'complimentary';
|
|
|
|
if (status === 'comped' || isComplimentary) {
|
2021-02-15 17:16:58 +03:00
|
|
|
status = 'comped';
|
|
|
|
} else {
|
|
|
|
status = 'paid';
|
|
|
|
}
|
2021-01-25 18:33:49 +03:00
|
|
|
}
|
|
|
|
}
|
2021-02-15 17:16:58 +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) {
|
|
|
|
this._logging.error(`Failed to update member - ${data.id} - with related products`);
|
|
|
|
this._logging.error(e);
|
|
|
|
updatedMember = await this._Member.edit({status: status}, {...options, id: data.id});
|
|
|
|
}
|
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,
|
|
|
|
to_status: updatedMember.get('status')
|
|
|
|
}, 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) {
|
|
|
|
throw new Error('Cannot get Stripe Subscription with no Stripe Connection');
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
throw new Error('Subscription not found');
|
|
|
|
}
|
|
|
|
|
|
|
|
return subscription.toJSON();
|
|
|
|
}
|
|
|
|
|
|
|
|
async cancelSubscription(data, options) {
|
|
|
|
if (!this._stripeAPIService.configured) {
|
|
|
|
throw new Error('Cannot update Stripe Subscription with no Stripe Connection');
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
throw new Error('Subscription not found');
|
|
|
|
}
|
|
|
|
|
|
|
|
const updatedSubscription = await this._stripeAPIService.cancelSubscription(data.subscription.subscription_id);
|
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription: updatedSubscription
|
|
|
|
}, options);
|
|
|
|
}
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
async updateSubscription(data, options) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
|
|
|
throw new Error('Cannot update Stripe Subscription with no Stripe Connection');
|
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) {
|
|
|
|
throw new Error('Cannot update Subscription without an id or email for the Member');
|
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne(findQuery);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
const subscription = await member.related('stripeSubscriptions').query({
|
|
|
|
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
|
|
|
|
|
|
|
if (!subscription) {
|
|
|
|
throw new Error('Subscription not found');
|
|
|
|
}
|
|
|
|
|
2021-03-25 15:19:01 +03:00
|
|
|
let updatedSubscription;
|
|
|
|
if (data.subscription.plan) {
|
|
|
|
updatedSubscription = await this._stripeAPIService.changeSubscriptionPlan(
|
|
|
|
data.subscription.subscription_id,
|
|
|
|
data.subscription.plan
|
|
|
|
);
|
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
|
|
|
|
);
|
|
|
|
} 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);
|
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) {
|
|
|
|
throw new Error('Cannot create Stripe Subscription with no Stripe Connection');
|
|
|
|
}
|
|
|
|
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) {
|
|
|
|
console.log('Ignoring error for fetching customer for checkout');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
async setComplimentarySubscription(data, options) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
|
|
|
throw new Error('Cannot update Stripe Subscription with no Stripe Connection');
|
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
|
|
|
});
|
|
|
|
|
|
|
|
// NOTE: Because we allow for multiple Complimentary plans, need to take into account currently availalbe
|
|
|
|
// plan currencies so that we don't end up giving a member complimentary subscription in wrong currency.
|
|
|
|
// Giving member a subscription in different currency would prevent them from resubscribing with a regular
|
|
|
|
// plan if Complimentary is cancelled (ref. https://stripe.com/docs/billing/customer#currency)
|
|
|
|
let complimentaryCurrency = this._stripePlansService.getPlans().find(plan => plan.interval === 'month').currency.toLowerCase();
|
|
|
|
|
|
|
|
if (activeSubscriptions.length) {
|
|
|
|
complimentaryCurrency = activeSubscriptions[0].get('plan_currency').toLowerCase();
|
|
|
|
}
|
|
|
|
|
|
|
|
const complimentaryPlan = this._stripePlansService.getComplimentaryPlan(complimentaryCurrency);
|
|
|
|
|
|
|
|
if (!complimentaryPlan) {
|
|
|
|
throw new Error('Could not find Complimentary plan');
|
|
|
|
}
|
|
|
|
|
|
|
|
let stripeCustomer;
|
|
|
|
|
2021-01-22 18:15:31 +03:00
|
|
|
await member.related('stripeCustomers').fetch(options);
|
2021-01-18 16:55:40 +03:00
|
|
|
|
|
|
|
for (const customer of member.related('stripeCustomers').models) {
|
|
|
|
try {
|
|
|
|
const fetchedCustomer = await this._stripeAPIService.getCustomer(customer.get('customer_id'));
|
|
|
|
if (!fetchedCustomer.deleted) {
|
|
|
|
stripeCustomer = fetchedCustomer;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.log('Ignoring error for fetching customer for checkout');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!stripeCustomer) {
|
|
|
|
stripeCustomer = await this._stripeAPIService.createCustomer({
|
|
|
|
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-01-25 16:19:24 +03:00
|
|
|
if (!activeSubscriptions.length) {
|
2021-01-18 16:55:40 +03:00
|
|
|
const subscription = await this._stripeAPIService.createSubscription(stripeCustomer.id, complimentaryPlan.id);
|
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
} else {
|
|
|
|
// NOTE: we should only ever have 1 active subscription, but just in case there is more update is done on all of them
|
|
|
|
for (const subscription of activeSubscriptions) {
|
|
|
|
const updatedSubscription = await this._stripeAPIService.changeSubscriptionPlan(
|
2021-02-22 17:00:24 +03:00
|
|
|
subscription.get('subscription_id'),
|
2021-01-18 16:55:40 +03:00
|
|
|
complimentaryPlan.id
|
|
|
|
);
|
|
|
|
|
|
|
|
await this.linkSubscription({
|
|
|
|
id: member.id,
|
|
|
|
subscription: updatedSubscription
|
2021-01-22 18:15:31 +03:00
|
|
|
}, options);
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async cancelComplimentarySubscription(data) {
|
2021-01-26 14:26:28 +03:00
|
|
|
if (!this._stripeAPIService.configured) {
|
|
|
|
throw new Error('Cannot cancel Complimentary Subscription with no Stripe Connection');
|
2021-01-18 16:55:40 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const member = await this._Member.findOne({
|
|
|
|
id: data.id
|
|
|
|
});
|
|
|
|
|
|
|
|
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({
|
|
|
|
id: data.id,
|
|
|
|
subscription: updatedSubscription
|
|
|
|
});
|
|
|
|
} catch (err) {
|
|
|
|
this._logging.error(`There was an error cancelling subscription ${subscription.get('subscription_id')}`);
|
|
|
|
this._logging.error(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
};
|