From 9079a9b9e05837370a96f46b6c3ea89f5327ef28 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Thu, 10 Jun 2021 18:33:22 +0100 Subject: [PATCH] Fixed products being removed when canceling subscriptions refs https://github.com/TryGhost/Team/issues/748 Previously when a change happened to a subscription the member's products would be reset purely based on the subscriptions. Since we now support setting products outside of subscriptions, we must make sure than a change to a subscription will only affect the product for which the subscription was for --- .../lib/repositories/member/index.js | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/ghost/members-api/lib/repositories/member/index.js b/ghost/members-api/lib/repositories/member/index.js index 616e43f985..cf5f9ebc15 100644 --- a/ghost/members-api/lib/repositories/member/index.js +++ b/ghost/members-api/lib/repositories/member/index.js @@ -409,36 +409,35 @@ module.exports = class MemberRepository { } let status = 'free'; - let memberProducts = []; + let memberProducts = (await member.related('products').fetch(options)).toJSON(); if (this.isActiveSubscriptionStatus(subscription.status)) { status = 'paid'; - 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}`); + if (ghostProduct) { + memberProducts.push(ghostProduct.toJSON()); } } else { const subscriptions = await member.related('stripeSubscriptions').fetch(options); + let activeSubscriptionForGhostProduct = false; for (const subscription of subscriptions.models) { if (this.isActiveSubscriptionStatus(subscription.get('status'))) { + status = 'paid'; try { const subscriptionProduct = await this._productRepository.get({stripe_price_id: subscription.get('stripe_price_id')}); - if (subscriptionProduct) { - memberProducts.push(subscriptionProduct.toJSON()); + if (subscriptionProduct && ghostProduct && subscriptionProduct.id === ghostProduct.id) { + activeSubscriptionForGhostProduct = true; } } catch (e) { this._logging.error(`Failed to attach products to member - ${data.id}`); this._logging.error(e); } - status = 'paid'; } } + + if (!activeSubscriptionForGhostProduct) { + memberProducts = memberProducts.filter((product) => { + return product.id !== ghostProduct.id; + }); + } } let updatedMember; try {