From 37a5464b1f98449ef27f36f8200232bb47669367 Mon Sep 17 00:00:00 2001 From: Sam Huynh Date: Thu, 7 Mar 2024 16:50:06 +1100 Subject: [PATCH] feat: block user from adding referral code if they have added for that service already --- src/commands/referral/referralNew.test.ts | 32 +++++++++++++++++++++++ src/commands/referral/referralNew.ts | 13 +++++++++ 2 files changed, 45 insertions(+) diff --git a/src/commands/referral/referralNew.test.ts b/src/commands/referral/referralNew.test.ts index 9d0139c1..cd312bf2 100644 --- a/src/commands/referral/referralNew.test.ts +++ b/src/commands/referral/referralNew.test.ts @@ -120,6 +120,38 @@ describe('execute', () => { expect(mockChatInputInteraction.reply).toBeCalledWith('expiry_date has already expired'); }); + it('should block adding referral code if the user already has one', async () => { + const data = { + service: services[0], + code: 'SomeCodeHere', + expiry_date: `04/04/${new Date().getFullYear() + 1}`, + userId: '1234', + }; + + const mockPrismaClient = mockDeep(); + mockPrismaClient.referralCode.findFirst.mockResolvedValueOnce({ + id: '12345', + service: data.service, + code: data.code, + expiry_date: new Date(data.expiry_date), + userId: data.userId, + }); + mockGetDbClient.mockReturnValueOnce(mockPrismaClient); + + mockChatInputInteraction.user.id = data.userId; + mockChatInputInteraction.options.getString.mockImplementation((name: string, required?: boolean) => { + if (name === 'service') return data.service; + if (name === 'link_or_code') return data.code; + if (name === 'expiry_date') return data.expiry_date; + + return null; + }); + + await execute(mockChatInputInteraction); + + expect(mockChatInputInteraction.reply).toBeCalledWith(`You have already entered the referral code for ${services[0]}.`); + }); + it('should create a new referral code', async () => { const data = { service: services[0], diff --git a/src/commands/referral/referralNew.ts b/src/commands/referral/referralNew.ts index 1383446c..d1ad7686 100644 --- a/src/commands/referral/referralNew.ts +++ b/src/commands/referral/referralNew.ts @@ -67,6 +67,19 @@ export const execute: CommandHandler = async (interaction) => { const userId = interaction.user.id; const nickname = interaction.user.displayName; + const existingReferralCode = await db.referralCode.findFirst({ + where: { + service, + userId, + }, + }); + + if (existingReferralCode) { + logger.error(`[referral-new]: Referral code for ${service} by ${nickname} already exists.`); + await interaction.reply(`You have already entered the referral code for ${service}.`); + return; + } + try { const newReferralCode = await db.referralCode.create({ data: {