diff --git a/components/Invite/__tests__/inviteCopy.test.ts b/components/Invite/__tests__/inviteCopy.test.ts index b7a53082e..950faef59 100644 --- a/components/Invite/__tests__/inviteCopy.test.ts +++ b/components/Invite/__tests__/inviteCopy.test.ts @@ -67,6 +67,51 @@ describe('inviteCopy', () => { }); }); +describe('inviteCopy with a KOL perk', () => { + const perk = { + tierDiscountPct: 50, + sepaFreeMonths: 1, + sepaFreeCapUsd: 10000, + endsAt: '2026-12-23T00:00:00.000Z', + }; + + it('leads with the discount, then the free SEPA and the card bonus', () => { + const copy = inviteCopy({ ...v4, code: 'ARTEM50', perk }); + + expect(copy.inviter).toBe('eli'); + expect(headline(copy.title)).toBe('Get 50% off your first\nyear of Prime or Ultra'); + expect(copy.title.filter(part => part.accent).map(part => part.text)).toEqual(['50% off']); + expect(copy.subtitle).toBe( + 'Plus free SEPA deposits for your first month, up to $10,000. And spend $150 in your first 30 days for a $10 card bonus.', + ); + expect(copy.steps).toEqual([ + 'Create your account', + 'Deposit euros by SEPA with no fee', + 'Upgrade to Prime or Ultra for 50% off', + ]); + expect(copy.footnote).toBe('For new accounts created by 23 Dec.'); + }); + + it('leads with free SEPA when there is no discount', () => { + const copy = inviteCopy({ ...v4, perk: { ...perk, tierDiscountPct: 0, sepaFreeMonths: 3 } }); + expect(headline(copy.title)).toBe('Free SEPA deposits\nfor your first 3 months'); + expect( + copy.subtitle.startsWith('Free SEPA deposits for your first 3 months, up to $10,000.'), + ).toBe(true); + expect(copy.steps).toEqual([ + 'Create your account', + 'Deposit euros by SEPA with no fee', + 'Get your free card', + ]); + }); + + it('falls back to the normal invite on a malformed perk', () => { + expect(headline(inviteCopy({ ...v4, perk: { tierDiscountPct: 'x' } }).title)).toBe( + 'Get $10 to spend\nwith your card', + ); + }); +}); + describe('inviterInitial', () => { it('upper-cases the first character', () => { expect(inviterInitial('eli')).toBe('E'); diff --git a/components/Invite/inviteCopy.ts b/components/Invite/inviteCopy.ts index 1087691cb..e4674181f 100644 --- a/components/Invite/inviteCopy.ts +++ b/components/Invite/inviteCopy.ts @@ -1,3 +1,9 @@ +import { + perkDay, + readInvitePerk, + sepaPerkPhrase, + sepaPerkSentence, +} from '@/lib/referral/invitePerk'; import { formatUsdWhole } from '@/lib/referral/referralV4'; import type { ReferralInviteLookup } from '@/lib/types'; @@ -17,9 +23,63 @@ export interface InviteCopy { footnote: string | null; } -/** What the page says, from the lookup: v4's card bonus, the cashback offer, or a plain welcome. */ +/** + * What the page says, from the lookup: a KOL's invite perk, v4's card bonus, + * the cashback offer, or a plain welcome. + */ export const inviteCopy = (lookup: ReferralInviteLookup | undefined): InviteCopy => { const inviter = lookup?.valid ? lookup.referrer.username : null; + const perk = lookup?.valid ? readInvitePerk(lookup.perk) : null; + + // A KOL's perk code leads with the perk; the referral offer still applies + // and is mentioned after it. + if (lookup?.valid && perk) { + const title: InviteTitlePart[] = + perk.tierDiscountPct > 0 + ? [ + { text: 'Get ' }, + { text: `${perk.tierDiscountPct}% off`, accent: true }, + { text: ' your first\nyear of Prime or Ultra' }, + ] + : [ + { text: 'Free ' }, + { text: 'SEPA deposits', accent: true }, + { + text: `\nfor your first ${perk.sepaFreeMonths === 1 ? 'month' : `${perk.sepaFreeMonths} months`}`, + }, + ]; + const sentences: string[] = []; + if (perk.tierDiscountPct > 0 && perk.sepaFreeMonths > 0) { + sentences.push(`Plus ${sepaPerkPhrase(perk)}.`); + } else if (perk.tierDiscountPct > 0) { + sentences.push('The discount applies to your first year of membership.'); + } else { + sentences.push(`${sepaPerkSentence(perk)}.`); + } + if (lookup.offer) { + sentences.push( + `And spend ${formatUsdWhole(lookup.offer.spendTargetUsd)} in your first ${lookup.offer.windowDays} days for a ${formatUsdWhole(lookup.offer.friendCreditUsd)} card bonus.`, + ); + } else if (lookup.legacyOffer) { + sentences.push( + `And spend ${formatUsdWhole(lookup.legacyOffer.spendTargetUsd)} in your first ${lookup.legacyOffer.windowDays} days to get ${formatUsdWhole(lookup.legacyOffer.friendRewardUsd)} in ${lookup.legacyOffer.payoutToken}.`, + ); + } + const steps = ['Create your account']; + if (perk.sepaFreeMonths > 0) steps.push('Deposit euros by SEPA with no fee'); + if (perk.tierDiscountPct > 0) { + steps.push(`Upgrade to Prime or Ultra for ${perk.tierDiscountPct}% off`); + } + if (steps.length < 3) steps.push('Get your free card'); + const lastDay = perkDay(perk.endsAt); + return { + inviter, + title, + subtitle: sentences.join(' '), + steps, + footnote: lastDay ? `For new accounts created by ${lastDay}.` : null, + }; + } if (lookup?.valid && lookup.offer) { const { friendCreditUsd, spendTargetUsd, merchantTarget, windowDays } = lookup.offer; diff --git a/components/Rewards/NewRewards/UpgradeTier/UpgradeReviewContent.tsx b/components/Rewards/NewRewards/UpgradeTier/UpgradeReviewContent.tsx index 4f769bbfb..a934c0bd7 100644 --- a/components/Rewards/NewRewards/UpgradeTier/UpgradeReviewContent.tsx +++ b/components/Rewards/NewRewards/UpgradeTier/UpgradeReviewContent.tsx @@ -28,6 +28,7 @@ import { canPayCashFor, findOffer, formatFuse, + formatInviteDiscount, formatLockDuration, formatRenewalTerms, formatSaleEnds, @@ -328,7 +329,7 @@ const UpgradeReviewContent = () => { {/* A bridged payment that landed short: what the bridge took comes diff --git a/components/Rewards/NewRewards/UpgradeTier/UpgradeTierContent.tsx b/components/Rewards/NewRewards/UpgradeTier/UpgradeTierContent.tsx index 1e3f3e344..2f9f781c7 100644 --- a/components/Rewards/NewRewards/UpgradeTier/UpgradeTierContent.tsx +++ b/components/Rewards/NewRewards/UpgradeTier/UpgradeTierContent.tsx @@ -41,6 +41,7 @@ import { membershipDateLabel, nextPurchasableTier, offerFirstYearFeeUsd, + offerInviteDiscount, offerPaymentMode, remainingFuseForTier, } from '@/lib/tierUpgrade'; @@ -321,7 +322,9 @@ const UpgradeTierContent = ({ onRouteSelected, onTopUp }: UpgradeTierContentProp listPriceUsd={offer.annualFeeUsd} secondaryValue={ isOfferOnSale(offer) && offer.annualFeeUsd !== null - ? `First year, then ${formatPriceUsd(offer.annualFeeUsd)}/year` + ? offerInviteDiscount(offer) + ? `First year with ${offerInviteDiscount(offer)?.pct}% invite discount, then ${formatPriceUsd(offer.annualFeeUsd)}/year` + : `First year, then ${formatPriceUsd(offer.annualFeeUsd)}/year` : undefined } /> diff --git a/components/Signup/InviteCodeField.tsx b/components/Signup/InviteCodeField.tsx index 9e9dfbb5a..674a9d88a 100644 --- a/components/Signup/InviteCodeField.tsx +++ b/components/Signup/InviteCodeField.tsx @@ -4,6 +4,7 @@ import * as Clipboard from 'expo-clipboard'; import Input from '@/components/ui/input'; import { Text } from '@/components/ui/text'; import { parseInviteCodeFromText } from '@/lib/referral/inviteCode'; +import { invitePerkShort, readInvitePerk } from '@/lib/referral/invitePerk'; import { formatUsdWhole } from '@/lib/referral/referralV4'; import { cn } from '@/lib/utils'; @@ -17,9 +18,11 @@ export type InviteCodeStatus = /** The lookup itself failed: say nothing, signup sends the code and the backend decides. */ | { kind: 'unverified' }; -/** "Dana invited you · $10 card bonus". */ +/** "Dana invited you · $10 card bonus", or "· 50% off Prime & Ultra + free SEPA" for a KOL's perk code. */ const validLine = (lookup: Extract) => { const who = `${lookup.referrer.username} invited you`; + const perk = readInvitePerk(lookup.perk); + if (perk) return `${who} · ${invitePerkShort(perk)}`; if (lookup.offer) return `${who} · ${formatUsdWhole(lookup.offer.friendCreditUsd)} card bonus`; if (lookup.legacyOffer) { return `${who} · ${formatUsdWhole(lookup.legacyOffer.friendRewardUsd)} in ${lookup.legacyOffer.payoutToken}`; diff --git a/components/WirexBankAccount/KolPerkNotice.tsx b/components/WirexBankAccount/KolPerkNotice.tsx new file mode 100644 index 000000000..d8ced4aca --- /dev/null +++ b/components/WirexBankAccount/KolPerkNotice.tsx @@ -0,0 +1,19 @@ +import { View } from 'react-native'; + +import { Text } from '@/components/ui/text'; + +/** + * "Your SEPA deposits are free until 23 Dec" on the euro account screen, while + * the user's KOL invite perk covers their deposits. Same look as the fee + * promotion notice, and shown in its place: the perk is the user's own and is + * used first. + */ +export const KolPerkNotice = ({ title, body }: { title: string; body: string }) => ( + + {title} + {body} + +); diff --git a/components/WirexBankAccount/WirexBankAccountDetails.tsx b/components/WirexBankAccount/WirexBankAccountDetails.tsx index 6a0d71b61..de67c61ef 100644 --- a/components/WirexBankAccount/WirexBankAccountDetails.tsx +++ b/components/WirexBankAccount/WirexBankAccountDetails.tsx @@ -10,11 +10,12 @@ import { DEPOSIT_MODAL } from '@/constants/modals'; import { path } from '@/constants/path'; import { TRACKING_EVENTS } from '@/constants/tracking-events'; import { useConfirmResidence } from '@/hooks/useConfirmResidence'; -import { useEurDepositPromotion } from '@/hooks/useProductFees'; +import { useEurDepositPromotion, useKolPerk } from '@/hooks/useProductFees'; import { useActivateWirexBankAccount, useWirexBankOverview } from '@/hooks/useWirexBankAccounts'; import { useWirexWalletLink } from '@/hooks/useWirexWalletLink'; import { track } from '@/lib/analytics'; import { getAsset } from '@/lib/assets'; +import { kolSepaPerkCopy } from '@/lib/referral/invitePerk'; import { WirexBankAccountType, WirexBankRailStatusDto } from '@/lib/types/wirex-bank'; import { cn } from '@/lib/utils'; import { useCountryStore } from '@/store/useCountryStore'; @@ -22,6 +23,7 @@ import { useDepositStore } from '@/store/useDepositStore'; import { useKycStore } from '@/store/useKycStore'; import { FeePromotionNotice } from './FeePromotionNotice'; +import { KolPerkNotice } from './KolPerkNotice'; import { detailRows, RAIL_PRESENTATION, @@ -161,6 +163,8 @@ export const WirexBankAccountDetails = ({ const walletLink = useWirexWalletLink(); // Free SEPA deposits, while a promotion runs and the user has some left. const eurPromotion = useEurDepositPromotion(); + // Free SEPA from a KOL's invite perk, which is used before any promotion. + const kolSepaCopy = kolSepaPerkCopy(useKolPerk()); const router = useRouter(); const setModal = useDepositStore(state => state.setModal); const countrySource = useCountryStore(state => state.countryInfo?.source); @@ -422,7 +426,9 @@ export const WirexBankAccountDetails = ({ rows={detailRows(activeRail)} header={switcher} notice={ - activeRail.accountType === WirexBankAccountType.SEPA && eurPromotion ? ( + activeRail.accountType !== WirexBankAccountType.SEPA ? null : kolSepaCopy ? ( + + ) : eurPromotion ? ( ) : null } diff --git a/hooks/__tests__/useKolPerk.test.tsx b/hooks/__tests__/useKolPerk.test.tsx new file mode 100644 index 000000000..b96b80200 --- /dev/null +++ b/hooks/__tests__/useKolPerk.test.tsx @@ -0,0 +1,77 @@ +import React from 'react'; + +import { useKolPerk } from '@/hooks/useProductFees'; + +const { act, create } = jest.requireActual('react-test-renderer'); +let mockQuery: { data: unknown; isError: boolean }; +let perk: ReturnType; +let root: any; +jest.mock('@tanstack/react-query', () => ({ + useQuery: () => mockQuery, + useMutation: jest.fn(), +})); +jest.mock('@/store/useUserStore', () => ({ + useUserStore: (selector: any) => selector({ users: [{ selected: true, userId: 'account-a' }] }), +})); +jest.mock('@/lib/api', () => ({ + fetchFeePromotions: jest.fn(), + fetchKolPerk: jest.fn(), + fetchProductFeeRates: jest.fn(), + recordSwapFee: jest.fn(), +})); +jest.mock('@/lib/utils', () => ({ withRefreshToken: jest.fn() })); + +const ACTIVE = { + kolUsername: 'artem.betev', + grantedAt: '2026-11-23T12:00:00.000Z', + tierDiscount: null, + sepa: { + freeUntil: '2026-12-23T12:00:00.000Z', + capUsd: 10000, + coveredUsd: 0, + remainingUsd: 10000, + waivedFeeUsd: 0, + active: true, + }, +}; + +function Probe() { + const value = useKolPerk(); + React.useEffect(() => { + perk = value; + }, [value]); + return null; +} +const render = () => act(() => root.update()); + +beforeEach(() => { + mockQuery = { data: ACTIVE, isError: false }; + act(() => { + root = create(); + }); +}); +afterEach(() => { + act(() => root.unmount()); +}); + +it('shows the perk it read', () => { + expect(perk).toBe(ACTIVE); +}); + +it('hides the perk once a refresh fails, though the last read is still cached', () => { + // TanStack Query keeps `data` from the last success when a refetch fails. + mockQuery = { data: ACTIVE, isError: true }; + render(); + expect(perk).toBeNull(); + + // A later refresh that succeeds shows it again. + mockQuery = { data: ACTIVE, isError: false }; + render(); + expect(perk).toBe(ACTIVE); +}); + +it('shows nothing before the first read', () => { + mockQuery = { data: undefined, isError: false }; + render(); + expect(perk).toBeNull(); +}); diff --git a/hooks/useProductFees.ts b/hooks/useProductFees.ts index d04379cc1..62fde361e 100644 --- a/hooks/useProductFees.ts +++ b/hooks/useProductFees.ts @@ -2,7 +2,8 @@ import { useEffect, useState } from 'react'; import { useMutation, useQuery } from '@tanstack/react-query'; import { minutesToMilliseconds, secondsToMilliseconds } from 'date-fns'; -import { fetchFeePromotions, fetchProductFeeRates, recordSwapFee } from '@/lib/api'; +import { fetchFeePromotions, fetchKolPerk, fetchProductFeeRates, recordSwapFee } from '@/lib/api'; +import { readUserKolPerk } from '@/lib/referral/invitePerk'; import { FeeProduct, RecordSwapFeeParams } from '@/lib/types'; import { withRefreshToken } from '@/lib/utils'; import { eurDepositPromotion, nextEurPromotionChange } from '@/lib/utils/feePromotion'; @@ -88,6 +89,29 @@ export const useEurDepositPromotion = () => { return eurDepositPromotion(data ?? null, now); }; +/** + * The user's KOL invite perk, or null — none, not loaded yet, or a failed + * load (the screen then simply doesn't advertise it). Polled like the fee + * promotions, so a deposit that uses up the cap reaches an open screen. + * A failed refresh hides it too: the perk it last read may since have run + * out, and a later refresh that succeeds shows it again. + */ +export const useKolPerk = () => { + const userId = useSelectedUserId(); + + const { data, isError } = useQuery({ + queryKey: [PRODUCT_FEES, 'kolPerk', userId], + queryFn: async () => readUserKolPerk(await withRefreshToken(() => fetchKolPerk())), + staleTime: secondsToMilliseconds(60), + refetchInterval: secondsToMilliseconds(60), + refetchIntervalInBackground: false, + gcTime: minutesToMilliseconds(5), + enabled: Boolean(userId), + retry: false, + }); + return isError ? null : (data ?? null); +}; + /** * The swap fee rate for this user, and where the fee must be sent. * diff --git a/lib/__tests__/invitePerk.test.ts b/lib/__tests__/invitePerk.test.ts new file mode 100644 index 000000000..71d75c50c --- /dev/null +++ b/lib/__tests__/invitePerk.test.ts @@ -0,0 +1,146 @@ +import { + inviteDiscountLine, + invitePerkShort, + kolSepaPerkCopy, + perkDay, + readInvitePerk, + readUserKolPerk, + sepaPerkSentence, +} from '@/lib/referral/invitePerk'; + +describe('readInvitePerk', () => { + it('reads a perk', () => { + expect( + readInvitePerk({ + tierDiscountPct: 50, + sepaFreeMonths: 1, + sepaFreeCapUsd: 10000, + endsAt: '2026-12-23T00:00:00.000Z', + }), + ).toEqual({ + tierDiscountPct: 50, + sepaFreeMonths: 1, + sepaFreeCapUsd: 10000, + endsAt: '2026-12-23T00:00:00.000Z', + }); + }); + + it('treats a missing, empty or malformed perk as none', () => { + expect(readInvitePerk(undefined)).toBeNull(); + expect(readInvitePerk(null)).toBeNull(); + expect(readInvitePerk('50%')).toBeNull(); + expect(readInvitePerk({ tierDiscountPct: 0, sepaFreeMonths: 0 })).toBeNull(); + expect(readInvitePerk({ tierDiscountPct: 'lots', sepaFreeMonths: -1 })).toBeNull(); + expect(readInvitePerk({ tierDiscountPct: 20 })).toEqual({ + tierDiscountPct: 20, + sepaFreeMonths: 0, + sepaFreeCapUsd: 0, + endsAt: '', + }); + }); + + it('never offers free SEPA months without a readable cap', () => { + for (const sepaFreeCapUsd of ['10000', null, -5, 0, undefined]) { + // Only the SEPA part: no perk at all. + expect(readInvitePerk({ sepaFreeMonths: 1, sepaFreeCapUsd })).toBeNull(); + // With a discount: the discount alone. + expect(readInvitePerk({ tierDiscountPct: 50, sepaFreeMonths: 1, sepaFreeCapUsd })).toEqual({ + tierDiscountPct: 50, + sepaFreeMonths: 0, + sepaFreeCapUsd: 0, + endsAt: '', + }); + } + }); +}); + +describe('readUserKolPerk', () => { + const perk = { + kolUsername: 'artem.betev', + grantedAt: '2026-11-23T12:00:00.000Z', + tierDiscount: { pct: 50, available: true }, + sepa: { + freeUntil: '2026-12-23T12:00:00.000Z', + capUsd: 10000, + coveredUsd: 2500, + remainingUsd: 7500, + waivedFeeUsd: 12.5, + active: true, + }, + }; + + it('reads the user’s perk', () => { + expect(readUserKolPerk({ perk })).toEqual(perk); + }); + + it('reads none from null, junk or a perk with no benefits', () => { + expect(readUserKolPerk({ perk: null })).toBeNull(); + expect(readUserKolPerk(undefined)).toBeNull(); + expect(readUserKolPerk({ perk: { kolUsername: 'x' } })).toBeNull(); + expect(readUserKolPerk({ perk: { ...perk, kolUsername: 7 } })).toBeNull(); + }); + + it('never reads an unclear flag as active', () => { + const read = readUserKolPerk({ perk: { ...perk, sepa: { ...perk.sepa, active: 'yes' } } }); + expect(read?.sepa?.active).toBe(false); + }); +}); + +describe('copy', () => { + it('says the perk on one line', () => { + expect( + invitePerkShort({ tierDiscountPct: 50, sepaFreeMonths: 1, sepaFreeCapUsd: 1, endsAt: '' }), + ).toBe('50% off Prime & Ultra + free SEPA'); + expect( + invitePerkShort({ tierDiscountPct: 0, sepaFreeMonths: 2, sepaFreeCapUsd: 1, endsAt: '' }), + ).toBe('free SEPA'); + }); + + it('words the free SEPA months', () => { + expect(sepaPerkSentence({ sepaFreeMonths: 1, sepaFreeCapUsd: 10000 })).toBe( + 'Free SEPA deposits for your first month, up to $10,000', + ); + expect(sepaPerkSentence({ sepaFreeMonths: 3, sepaFreeCapUsd: 0 })).toBe( + 'Free SEPA deposits for your first 3 months', + ); + }); + + it('builds the euro account notice only while the perk is active', () => { + const perk = readUserKolPerk({ + perk: { + kolUsername: 'artem.betev', + grantedAt: '', + tierDiscount: null, + sepa: { + freeUntil: '2026-12-23T12:00:00.000Z', + capUsd: 10000, + coveredUsd: 2500, + remainingUsd: 7500.75, + waivedFeeUsd: 0, + active: true, + }, + }, + }); + expect(kolSepaPerkCopy(perk)).toEqual({ + title: 'Your SEPA deposits are free until 23 Dec', + body: "€0 fee on your next $7,500 of deposits, thanks to artem.betev's invite.", + }); + expect(kolSepaPerkCopy(null)).toBeNull(); + expect( + kolSepaPerkCopy(perk && { ...perk, sepa: perk.sepa && { ...perk.sepa, active: false } }), + ).toBeNull(); + }); + + it('words the invite discount', () => { + expect(inviteDiscountLine({ pct: 50, inviterUsername: 'artem.betev' })).toBe( + "50% off your first year with artem.betev's invite", + ); + expect(inviteDiscountLine({ pct: 50, inviterUsername: '' })).toBe('50% off your first year'); + expect(inviteDiscountLine(null)).toBe(''); + }); + + it('formats a UTC day', () => { + expect(perkDay('2026-12-23T23:30:00.000Z')).toBe('23 Dec'); + expect(perkDay('not a date')).toBe(''); + }); +}); diff --git a/lib/__tests__/tierUpgrade.test.ts b/lib/__tests__/tierUpgrade.test.ts index 6862b37d8..a6e764183 100644 --- a/lib/__tests__/tierUpgrade.test.ts +++ b/lib/__tests__/tierUpgrade.test.ts @@ -6,6 +6,7 @@ import { formatFuse, formatFuseHeld, formatFuseShortfall, + formatInviteDiscount, formatLockDuration, formatMembershipDate, formatMembershipDay, @@ -24,6 +25,7 @@ import { membershipDateLabel, nextPurchasableTier, offerFirstYearFeeUsd, + offerInviteDiscount, offerMandateUsd, offerPaymentMode, remainingFuseForTier, @@ -609,3 +611,34 @@ describe('formatting', () => { expect(formatLockDuration(0)).toBe(''); }); }); + +describe('offerInviteDiscount', () => { + it('reads the KOL invite discount that prices the first year', () => { + const discounted = offer({ + firstYearFeeUsd: 99.5, + inviteDiscount: { pct: 50, inviterUsername: 'artem.betev' }, + }); + expect(offerInviteDiscount(discounted)).toEqual({ pct: 50, inviterUsername: 'artem.betev' }); + expect(formatInviteDiscount(discounted)).toBe( + "50% off your first year with artem.betev's invite", + ); + // No sale-style end: the invite line is what explains the price. + expect(formatSaleEnds(discounted)).toBe(''); + }); + + it('ignores a discount that does not lower the price, or is malformed', () => { + expect( + offerInviteDiscount(offer({ inviteDiscount: { pct: 50, inviterUsername: 'x' } })), + ).toBeNull(); + expect( + offerInviteDiscount( + offer({ + firstYearFeeUsd: 99.5, + inviteDiscount: { pct: Number.NaN, inviterUsername: 'x' }, + }), + ), + ).toBeNull(); + expect(offerInviteDiscount(offer({ firstYearFeeUsd: 99.5, inviteDiscount: null }))).toBeNull(); + expect(formatInviteDiscount(undefined)).toBe(''); + }); +}); diff --git a/lib/api.ts b/lib/api.ts index 40d3b316c..24744a9ad 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -3004,6 +3004,26 @@ export const fetchFeePromotions = async (): Promise = return response.json(); }; +/** + * The user's own KOL invite perk — the membership discount they can still + * take and their free SEPA months — as `{ perk }`, `perk` null when they hold + * none. Untrusted: read it through `readUserKolPerk`. + */ +export const fetchKolPerk = async (): Promise => { + const jwt = getJWTToken(); + const response = await fetch(`${EXPO_PUBLIC_FLASH_API_BASE_URL}/accounts/v1/kol-perks/me`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + ...getPlatformHeaders(), + ...(jwt ? { Authorization: `Bearer ${jwt}` } : {}), + }, + credentials: 'include', + }); + if (!response.ok) throw response; + return response.json(); +}; + /** What this user would pay on a given amount, right now. */ export const fetchProductFeeQuote = async ( product: FeeProduct, diff --git a/lib/referral/invitePerk.ts b/lib/referral/invitePerk.ts new file mode 100644 index 000000000..a0f762271 --- /dev/null +++ b/lib/referral/invitePerk.ts @@ -0,0 +1,165 @@ +/** + * KOL invite perks: what a KOL's special referral code adds for a friend who + * signs up with it — a discount on the first year of a Prime or Ultra + * membership, and free SEPA deposits to the euro account for their first + * months, up to a cap. UI-free so Jest can import it. + * + * Everything here reads network data, so every reader tolerates a missing, + * null or malformed field and treats it as "no perk". + */ + +/** What a perk code would grant someone signing up now (`GET /referral/invite/:code`). */ +export interface InvitePerk { + /** Off the first year of the first membership; 0 when none. */ + tierDiscountPct: number; + /** Months of free SEPA deposits from signing up; 0 when none. */ + sepaFreeMonths: number; + /** The most deposit volume, in USD, those months make free. */ + sepaFreeCapUsd: number; + /** Signups after this get no perk. */ + endsAt: string; +} + +/** The signed-in user's own perk (`GET /kol-perks/me`). */ +export interface UserKolPerk { + kolUsername: string; + grantedAt: string; + tierDiscount: { pct: number; available: boolean } | null; + sepa: { + freeUntil: string; + capUsd: number; + coveredUsd: number; + remainingUsd: number; + waivedFeeUsd: number; + /** The next SEPA deposit would be free: in the window, under the cap, on a plan that pays a fee. */ + active: boolean; + } | null; +} + +const isCount = (value: unknown): value is number => + typeof value === 'number' && Number.isFinite(value) && value >= 0; + +/** An invite lookup's `perk`, or null when absent or unusable. */ +export function readInvitePerk(raw: unknown): InvitePerk | null { + if (!raw || typeof raw !== 'object') return null; + const perk = raw as Partial; + const tierDiscountPct = isCount(perk.tierDiscountPct) ? Math.round(perk.tierDiscountPct) : 0; + // Free months always come with a cap above zero; without a readable one + // the SEPA part is not offered, rather than offered without a limit. + const capUsd = isCount(perk.sepaFreeCapUsd) ? perk.sepaFreeCapUsd : 0; + const months = isCount(perk.sepaFreeMonths) ? Math.round(perk.sepaFreeMonths) : 0; + const sepaFreeMonths = capUsd > 0 ? months : 0; + const sepaFreeCapUsd = sepaFreeMonths > 0 ? capUsd : 0; + if (tierDiscountPct <= 0 && sepaFreeMonths <= 0) return null; + return { + tierDiscountPct, + sepaFreeMonths, + sepaFreeCapUsd, + endsAt: typeof perk.endsAt === 'string' ? perk.endsAt : '', + }; +} + +/** `GET /kol-perks/me`'s `perk`, or null when absent or unusable. */ +export function readUserKolPerk(raw: unknown): UserKolPerk | null { + const perk = (raw as { perk?: unknown } | null | undefined)?.perk as + | Partial + | null + | undefined; + if (!perk || typeof perk !== 'object' || typeof perk.kolUsername !== 'string') return null; + + const tier = perk.tierDiscount as Partial> | null; + const tierDiscount = + tier && typeof tier === 'object' && isCount(tier.pct) && tier.pct > 0 + ? { pct: Math.round(tier.pct), available: tier.available === true } + : null; + + const sepaRaw = perk.sepa as Partial> | null; + const sepa = + sepaRaw && + typeof sepaRaw === 'object' && + typeof sepaRaw.freeUntil === 'string' && + isCount(sepaRaw.capUsd) + ? { + freeUntil: sepaRaw.freeUntil, + capUsd: sepaRaw.capUsd, + coveredUsd: isCount(sepaRaw.coveredUsd) ? sepaRaw.coveredUsd : 0, + remainingUsd: isCount(sepaRaw.remainingUsd) ? sepaRaw.remainingUsd : 0, + waivedFeeUsd: isCount(sepaRaw.waivedFeeUsd) ? sepaRaw.waivedFeeUsd : 0, + active: sepaRaw.active === true, + } + : null; + + if (!tierDiscount && !sepa) return null; + return { + kolUsername: perk.kolUsername, + grantedAt: typeof perk.grantedAt === 'string' ? perk.grantedAt : '', + tierDiscount, + sepa, + }; +} + +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/** "23 Dec", in UTC, or '' for an unreadable date. */ +export function perkDay(iso: string): string { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return ''; + return `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]}`; +} + +/** "$10,000", whole dollars. */ +export function perkUsd(amount: number): string { + return `$${Math.floor(amount).toLocaleString('en-US')}`; +} + +const monthsLabel = (months: number) => (months === 1 ? 'month' : `${months} months`); + +/** "50% off Prime & Ultra + free SEPA", for the one line under the invite code field. */ +export function invitePerkShort(perk: InvitePerk): string { + const parts: string[] = []; + if (perk.tierDiscountPct > 0) parts.push(`${perk.tierDiscountPct}% off Prime & Ultra`); + if (perk.sepaFreeMonths > 0) parts.push('free SEPA'); + return parts.join(' + '); +} + +/** "free SEPA deposits for your first month, up to $10,000", to sit mid-sentence. */ +export function sepaPerkPhrase( + perk: Pick, +): string { + const cap = perk.sepaFreeCapUsd > 0 ? `, up to ${perkUsd(perk.sepaFreeCapUsd)}` : ''; + return `free SEPA deposits for your first ${monthsLabel(perk.sepaFreeMonths)}${cap}`; +} + +/** "Free SEPA deposits for your first month, up to $10,000". */ +export function sepaPerkSentence( + perk: Pick, +): string { + const phrase = sepaPerkPhrase(perk); + return `${phrase.charAt(0).toUpperCase()}${phrase.slice(1)}`; +} + +/** + * The euro account screen's notice while the user's free SEPA months run: + * "Your SEPA deposits are free until 23 Dec", and what is left of the cap. + * Null when there is nothing to tell them. + */ +export function kolSepaPerkCopy(perk: UserKolPerk | null): { title: string; body: string } | null { + if (!perk?.sepa?.active) return null; + const day = perkDay(perk.sepa.freeUntil); + return { + title: day ? `Your SEPA deposits are free until ${day}` : 'Your SEPA deposits are free', + body: + `€0 fee on your next ${perkUsd(perk.sepa.remainingUsd)} of deposits, ` + + `thanks to ${perk.kolUsername}'s invite.`, + }; +} + +/** "50% off your first year with artem.betev's invite", or '' when there is none to take. */ +export function inviteDiscountLine( + discount: { pct: number; inviterUsername: string } | null | undefined, +): string { + if (!discount || !(discount.pct > 0)) return ''; + return discount.inviterUsername + ? `${discount.pct}% off your first year with ${discount.inviterUsername}'s invite` + : `${discount.pct}% off your first year`; +} diff --git a/lib/tierUpgrade.ts b/lib/tierUpgrade.ts index a34c641fa..05890faf5 100644 --- a/lib/tierUpgrade.ts +++ b/lib/tierUpgrade.ts @@ -1,3 +1,4 @@ +import { inviteDiscountLine } from '@/lib/referral/invitePerk'; import { isHigherTier } from '@/lib/rewardsUpgrade'; import { getTierDisplayName } from '@/lib/tierNames'; import { @@ -440,6 +441,27 @@ export const formatSaleEnds = (offer: TierOffer | undefined): string => { return day ? `Offer ends ${day}` : ''; }; +/** + * The KOL invite discount pricing this offer's first year, or null: absent, + * malformed, or not actually making the first year cheaper. + */ +export const offerInviteDiscount = ( + offer: TierOffer | undefined, +): { pct: number; inviterUsername: string } | null => { + const discount = offer?.inviteDiscount; + if (!discount || typeof discount !== 'object' || !isOfferOnSale(offer)) return null; + const { pct, inviterUsername } = discount; + if (typeof pct !== 'number' || !Number.isFinite(pct) || pct <= 0) return null; + return { + pct: Math.round(pct), + inviterUsername: typeof inviterUsername === 'string' ? inviterUsername : '', + }; +}; + +/** "50% off your first year with dana's invite" while one prices the offer; otherwise nothing. */ +export const formatInviteDiscount = (offer: TierOffer | undefined): string => + inviteDiscountLine(offerInviteDiscount(offer)); + /** * What buying this tier does to the membership the user already pays for, or * nothing when it replaces none: the old one ends now, the new one runs a full diff --git a/lib/types.ts b/lib/types.ts index 5418d2d3c..0e61daa81 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -4576,6 +4576,12 @@ export type ReferralInviteLookup = windowDays: number; payoutToken: string; } | null; + /** + * What a KOL's perk code adds while it would be granted: a first-year + * membership discount and free SEPA deposits. Absent on a user's own + * code and on older backends; read it through `readInvitePerk`. + */ + perk?: unknown; } | { valid: false; code: string }; @@ -4781,6 +4787,11 @@ export interface TierOffer { paymentMode?: TierPaymentMode; /** The lower-tier membership buying this one ends, when there is one. */ replacesSubscription?: TierReplacedSubscription | null; + /** + * The KOL invite discount in `firstYearFeeUsd`, when one made the first year + * cheaper. Read it through `offerInviteDiscount`. + */ + inviteDiscount?: { pct: number; inviterUsername: string } | null; } /** The user's locked FUSE position. */ diff --git a/lib/utils/__tests__/feePromotion.test.ts b/lib/utils/__tests__/feePromotion.test.ts index ca5191ebd..c7a407afa 100644 --- a/lib/utils/__tests__/feePromotion.test.ts +++ b/lib/utils/__tests__/feePromotion.test.ts @@ -144,6 +144,37 @@ describe('bankDepositFeeLine', () => { }); }); + it('credits the KOL invite perk on a deposit it made free', () => { + expect( + bankDepositFeeLine({ + ...base, + amount: '0.00', + waiveReason: 'KolPerk', + waivedAmount: '0.50', + kolPerk: { kolUsername: 'artem.betev' }, + }), + ).toEqual({ + value: '€0.00', + note: 'Free with your invite perk from artem.betev · you saved €0.50', + }); + expect(bankDepositFeeLine({ ...base, amount: '0.00', waiveReason: 'KolPerk' })).toEqual({ + value: '€0.00', + note: 'Free with your invite perk', + }); + }); + + it('reads the perk off the activity, ignoring junk', () => { + expect( + readBankDepositFee({ + fee: { ...base, amount: '0.00', waiveReason: 'KolPerk', kolPerk: { kolUsername: 'k' } }, + })?.kolPerk, + ).toEqual({ kolUsername: 'k' }); + expect( + readBankDepositFee({ fee: { ...base, amount: '0.00', kolPerk: { kolUsername: 4 } } }) + ?.kolPerk, + ).toEqual({}); + }); + it('credits the plan on Ultra', () => { expect(bankDepositFeeLine({ ...base, amount: '0.00', waiveReason: 'TierFree' })).toEqual({ value: '€0.00', diff --git a/lib/utils/feePromotion.ts b/lib/utils/feePromotion.ts index 16188229f..9efe15c19 100644 --- a/lib/utils/feePromotion.ts +++ b/lib/utils/feePromotion.ts @@ -16,6 +16,8 @@ export const EUR_BANK_DEPOSIT_PROMOTION_SCOPE = 'eur_bank_deposit'; /** Mirrors ProductFeeWaiveReason on the backend. */ export const FEE_WAIVE_REASON_PROMOTION = 'Promotion'; +/** A KOL invite perk's free SEPA months covered the fee. */ +export const FEE_WAIVE_REASON_KOL_PERK = 'KolPerk'; export const FEE_WAIVE_REASON_TIER_FREE = 'TierFree'; /** A live fee promotion, as one user sees it. */ @@ -49,6 +51,8 @@ export interface BankDepositFeeSummary { /** What the fee would have been, when a promotion covered it. */ waivedAmount?: string; promotion?: { id: string; name?: string; slot: number; freeCount?: number }; + /** The KOL whose invite perk made the deposit free. */ + kolPerk?: { kolUsername?: string }; } const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; @@ -161,6 +165,15 @@ export function readBankDepositFee(metadata: unknown): BankDepositFeeSummary | n } : undefined; + const kolPerk = + fee.kolPerk && typeof fee.kolPerk === 'object' + ? { + ...(typeof fee.kolPerk.kolUsername === 'string' && { + kolUsername: fee.kolPerk.kolUsername, + }), + } + : undefined; + return { amount: fee.amount, currency: fee.currency.toUpperCase(), @@ -169,6 +182,7 @@ export function readBankDepositFee(metadata: unknown): BankDepositFeeSummary | n ...(typeof fee.waiveReason === 'string' && { waiveReason: fee.waiveReason }), ...(isNonNegativeDecimal(fee.waivedAmount) && { waivedAmount: fee.waivedAmount }), ...(promotion && { promotion }), + ...(kolPerk && { kolPerk }), }; } @@ -201,6 +215,14 @@ export function bankDepositFeeLine(fee: BankDepositFeeSummary): { : ''; return { value, note: `${which}${saved}` }; } + if (fee.waiveReason === FEE_WAIVE_REASON_KOL_PERK) { + const from = fee.kolPerk?.kolUsername ? ` from ${fee.kolPerk.kolUsername}` : ''; + const saved = + fee.waivedAmount && Number(fee.waivedAmount) > 0 + ? ` · you saved ${formatFiat(fee.waivedAmount, fee.currency)}` + : ''; + return { value, note: `Free with your invite perk${from}${saved}` }; + } if (fee.waiveReason === FEE_WAIVE_REASON_TIER_FREE) { return { value, note: 'Free on your plan' }; }