diff --git a/components/Assets/__tests__/fixtures.ts b/components/Assets/__tests__/fixtures.ts index 478c7fd1a..c247dd735 100644 --- a/components/Assets/__tests__/fixtures.ts +++ b/components/Assets/__tests__/fixtures.ts @@ -100,6 +100,7 @@ export const spendFixture: SpendModeFigures = { borrowApy: '5.57%', borrowedProgress: 0.175, segmentValue: { cash: '$228.40', credit: '$1,650.00', smart: '$1,650.00' }, + availableUsd: 1650, hasPosition: true, canBorrow: true, showsBorrowPosition: true, diff --git a/components/Card/NewCardDetails/SpendMode/useSpendModeFigures.ts b/components/Card/NewCardDetails/SpendMode/useSpendModeFigures.ts index 3d1fbf040..e9c104c18 100644 --- a/components/Card/NewCardDetails/SpendMode/useSpendModeFigures.ts +++ b/components/Card/NewCardDetails/SpendMode/useSpendModeFigures.ts @@ -52,6 +52,14 @@ export interface SpendModeFigures { /** The figure under each segment name in the control. */ segmentValue: Record; + /** + * What the home Available to spend tile shows for the mode in force, in dollars, before it is + * formatted: the cash balance in Cash, the credit left in Credit, the larger of the two in Smart. + * + * For anything that has to quote the tile's number rather than work out one of its own (the + * declined-payment banner and receipt). Null while the tile is loading or reads "—". + */ + availableUsd: number | null; /** Whether there is a loan at all. What gates the Repay button. */ hasPosition: boolean; @@ -172,6 +180,13 @@ export const useSpendModeFigures = (): SpendModeFigures => { // The tile's own placeholder, on the figures that count Base and nowhere else: `isLoading` // also holds the Assets screen's Fuse-only credit line, which has nothing to wait for. const unknownWithoutBase = isBaseCreditUnavailable ? '—' : undefined; + const isLoading = + isRegistrationLoading || isBalanceLoading || isBaseAccessLoading || isBaseCreditLoading; + // The tile's figure for the mode in force, by the same rules as the labels below. + const smartMicro = cashMicro > spendableHeadroom ? cashMicro : spendableHeadroom; + const availableMicro = + mode === 'cash' ? cashMicro : mode === 'credit' ? spendableHeadroom : smartMicro; + const isAvailableKnown = !isLoading && (mode === 'cash' || !unknownWithoutBase); return { mode, @@ -201,10 +216,9 @@ export const useSpendModeFigures = (): SpendModeFigures => { // takes exactly one path, so the most Smart can fund is the larger of the two; the // two figures also overlap heavily, both deriving from the same balance, so adding // them would quote money the Safe does not have. - smart: - unknownWithoutBase ?? - formatMicroUsd(cashMicro > spendableHeadroom ? cashMicro : spendableHeadroom), + smart: unknownWithoutBase ?? formatMicroUsd(smartMicro), }, + availableUsd: isAvailableKnown ? Number(availableMicro) / Number(ONE_USD) : null, hasPosition: debt > 0n, canBorrow, @@ -215,8 +229,7 @@ export const useSpendModeFigures = (): SpendModeFigures => { fullyPriced: position?.fullyPriced ?? true, // Base too, so the tile doesn't land on the Fuse figure and then jump to the whole line. - isLoading: - isRegistrationLoading || isBalanceLoading || isBaseAccessLoading || isBaseCreditLoading, + isLoading, }; }, [ mode, diff --git a/hooks/__tests__/useDeclinedPaymentPrompt.test.tsx b/hooks/__tests__/useDeclinedPaymentPrompt.test.tsx index 318ca24d9..2813ac72b 100644 --- a/hooks/__tests__/useDeclinedPaymentPrompt.test.tsx +++ b/hooks/__tests__/useDeclinedPaymentPrompt.test.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { DeclinedPaymentPrompt, useDeclinedPaymentPrompt } from '@/hooks/useDeclinedPaymentPrompt'; +import { useDeclineSpendable } from '@/hooks/useDeclineSpendable'; import { CardTransactionCategory } from '@/lib/types'; const { act, create } = jest.requireActual('react-test-renderer'); @@ -13,8 +14,26 @@ let mockDisplayCurrency: any; jest.mock('@/hooks/useCardTransactions', () => ({ useCardTransactions: () => ({ data: mockTransactions }), })); +let mockSpendableLoading: boolean; +const mockRefetchSpendable = jest.fn(); jest.mock('@/hooks/useCardSpendable', () => ({ - useCardSpendable: () => ({ data: mockSpendable }), + useCardSpendable: () => ({ + data: mockSpendable, + isLoading: mockSpendableLoading, + refetch: mockRefetchSpendable, + }), +})); +let mockBalancesRefresh: any; +const mockRefetchBalances = jest.fn(); +jest.mock('@/hooks/useBalances', () => ({ + useBalancesRefresh: (options: any) => { + mockBalancesRefresh = options; + return { refetch: mockRefetchBalances }; + }, +})); +let mockTile: { availableUsd: number | null; isLoading: boolean }; +jest.mock('@/components/Card/NewCardDetails/SpendMode/useSpendModeFigures', () => ({ + useSpendModeFigures: () => mockTile, })); jest.mock('@/hooks/useCardSpendRegistration', () => ({ useCardSpendRegistration: () => mockRegistration, @@ -59,9 +78,14 @@ describe('useDeclinedPaymentPrompt', () => { beforeEach(() => { jest.useFakeTimers({ now: NOW }); mockSpendable = { available: { amount: '0', currency: 'usd' } }; + mockSpendableLoading = false; + mockRefetchSpendable.mockReset(); + mockRefetchBalances.mockReset(); mockRegistration = { registration: {}, mode: 'cash', isRegistered: true }; mockBaseCredit = { base: {}, readsBase: false, isBaseGateReady: true }; mockDisplayCurrency = { inEuros: false }; + // The tile cannot say unless a test gives it a number: the hook's own figures stand. + mockTile = { availableUsd: null, isLoading: false }; }); afterEach(() => { @@ -167,4 +191,123 @@ describe('useDeclinedPaymentPrompt', () => { expect(prompt).toBeNull(); }); + + describe("the Available to spend tile's number (T-174)", () => { + beforeEach(() => { + mockTransactions = { pages: [{ data: [declined(new Date(NOW.getTime() - 2 * HOUR_MS))] }] }; + // Cash only, as the backend counts it. + mockSpendable = { available: { amount: '5', currency: 'usd' } }; + }); + + it('is what the banner quotes, not the cash-only figure', () => { + mockTile = { availableUsd: 12.5, isLoading: false }; + + act(() => { + root = create(); + }); + + expect(prompt?.available).toEqual({ amount: 12.5, currency: 'USD' }); + }); + + it('is what the banner quotes in Credit mode, in the main currency', () => { + // On its own the hook would say the larger single line, $11. The tile reads $43.40. + mockRegistration = { + ...mockRegistration, + mode: 'credit', + position: { availableToBorrowUsd: 11_000_000n }, + }; + mockBaseCredit = { + ...mockBaseCredit, + readsBase: true, + base: { data: { availableToBorrowUsd: 5_000_000n } }, + }; + mockDisplayCurrency = { inEuros: true, usdPerEur: 1.1657 }; + mockTransactions = { + pages: [{ data: [{ ...declined(new Date(NOW.getTime() - HOUR_MS)), amount: '110.96' }] }], + }; + mockTile = { availableUsd: 43.4, isLoading: false }; + + act(() => { + root = create(); + }); + expect(prompt?.available).toEqual({ amount: 37.23, currency: 'EUR' }); + + mockTile = { availableUsd: 111, isLoading: false }; + act(() => root.update()); + expect(prompt).toBeNull(); + }); + + it('hides the banner once it covers the payment', () => { + mockTile = { availableUsd: 20, isLoading: false }; + + act(() => { + root = create(); + }); + + expect(prompt).toBeNull(); + }); + + it('waits for the tile rather than show one number and then another', () => { + mockTile = { availableUsd: null, isLoading: true }; + + act(() => { + root = create(); + }); + + expect(prompt).toBeNull(); + }); + + it('still quotes the tile, in dollars, when the backend cash read failed', () => { + mockSpendable = undefined; + mockTile = { availableUsd: 12.5, isLoading: false }; + + act(() => { + root = create(); + }); + + expect(prompt?.available).toEqual({ amount: 12.5, currency: 'USD' }); + }); + + it('waits for the backend cash read while it is still loading', () => { + mockSpendable = undefined; + mockSpendableLoading = true; + mockTile = { availableUsd: 12.5, isLoading: false }; + + act(() => { + root = create(); + }); + + expect(prompt).toBeNull(); + }); + + it("re-reads the tile's balances with the receipt's poll and its refresh", async () => { + let refetchCash: (() => Promise) | undefined; + const Receipt = () => { + const { refetchCash: current } = useDeclineSpendable({ refetchInterval: 15_000 }); + React.useEffect(() => { + refetchCash = current; + }, [current]); + return null; + }; + + act(() => { + root = create(); + }); + expect(mockBalancesRefresh).toEqual({ enabled: true, refetchInterval: 15_000 }); + + await refetchCash?.(); + expect(mockRefetchSpendable).toHaveBeenCalledTimes(1); + expect(mockRefetchBalances).toHaveBeenCalledTimes(1); + }); + + it('falls back to the cash figure when the tile cannot say', () => { + mockTile = { availableUsd: null, isLoading: false }; + + act(() => { + root = create(); + }); + + expect(prompt?.available).toEqual({ amount: 5, currency: 'USD' }); + }); + }); }); diff --git a/hooks/useBalances.ts b/hooks/useBalances.ts index cc3cc12db..cefbe98f7 100644 --- a/hooks/useBalances.ts +++ b/hooks/useBalances.ts @@ -1222,3 +1222,28 @@ export const useBalancesPolling = (): void => { notifyOnChangeProps: [], }); }; + +/** + * A faster re-read of the same balances for a screen that is waiting on a top-up: the declined + * receipt, whose Cash figure is the Available to spend tile's and so comes from these balances. + * The app-wide timer above can be a minute apart; this one runs at the screen's own pace, and only + * while that screen asks. Renders nothing. `refetch` reads them at once. + */ +export const useBalancesRefresh = ({ + enabled = true, + refetchInterval, +}: { enabled?: boolean; refetchInterval?: number } = {}) => { + const { user } = useUser(); + const options = tokenBalancesQueryOptions(user?.safeAddress); + + const { refetch } = useQuery({ + ...options, + ...balancesObserverOptions, + enabled: options.enabled && enabled && !!refetchInterval, + refetchInterval, + refetchIntervalInBackground: false, + notifyOnChangeProps: [], + }); + + return { refetch }; +}; diff --git a/hooks/useDeclineSpendable.ts b/hooks/useDeclineSpendable.ts index c33c35039..92d9e949a 100644 --- a/hooks/useDeclineSpendable.ts +++ b/hooks/useDeclineSpendable.ts @@ -1,15 +1,27 @@ import { useCallback } from 'react'; +import { useSpendModeFigures } from '@/components/Card/NewCardDetails/SpendMode/useSpendModeFigures'; import { ONE_USD } from '@/constants/cardSpendModule'; +import { useBalancesRefresh } from '@/hooks/useBalances'; import { useCardCreditPositions } from '@/hooks/useCardCreditPositions'; import { useCardSpendable } from '@/hooks/useCardSpendable'; import { useCardSpendRegistration } from '@/hooks/useCardSpendRegistration'; import { useCardDisplayCurrency } from '@/hooks/useMainCurrency'; -import { declinedPaymentFigures } from '@/lib/utils/cardCurrency'; +import { declinedPaymentFigures, withTileAvailable } from '@/lib/utils/cardCurrency'; -import type { CardTransaction } from '@/lib/types'; +import type { CardSpendableResponse, CardTransaction } from '@/lib/types'; -/** Live spending power for the declined receipt and its Home banner. */ +/** + * Live spending power for the declined receipt and its Home banner. + * + * What is available is the home Available to spend tile's own number, so the banner under the tile + * and the receipt it opens quote the figure the tile shows — and neither says a payment is short + * when the tile covers it. Nothing while the tile is still loading, so they do not show one number + * and then another. When the tile cannot say (it reads "—"), the figures worked out here stand. + * + * The tile's cash comes from the token balances, not from the backend's spendable read, so the + * poll and `refetchCash` re-read both: a top-up shows on the receipt at the poll's pace. + */ export const useDeclineSpendable = ({ enabled = true, refetchInterval, @@ -18,13 +30,23 @@ export const useDeclineSpendable = ({ useCardSpendRegistration({ refetchInterval: enabled ? refetchInterval : undefined, }); - const { data: cash, refetch: refetchCash } = useCardSpendable({ enabled, refetchInterval }); + const { + data: cash, + isLoading: isCashLoading, + refetch: refetchSpendable, + } = useCardSpendable({ enabled, refetchInterval }); + const { refetch: refetchBalances } = useBalancesRefresh({ enabled, refetchInterval }); + const refetchCash = useCallback( + () => Promise.all([refetchSpendable(), refetchBalances()]), + [refetchSpendable, refetchBalances], + ); const hasMode = enabled && !!registration; const { base, readsBase, isBaseGateReady } = useCardCreditPositions({ enabled: hasMode && mode !== 'cash', refetchInterval, }); - const { inEuros, usdPerEur } = useCardDisplayCurrency(); + const { inEuros, usdPerEur, toDisplayAmount } = useCardDisplayCurrency(); + const { availableUsd: tileUsd, isLoading: isTileLoading } = useSpendModeFigures(); // One card authorization draws credit from one instance, subject to its remaining limits. const fuseMicroUsd = @@ -40,14 +62,46 @@ export const useDeclineSpendable = ({ const figuresFor = useCallback( (transaction: CardTransaction) => { if (!enabled || (!hasMode && isLoading)) return declinedPaymentFigures(transaction); - if (!hasMode || mode === 'cash') return declinedPaymentFigures(transaction, cash); + const displayUsdPerEur = inEuros ? usdPerEur : undefined; + if (tileUsd === null) { + if (isTileLoading) return declinedPaymentFigures(transaction); + if (!hasMode || mode === 'cash') return declinedPaymentFigures(transaction, cash); + return declinedPaymentFigures(transaction, cash, { mode, availableUsd, displayUsdPerEur }); + } + if (!hasMode || mode === 'cash') { + // Still being read: wait for the card's own quote rather than show dollars and then euros. + if (!cash && isCashLoading) return declinedPaymentFigures(transaction); + // The read failed: the tile's number still stands, in dollars, with no card quote. + const known: CardSpendableResponse = cash ?? { + available: { amount: '0', currency: 'usd' }, + }; + const tileCash = withTileAvailable(known, { + usd: tileUsd, + eur: inEuros ? toDisplayAmount(tileUsd) : undefined, + }); + return declinedPaymentFigures(transaction, tileCash); + } return declinedPaymentFigures(transaction, cash, { mode, - availableUsd, - displayUsdPerEur: inEuros ? usdPerEur : undefined, + availableUsd: tileUsd, + displayUsdPerEur, + isTileFigure: true, }); }, - [enabled, hasMode, isLoading, mode, cash, availableUsd, inEuros, usdPerEur], + [ + enabled, + hasMode, + isLoading, + mode, + cash, + isCashLoading, + availableUsd, + inEuros, + usdPerEur, + toDisplayAmount, + tileUsd, + isTileLoading, + ], ); return { mode, figuresFor, refetchCash }; diff --git a/hooks/useDeclinedPaymentPrompt.ts b/hooks/useDeclinedPaymentPrompt.ts index 71bb69a2f..2f7b2a07a 100644 --- a/hooks/useDeclinedPaymentPrompt.ts +++ b/hooks/useDeclinedPaymentPrompt.ts @@ -16,7 +16,10 @@ export interface DeclinedPaymentPrompt { /** Card transaction id — what the banner's "Fix it" opens. */ transactionId: string; payment: Money; - /** What the card can spend now, live — less than {@link payment}, or there is no banner. */ + /** + * What the card can spend now, live — the Available to spend tile's own number. Less than + * {@link payment}, or there is no banner. + */ available: Money; merchantName?: string; } diff --git a/lib/utils/__tests__/cardCurrency.test.ts b/lib/utils/__tests__/cardCurrency.test.ts index e5b20ea1c..4de6ef081 100644 --- a/lib/utils/__tests__/cardCurrency.test.ts +++ b/lib/utils/__tests__/cardCurrency.test.ts @@ -9,6 +9,7 @@ import { shortfallOf, spendableDisplay, usdToEur, + withTileAvailable, } from '@/lib/utils/cardCurrency'; const EUR_SPENDABLE = { @@ -184,6 +185,20 @@ describe('declinedPaymentFigures', () => { expect(figures.cashComparable).toEqual(figures.comparable); }); + it("quotes the tile's Smart number as it is, and keeps the cash path for a top-up", () => { + // The tile reads the larger of cash and credit. Weighed against cash again, a near tie showed + // the backend's cash figure, cents off the tile. + const figures = declinedPaymentFigures({ amount: '32', currency: 'USD' }, EUR_SPENDABLE, { + mode: 'smart', + availableUsd: 14.4, + isTileFigure: true, + }); + + expect(figures.available).toEqual({ amount: 14.4, currency: 'USD' }); + expect(figures.comparable).toMatchObject({ payment: 32, available: 14.4 }); + expect(figures.cashComparable?.available).toBe(14.46); + }); + it('keeps the credit balance in Smart mode while cash is unavailable', () => { const figures = declinedPaymentFigures({ amount: '50', currency: 'USD' }, undefined, { mode: 'smart', @@ -322,3 +337,53 @@ describe('euro main currency', () => { expect(formatEur(1000)).toBe('€1,000'); }); }); + +describe('withTileAvailable', () => { + // T-174: the banner said €10.02 under a tile reading €36.54. The backend counts cash only; in + // Credit mode the tile counts the credit line. + const CASH_ONLY = { + available: { amount: '11.38', currency: 'usd' as const }, + available_in_card_currency: { ...EUR_SPENDABLE.available_in_card_currency, amount: '10.02' }, + }; + + it("puts the tile's euro figure in place of the backend's, to the cent", () => { + const onTile = withTileAvailable(CASH_ONLY, { usd: 41.5, eur: 36.54 }); + + expect(onTile.available).toEqual({ amount: '41.5', currency: 'usd' }); + expect(onTile.available_in_card_currency).toEqual({ + ...CASH_ONLY.available_in_card_currency, + amount: '36.54', + }); + }); + + it("makes the declined receipt quote the tile's number", () => { + const figures = declinedPaymentFigures( + { + amount: '149', + currency: 'ILS', + spend_details: { card_amount: '39.80', card_currency: 'EUR' }, + }, + withTileAvailable(CASH_ONLY, { usd: 41.5, eur: 36.54 }), + ); + + expect(figures.available).toEqual({ amount: 36.54, currency: 'EUR' }); + expect(figures.comparable).toMatchObject({ payment: 39.8, available: 36.54, currency: 'EUR' }); + }); + + it("converts at the card's quote, rounded down, when the tile shows dollars", () => { + // 41.5 / 1.1358 = 36.538… + const onTile = withTileAvailable(CASH_ONLY, { usd: 41.5 }); + + expect(onTile.available_in_card_currency?.amount).toBe('36.53'); + }); + + it('stays in dollars when there is no card-currency quote', () => { + const onTile = withTileAvailable( + { available: { amount: '11.38', currency: 'usd' } }, + { usd: 41.5, eur: 36.54 }, + ); + + expect(onTile.available).toEqual({ amount: '41.5', currency: 'usd' }); + expect(onTile.available_in_card_currency).toBeUndefined(); + }); +}); diff --git a/lib/utils/cardCurrency.ts b/lib/utils/cardCurrency.ts index aa6b6a4db..fcc1e6ed6 100644 --- a/lib/utils/cardCurrency.ts +++ b/lib/utils/cardCurrency.ts @@ -143,6 +143,11 @@ interface DeclineCreditAvailability { mode: 'credit' | 'smart'; availableUsd?: number; displayUsdPerEur?: number; + /** + * `availableUsd` is the home Available to spend tile's own number — in Smart, already the larger + * of cash and credit — so it is quoted as it is rather than weighed against the cash path again. + */ + isTileFigure?: boolean; } /** @@ -230,6 +235,47 @@ const cashPaymentFigures = ( return { payment, available }; }; +/** + * The backend's spendable figures with the home Available to spend tile's number in their place. + * + * The backend counts cash only. The tile follows the spend mode, so in Credit it counts the credit + * line too — and the declined-payment banner under it said "You have €10.02 available to spend" + * beside a tile reading €36.54. The banner and the receipt take this, so all three quote one + * number. + * + * For the cash path. In Credit and Smart the tile's number goes to `declinedPaymentFigures` as the + * credit figure instead (`isTileFigure`). + * + * `usd` is the tile's figure in dollars. `eur` is what the tile shows when it shows euros: used as + * it is for a euro card, so the two match to the cent; otherwise the dollars are converted at the + * card's own quote and rounded down, as the backend's figure is. The quote itself is kept. + */ +export const withTileAvailable = ( + spendable: CardSpendableResponse, + tile: { usd: number; eur?: number }, +): CardSpendableResponse => { + const usd = Math.max(0, tile.usd); + const inCard = spendable.available_in_card_currency; + const rate = inCard?.rate; + const isEuroCard = inCard?.currency?.trim().toUpperCase() === 'EUR'; + const inCardAmount = + isEuroCard && tile.eur !== undefined + ? Math.max(0, tile.eur) + : rate && rate > 0 + ? usdToEur(usd, rate) + : undefined; + + return { + ...spendable, + available: { amount: String(usd), currency: 'usd' }, + // Without a usable quote there is no figure in the card's currency to give: dollars it is. + available_in_card_currency: + inCard && inCardAmount !== undefined + ? { ...inCard, amount: inCardAmount.toFixed(2) } + : undefined, + }; +}; + export const declinedPaymentFigures = ( transaction: DeclinedPayment, spendable?: CardSpendableResponse | null, @@ -261,6 +307,11 @@ export const declinedPaymentFigures = ( : undefined; if (credit.mode === 'credit') return { payment, available, comparable }; + // The tile's Smart number: one figure for the banner, the receipt and the tile. A top-up still + // funds the cash path, so the cash comparison stays beside it. + if (credit.isTileFigure) { + return { payment, available, comparable, cashComparable: cash.comparable }; + } // Smart can use either path. Compare the gaps in USD, since the two paths can use different FX. const cashUsd = Number(spendable?.available?.amount);