From d3b1283241f22b13eb7c6a5175b60d9032ed6ed2 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Thu, 26 Aug 2021 13:00:56 +0200 Subject: [PATCH] Removed old product when subscription is updated refs https://github.com/TryGhost/Team/issues/979 This correctly handles updates to subscriptions so that if the product a subscription is for has changed, we will remove the previous product, if and only if there is not another subscription which gives access to it. --- ghost/members-api/lib/repositories/member.js | 39 +++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/ghost/members-api/lib/repositories/member.js b/ghost/members-api/lib/repositories/member.js index 96bc8289ab..ae58827407 100644 --- a/ghost/members-api/lib/repositories/member.js +++ b/ghost/members-api/lib/repositories/member.js @@ -601,8 +601,43 @@ module.exports = class MemberRepository { let status = memberProducts.length === 0 ? 'free' : 'comped'; if (this.isActiveSubscriptionStatus(subscription.status)) { status = 'paid'; - if (ghostProduct) { - memberProducts.push(ghostProduct.toJSON()); + if (!model) { + // This is a new subscription! Add the product + if (ghostProduct) { + memberProducts.push(ghostProduct.toJSON()); + } + } else { + if (model.get('stripe_price_id') !== subscriptionData.stripe_price_id) { + // The subscription has changed plan - we may need to update the products + memberProducts.push(ghostProduct.toJSON()); + + 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; + + for (const subscription of subscriptions.models) { + if (this.isActiveSubscriptionStatus(subscription.get('status'))) { + try { + const subscriptionProduct = await this._productRepository.get({stripe_price_id: subscription.get('stripe_price_id')}); + if (subscriptionProduct && changedProduct && subscriptionProduct.id === changedProduct.id) { + activeSubscriptionForChangedProduct = true; + } + } catch (e) { + this._logging.error(`Failed to attach products to member - ${data.id}`); + this._logging.error(e); + } + } + } + + if (!activeSubscriptionForChangedProduct) { + memberProducts = memberProducts.filter((product) => { + return product.id !== changedProduct.id; + }); + } + } } } else { const subscriptions = await member.related('stripeSubscriptions').fetch(options);