From 06042d76f0f5631bd9c9d5312c679e0e147a4b6c Mon Sep 17 00:00:00 2001 From: Xavier Abad <77491413+xabg2@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:17:32 +0200 Subject: [PATCH] refactor(webhook): remove useless params in event handlers --- src/services/tiers.service.ts | 12 +++--- src/webhooks/handleDisputeResult.ts | 4 -- src/webhooks/handleFundsCaptured.ts | 17 ++++---- src/webhooks/handleInvoicePaymentFailed.ts | 15 ++++--- src/webhooks/handleLifetimeRefunded.ts | 10 ++--- src/webhooks/handleSubscriptionCanceled.ts | 20 ++++----- src/webhooks/handleSubscriptionUpdated.ts | 25 +++++------ src/webhooks/index.ts | 16 +------ src/webhooks/utils/handleCancelPlan.ts | 20 +++++---- tests/src/services/tiers.service.test.ts | 18 ++++---- .../src/webhooks/handleDisputeResult.test.ts | 7 +--- .../src/webhooks/handleFundsCaptured.test.ts | 30 ++++++------- .../handleInvoicePaymentFailed.test.ts | 42 ++++++++----------- .../webhooks/handleLifetimeRefunded.test.ts | 7 +--- .../handleSubscriptionCanceled.test.ts | 9 +--- .../webhooks/utils/handleCancelPlan.test.ts | 14 +------ tests/src/webhooks/webhook.test.ts | 2 - 17 files changed, 100 insertions(+), 168 deletions(-) diff --git a/src/services/tiers.service.ts b/src/services/tiers.service.ts index 28dcb756..93967c6e 100644 --- a/src/services/tiers.service.ts +++ b/src/services/tiers.service.ts @@ -1,5 +1,4 @@ import axios from 'axios'; -import { FastifyBaseLogger } from 'fastify'; import { TiersRepository } from '../core/users/MongoDBTiersRepository'; import { UsersTiersRepository } from '../core/users/MongoDBUsersTiersRepository'; import { Service, Tier } from '../core/users/Tier'; @@ -8,6 +7,7 @@ import { BadRequestError } from '../errors/Errors'; import { MailService } from './mail.service'; import { StorageService } from './storage.service'; import { UsersService } from './users.service'; +import Logger from '../Logger'; export class TierNotFoundError extends Error { constructor(message: string) { @@ -100,7 +100,7 @@ export class TiersService { return tier; } - async removeTier(userWithEmail: User & { email: string }, productId: string, log: FastifyBaseLogger): Promise { + async removeTier(userWithEmail: User & { email: string }, productId: string): Promise { const tier = await this.tiersRepository.findByProductId({ productId }); const { uuid: userUuid } = userWithEmail; @@ -117,7 +117,7 @@ export class TiersService { switch (s) { case Service.Drive: - await this.removeDriveFeatures(userUuid, tier, log); + await this.removeDriveFeatures(userUuid, tier); break; case Service.Vpn: await this.removeVPNFeatures(userUuid, tier.featuresPerService['vpn']); @@ -152,7 +152,7 @@ export class TiersService { ); } - async removeDriveFeatures(userUuid: User['uuid'], tier: Tier, log: FastifyBaseLogger): Promise { + async removeDriveFeatures(userUuid: User['uuid'], tier: Tier): Promise { const freeTier = await this.getTierProductsByProductsId('free'); const features = tier.featuresPerService[Service.Drive]; @@ -163,12 +163,12 @@ export class TiersService { } catch (error) { if (axios.isAxiosError(error) && error.response) { const { status, data } = error.response; - log.error( + Logger.error( `Failed to delete workspace for user ${userUuid}. Status: ${status}, Response: ${JSON.stringify(data)}`, ); throw data; } else { - log.error(`Unexpected error deleting workspace for user ${userUuid}: ${error}`); + Logger.error(`Unexpected error deleting workspace for user ${userUuid}: ${error}`); throw error; } } diff --git a/src/webhooks/handleDisputeResult.ts b/src/webhooks/handleDisputeResult.ts index 1d4d0307..fa0bfea1 100644 --- a/src/webhooks/handleDisputeResult.ts +++ b/src/webhooks/handleDisputeResult.ts @@ -4,7 +4,6 @@ import { StorageService } from '../services/storage.service'; import CacheService from '../services/cache.service'; import handleLifetimeRefunded from './handleLifetimeRefunded'; import { PaymentService } from '../services/payment.service'; -import { FastifyBaseLogger } from 'fastify'; import { TiersService } from '../services/tiers.service'; import { PreCreatedUserService } from '../services/preCreatedUser.service'; @@ -16,7 +15,6 @@ interface HandleDisputeResultProps { storageService: StorageService; cacheService: CacheService; tiersService: TiersService; - log: FastifyBaseLogger; preCreatedUserService: PreCreatedUserService; } @@ -28,7 +26,6 @@ export async function handleDisputeResult({ storageService, cacheService, tiersService, - log, preCreatedUserService, }: HandleDisputeResultProps) { if (dispute.status !== 'lost') { @@ -51,7 +48,6 @@ export async function handleDisputeResult({ charge, cacheService, paymentService, - log, tiersService, preCreatedUserService, ); diff --git a/src/webhooks/handleFundsCaptured.ts b/src/webhooks/handleFundsCaptured.ts index 513dba4d..0c9ecd5f 100644 --- a/src/webhooks/handleFundsCaptured.ts +++ b/src/webhooks/handleFundsCaptured.ts @@ -1,5 +1,4 @@ import Stripe from 'stripe'; -import { FastifyBaseLogger } from 'fastify'; import { PaymentService } from '../services/payment.service'; import { ObjectStorageService } from '../services/objectStorage.service'; @@ -8,13 +7,13 @@ import { UserType } from '../core/users/User'; import axios from 'axios'; import { VERIFICATION_CHARGE } from '../constants'; import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter'; +import Logger from '../Logger'; export default async function handleFundsCaptured( paymentIntent: Stripe.PaymentIntent, paymentsService: PaymentService, objectStorageService: ObjectStorageService, stripe: Stripe, - logger: FastifyBaseLogger, ): Promise { const isMissingType = !paymentIntent.metadata.type; const isNotObjectStorage = paymentIntent.metadata.type !== 'object-storage'; @@ -28,13 +27,13 @@ export default async function handleFundsCaptured( return; } - logger.info( + Logger.info( `Received successful payment intent ${paymentIntent.id} from customer ${paymentIntent.customer as string}`, ); const customer = await stripePaymentsAdapter.getCustomer(paymentIntent.customer as string); - logger.info(`Object Storage for user ${customer.email} (customer ${customer.id}) is being initialized...`); + Logger.info(`Object Storage for user ${customer.email} (customer ${customer.id}) is being initialized...`); const isPaymentIntentCanceled = paymentIntent.status === 'canceled'; @@ -44,7 +43,7 @@ export default async function handleFundsCaptured( } } catch (error) { const err = error as Error; - logger.error( + Logger.error( `[OBJECT STORAGE] Unexpected error while attempting to cancel the verification payment intent for user ${customer.id}. Error: ${err.message}`, ); @@ -71,7 +70,7 @@ export default async function handleFundsCaptured( } } catch (error) { const err = error as Error; - logger.error( + Logger.error( `[OBJECT STORAGE] Unexpected error while attempting to create a user subscription for user ${customer.id}. Error: ${err.message}`, ); @@ -88,15 +87,15 @@ export default async function handleFundsCaptured( const { status, data } = error.response; if (status === 409) { - logger.error('The user already has an Object Storage account activated'); + Logger.error('The user already has an Object Storage account activated'); throw new ConflictError(error.message); } - logger.error(`Unexpected error from Object Storage service [status=${status}]: ${JSON.stringify(data)}`); + Logger.error(`Unexpected error from Object Storage service [status=${status}]: ${JSON.stringify(data)}`); } throw error; } - logger.info(`Object Storage for user ${customer.email} (customer ${customer.id}) has been initialized!`); + Logger.info(`Object Storage for user ${customer.email} (customer ${customer.id}) has been initialized!`); } diff --git a/src/webhooks/handleInvoicePaymentFailed.ts b/src/webhooks/handleInvoicePaymentFailed.ts index df50b81d..9c7a9eea 100644 --- a/src/webhooks/handleInvoicePaymentFailed.ts +++ b/src/webhooks/handleInvoicePaymentFailed.ts @@ -1,9 +1,9 @@ import Stripe from 'stripe'; -import { FastifyLoggerInstance } from 'fastify'; import { PaymentService } from '../services/payment.service'; import { ObjectStorageService } from '../services/objectStorage.service'; import { UsersService } from '../services/users.service'; import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter'; +import Logger from '../Logger'; function isProduct(product: Stripe.Product | Stripe.DeletedProduct): product is Stripe.Product { return ( @@ -45,7 +45,6 @@ export default async function handleInvoicePaymentFailed( objectStorageService: ObjectStorageService, paymentService: PaymentService, usersService: UsersService, - logger: FastifyLoggerInstance, ): Promise { if (!invoice.customer) { throw new Error('No customer found for this payment'); @@ -60,27 +59,27 @@ export default async function handleInvoicePaymentFailed( const user = await usersService.findUserByCustomerID(customer.id); if (user) { await usersService.notifyFailedPayment(user.uuid); - logger.info(`Drive payment failure notification sent for customer ${customer.id} (user UUID: ${user.uuid})`); + Logger.info(`Drive payment failure notification sent for customer ${customer.id} (user UUID: ${user.uuid})`); } else { - logger.warn(`User not found for customer ${customer.id}. Skipping failed payment notification.`); + Logger.warn(`User not found for customer ${customer.id}. Skipping failed payment notification.`); } } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); - logger.error(`Failed to send payment notification for customer ${customer.id}. Error: ${errorMessage}`); + Logger.error(`Failed to send payment notification for customer ${customer.id}. Error: ${errorMessage}`); } - logger.info( + Logger.info( `Invoice ${invoice.id} does not contain an object storage product. Skipping object storage suspension...`, ); return; } - logger.info( + Logger.info( `Handling invoice not paid ${invoice.id} for customer ${customer.id} > Suspending object storage account..`, ); await objectStorageService.suspendAccount({ customerId: customer.id }); - logger.info( + Logger.info( `Handling invoice not paid ${invoice.id} for customer ${customer.id} > Object storage account suspended..`, ); } diff --git a/src/webhooks/handleLifetimeRefunded.ts b/src/webhooks/handleLifetimeRefunded.ts index 9d5323c6..af1097d1 100644 --- a/src/webhooks/handleLifetimeRefunded.ts +++ b/src/webhooks/handleLifetimeRefunded.ts @@ -1,4 +1,3 @@ -import { FastifyLoggerInstance } from 'fastify'; import CacheService from '../services/cache.service'; import { StorageService } from '../services/storage.service'; import { UsersService } from '../services/users.service'; @@ -8,6 +7,7 @@ import Stripe from 'stripe'; import { PaymentService } from '../services/payment.service'; import { Service } from '../core/users/Tier'; import { PreCreatedUserService } from '../services/preCreatedUser.service'; +import Logger from '../Logger'; export default async function handleLifetimeRefunded( storageService: StorageService, @@ -15,7 +15,6 @@ export default async function handleLifetimeRefunded( charge: Stripe.Charge, cacheService: CacheService, paymentsService: PaymentService, - log: FastifyLoggerInstance, tiersService: TiersService, preCreatedUserService: PreCreatedUserService, ): Promise { @@ -35,7 +34,7 @@ export default async function handleLifetimeRefunded( productId = product.id; } - log.info( + Logger.info( `[LIFETIME REFUNDED]: User with customerId ${customerId} found. The uuid of the user is: ${uuid} and productId: ${productId}`, ); @@ -44,7 +43,7 @@ export default async function handleLifetimeRefunded( await cacheService.clearUsedUserPromoCodes(customerId); await cacheService.clearUserTier(uuid); } catch (err) { - log.error(`Error in handleLifetimeRefunded after trying to clear ${customerId} subscription`); + Logger.error(`Error in handleLifetimeRefunded after trying to clear ${customerId} subscription`); } try { @@ -55,12 +54,11 @@ export default async function handleLifetimeRefunded( productId, usersService, tiersService, - log, preCreatedUserService, }); } catch (error) { const err = error as Error; - log.error(`[LIFETIME REFUNDED/ERROR]: Error canceling tier product. ERROR: ${err.stack ?? err.message}`); + Logger.error(`[LIFETIME REFUNDED/ERROR]: Error canceling tier product. ERROR: ${err.stack ?? err.message}`); if (!(error instanceof TierNotFoundError)) { throw error; } diff --git a/src/webhooks/handleSubscriptionCanceled.ts b/src/webhooks/handleSubscriptionCanceled.ts index b58b2eba..c4100051 100644 --- a/src/webhooks/handleSubscriptionCanceled.ts +++ b/src/webhooks/handleSubscriptionCanceled.ts @@ -1,5 +1,4 @@ import { UserType } from './../core/users/User'; -import { FastifyBaseLogger } from 'fastify'; import CacheService from '../services/cache.service'; import { StorageService } from '../services/storage.service'; import { UsersService } from '../services/users.service'; @@ -24,7 +23,6 @@ async function handleObjectStorageSubscriptionCancelled( subscription: Stripe.Subscription, objectStorageService: ObjectStorageService, paymentService: PaymentService, - logger: FastifyBaseLogger, ): Promise { const activeSubscriptions = await paymentService.getActiveSubscriptions(customer.id); const objectStorageActiveSubscriptions = activeSubscriptions.filter( @@ -32,19 +30,19 @@ async function handleObjectStorageSubscriptionCancelled( ); if (objectStorageActiveSubscriptions.length > 0) { - logger.info( + Logger.info( `Preventing removal of an object storage customer ${customer.id} with sub ${subscription.id} due to the existence of another active subscription`, ); return; } - logger.info(`Deleting object storage customer ${customer.id} with sub ${subscription.id}`); + Logger.info(`Deleting object storage customer ${customer.id} with sub ${subscription.id}`); await objectStorageService.suspendAccount({ customerId: customer.id, }); - logger.info(`Object storage customer ${customer.id} with sub ${subscription.id} deleted successfully`); + Logger.info(`Object storage customer ${customer.id} with sub ${subscription.id} deleted successfully`); } export default async function handleSubscriptionCanceled( @@ -55,7 +53,6 @@ export default async function handleSubscriptionCanceled( cacheService: CacheService, objectStorageService: ObjectStorageService, tiersService: TiersService, - log: FastifyBaseLogger, preCreatedUserService: PreCreatedUserService, ): Promise { const customerId = subscription.customer as string; @@ -64,7 +61,7 @@ export default async function handleSubscriptionCanceled( const customer = await stripePaymentsAdapter.getCustomer(customerId); if (isObjectStorageProduct(productMetadata)) { - await handleObjectStorageSubscriptionCancelled(customer, subscription, objectStorageService, paymentService, log); + await handleObjectStorageSubscriptionCancelled(customer, subscription, objectStorageService, paymentService); return; } @@ -72,7 +69,7 @@ export default async function handleSubscriptionCanceled( const productType = productMetadata?.type === UserType.Business ? UserType.Business : UserType.Individual; - log.info( + Logger.info( `[SUB CANCEL]: User with customerId ${customerId} found. The uuid of the user is: ${uuid} and productId: ${productId}`, ); @@ -81,11 +78,11 @@ export default async function handleSubscriptionCanceled( await cacheService.clearUsedUserPromoCodes(customerId); await cacheService.clearUserTier(uuid); } catch (err) { - log.error(`Error in handleSubscriptionCanceled after trying to clear ${customerId} subscription`); + Logger.error(`Error in handleSubscriptionCanceled after trying to clear ${customerId} subscription`); } if (hasBoughtALifetime && productType === UserType.Individual) { - log.info(`User with uuid ${uuid} has a lifetime subscription. No need to downgrade the user.`); + Logger.info(`User with uuid ${uuid} has a lifetime subscription. No need to downgrade the user.`); // This user has switched from a subscription to a lifetime, therefore we do not want to downgrade his space // The space should not be set to Free plan. return; @@ -98,12 +95,11 @@ export default async function handleSubscriptionCanceled( productId, usersService, tiersService, - log, preCreatedUserService, }); } catch (error) { const err = error as Error; - log.error(`[SUB CANCEL/ERROR]: Error canceling tier product. ERROR: ${err.stack ?? err.message}`); + Logger.error(`[SUB CANCEL/ERROR]: Error canceling tier product. ERROR: ${err.stack ?? err.message}`); if (!(error instanceof TierNotFoundError)) { throw error; diff --git a/src/webhooks/handleSubscriptionUpdated.ts b/src/webhooks/handleSubscriptionUpdated.ts index e042ed25..bb3bf50d 100644 --- a/src/webhooks/handleSubscriptionUpdated.ts +++ b/src/webhooks/handleSubscriptionUpdated.ts @@ -1,14 +1,12 @@ -import { FastifyBaseLogger } from 'fastify'; import Stripe from 'stripe'; import CacheService from '../services/cache.service'; import { PaymentService } from '../services/payment.service'; -import { StorageService } from '../services/storage.service'; import { UsersService } from '../services/users.service'; -import { AppConfig } from '../config'; import { UserType } from '../core/users/User'; import { ObjectStorageService } from '../services/objectStorage.service'; import { stripePaymentsAdapter } from '../infrastructure/adapters/stripe.adapter'; import { Customer } from '../infrastructure/domain/entities/customer'; +import Logger from '../Logger'; function isObjectStorageProduct(meta: Stripe.Metadata): boolean { return !!meta && !!meta.type && meta.type === 'object-storage'; @@ -18,26 +16,22 @@ async function handleObjectStorageScheduledForCancelation( customer: Customer, subscription: Stripe.Subscription, objectStorageService: ObjectStorageService, - logger: FastifyBaseLogger, ): Promise { - logger.info(`Deleting object storage customer ${customer.id} with sub ${subscription.id}`); + Logger.info(`Deleting object storage customer ${customer.id} with sub ${subscription.id}`); await objectStorageService.suspendAccount({ customerId: customer.id, }); - logger.info(`Object storage customer ${customer.id} with sub ${subscription.id} deleted successfully`); + Logger.info(`Object storage customer ${customer.id} with sub ${subscription.id} deleted successfully`); } export default async function handleSubscriptionUpdated( - storageService: StorageService, usersService: UsersService, subscription: Stripe.Subscription, cacheService: CacheService, paymentService: PaymentService, objectStorageService: ObjectStorageService, - log: FastifyBaseLogger, - config: AppConfig, ): Promise { let uuid = ''; const customerId = subscription.customer as string; @@ -49,18 +43,19 @@ export default async function handleSubscriptionUpdated( const { metadata: productMetadata } = product; if (isObjectStorageProduct(productMetadata)) { - log.info(`Object storage customer ${customerId} with sub ${subscription.id} updated its sub`); + Logger.info(`Object storage customer ${customerId} with sub ${subscription.id} updated its sub`); if (isSubscriptionCanceled) { - log.info(`Object storage customer ${customerId} with sub ${subscription.id} has been canceled`); + Logger.info(`Object storage customer ${customerId} with sub ${subscription.id} has been canceled`); } else if (subscriptionScheduledForCancelation) { - log.info(`Object storage customer ${customerId} with sub ${subscription.id} has been scheduled for cancelation`); + Logger.info( + `Object storage customer ${customerId} with sub ${subscription.id} has been scheduled for cancelation`, + ); await handleObjectStorageScheduledForCancelation( await stripePaymentsAdapter.getCustomer(customerId), subscription, objectStorageService, - log, ); } return; @@ -73,7 +68,7 @@ export default async function handleSubscriptionUpdated( return; } } catch (error) { - log.error(`Error in handleSubscriptionUpdated trying to fetch the customer by ID ${customerId}`); + Logger.error(`Error in handleSubscriptionUpdated trying to fetch the customer by ID ${customerId}`); return; } @@ -82,7 +77,7 @@ export default async function handleSubscriptionUpdated( try { await cacheService.clearSubscription(customerId, productType); } catch (err) { - log.error(`Error in handleSubscriptionUpdated after trying to clear ${customerId} subscription`); + Logger.error(`Error in handleSubscriptionUpdated after trying to clear ${customerId} subscription`); } if (productType === UserType.Business) { diff --git a/src/webhooks/index.ts b/src/webhooks/index.ts index 26242b0a..4aee6910 100644 --- a/src/webhooks/index.ts +++ b/src/webhooks/index.ts @@ -68,17 +68,11 @@ export function webhookHandler({ switch (event.type) { case 'invoice.payment_failed': - await handleInvoicePaymentFailed( - event.data.object, - objectStorageService, - paymentService, - usersService, - fastify.log, - ); + await handleInvoicePaymentFailed(event.data.object, objectStorageService, paymentService, usersService); break; case 'payment_intent.amount_capturable_updated': - await handleFundsCaptured(event.data.object, paymentService, objectStorageService, stripe, fastify.log); + await handleFundsCaptured(event.data.object, paymentService, objectStorageService, stripe); break; case 'customer.subscription.deleted': @@ -90,21 +84,17 @@ export function webhookHandler({ cacheService, objectStorageService, tiersService, - fastify.log, preCreatedUserService, ); break; case 'customer.subscription.updated': await handleSubscriptionUpdated( - storageService, usersService, event.data.object, cacheService, paymentService, objectStorageService, - fastify.log, - config, ); break; @@ -172,7 +162,6 @@ export function webhookHandler({ event.data.object, cacheService, paymentService, - fastify.log, tiersService, preCreatedUserService, ); @@ -190,7 +179,6 @@ export function webhookHandler({ storageService, cacheService, tiersService, - log: fastify.log, preCreatedUserService, }); break; diff --git a/src/webhooks/utils/handleCancelPlan.ts b/src/webhooks/utils/handleCancelPlan.ts index 454e8f04..bd9864f6 100644 --- a/src/webhooks/utils/handleCancelPlan.ts +++ b/src/webhooks/utils/handleCancelPlan.ts @@ -2,10 +2,10 @@ import { CustomerId } from '../../types/stripe'; import { UsersService } from '../../services/users.service'; import { TierNotFoundError, TiersService } from '../../services/tiers.service'; import Stripe from 'stripe'; -import { FastifyBaseLogger } from 'fastify'; import { PreCreatedUserService } from '../../services/preCreatedUser.service'; import { PreCreatedUserStatus } from '../../infrastructure/domain/entities/preCreatedUser'; import { PreCreatedUserNotFoundError } from '../../errors/PreCreatedUsersErrors'; +import Logger from '../../Logger'; interface HandleCancelPlanProps { customerId: CustomerId; @@ -14,7 +14,6 @@ interface HandleCancelPlanProps { usersService: UsersService; tiersService: TiersService; preCreatedUserService: PreCreatedUserService; - log: FastifyBaseLogger; isLifetime?: boolean; } @@ -26,22 +25,25 @@ export const handleCancelPlan = async ({ tiersService, preCreatedUserService, isLifetime, - log, }: HandleCancelPlanProps) => { const user = await usersService.findUserByCustomerID(customerId); const { id: userId } = user; const billingType = isLifetime ? 'lifetime' : 'subscription'; const tier = await tiersService.getTierProductsByProductsId(productId, billingType); - log.info(`[CANCEL PLAN HANDLER]: The user with id ${userId} exists, and the product with id ${tier.id} also exists.`); + Logger.info( + `[CANCEL PLAN HANDLER]: The user with id ${userId} exists, and the product with id ${tier.id} also exists.`, + ); await usersService.updateUser(customerId, { lifetime: false }); - log.info(`[CANCEL PLAN HANDLER]: THe user data for the customer ${userId} has been downgraded in handleCancelPlan`); + Logger.info( + `[CANCEL PLAN HANDLER]: THe user data for the customer ${userId} has been downgraded in handleCancelPlan`, + ); - await tiersService.removeTier({ ...user, email: customerEmail }, productId, log); + await tiersService.removeTier({ ...user, email: customerEmail }, productId); - log.info(`[CANCEL PLAN HANDLER]: The tier for the user ${userId} has been removed`); + Logger.info(`[CANCEL PLAN HANDLER]: The tier for the user ${userId} has been removed`); const userTiers = await tiersService.getTiersProductsByUserId(user.id); @@ -68,10 +70,10 @@ export const handleCancelPlan = async ({ status: PreCreatedUserStatus.Cancelled, }); } else { - log.info(`[CANCEL PLAN HANDLER]: The preCreatedUser with email ${customerEmail} does not exist. Continuing...`); + Logger.info(`[CANCEL PLAN HANDLER]: The preCreatedUser with email ${customerEmail} does not exist. Continuing...`); } - log.info( + Logger.info( `[CANCEL PLAN HANDLER]: The user-tier relationship using the user id ${userId} and tier id ${tier.id} has been deleted`, ); }; diff --git a/tests/src/services/tiers.service.test.ts b/tests/src/services/tiers.service.test.ts index 7efe264b..f44fc668 100644 --- a/tests/src/services/tiers.service.test.ts +++ b/tests/src/services/tiers.service.test.ts @@ -3,7 +3,7 @@ import { UserTier } from '../../../src/core/users/MongoDBUsersTiersRepository'; import { Service } from '../../../src/core/users/Tier'; import { BadRequestError } from '../../../src/errors/Errors'; import { TierNotFoundError } from '../../../src/services/tiers.service'; -import { getLogger, getUser, newTier, voidPromise } from '../fixtures'; +import { getUser, newTier, voidPromise } from '../fixtures'; import { createTestServices } from '../helpers/services-factory'; describe('TiersService tests', () => { @@ -225,7 +225,7 @@ describe('TiersService tests', () => { .mockImplementation(() => Promise.resolve(null)); await expect( - tiersService.removeTier({ ...mockedUser, email: 'example@internxt.com' }, productId, getLogger()), + tiersService.removeTier({ ...mockedUser, email: 'example@internxt.com' }, productId), ).rejects.toThrow(TierNotFoundError); expect(findTierByProductId).toHaveBeenCalledWith({ productId }); @@ -233,7 +233,6 @@ describe('TiersService tests', () => { it('When removing the tier, then skips the disabled features the tier had', async () => { const mockedUser = getUser(); - const log = getLogger(); const mockedTier = newTier(); const userWithEmail = { ...mockedUser, email: 'example@internxt.com' }; const { productId } = mockedTier; @@ -250,16 +249,15 @@ describe('TiersService tests', () => { .spyOn(tiersService, 'removeVPNFeatures') .mockImplementation(() => Promise.resolve()); - await tiersService.removeTier(userWithEmail, productId, log); + await tiersService.removeTier(userWithEmail, productId); expect(findTierByProductId).toHaveBeenCalledWith({ productId }); - expect(removeDriveFeatures).toHaveBeenCalledWith(userWithEmail.uuid, mockedTier, log); + expect(removeDriveFeatures).toHaveBeenCalledWith(userWithEmail.uuid, mockedTier); expect(removeVPNFeatures).not.toHaveBeenCalled(); }); it('When removing the tier, then removes the applied features', async () => { const mockedUser = getUser(); - const log = getLogger(); const mockedTier = newTier(); const userWithEmail = { ...mockedUser, email: 'example@internxt.com' }; const { productId } = mockedTier; @@ -280,10 +278,10 @@ describe('TiersService tests', () => { .spyOn(tiersService, 'removeMailFeatures') .mockImplementation(() => Promise.resolve()); - await tiersService.removeTier(userWithEmail, productId, log); + await tiersService.removeTier(userWithEmail, productId); expect(findTierByProductId).toHaveBeenCalledWith({ productId }); - expect(removeDriveFeatures).toHaveBeenCalledWith(userWithEmail.uuid, mockedTier, log); + expect(removeDriveFeatures).toHaveBeenCalledWith(userWithEmail.uuid, mockedTier); expect(removeVPNFeatures).toHaveBeenCalledWith(userWithEmail.uuid, mockedTier.featuresPerService['vpn']); expect(removeMailFeatures).toHaveBeenCalledWith(userWithEmail.uuid); }); @@ -299,7 +297,7 @@ describe('TiersService tests', () => { const destroyWorkspace = jest.spyOn(usersService, 'destroyWorkspace').mockImplementation(() => Promise.resolve()); - await tiersService.removeDriveFeatures(uuid, tier, getLogger()); + await tiersService.removeDriveFeatures(uuid, tier); expect(destroyWorkspace).toHaveBeenCalledWith(uuid); }); @@ -324,7 +322,7 @@ describe('TiersService tests', () => { const destroyWorkspaceSpy = jest.spyOn(usersService, 'destroyWorkspace'); const changeStorageSpy = jest.spyOn(storageService, 'updateUserStorageAndTier').mockImplementation(voidPromise); - await tiersService.removeDriveFeatures(uuid, tier, getLogger()); + await tiersService.removeDriveFeatures(uuid, tier); expect(destroyWorkspaceSpy).not.toHaveBeenCalled(); expect(changeStorageSpy).toHaveBeenCalledWith( diff --git a/tests/src/webhooks/handleDisputeResult.test.ts b/tests/src/webhooks/handleDisputeResult.test.ts index 460bc54e..fe2737fb 100644 --- a/tests/src/webhooks/handleDisputeResult.test.ts +++ b/tests/src/webhooks/handleDisputeResult.test.ts @@ -1,7 +1,7 @@ import axios from 'axios'; import { handleDisputeResult } from '../../../src/webhooks/handleDisputeResult'; import handleLifetimeRefunded from '../../../src/webhooks/handleLifetimeRefunded'; -import { getCharge, getDispute, getInvoice, getLogger, getUser, voidPromise } from '../fixtures'; +import { getCharge, getDispute, getInvoice, getUser, voidPromise } from '../fixtures'; import { createTestServices } from '../helpers/services-factory'; jest.mock('../../../src/webhooks/handleLifetimeRefunded', () => ({ @@ -30,7 +30,6 @@ const { } = createTestServices({ stripe: mockStripe, }); -const logger = getLogger(); describe('handleDisputeResult()', () => { beforeEach(() => { @@ -61,7 +60,6 @@ describe('handleDisputeResult()', () => { usersService, stripe, storageService, - log: logger, tiersService, }); @@ -101,7 +99,6 @@ describe('handleDisputeResult()', () => { usersService, stripe, storageService, - log: logger, tiersService, }); @@ -114,7 +111,6 @@ describe('handleDisputeResult()', () => { mockedCharge, cacheService, paymentService, - logger, tiersService, preCreatedUserService, ); @@ -152,7 +148,6 @@ describe('handleDisputeResult()', () => { usersService, stripe, storageService, - log: logger, tiersService, }); diff --git a/tests/src/webhooks/handleFundsCaptured.test.ts b/tests/src/webhooks/handleFundsCaptured.test.ts index a008bdb6..869c4cbf 100644 --- a/tests/src/webhooks/handleFundsCaptured.test.ts +++ b/tests/src/webhooks/handleFundsCaptured.test.ts @@ -1,14 +1,12 @@ import Stripe from 'stripe'; -import { getPaymentIntent, getLogger, getCustomer, getCreateSubscriptionResponse } from '../fixtures'; -import { FastifyBaseLogger } from 'fastify'; +import { getPaymentIntent, getCustomer, getCreateSubscriptionResponse } from '../fixtures'; import handleFundsCaptured from '../../../src/webhooks/handleFundsCaptured'; import { ConflictError, InternalServerError } from '../../../src/errors/Errors'; import { UserSubscription, UserType } from '../../../src/core/users/User'; import { createTestServices } from '../helpers/services-factory'; import { stripePaymentsAdapter } from '../../../src/infrastructure/adapters/stripe.adapter'; import { Customer } from '../../../src/infrastructure/domain/entities/customer'; - -const logger: jest.Mocked = getLogger(); +import Logger from '../../../src/Logger'; const stripeMock = { paymentIntents: { @@ -31,7 +29,7 @@ describe('Handling captured funds from a payment method', () => { const mockPaymentIntent = getPaymentIntent(); const getCustomerSpy = jest.spyOn(stripePaymentsAdapter, 'getCustomer'); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(getCustomerSpy).not.toHaveBeenCalled(); }); @@ -44,7 +42,7 @@ describe('Handling captured funds from a payment method', () => { }); const getCustomerSpy = jest.spyOn(stripePaymentsAdapter, 'getCustomer'); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(getCustomerSpy).not.toHaveBeenCalled(); }); @@ -57,7 +55,7 @@ describe('Handling captured funds from a payment method', () => { }); const getCustomerSpy = jest.spyOn(stripePaymentsAdapter, 'getCustomer'); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(getCustomerSpy).not.toHaveBeenCalled(); }); @@ -85,7 +83,7 @@ describe('Handling captured funds from a payment method', () => { .spyOn(objectStorageService, 'initObjectStorageUser') .mockResolvedValue(); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(cancelPaymentIntentSpy).not.toHaveBeenCalled(); expect(getUserSubscriptionSpy).toHaveBeenCalledWith(mockCustomer.id, UserType.ObjectStorage); @@ -128,7 +126,7 @@ describe('Handling captured funds from a payment method', () => { .mockResolvedValue(); await expect( - handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger), + handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe), ).rejects.toThrow(unexpectedError); expect(getUserSubscriptionSpy).not.toHaveBeenCalled(); @@ -160,7 +158,7 @@ describe('Handling captured funds from a payment method', () => { .spyOn(objectStorageService, 'initObjectStorageUser') .mockResolvedValue(); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(cancelPaymentIntentSpy).toHaveBeenCalledWith(mockPaymentIntent.id); expect(getUserSubscriptionSpy).toHaveBeenCalledWith(mockCustomer.id, UserType.ObjectStorage); @@ -195,7 +193,7 @@ describe('Handling captured funds from a payment method', () => { .mockResolvedValue(); await expect( - handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger), + handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe), ).rejects.toThrow(unexpectedError); expect(cancelPaymentIntentSpy).toHaveBeenCalledWith(mockPaymentIntent.id); @@ -225,7 +223,7 @@ describe('Handling captured funds from a payment method', () => { .spyOn(objectStorageService, 'initObjectStorageUser') .mockResolvedValue(); - await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger); + await handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe); expect(cancelPaymentIntentSpy).toHaveBeenCalledWith(mockPaymentIntent.id); expect(getUserSubscriptionSpy).toHaveBeenCalledWith(mockCustomer.id, UserType.ObjectStorage); @@ -270,10 +268,12 @@ describe('Handling captured funds from a payment method', () => { message: 'Conflict', }); + const loggerErrorSpy = jest.spyOn(Logger, 'error'); + await expect( - handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger), + handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe), ).rejects.toThrow(ConflictError); - expect(logger.error).toHaveBeenCalledWith('The user already has an Object Storage account activated'); + expect(loggerErrorSpy).toHaveBeenCalledWith('The user already has an Object Storage account activated'); }); it('if an unexpected error occurs while initializing the object storage account, then an error indicating so is thrown', async () => { @@ -294,7 +294,7 @@ describe('Handling captured funds from a payment method', () => { jest.spyOn(objectStorageService, 'initObjectStorageUser').mockRejectedValue(unexpectedError); await expect( - handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe, logger), + handleFundsCaptured(mockPaymentIntent, paymentService, objectStorageService, stripe), ).rejects.toThrow(unexpectedError); }); }); diff --git a/tests/src/webhooks/handleInvoicePaymentFailed.test.ts b/tests/src/webhooks/handleInvoicePaymentFailed.test.ts index eb45b27a..b2f4b8f8 100644 --- a/tests/src/webhooks/handleInvoicePaymentFailed.test.ts +++ b/tests/src/webhooks/handleInvoicePaymentFailed.test.ts @@ -1,11 +1,9 @@ -import { FastifyBaseLogger } from 'fastify'; -import { getCustomer, getInvoice, getLogger, getProduct } from '../fixtures'; +import { getCustomer, getInvoice, getProduct } from '../fixtures'; import handleInvoicePaymentFailed from '../../../src/webhooks/handleInvoicePaymentFailed'; import { createTestServices } from '../helpers/services-factory'; import { stripePaymentsAdapter } from '../../../src/infrastructure/adapters/stripe.adapter'; import { Customer } from '../../../src/infrastructure/domain/entities/customer'; - -const logger: jest.Mocked = getLogger(); +import Logger from '../../../src/Logger'; const { paymentService, usersService, objectStorageService } = createTestServices(); @@ -30,13 +28,7 @@ describe('Handle Invoice Payment Failed', () => { const notifyFailedPaymentSpy = jest.spyOn(usersService, 'notifyFailedPayment'); const suspendAccountSpy = jest.spyOn(objectStorageService, 'suspendAccount').mockResolvedValue(); - await handleInvoicePaymentFailed( - mockedInvoice as any, - objectStorageService, - paymentService, - usersService, - logger, - ); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(getCustomerSpy).toHaveBeenCalledWith(customerId); expect(findUserByCustomerIDSpy).not.toHaveBeenCalled(); @@ -58,7 +50,7 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(usersService, 'notifyFailedPayment').mockRejectedValue(new Error('Gateway error')); await expect( - handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger), + handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService), ).resolves.toBeUndefined(); }); @@ -74,9 +66,9 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(paymentService, 'getProduct').mockResolvedValue(mockedProduct as any); jest.spyOn(usersService, 'findUserByCustomerID').mockResolvedValue(mockedUser as any); jest.spyOn(usersService, 'notifyFailedPayment').mockRejectedValue(new Error(errorMessage)); - const loggerErrorSpy = jest.spyOn(logger, 'error'); + const loggerErrorSpy = jest.spyOn(Logger, 'error'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(loggerErrorSpy).toHaveBeenCalledWith( `Failed to send payment notification for customer ${customerId}. Error: ${errorMessage}`, @@ -95,9 +87,9 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(paymentService, 'getProduct').mockResolvedValue(mockedProduct as any); jest.spyOn(usersService, 'findUserByCustomerID').mockResolvedValue(mockedUser as any); jest.spyOn(usersService, 'notifyFailedPayment').mockRejectedValue(nonErrorObject); - const loggerErrorSpy = jest.spyOn(logger, 'error'); + const loggerErrorSpy = jest.spyOn(Logger, 'error'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(loggerErrorSpy).toHaveBeenCalledWith( `Failed to send payment notification for customer ${customerId}. Error: ${String(nonErrorObject)}`, @@ -114,9 +106,9 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(stripePaymentsAdapter, 'getCustomer').mockResolvedValue(Customer.toDomain(mockedCustomer)); jest.spyOn(paymentService, 'getProduct').mockResolvedValue(mockedProduct as any); jest.spyOn(usersService, 'findUserByCustomerID').mockRejectedValue(new Error(errorMessage)); - const loggerErrorSpy = jest.spyOn(logger, 'error'); + const loggerErrorSpy = jest.spyOn(Logger, 'error'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(loggerErrorSpy).toHaveBeenCalledWith( `Failed to send payment notification for customer ${customerId}. Error: ${errorMessage}`, @@ -127,7 +119,7 @@ describe('Handle Invoice Payment Failed', () => { const mockedInvoice = getInvoice({ customer: null }); await expect( - handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger), + handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService), ).rejects.toThrow('No customer found for this payment'); }); @@ -143,7 +135,7 @@ describe('Handle Invoice Payment Failed', () => { const notifyFailedPaymentSpy = jest.spyOn(usersService, 'notifyFailedPayment'); const suspendAccountSpy = jest.spyOn(objectStorageService, 'suspendAccount').mockResolvedValue(); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(findUserByCustomerIDSpy).not.toHaveBeenCalled(); expect(notifyFailedPaymentSpy).not.toHaveBeenCalled(); @@ -161,9 +153,9 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(paymentService, 'getProduct').mockResolvedValue(mockedProduct as any); jest.spyOn(usersService, 'findUserByCustomerID').mockResolvedValue(mockedUser as any); jest.spyOn(usersService, 'notifyFailedPayment').mockResolvedValue(); - const loggerInfoSpy = jest.spyOn(logger, 'info'); + const loggerInfoSpy = jest.spyOn(Logger, 'info'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(loggerInfoSpy).toHaveBeenCalledWith( `Drive payment failure notification sent for customer ${customerId} (user UUID: ${mockedUser.uuid})`, @@ -179,9 +171,9 @@ describe('Handle Invoice Payment Failed', () => { jest.spyOn(stripePaymentsAdapter, 'getCustomer').mockResolvedValue(Customer.toDomain(mockedCustomer)); jest.spyOn(paymentService, 'getProduct').mockResolvedValue(mockedProduct as any); jest.spyOn(usersService, 'findUserByCustomerID').mockResolvedValue(null as any); - const loggerWarnSpy = jest.spyOn(logger, 'warn'); + const loggerWarnSpy = jest.spyOn(Logger, 'warn'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(loggerWarnSpy).toHaveBeenCalledWith( `User not found for customer ${customerId}. Skipping failed payment notification.`, @@ -201,7 +193,7 @@ describe('Handle Invoice Payment Failed', () => { const notifyFailedPaymentSpy = jest.spyOn(usersService, 'notifyFailedPayment'); const suspendAccountSpy = jest.spyOn(objectStorageService, 'suspendAccount'); - await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService, logger); + await handleInvoicePaymentFailed(mockedInvoice as any, objectStorageService, paymentService, usersService); expect(notifyFailedPaymentSpy).toHaveBeenCalledWith('test-uuid-123'); expect(suspendAccountSpy).not.toHaveBeenCalled(); diff --git a/tests/src/webhooks/handleLifetimeRefunded.test.ts b/tests/src/webhooks/handleLifetimeRefunded.test.ts index a2270ce7..191b104e 100644 --- a/tests/src/webhooks/handleLifetimeRefunded.test.ts +++ b/tests/src/webhooks/handleLifetimeRefunded.test.ts @@ -1,6 +1,6 @@ import Stripe from 'stripe'; import { TierNotFoundError } from '../../../src/services/tiers.service'; -import { getCharge, getInvoice, getLogger, getUser, newTier } from '../fixtures'; +import { getCharge, getInvoice, getUser, newTier } from '../fixtures'; import { handleCancelPlan } from '../../../src/webhooks/utils/handleCancelPlan'; import handleLifetimeRefunded from '../../../src/webhooks/handleLifetimeRefunded'; import { FREE_PLAN_BYTES_SPACE } from '../../../src/constants'; @@ -8,7 +8,6 @@ import { createTestServices } from '../helpers/services-factory'; jest.mock('../../../src/webhooks/utils/handleCancelPlan'); -const logger = getLogger(); const { paymentService, usersService, storageService, tiersService, cacheService, preCreatedUserService } = createTestServices(); @@ -37,7 +36,6 @@ describe('Process when a lifetime is refunded', () => { mockedCharge, cacheService, paymentService, - logger, tiersService, preCreatedUserService, ); @@ -51,7 +49,6 @@ describe('Process when a lifetime is refunded', () => { isLifetime: mockedUser.lifetime, usersService: usersService, tiersService: tiersService, - log: logger, preCreatedUserService, }); }); @@ -85,7 +82,6 @@ describe('Process when a lifetime is refunded', () => { mockedCharge, cacheService, paymentService, - logger, tiersService, preCreatedUserService, ); @@ -118,7 +114,6 @@ describe('Process when a lifetime is refunded', () => { mockedCharge, cacheService, paymentService, - logger, tiersService, preCreatedUserService, ), diff --git a/tests/src/webhooks/handleSubscriptionCanceled.test.ts b/tests/src/webhooks/handleSubscriptionCanceled.test.ts index 4042ad67..b4a4db92 100644 --- a/tests/src/webhooks/handleSubscriptionCanceled.test.ts +++ b/tests/src/webhooks/handleSubscriptionCanceled.test.ts @@ -1,6 +1,5 @@ import { TierNotFoundError } from '../../../src/services/tiers.service'; -import { FastifyBaseLogger } from 'fastify'; -import { getCreatedSubscription, getCustomer, getLogger, getProduct, getUser, newTier } from '../fixtures'; +import { getCreatedSubscription, getCustomer, getProduct, getUser, newTier } from '../fixtures'; import handleSubscriptionCanceled from '../../../src/webhooks/handleSubscriptionCanceled'; import { handleCancelPlan } from '../../../src/webhooks/utils/handleCancelPlan'; import { FREE_PLAN_BYTES_SPACE } from '../../../src/constants'; @@ -10,8 +9,6 @@ import { Customer } from '../../../src/infrastructure/domain/entities/customer'; jest.mock('../../../src/webhooks/utils/handleCancelPlan'); -const logger: jest.Mocked = getLogger(); - const { paymentService, usersService, @@ -47,7 +44,6 @@ describe('Process when a subscription is cancelled', () => { cacheService, objectStorageService, tiersService, - logger, preCreatedUserService, ); @@ -60,7 +56,6 @@ describe('Process when a subscription is cancelled', () => { productId: mockedSubscription.items.data[0].price.product, usersService, tiersService, - log: logger, preCreatedUserService, }); }); @@ -97,7 +92,6 @@ describe('Process when a subscription is cancelled', () => { cacheService, objectStorageService, tiersService, - logger, preCreatedUserService, ); @@ -133,7 +127,6 @@ describe('Process when a subscription is cancelled', () => { cacheService, objectStorageService, tiersService, - logger, preCreatedUserService, ), ).rejects.toThrow(randomError); diff --git a/tests/src/webhooks/utils/handleCancelPlan.test.ts b/tests/src/webhooks/utils/handleCancelPlan.test.ts index 50b787c6..4d12ecbd 100644 --- a/tests/src/webhooks/utils/handleCancelPlan.test.ts +++ b/tests/src/webhooks/utils/handleCancelPlan.test.ts @@ -1,5 +1,5 @@ import { TierNotFoundError } from '../../../../src/services/tiers.service'; -import { getCustomer, getLogger, getUser, newTier, voidPromise } from '../../fixtures'; +import { getCustomer, getUser, newTier, voidPromise } from '../../fixtures'; import { handleCancelPlan } from '../../../../src/webhooks/utils/handleCancelPlan'; import { createTestServices } from '../../helpers/services-factory'; import { getPreCreatedUserEntity } from '../../entity.fixtures'; @@ -18,7 +18,6 @@ beforeEach(() => { describe('Handling canceled plans and refunded lifetimes', () => { it('When the tier id to remove the user-tier relationship does not exists, then an error indicating so is thrown', async () => { const mockedCustomer = getCustomer(); - const log = getLogger(); const mockedUser = getUser({ customerId: mockedCustomer.id, lifetime: false }); const mockedTier = newTier(); const mockedRandomTier = newTier({ @@ -39,7 +38,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { productId: mockedRandomTier.productId, tiersService, usersService, - log, preCreatedUserService, }), ).rejects.toThrow(TierNotFoundError); @@ -48,7 +46,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { expect(removeTierSpy).toHaveBeenCalledWith( { ...mockedUser, email: mockedCustomer.email as string }, mockedRandomTier.productId, - log, ); expect(userTiersSpy).toHaveBeenCalledWith(mockedUser.id); expect(deleteTierFromUserSpy).not.toHaveBeenCalled(); @@ -56,7 +53,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { it('When the user cancels a subscription, then the tier is removed and the free space is applied', async () => { const mockedCustomer = getCustomer(); - const log = getLogger(); const mockedUser = getUser({ customerId: mockedCustomer.id, lifetime: false }); const mockedTier = newTier(); @@ -73,7 +69,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { productId: mockedTier.productId, tiersService, usersService, - log, preCreatedUserService, }); @@ -81,7 +76,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { expect(removeTierSpy).toHaveBeenCalledWith( { ...mockedUser, email: mockedCustomer.email as string }, mockedTier.productId, - log, ); expect(userTiersSpy).toHaveBeenCalledWith(mockedUser.id); expect(deleteTierFromUserSpy).toHaveBeenCalledWith(mockedUser.id, mockedTier.id); @@ -89,7 +83,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { it('When the user cancels a lifetime (refund), then the lifetime field is set to false, the tier is removed and the free space is applied', async () => { const mockedCustomer = getCustomer(); - const log = getLogger(); const mockedUser = getUser({ customerId: mockedCustomer.id, lifetime: true }); const mockedTier = newTier({ billingType: 'lifetime' }); @@ -111,7 +104,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { productId: mockedTier.productId, tiersService, usersService, - log, preCreatedUserService, }); @@ -120,7 +112,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { expect(removeTierSpy).toHaveBeenCalledWith( { ...mockedUser, email: mockedCustomer.email as string }, mockedTier.productId, - log, ); expect(userTiersSpy).toHaveBeenCalledWith(mockedUser.id); expect(deleteTierFromUserSpy).toHaveBeenCalledWith(mockedUser.id, mockedTier.id); @@ -129,7 +120,6 @@ describe('Handling canceled plans and refunded lifetimes', () => { describe('Cancelling the pre-created user', () => { const setUpCancellation = () => { const mockedCustomer = getCustomer(); - const log = getLogger(); const mockedUser = getUser({ customerId: mockedCustomer.id, lifetime: false }); const mockedTier = newTier(); @@ -141,14 +131,12 @@ describe('Handling canceled plans and refunded lifetimes', () => { jest.spyOn(tiersService, 'deleteTierFromUser').mockImplementation(voidPromise); return { - log, params: { customerEmail: mockedCustomer.email as string, customerId: mockedCustomer.id, productId: mockedTier.productId, tiersService, usersService, - log, preCreatedUserService, }, }; diff --git a/tests/src/webhooks/webhook.test.ts b/tests/src/webhooks/webhook.test.ts index 0165a5e6..e2ded225 100644 --- a/tests/src/webhooks/webhook.test.ts +++ b/tests/src/webhooks/webhook.test.ts @@ -61,7 +61,6 @@ describe('Webhook events', () => { expect.any(PaymentService), expect.any(ObjectStorageService), expect.any(Stripe), - app.log, ); }); @@ -96,7 +95,6 @@ describe('Webhook events', () => { expect.any(ObjectStorageService), expect.any(PaymentService), expect.any(UsersService), - app.log, ); });