π OpenHands: AI-Driven Development
fix(frontend): prevent duplicate payment successful toast on stripe checkout return (#14143)
Hiep Le1093afdced3f
diff --git a/frontend/__tests__/routes/billing.test.tsx b/frontend/__tests__/routes/billing.test.tsxindex 090ccbd085..a10eba83db 100644--- a/frontend/__tests__/routes/billing.test.tsx+++ b/frontend/__tests__/routes/billing.test.tsx@@ -1,5 +1,6 @@-import { render, screen, waitFor } from "@testing-library/react";-import { createRoutesStub } from "react-router";+import { act, render, screen, waitFor } from "@testing-library/react";+import React, { StrictMode } from "react";+import { createRoutesStub, MemoryRouter } from "react-router";import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";import { QueryClientProvider } from "@tanstack/react-query";import BillingSettingsScreen, { clientLoader } from "#/routes/billing";@@ -33,14 +34,36 @@ vi.mock("#/utils/custom-toast-handlers", () => ({displayErrorToast: (...args: unknown[]) => mockDisplayErrorToast(...args),}));-// Mock useTracking hook-const mockTrackCreditsPurchased = vi.fn();-vi.mock("#/hooks/use-tracking", () => ({- useTracking: () => ({- trackCreditsPurchased: mockTrackCreditsPurchased,+// Mock the underlying posthog service so the real useTracking hook runs.+// This is intentional: the real hook produces a fresh `trackCreditsPurchased`+// reference on every render, which is the production-side trigger for the+// duplicate-toast bug we're guarding against.+const mockPostHogCapture = vi.fn();+vi.mock("posthog-js/react", () => ({+ usePostHog: () => ({+ capture: mockPostHogCapture,}),}));+// Allow individual tests to pin `useSearchParams` to a fixed value (e.g. to+// hold checkout=success across forced re-renders). When unset, the real+// react-router implementation is used.+const { searchParamsOverride } = vi.hoisted(() => ({+ searchParamsOverride: {+ current: null as null | [URLSearchParams, () => void],+ },+}));+vi.mock("react-router", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react-router")>();+ return {+ ...actual,+ useRevalidator: () => ({ revalidate: vi.fn() }),+ useSearchParams: ((...args: Parameters<typeof actual.useSearchParams>) =>+ searchParamsOverride.current ??+ actual.useSearchParams(...args)) as typeof actual.useSearchParams,+ };+});+// Mock useBalance hookconst mockUseBalance = vi.fn();vi.mock("#/hooks/query/use-balance", () => ({@@ -122,6 +145,7 @@ describe("Billing Route", () => {afterEach(() => {vi.clearAllMocks();+ searchParamsOverride.current = null;});describe("clientLoader cache key", () => {@@ -327,66 +351,92 @@ describe("Billing Route", () => {});});- it("should display success toast exactly once and track credits on checkout success", async () => {- const RouterStub = createRoutesStub([- {- Component: BillingSettingsScreen,- path: "/settings/billing",- },- ]);-- render(- <RouterStub- initialEntries={[- "/settings/billing?checkout=success&amount=25&session_id=sess_123",- ]}- />,- {- wrapper: ({ children }) => (+ /**+ * Forces multiple parent re-renders of `BillingSettingsScreen` while+ * `useSearchParams` is pinned to `?checkout=...`, simulating the+ * production timing window where re-renders fire the effect again+ * before the URL has cleared.+ */+ function renderWithForcedReRenders(+ query:+ | "checkout=success&amount=25&session_id=sess_123"+ | "checkout=cancel",+ ) {+ searchParamsOverride.current = [new URLSearchParams(query), vi.fn()];++ let triggerReRender: (() => void) | undefined;++ function ReRenderHarness() {+ const [, setTick] = React.useState(0);+ React.useEffect(() => {+ triggerReRender = () => setTick((t) => t + 1);+ }, []);+ return <BillingSettingsScreen />;+ }++ const result = render(<ReRenderHarness />, {+ wrapper: ({ children }) => (+ <StrictMode><QueryClientProvider client={mockQueryClient}>- {children}+ <MemoryRouter initialEntries={[`/settings/billing?${query}`]}>+ {children}+ </MemoryRouter></QueryClientProvider>- ),+ </StrictMode>+ ),+ });++ return {+ ...result,+ forceReRenders: async (count: number) => {+ const trigger = triggerReRender;+ for (let i = 0; i < count; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await act(async () => {+ trigger?.();+ });+ }},+ };+ }++ it("should display success toast exactly once and capture credits_purchased even when the effect re-fires before the URL clears", async () => {+ // Arrange + Act+ const { forceReRenders } = renderWithForcedReRenders(+ "checkout=success&amount=25&session_id=sess_123",);+ await forceReRenders(3);+ // Assertawait waitFor(() => {expect(mockDisplaySuccessToast).toHaveBeenCalledTimes(1);});- expect(mockTrackCreditsPurchased).toHaveBeenCalledTimes(1);- expect(mockTrackCreditsPurchased).toHaveBeenCalledWith({- amountUsd: 25,- stripeSessionId: "sess_123",+ const creditsPurchasedCalls = mockPostHogCapture.mock.calls.filter(+ ([event]) => event === "credits_purchased",+ );+ expect(creditsPurchasedCalls).toHaveLength(1);+ expect(creditsPurchasedCalls[0][1]).toMatchObject({+ amount_usd: 25,+ stripe_session_id: "sess_123",});});- it("should display error toast exactly once on checkout cancel", async () => {- const RouterStub = createRoutesStub([- {- Component: BillingSettingsScreen,- path: "/settings/billing",- },- ]);-- render(- <RouterStub- initialEntries={["/settings/billing?checkout=cancel"]}- />,- {- wrapper: ({ children }) => (- <QueryClientProvider client={mockQueryClient}>- {children}- </QueryClientProvider>- ),- },- );+ it("should display error toast exactly once on checkout cancel even when the effect re-fires", async () => {+ // Arrange + Act+ const { forceReRenders } = renderWithForcedReRenders("checkout=cancel");+ await forceReRenders(3);+ // Assertawait waitFor(() => {expect(mockDisplayErrorToast).toHaveBeenCalledTimes(1);});- expect(mockTrackCreditsPurchased).not.toHaveBeenCalled();+ expect(+ mockPostHogCapture.mock.calls.some(+ ([event]) => event === "credits_purchased",+ ),+ ).toBe(false);});});diff --git a/frontend/src/routes/billing.tsx b/frontend/src/routes/billing.tsxindex c4ad23c08c..11324045d2 100644--- a/frontend/src/routes/billing.tsx+++ b/frontend/src/routes/billing.tsx@@ -59,8 +59,13 @@ function BillingSettingsScreen() {const checkoutStatus = searchParams.get("checkout");const amount = searchParams.get("amount");const sessionId = searchParams.get("session_id");+ const hasHandledCheckoutRef = React.useRef(false);React.useEffect(() => {+ if (!checkoutStatus) return;+ if (hasHandledCheckoutRef.current) return;+ hasHandledCheckoutRef.current = true;+if (checkoutStatus === "success") {// Track credits purchased if we have the necessary dataif (amount && sessionId) {