Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Allow retrying failed payments in-app (#4202)

Pedro Ladeiraed230ca4ef17
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/route.ts
index 5dee83a400..f5272bddd0 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/invoices/route.ts
@@ -4,6 +4,7 @@ import { stripe } from "@/lib/stripe";
import { InvoiceSchema } from "@/lib/zod/schemas/invoices";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
+import Stripe from "stripe";
import * as z from "zod/v4";
const querySchema = z.object({
@@ -11,6 +12,7 @@ const querySchema = z.object({
.enum(["subscription", "partnerPayout", "domainRenewal"])
.optional()
.default("subscription"),
+ stripeStatus: z.enum(["open"]).optional(), // only for Stripe subscription invoices
});
// TODO: move to GET /invoices
@@ -20,12 +22,14 @@ export const GET = withWorkspace(
return NextResponse.json([]);
}
- const { type } = querySchema.parse(searchParams);
+ const { type, stripeStatus } = querySchema.parse(searchParams);
const invoices =
type === "subscription"
- ? await subscriptionInvoices(workspace.stripeId)
- : await otherInvoices({
+ ? await getSubscriptionInvoices(workspace.stripeId, {
+ status: stripeStatus,
+ })
+ : await getOtherInvoices({
workspaceId: workspace.id,
type,
});
@@ -37,29 +41,34 @@ export const GET = withWorkspace(
},
);
-const subscriptionInvoices = async (stripeId: string) => {
+const getSubscriptionInvoices = async (
+ stripeId: string,
+ { status }: { status?: "open" } = {},
+) => {
try {
const invoices = await stripe.invoices.list({
customer: stripeId,
limit: 100,
+ ...(status && { status }),
});
- return invoices.data.map((invoice) => {
- return {
- id: invoice.id,
- total: invoice.amount_paid,
- createdAt: new Date(invoice.created * 1000),
- description: "Dub subscription",
- pdfUrl: invoice.invoice_pdf,
- };
- });
+ return invoices.data.map((invoice) => mapSubscriptionInvoice(invoice));
} catch (error) {
console.log(error);
return [];
}
};
-const otherInvoices = async ({
+const mapSubscriptionInvoice = (invoice: Stripe.Invoice) => ({
+ id: invoice.id,
+ total: invoice.total ?? invoice.amount_due,
+ stripeStatus: invoice.status,
+ createdAt: new Date(invoice.created * 1000),
+ description: "Dub subscription",
+ pdfUrl: invoice.invoice_pdf,
+});
+
+const getOtherInvoices = async ({
workspaceId,
type,
}: {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/retry-payment/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/retry-payment/route.ts
new file mode 100644
index 0000000000..174da912a4
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/retry-payment/route.ts
@@ -0,0 +1,78 @@
+import { DubApiError } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+import { NextResponse } from "next/server";
+import Stripe from "stripe";
+import * as z from "zod/v4";
+
+const retryPaymentSchema = z.object({
+ invoiceId: z.string().startsWith("in_"),
+});
+
+// POST /api/workspaces/[idOrSlug]/billing/retry-payment — pay a specific open invoice
+export const POST = withWorkspace(
+ async ({ workspace, req }) => {
+ if (!workspace.stripeId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "No Stripe customer ID",
+ });
+ }
+
+ try {
+ const { invoiceId } = retryPaymentSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const invoice = await stripe.invoices.retrieve(invoiceId);
+
+ if (!invoice || invoice.customer !== workspace.stripeId) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Invoice not found",
+ });
+ }
+
+ if (invoice.status !== "open") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invoice is not open and cannot be retried.",
+ });
+ }
+
+ const paidInvoice = await stripe.invoices.pay(invoiceId);
+
+ if (paidInvoice.status !== "paid") {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Payment could not be completed. Please update your payment method and try again.",
+ });
+ }
+
+ return NextResponse.json({
+ invoiceId: paidInvoice.id,
+ amountDue: paidInvoice.amount_due,
+ amountPaid: paidInvoice.amount_paid,
+ currency: paidInvoice.currency,
+ status: paidInvoice.status,
+ });
+ } catch (error) {
+ if (error instanceof DubApiError || error instanceof z.ZodError) {
+ throw error;
+ }
+
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ error instanceof Stripe.errors.StripeError
+ ? error.message
+ : "Failed to retry payment. Please update your payment method and try again.",
+ });
+ }
+ },
+ {
+ requiredPermissions: ["billing.write"],
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx
index 50a5160b7d..0736575ed6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx
@@ -16,6 +16,7 @@ import {
useRouterStuff,
} from "@dub/ui";
import { cn, currencyFormatter, fetcher } from "@dub/utils";
+import { StripeInvoiceStatusBadges } from "app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/stripe-invoice-status-badges";
import { AlertCircle } from "lucide-react";
import Link from "next/link";
import { useMemo } from "react";
@@ -85,6 +86,7 @@ export default function WorkspaceInvoices() {
key={invoice.id}
invoice={invoice}
displayPaymentMethod={displayPaymentMethod}
+ isSubscription={selectedInvoiceType.id === "subscription"}
/>
))
) : (
@@ -123,13 +125,51 @@ export default function WorkspaceInvoices() {
const InvoiceCard = ({
invoice,
displayPaymentMethod = false,
+ isSubscription = false,
}: {
invoice: InvoiceProps;
displayPaymentMethod: boolean;
+ isSubscription?: boolean;
}) => {
const invoicePaymentMethod =
INVOICE_PAYMENT_METHODS[invoice.paymentMethod ?? "ach"];
+ const formattedTotal = currencyFormatter(invoice.total);
+
+ const statusBadge = isSubscription
+ ? invoice.stripeStatus && (
+ <StatusBadge
+ variant={StripeInvoiceStatusBadges[invoice.stripeStatus].variant}
+ className="rounded-md py-0.5"
+ >
+ {StripeInvoiceStatusBadges[invoice.stripeStatus].label}
+ </StatusBadge>
+ )
+ : invoice.status &&
+ (() => {
+ const badge = PayoutStatusBadges[invoice.status];
+ return (
+ <StatusBadge
+ icon={invoice.status === "failed" ? AlertCircle : null}
+ variant={badge.variant}
+ className="rounded-md py-0.5"
+ {...(invoice.status === "failed" && invoice.failedReason
+ ? { tooltip: invoice.failedReason }
+ : {})}
+ >
+ {badge.label}
+ </StatusBadge>
+ );
+ })();
+
+ const pdfUrl =
+ invoice.pdfUrl &&
+ (isSubscription
+ ? invoice.stripeStatus !== "void"
+ : invoice.status !== "failed")
+ ? invoice.pdfUrl
+ : null;
+
return (
<div className="px-3 py-4 xl:px-12">
{/* Mobile layout */}
@@ -146,9 +186,9 @@ const InvoiceCard = ({
</div>
</div>
<div className="flex items-center">
- {invoice.pdfUrl && invoice.status !== "failed" ? (
+ {pdfUrl ? (
<a
- href={invoice.pdfUrl}
+ href={pdfUrl}
target="_blank"
className={cn(
buttonVariants({ variant: "secondary" }),
@@ -167,25 +207,8 @@ const InvoiceCard = ({
<div className="text-left text-sm">
<div className="font-medium">Total</div>
<div className="flex items-center gap-1.5 text-neutral-500">
- <span className="text-sm font-medium">
- {currencyFormatter(invoice.total)}
- </span>
- {invoice.status &&
- (() => {
- const badge = PayoutStatusBadges[invoice.status];
- return (
- <StatusBadge
- icon={invoice.status === "failed" ? AlertCircle : null}
- variant={badge.variant}
- className="rounded-md py-0.5"
- {...(invoice.status === "failed" && invoice.failedReason
- ? { tooltip: invoice.failedReason }
- : {})}
- >
- {badge.label}
- </StatusBadge>
- );
- })()}
+ <span className="text-sm font-medium">{formattedTotal}</span>
+ {statusBadge}
</div>
</div>
@@ -229,25 +252,8 @@ const InvoiceCard = ({
<div className="text-left text-sm sm:col-span-1">
<div className="font-medium">Total</div>
<div className="flex items-center gap-1.5 text-neutral-500">
- <span className="text-sm font-medium">
- {currencyFormatter(invoice.total)}
- </span>
- {invoice.status &&
- (() => {
- const badge = PayoutStatusBadges[invoice.status];
- return (
- <StatusBadge
- icon={invoice.status === "failed" ? AlertCircle : null}
- variant={badge.variant}
- className="rounded-md py-0.5"
- {...(invoice.status === "failed" && invoice.failedReason
- ? { tooltip: invoice.failedReason }
- : {})}
- >
- {badge.label}
- </StatusBadge>
- );
- })()}
+ <span className="text-sm font-medium">{formattedTotal}</span>
+ {statusBadge}
</div>
</div>
@@ -274,9 +280,9 @@ const InvoiceCard = ({
)}
<div className="flex items-center justify-end sm:col-span-1 sm:justify-end">
- {invoice.pdfUrl && invoice.status !== "failed" ? (
+ {pdfUrl ? (
<a
- href={invoice.pdfUrl}
+ href={pdfUrl}
target="_blank"
className={cn(
buttonVariants({ variant: "secondary" }),
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/stripe-invoice-status-badges.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/stripe-invoice-status-badges.tsx
new file mode 100644
index 0000000000..dfb9bdb1f6
--- /dev/null
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/stripe-invoice-status-badges.tsx
@@ -0,0 +1,34 @@
+import { StripeInvoiceStatusSchema } from "@/lib/zod/schemas/invoices";
+import { StatusBadgeVariant } from "@dub/ui";
+import * as z from "zod/v4";
+
+type StripeInvoiceStatus = z.infer<typeof StripeInvoiceStatusSchema>;
+
+export const StripeInvoiceStatusBadges: Record<
+ StripeInvoiceStatus,
+ {
+ label: string;
+ variant: StatusBadgeVariant["variant"];
+ }
+> = {
+ draft: {
+ label: "Upcoming",
+ variant: "new",
+ },
+ open: {
+ label: "Open",
+ variant: "error",
+ },
+ paid: {
+ label: "Paid",
+ variant: "success",
+ },
+ uncollectible: {
+ label: "Uncollectible",
+ variant: "neutral",
+ },
+ void: {
+ label: "Void",
+ variant: "neutral",
+ },
+};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
index b680213c25..f31b3b5c75 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
@@ -60,7 +60,10 @@ export default function PaymentMethods() {
}
return (
- <div className="mb-8 rounded-xl border border-neutral-200 bg-white">
+ <div
+ id="payment-methods"
+ className="mb-8 scroll-mt-16 rounded-xl border border-neutral-200 bg-white"
+ >
<div className="flex flex-col items-start justify-between gap-y-4 p-6 md:flex-row md:items-center md:p-8">
<div>
<h2 className="text-xl font-medium">Payment methods</h2>
diff --git a/apps/web/lib/zod/schemas/invoices.ts b/apps/web/lib/zod/schemas/invoices.ts
index 00b4382f84..7c47530d2c 100644
--- a/apps/web/lib/zod/schemas/invoices.ts
+++ b/apps/web/lib/zod/schemas/invoices.ts
@@ -1,10 +1,19 @@
import { InvoiceStatus, PaymentMethod } from "@prisma/client";
import * as z from "zod/v4";
+export const StripeInvoiceStatusSchema = z.enum([
+ "draft",
+ "open",
+ "paid",
+ "uncollectible",
+ "void",
+]);
+
export const InvoiceSchema = z.object({
id: z.string(),
total: z.number(),
status: z.enum(InvoiceStatus).optional(),
+ stripeStatus: StripeInvoiceStatusSchema.nullish(), // only for Stripe subscription invoices
paymentMethod: z.enum(PaymentMethod).nullable().optional(),
createdAt: z.date(),
description: z.string().default("Dub payout"),
diff --git a/apps/web/ui/layout/sidebar/sidebar-usage.tsx b/apps/web/ui/layout/sidebar/sidebar-usage.tsx
index 6d0f6d8138..d13e07a156 100644
--- a/apps/web/ui/layout/sidebar/sidebar-usage.tsx
+++ b/apps/web/ui/layout/sidebar/sidebar-usage.tsx
@@ -2,8 +2,8 @@
import { clientAccessCheck } from "@/lib/client-access-check";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useRetryPaymentModal } from "@/ui/modals/retry-payment-modal";
import { useStartPaidPlanModal } from "@/ui/modals/start-paid-plan-modal";
-import ManageSubscriptionButton from "@/ui/workspaces/manage-subscription-button";
import {
AnimatedSizeContainer,
Button,
@@ -63,6 +63,8 @@ function UsageInner() {
const { StartPaidPlanModal, setShowStartPaidPlanModal } =
useStartPaidPlanModal();
+ const { RetryPaymentModal, setShowRetryPaymentModal } =
+ useRetryPaymentModal();
const trialDaysLeft = useMemo(() => {
if (!trialEndsAt || !isWorkspaceBillingTrialActive(trialEndsAt)) {
@@ -117,6 +119,7 @@ function UsageInner() {
return loading || usage !== undefined ? (
<>
{isTrial ? <StartPaidPlanModal /> : null}
+ {paymentFailedAt ? <RetryPaymentModal /> : null}
<AnimatedSizeContainer height>
<div className="border-t border-neutral-300/80 p-3">
{isTrial ? (
@@ -226,17 +229,25 @@ function UsageInner() {
</div>
{paymentFailedAt ? (
- <ManageSubscriptionButton
- text="Update Payment Method"
- variant="primary"
- className="mt-4 w-full"
- onMouseEnter={() => {
- setHovered(true);
- }}
- onMouseLeave={() => {
- setHovered(false);
- }}
- />
+ <DynamicTooltipWrapper
+ tooltipProps={
+ permissionsError ? { content: permissionsError } : undefined
+ }
+ >
+ <Button
+ text="Retry payment"
+ variant="primary"
+ className="mt-4 w-full"
+ disabled={Boolean(permissionsError)}
+ onClick={() => setShowRetryPaymentModal(true)}
+ onMouseEnter={() => {
+ setHovered(true);
+ }}
+ onMouseLeave={() => {
+ setHovered(false);
+ }}
+ />
+ </DynamicTooltipWrapper>
) : isTrial ? (
<DynamicTooltipWrapper
tooltipProps={
diff --git a/apps/web/ui/layout/upgrade-banner.tsx b/apps/web/ui/layout/upgrade-banner.tsx
index 35baa45bd8..90854fc92c 100644
--- a/apps/web/ui/layout/upgrade-banner.tsx
+++ b/apps/web/ui/layout/upgrade-banner.tsx
@@ -1,8 +1,16 @@
"use client";
+import { clientAccessCheck } from "@/lib/client-access-check";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useRetryPaymentModal } from "@/ui/modals/retry-payment-modal";
import { useTrialLimitActivateModal } from "@/ui/modals/trial-limit-activate-modal";
-import { Button, Crown, TriangleWarning, useMediaQuery } from "@dub/ui";
+import {
+ Button,
+ Crown,
+ DynamicTooltipWrapper,
+ TriangleWarning,
+ useMediaQuery,
+} from "@dub/ui";
import {
cn,
getTrialLimitResourceForOverageBanner,
@@ -10,7 +18,6 @@ import {
} from "@dub/utils";
import { motion } from "motion/react";
import Link from "next/link";
-import ManageSubscriptionButton from "../workspaces/manage-subscription-button";
export function useUpgradeBannerVisibility() {
const {
@@ -34,15 +41,28 @@ export function useUpgradeBannerVisibility() {
}
export function UpgradeBanner() {
- const { slug, exceededEvents, exceededLinks, exceededPayouts, trialEndsAt } =
- useWorkspace();
+ const {
+ slug,
+ exceededEvents,
+ exceededLinks,
+ exceededPayouts,
+ trialEndsAt,
+ role,
+ } = useWorkspace();
const { openTrialLimitModal, TrialLimitActivateModal } =
useTrialLimitActivateModal();
+ const { setShowRetryPaymentModal, RetryPaymentModal } =
+ useRetryPaymentModal();
const trialActive = isWorkspaceBillingTrialActive(trialEndsAt);
- const { isVisible, needsUpgrade, paymentFailed, subscriptionCanceled } =
+ const { isVisible, needsUpgrade, subscriptionCanceled } =
useUpgradeBannerVisibility();
+ const permissionsError = clientAccessCheck({
+ action: "billing.write",
+ role,
+ }).error;
+
const overageLimitResource = getTrialLimitResourceForOverageBanner({
exceededEvents: Boolean(exceededEvents),
exceededLinks: Boolean(exceededLinks),
@@ -58,6 +78,7 @@ export function UpgradeBanner() {
return (
<>
<TrialLimitActivateModal />
+ <RetryPaymentModal />
<motion.div
initial={{ transform: "translateY(-100%)" }}
animate={{ transform: "translateY(0)" }}
@@ -94,7 +115,16 @@ export function UpgradeBanner() {
) : subscriptionCanceled ? (
"Your subscription has been canceled. To reactivate, please upgrade to a paid plan."
) : (
- "Your last payment failed. Please update your payment method to avoid service disruption."
+ <>
+ Your last payment failed. Please{" "}
+ <Link
+ href={`/${slug}/settings/billing#payment-methods`}
+ className="underline"
+ >
+ update your payment method
+ </Link>{" "}
+ to avoid service disruption.
+ </>
)}
</p>
{needsUpgrade || subscriptionCanceled ? (
@@ -124,11 +154,19 @@ export function UpgradeBanner() {
</Link>
)
) : (
- <ManageSubscriptionButton
- text={isMobile ? "Update" : "Update Payment Method"}
- variant="secondary"
- className={customButtonClassname}
- />
+ <DynamicTooltipWrapper
+ tooltipProps={
+ permissionsError ? { content: permissionsError } : undefined
+ }
+ >
+ <Button
+ text={isMobile ? "Retry" : "Retry payment"}
+ variant="secondary"
+ disabled={Boolean(permissionsError)}
+ onClick={() => setShowRetryPaymentModal(true)}
+ className={customButtonClassname}
+ />
+ </DynamicTooltipWrapper>
)}
</motion.div>
</>
diff --git a/apps/web/ui/modals/retry-payment-modal.tsx b/apps/web/ui/modals/retry-payment-modal.tsx
new file mode 100644
index 0000000000..9d9aa7a1e7
--- /dev/null
+++ b/apps/web/ui/modals/retry-payment-modal.tsx
@@ -0,0 +1,205 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { InvoiceProps } from "@/lib/types";
+import { Button, LoadingSpinner, Modal } from "@dub/ui";
+import { currencyFormatter } from "@dub/utils";
+import Link from "next/link";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { toast } from "sonner";
+
+function RetryPaymentModal({
+ showModal,
+ setShowModal,
+}: {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { id: workspaceId, slug, mutate } = useWorkspace();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const submittingRef = useRef(false);
+ const [isLoadingInvoice, setIsLoadingInvoice] = useState(false);
+ const [invoice, setInvoice] = useState<InvoiceProps | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!showModal || !workspaceId) return;
+
+ let cancelled = false;
+ setIsLoadingInvoice(true);
+ setInvoice(null);
+ setLoadError(null);
+
+ fetch(
+ `/api/workspaces/${workspaceId}/billing/invoices?type=subscription&stripeStatus=open`,
+ )
+ .then(async (res) => {
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ throw new Error(
+ body?.error?.message ?? "Failed to load open invoice.",
+ );
+ }
+ const firstOpenInvoice = Array.isArray(body) ? body[0] : null;
+ if (!cancelled) {
+ setInvoice(firstOpenInvoice ?? null);
+ }
+ })
+ .catch((error) => {
+ if (!cancelled) {
+ setLoadError(
+ error instanceof Error
+ ? error.message
+ : "Failed to load open invoice.",
+ );
+ }
+ })
+ .finally(() => {
+ if (!cancelled) {
+ setIsLoadingInvoice(false);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [showModal, workspaceId]);
+
+ const handleConfirm = async () => {
+ if (submittingRef.current || !workspaceId || !invoice) {
+ return;
+ }
+ submittingRef.current = true;
+ setIsSubmitting(true);
+ try {
+ const res = await fetch(
+ `/api/workspaces/${workspaceId}/billing/retry-payment`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ invoiceId: invoice.id }),
+ },
+ );
+ if (res.ok) {
+ toast.success("Payment succeeded.");
+ // optimistically hide the banner; charge.succeeded / subscription webhooks clear paymentFailedAt in DB
+ await mutate(
+ (current) =>
+ current ? { ...current, paymentFailedAt: null } : current,
+ { revalidate: false },
+ );
+ setShowModal(false);
+ return;
+ }
+
+ const body = await res.json().catch(() => null);
+ toast.error(
+ body?.error?.message ??
+ "Failed to retry payment. Please update your payment method and try again.",
+ );
+ } catch (error) {
+ console.error(error);
+ toast.error(
+ "Failed to retry payment. Please update your payment method and try again.",
+ );
+ } finally {
+ submittingRef.current = false;
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="max-w-md"
+ >
+ <div className="sm:py-4.5 border-b border-neutral-200 px-4 py-3 sm:px-6">
+ <h3 className="text-lg font-medium text-neutral-900">Retry payment</h3>
+ </div>
+
+ <div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">
+ {isLoadingInvoice ? (
+ <div className="flex items-center justify-center py-6">
+ <LoadingSpinner className="size-5" />
+ </div>
+ ) : loadError || !invoice ? (
+ <div className="space-y-2 text-sm text-neutral-600">
+ <p>{loadError ?? "No open invoice found to retry."}</p>
+ {slug && (
+ <p>
+ You can{" "}
+ <Link
+ href={`/${slug}/settings/billing#payment-methods`}
+ className="font-medium text-neutral-900 underline underline-offset-2"
+ onClick={() => setShowModal(false)}
+ >
+ update your payment method
+ </Link>{" "}
+ instead.
+ </p>
+ )}
+ </div>
+ ) : (
+ <>
+ <div className="rounded-lg border border-neutral-200 bg-white p-4">
+ <p className="text-sm text-neutral-500">Amount due</p>
+ <p className="mt-1 text-base font-semibold tabular-nums text-neutral-900">
+ {currencyFormatter(invoice.total)}
+ </p>
+ </div>
+ <p className="text-sm text-neutral-600">
+ We&apos;ll charge your default payment method for this amount.
+ </p>
+ </>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-4 py-5 sm:px-6">
+ <Button
+ variant="secondary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Cancel"
+ onClick={() => setShowModal(false)}
+ disabled={isSubmitting}
+ />
+ <Button
+ variant="primary"
+ className="h-8 rounded-lg px-3 text-sm"
+ text="Retry payment"
+ loading={isSubmitting}
+ disabled={isSubmitting || isLoadingInvoice || !invoice}
+ onClick={handleConfirm}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+export function useRetryPaymentModal() {
+ const [showModal, setShowModal] = useState(false);
+
+ const RetryPaymentModalCallback = useCallback(() => {
+ return (
+ <RetryPaymentModal showModal={showModal} setShowModal={setShowModal} />
+ );
+ }, [showModal]);
+
+ return useMemo(
+ () => ({
+ setShowRetryPaymentModal: setShowModal,
+ RetryPaymentModal: RetryPaymentModalCallback,
+ }),
+ [setShowModal, RetryPaymentModalCallback],
+ );
+}
diff --git a/packages/ui/src/status-badge.tsx b/packages/ui/src/status-badge.tsx
index 1af95a5652..905a3b5437 100644
--- a/packages/ui/src/status-badge.tsx
+++ b/packages/ui/src/status-badge.tsx
@@ -33,6 +33,8 @@ const statusBadgeVariants = cva(
},
);
+export type StatusBadgeVariant = VariantProps<typeof statusBadgeVariants>;
+
const defaultIcons = {
neutral: CircleInfo,
new: CircleHalfDottedCheck,
@@ -44,12 +46,12 @@ const defaultIcons = {
interface BadgeProps
extends React.HTMLAttributes<HTMLSpanElement>,
- VariantProps<typeof statusBadgeVariants> {
+ StatusBadgeVariant {
icon?: Icon | null;
tooltip?: string | React.ReactNode;
}
-function StatusBadge({
+export function StatusBadge({
className,
variant,
size,
@@ -79,5 +81,3 @@ function StatusBadge({
</DynamicTooltipWrapper>
);
}
-
-export { StatusBadge, statusBadgeVariants };