feat(payment): confirm renewal only at checkout

This commit is contained in:
Codex
2026-07-29 11:26:42 +08:00
parent 196f9e39dc
commit 47c5f4098f
15 changed files with 492 additions and 240 deletions
+4 -5
View File
@@ -2,18 +2,17 @@ import { expect, type Page } from "@playwright/test";
export async function completeVipPayment(page: Page) {
const checkoutButton = page.getByRole("button", { name: "Pay and Top Up" });
await expect(checkoutButton).toBeDisabled();
await page.getByRole("button", { name: /Monthly,/i }).click();
await expect(checkoutButton).toBeEnabled();
await checkoutButton.click();
const renewalDialog = page.getByRole("dialog", {
name: "Automatic Renewal Confirmation",
});
await expect(renewalDialog).toBeVisible();
await renewalDialog.getByRole("button", { name: "Confirm" }).click();
await expect(checkoutButton).toBeEnabled();
const createOrderRequestPromise = page.waitForRequest("**/api/payment/create-order");
const orderStatusRequestPromise = page.waitForRequest("**/api/payment/order-status**");
await checkoutButton.click();
await renewalDialog.getByRole("button", { name: "Confirm" }).click();
const createOrderRequest = await createOrderRequestPromise;
expect(createOrderRequest.postDataJSON()).toMatchObject({ planId: "vip_monthly", payChannel: "stripe" });
await orderStatusRequestPromise;
@@ -74,16 +74,17 @@ test("offers the Facebook external-browser path before creating a Stripe order",
});
await seedEmailSession(page);
await page.goto("/subscription?type=vip&payChannel=stripe");
await page.goto(
"/subscription?type=vip&payChannel=stripe&character=elio",
);
await page.getByRole("button", { name: /Monthly,/i }).click();
await page
.getByRole("dialog", { name: "Automatic Renewal Confirmation" })
.getByRole("button", { name: "Confirm" })
.click();
const externalButton = page.getByRole("button", {
name: "Open in browser for more payment methods",
});
await expect(externalButton).toBeVisible();
await expect(externalButton).toBeEnabled();
await expect(
page.getByRole("dialog", { name: "Automatic Renewal Confirmation" }),
).toHaveCount(0);
const handoffRequest = page.waitForRequest("**/api/auth/handoff/checkout");
await externalButton.click();
expect((await handoffRequest).postDataJSON()).toMatchObject({
+4 -12
View File
@@ -223,19 +223,11 @@ test("Indonesia VIP defaults to QRIS and completes after status polling", async
"true",
);
const checkoutButton = page.getByRole("button", { name: "Pay and Top Up" });
await expect(checkoutButton).toBeDisabled();
await expectCheckoutButtonLayout(page);
await page.getByRole("button", { name: /Monthly, 195900 IDR/i }).click();
const renewalDialog = page.getByRole("dialog", {
name: "Automatic Renewal Confirmation",
});
await expect(renewalDialog).toBeVisible();
expect(payment.getCreateOrderCount()).toBe(0);
await renewalDialog.getByRole("button", { name: "Confirm" }).click();
await expect(renewalDialog).toBeHidden();
await expect(checkoutButton).toBeEnabled();
await expectCheckoutButtonLayout(page);
await expect(
page.getByRole("dialog", { name: "Automatic Renewal Confirmation" }),
).toHaveCount(0);
expect(payment.getCreateOrderCount()).toBe(0);
const orderId = await expectQrisOrder(
@@ -0,0 +1,23 @@
import { expect, test } from "@playwright/test";
test("serves the VIP membership benefits agreement from the same site", async ({
page,
}) => {
const response = await page.goto("/legal/vip-membership-benefits.html");
expect(response?.status()).toBe(200);
await expect(
page.getByRole("heading", { name: "VIP Membership Benefits Agreement" }),
).toBeVisible();
});
test("serves the automatic renewal agreement from the same site", async ({
page,
}) => {
const response = await page.goto("/legal/automatic-renewal.html");
expect(response?.status()).toBe(200);
await expect(
page.getByRole("heading", { name: "Automatic Renewal Agreement" }),
).toBeVisible();
});
+65
View File
@@ -0,0 +1,65 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light" />
<title>Automatic Renewal Agreement | Cozsweet</title>
<style>
:root { font-family: Georgia, "Times New Roman", serif; color: #2b1721; background: #fff8fb; }
* { box-sizing: border-box; }
body { margin: 0; padding: 24px 16px 48px; line-height: 1.65; }
main { width: min(100%, 760px); margin: 0 auto; padding: clamp(22px, 6vw, 48px); border: 1px solid #f3c6dc; border-radius: 24px; background: #fff; box-shadow: 0 18px 50px rgba(133, 45, 88, .1); }
h1 { margin: 0 0 8px; font-size: clamp(28px, 7vw, 42px); line-height: 1.12; }
h2 { margin: 28px 0 8px; font-size: 21px; }
p, li { font-family: Arial, Helvetica, sans-serif; color: #553d49; }
.meta { margin: 0 0 28px; color: #8c6176; font-size: 14px; }
.notice { padding: 14px 16px; border-radius: 14px; background: #fff0f7; }
</style>
</head>
<body>
<main>
<h1>Automatic Renewal Agreement</h1>
<p class="meta">Effective date: July 29, 2026</p>
<p class="notice">
By selecting <strong>Confirm</strong> before payment, you authorize Cozsweet and its payment provider to renew the selected membership automatically under the terms shown below.
</p>
<h2>1. When renewal applies</h2>
<p>
Automatic renewal applies only when the selected membership is identified as auto-renewing in the purchase flow. One-time credit purchases, tips, gifts, lifetime plans, and payment methods explicitly shown as one-time purchases do not automatically renew.
</p>
<h2>2. Billing frequency</h2>
<p>
The plan renews at the end of the billing period shown at checkout, such as monthly, quarterly, or annually. Renewal continues until cancelled. Your payment method may be charged shortly before or on the start of the next period as permitted by the payment provider.
</p>
<h2>3. Renewal amount</h2>
<p>
The initial charge and renewal amount are displayed before confirmation. A promotion may reduce the first charge without reducing later renewals. Unless another renewal amount is shown, renewal uses the applicable regular price for the selected plan, together with any taxes or fees required by law.
</p>
<h2>4. Confirmation</h2>
<p>
Cozsweet asks for renewal confirmation when an account first attempts to pay for an automatically renewing membership in the current agreement version. Cancelling the confirmation does not create an order. Confirming records the acknowledgement in the current browser and continues to payment.
</p>
<h2>5. Cancellation</h2>
<p>
You may cancel future renewal using a cancellation option made available in the product or by using the support/payment-issue path before the next renewal is processed. Cancellation takes effect for future billing; membership already paid for normally remains available until the end of the current term.
</p>
<h2>6. Failed or disputed payments</h2>
<p>
A failed renewal can interrupt membership benefits. If you see a duplicate charge, a long-pending payment, or missing benefits, do not repeatedly submit payment. Use <strong>Payment issue?</strong> on the purchase page and keep the returned Feedback ID. Never provide passwords, full card numbers, security codes, verification codes, or access tokens.
</p>
<h2>7. Material changes</h2>
<p>
If the renewal terms materially change, Cozsweet will update this agreement and request a new acknowledgement when required. The version effective for a payment is the version linked from its confirmation dialog.
</p>
</main>
</body>
</html>
+66
View File
@@ -0,0 +1,66 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light" />
<title>VIP Membership Benefits Agreement | Cozsweet</title>
<style>
:root { font-family: Georgia, "Times New Roman", serif; color: #2b1721; background: #fff8fb; }
* { box-sizing: border-box; }
body { margin: 0; padding: 24px 16px 48px; line-height: 1.65; }
main { width: min(100%, 760px); margin: 0 auto; padding: clamp(22px, 6vw, 48px); border: 1px solid #f3c6dc; border-radius: 24px; background: #fff; box-shadow: 0 18px 50px rgba(133, 45, 88, .1); }
h1 { margin: 0 0 8px; font-size: clamp(28px, 7vw, 42px); line-height: 1.12; }
h2 { margin: 28px 0 8px; font-size: 21px; }
p, li { font-family: Arial, Helvetica, sans-serif; color: #553d49; }
.meta { margin: 0 0 28px; color: #8c6176; font-size: 14px; }
a { color: #d8327c; }
.notice { padding: 14px 16px; border-radius: 14px; background: #fff0f7; }
</style>
</head>
<body>
<main>
<h1>VIP Membership Benefits Agreement</h1>
<p class="meta">Effective date: July 29, 2026</p>
<p class="notice">
This agreement explains the VIP membership displayed on the Cozsweet purchase page. The plan name, price, currency, duration, credits, and benefits shown at checkout are the terms that apply to your purchase.
</p>
<h2>1. Membership benefits</h2>
<p>
VIP may include the chat access, credits, private content access, or other benefits displayed for the selected plan. Benefits are available only for the membership period and account shown at checkout. A membership does not guarantee that every feature or item is free; some content can still require credits or a separate purchase when clearly shown in the product.
</p>
<h2>2. Plan term and account</h2>
<p>
Membership is attached to the Cozsweet account used for payment. The selected monthly, quarterly, annual, lifetime, or other plan term is shown before payment. Do not share payment credentials or account access with another person.
</p>
<h2>3. Automatic renewal</h2>
<p>
A plan marked as automatically renewing continues until cancelled. Before the first automatically renewing purchase, Cozsweet displays a separate confirmation. Please also read the <a href="/legal/automatic-renewal.html">Automatic Renewal Agreement</a>.
</p>
<h2>4. Prices and promotions</h2>
<p>
The checkout page is the source of truth for the current amount and currency. A first-payment or limited promotion can apply only to the initial charge; the renewal amount may be the regular price displayed in the renewal notice. Cozsweet does not ask you to pay a price that is not shown in the checkout flow.
</p>
<h2>5. Payment and access</h2>
<p>
Benefits are activated only after payment is confirmed and the order is fulfilled. A pending or failed payment does not activate membership. If payment is duplicated, remains pending, or benefits are missing, do not submit repeated payments; use the <strong>Payment issue?</strong> entry on the purchase page and retain the returned Feedback ID.
</p>
<h2>6. Cancellation, refunds, and applicable rights</h2>
<p>
Cancellation stops future renewal but does not normally remove benefits already paid for during the current term. Refund rights depend on applicable law, the payment provider, and the circumstances of the order. Use the product support or payment-issue path for review; never send a password, card number, security code, verification code, or access token.
</p>
<h2>7. Changes</h2>
<p>
If a material membership term changes, the updated version and effective date will be made available before it applies to a new purchase or renewal where required.
</p>
</main>
</body>
</html>
@@ -51,6 +51,7 @@ const mocks = vi.hoisted(() => {
commercialOffer: null,
selectedPlanId: "vip_monthly",
payChannel: "stripe" as const,
autoRenew: true,
agreed: true,
currentOrderId: null,
isCreatingOrder: false,
@@ -100,7 +101,9 @@ vi.mock("@/hooks/use-has-hydrated", () => ({
}));
vi.mock("@/stores/user/user-context", () => ({
useUserState: () => ({ currentUser: { countryCode: "ID" } }),
useUserState: () => ({
currentUser: { id: "user-renewal-1", countryCode: "ID" },
}),
}));
vi.mock("@/providers/character-catalog-provider", () => ({
@@ -164,26 +167,25 @@ vi.mock("../components", () => ({
))}
</div>
),
SubscriptionCheckoutButton: ({ disabled }: { disabled: boolean }) => (
<button type="button" data-testid="checkout" disabled={disabled}>
SubscriptionCheckoutButton: ({
disabled,
renewalPlan,
renewalConsentSubjectId,
}: {
disabled: boolean;
renewalPlan: { id: string } | null;
renewalConsentSubjectId: string | null;
}) => (
<button
type="button"
data-testid="checkout"
data-renewal-plan={renewalPlan?.id ?? ""}
data-renewal-subject={renewalConsentSubjectId ?? ""}
disabled={disabled}
>
Pay and Top Up
</button>
),
SubscriptionRenewalConfirmationDialog: ({
open,
onCancel,
onConfirm,
}: {
open: boolean;
onCancel: () => void;
onConfirm: () => void;
}) =>
open ? (
<div role="dialog">
<button type="button" onClick={onCancel}>Cancel</button>
<button type="button" onClick={onConfirm}>Confirm</button>
</div>
) : null,
SubscriptionPaymentIssueDialog: () => null,
SubscriptionPaymentSuccessDialog: () => null,
}));
@@ -218,66 +220,30 @@ describe("SubscriptionScreen payment selection flow", () => {
container.remove();
});
it("confirms VIP selection before enabling the separate checkout button", () => {
it("allows immediate checkout and changes VIP plans without opening renewal confirmation", () => {
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
const checkout = container.querySelector<HTMLButtonElement>(
'[data-testid="checkout"]',
);
expect(checkout?.disabled).toBe(true);
expect(checkout?.disabled).toBe(false);
expect(checkout?.dataset.renewalPlan).toBe("vip_monthly");
expect(checkout?.dataset.renewalSubject).toBe("user-renewal-1");
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
act(() => clickButton(container, "Confirm"));
expect(mocks.paymentDispatch).toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "vip_monthly",
});
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
expect(checkout?.disabled).toBe(false);
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
act(() => clickButton(container, "vip_quarterly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.payment.selectedPlanId).toBe("vip_monthly");
});
it("keeps the original selection when VIP confirmation is cancelled", () => {
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
act(() => clickButton(container, "vip_quarterly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
act(() => clickButton(container, "Cancel"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.payment.selectedPlanId).toBe("vip_monthly");
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith({
expect(mocks.paymentDispatch).toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "vip_quarterly",
});
});
it("requires VIP confirmation again after the page is remounted", () => {
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
act(() => clickButton(container, "vip_monthly"));
act(() => clickButton(container, "Confirm"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
act(() => root.unmount());
root = createRoot(container);
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
});
it("selects a coin package without showing the renewal dialog", () => {
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
act(() => clickButton(container, "coin_1000"));
@@ -7,11 +7,9 @@ import {
} from "@/data/schemas/payment";
import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan,
getDefaultSubscriptionPlanId,
getFirstRechargeOfferView,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews,
toVipOfferPlanViews,
} from "../subscription-screen.helpers";
@@ -280,85 +278,4 @@ describe("subscription screen helpers", () => {
).toBeNull();
});
it("requires confirmation for each unconfirmed VIP plan", () => {
const vipPlans = [
{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "",
},
{
id: "vip_quarterly",
title: "Quarterly",
price: "49.90",
currency: "usd",
originalPrice: "",
},
];
expect(
requiresVipPlanConfirmation({
planId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(true);
expect(
requiresVipPlanConfirmation({
planId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(["vip_monthly"]),
}),
).toBe(false);
expect(
requiresVipPlanConfirmation({
planId: "coin_1000",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
});
it("allows checkout only after the selected VIP plan is confirmed", () => {
const vipPlans = [
{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "",
},
];
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(["vip_monthly"]),
}),
).toBe(true);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "coin_1000",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(true);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
});
});
@@ -0,0 +1,208 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
dispatch: vi.fn(),
resetLaunchState: vi.fn(),
payment: {
selectedPlanId: "vip_monthly",
autoRenew: true,
payChannel: "stripe" as "stripe" | "ezpay",
commercialOfferId: null,
chatActionId: null,
currentOrderId: null,
errorMessage: null,
isCreatingOrder: false,
isPollingOrder: false,
},
}));
vi.mock("@/stores/payment/payment-context", () => ({
usePaymentState: () => mocks.payment,
usePaymentDispatch: () => mocks.dispatch,
}));
vi.mock("@/app/_hooks/use-payment-launch-flow", () => ({
usePaymentLaunchFlow: () => ({
resetLaunchState: mocks.resetLaunchState,
launch: {},
}),
}));
vi.mock("@/app/_components/payment/payment-launch-dialogs", () => ({
PaymentLaunchDialogs: () => null,
}));
vi.mock("@/app/_components/payment/external-browser-checkout-button", () => ({
ExternalBrowserCheckoutButton: () => null,
}));
vi.mock("../subscription-cta-button", () => ({
SubscriptionCtaButton: ({
children,
disabled,
onClick,
}: {
children: React.ReactNode;
disabled?: boolean;
onClick?: () => void;
}) => (
<button type="button" disabled={disabled} onClick={onClick}>
{children}
</button>
),
}));
vi.mock("../subscription-renewal-confirmation-dialog", () => ({
SubscriptionRenewalConfirmationDialog: ({
open,
onCancel,
onConfirm,
}: {
open: boolean;
onCancel: () => void;
onConfirm: () => void;
}) =>
open ? (
<div role="dialog">
<button type="button" onClick={onCancel}>Cancel</button>
<button type="button" onClick={onConfirm}>Confirm</button>
</div>
) : null,
}));
import { SubscriptionCheckoutButton } from "../subscription-checkout-button";
const renewalPlan = {
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "39.90",
};
describe("SubscriptionCheckoutButton renewal confirmation", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
localStorage.clear();
mocks.dispatch.mockClear();
mocks.resetLaunchState.mockClear();
mocks.payment.selectedPlanId = "vip_monthly";
mocks.payment.autoRenew = true;
mocks.payment.payChannel = "stripe";
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("shows confirmation on the first auto-renewing VIP checkout and resumes after confirm", () => {
renderButton(root, "user-1");
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.dispatch).not.toHaveBeenCalled();
act(() => clickButton(container, "Confirm"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.resetLaunchState).toHaveBeenCalledOnce();
expect(mocks.dispatch).toHaveBeenCalledWith({
type: "PaymentCreateOrderSubmitted",
});
});
it("does not ask the same user again after confirmation", () => {
renderButton(root, "user-1");
act(() => clickButton(container, "Pay and Top Up"));
act(() => clickButton(container, "Confirm"));
mocks.dispatch.mockClear();
mocks.resetLaunchState.mockClear();
act(() => root.unmount());
root = createRoot(container);
renderButton(root, "user-1");
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.resetLaunchState).toHaveBeenCalledOnce();
expect(mocks.dispatch).toHaveBeenCalledWith({
type: "PaymentCreateOrderSubmitted",
});
});
it("keeps asking after cancel and isolates acknowledgement by user", () => {
renderButton(root, "user-1");
act(() => clickButton(container, "Pay and Top Up"));
act(() => clickButton(container, "Cancel"));
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
act(() => clickButton(container, "Confirm"));
mocks.dispatch.mockClear();
act(() => root.unmount());
root = createRoot(container);
renderButton(root, "user-2");
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.dispatch).not.toHaveBeenCalled();
});
it("skips confirmation for a non-renewing purchase", () => {
mocks.payment.autoRenew = false;
renderButton(root, "user-1", null);
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.dispatch).toHaveBeenCalledWith({
type: "PaymentCreateOrderSubmitted",
});
});
it("skips confirmation for one-time EzPay membership checkout", () => {
mocks.payment.payChannel = "ezpay";
renderButton(root, "user-1");
act(() => clickButton(container, "Pay and Top Up"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.dispatch).toHaveBeenCalledWith({
type: "PaymentCreateOrderSubmitted",
});
});
});
function renderButton(
root: Root,
renewalConsentSubjectId: string,
plan: typeof renewalPlan | null = renewalPlan,
): void {
act(() =>
root.render(
<SubscriptionCheckoutButton
subscriptionType="vip"
sourceCharacterSlug="elio"
renewalPlan={plan}
renewalConsentSubjectId={renewalConsentSubjectId}
/>,
),
);
}
function clickButton(root: ParentNode, label: string): void {
const button = Array.from(root.querySelectorAll("button")).find(
(item) => item.textContent?.trim() === label,
);
if (!button) throw new Error(`Expected ${label} button`);
button.click();
}
@@ -71,7 +71,14 @@ describe("subscription payment dialogs", () => {
expect(dialog?.textContent).toContain("Automatic Renewal Confirmation");
expect(dialog?.textContent).toContain("Monthly");
expect(dialog?.textContent).toContain("19.90 usd");
expect(dialog?.querySelectorAll("a")).toHaveLength(2);
expect(
Array.from(dialog?.querySelectorAll("a") ?? []).map((link) =>
link.getAttribute("href"),
),
).toEqual([
"/legal/vip-membership-benefits.html",
"/legal/automatic-renewal.html",
]);
act(() => clickButton(dialog, "Confirm"));
expect(onConfirm).toHaveBeenCalledOnce();
@@ -4,11 +4,17 @@
*
* 包装 `SubscriptionCtaButton` —— 通过 payment 状态机创建后端订单并拉起支付。
*/
import { useState } from "react";
import { usePaymentLaunchFlow } from "@/app/_hooks/use-payment-launch-flow";
import { PaymentLaunchDialogs } from "@/app/_components/payment/payment-launch-dialogs";
import { ExternalBrowserCheckoutButton } from "@/app/_components/payment/external-browser-checkout-button";
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
import {
hasAutomaticRenewalAcknowledgement,
rememberAutomaticRenewalAcknowledgement,
} from "@/lib/payment/automatic_renewal_acknowledgement";
import {
usePaymentDispatch,
usePaymentState,
@@ -16,15 +22,19 @@ import {
import { Logger } from "@/utils/logger";
import { SubscriptionCtaButton } from "./subscription-cta-button";
import { SubscriptionRenewalConfirmationDialog } from "./subscription-renewal-confirmation-dialog";
import type { VipOfferPlanView } from "./subscription-vip-offer-section";
const log = new Logger("SubscriptionCheckoutButton");
export interface SubscriptionCheckoutButtonProps {
/** 是否可用(未选套餐或 VIP 套餐尚未确认自动续费时为 false */
/** 是否可用(未选套餐、缺少角色来源或支付处理中为 false */
disabled?: boolean;
subscriptionType: "vip" | "topup";
returnTo?: SubscriptionReturnTo;
sourceCharacterSlug?: string;
renewalPlan?: VipOfferPlanView | null;
renewalConsentSubjectId?: string | null;
}
export function SubscriptionCheckoutButton({
@@ -32,7 +42,11 @@ export function SubscriptionCheckoutButton({
subscriptionType,
returnTo = null,
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
renewalPlan = null,
renewalConsentSubjectId = null,
}: SubscriptionCheckoutButtonProps) {
const [showRenewalConfirmation, setShowRenewalConfirmation] =
useState(false);
const payment = usePaymentState();
const paymentDispatch = usePaymentDispatch();
const paymentLaunch = usePaymentLaunchFlow({
@@ -53,12 +67,32 @@ export function SubscriptionCheckoutButton({
? "Creating order..."
: readyLabel;
const handleClick = () => {
const startCheckout = () => {
if (disabled || isLoading) return;
paymentLaunch.resetLaunchState();
paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
};
const handleClick = () => {
if (disabled || isLoading) return;
if (
payment.payChannel === "stripe" &&
payment.autoRenew &&
renewalPlan !== null &&
!hasAutomaticRenewalAcknowledgement(renewalConsentSubjectId)
) {
setShowRenewalConfirmation(true);
return;
}
startCheckout();
};
const handleRenewalConfirm = () => {
rememberAutomaticRenewalAcknowledgement(renewalConsentSubjectId);
setShowRenewalConfirmation(false);
startCheckout();
};
return (
<>
<SubscriptionCtaButton
@@ -105,6 +139,12 @@ export function SubscriptionCheckoutButton({
ezpayDescription="Your order has been created. Continue to the secure payment page to finish."
launch={paymentLaunch}
/>
<SubscriptionRenewalConfirmationDialog
open={showRenewalConfirmation}
plan={renewalPlan}
onCancel={() => setShowRenewalConfirmation(false)}
onConfirm={handleRenewalConfirm}
/>
</>
);
}
@@ -105,30 +105,6 @@ export function findSelectedSubscriptionPlan(input: {
return plans.find((plan) => plan.id === input.selectedPlanId) ?? null;
}
export function requiresVipPlanConfirmation(input: {
planId: string;
vipPlans: readonly VipOfferPlanView[];
confirmedVipPlanIds: ReadonlySet<string>;
}): boolean {
return (
input.vipPlans.some((plan) => plan.id === input.planId) &&
!input.confirmedVipPlanIds.has(input.planId)
);
}
export function canCheckoutSubscriptionPlan(input: {
selectedPlanId: string;
vipPlans: readonly VipOfferPlanView[];
confirmedVipPlanIds: ReadonlySet<string>;
}): boolean {
if (!input.selectedPlanId) return false;
return !requiresVipPlanConfirmation({
planId: input.selectedPlanId,
vipPlans: input.vipPlans,
confirmedVipPlanIds: input.confirmedVipPlanIds,
});
}
export function getDefaultSubscriptionPlanId(input: {
canSubscribeVip: boolean;
selectedPlanId: string;
+5 -46
View File
@@ -24,16 +24,13 @@ import {
SubscriptionCoinsOfferSection,
SubscriptionPaymentIssueDialog,
SubscriptionPaymentSuccessDialog,
SubscriptionRenewalConfirmationDialog,
SubscriptionVipOfferSection,
} from "./components";
import styles from "./components/subscription-screen.module.css";
import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan,
getFirstRechargeOfferView,
getDefaultSubscriptionPlanId,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews,
toVipOfferPlanViews,
type SubscriptionType,
@@ -69,10 +66,6 @@ export function SubscriptionScreen({
resumeOrderId = null,
chatActionId = null,
}: SubscriptionScreenProps) {
const [confirmedVipPlanIds, setConfirmedVipPlanIds] = useState<
ReadonlySet<string>
>(() => new Set());
const [pendingVipPlanId, setPendingVipPlanId] = useState<string | null>(null);
const [showPaymentIssueDialog, setShowPaymentIssueDialog] = useState(false);
const [paymentIssueNotice, setPaymentIssueNotice] = useState<string | null>(
null,
@@ -156,49 +149,20 @@ export function SubscriptionScreen({
const isPaymentBusy =
payment.isCreatingOrder ||
payment.isPollingOrder;
const selectedPlanIsVip = vipOfferPlans.some(
(plan) => plan.id === payment.selectedPlanId,
);
const selectedVipPlan =
vipOfferPlans.find((plan) => plan.id === payment.selectedPlanId) ?? null;
const selectedPlanIsVip = selectedVipPlan !== null;
const canActivate =
sourceCharacter !== null &&
selectedPlan !== null &&
canCheckoutSubscriptionPlan({
selectedPlanId: payment.selectedPlanId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
}) &&
!isPaymentBusy;
const pendingVipPlan =
vipOfferPlans.find((plan) => plan.id === pendingVipPlanId) ?? null;
const handleSelectPlan = (planId: string) => {
const plan = payment.plans.find((item) => item.planId === planId);
if (plan) behaviorAnalytics.planClick(plan, analyticsContext);
if (
requiresVipPlanConfirmation({
planId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
})
) {
setPendingVipPlanId(planId);
return;
}
paymentDispatch({ type: "PaymentPlanSelected", planId });
};
const handleConfirmVipPlan = () => {
if (!pendingVipPlanId) return;
const planId = pendingVipPlanId;
setConfirmedVipPlanIds((current) => {
const next = new Set(current);
next.add(planId);
return next;
});
paymentDispatch({ type: "PaymentPlanSelected", planId });
setPendingVipPlanId(null);
};
const handlePaymentMethodChange = (payChannel: PayChannel) => {
paymentDispatch({
type: "PaymentPayChannelChanged",
@@ -338,16 +302,11 @@ export function SubscriptionScreen({
subscriptionType={subscriptionType}
returnTo={returnTo}
sourceCharacterSlug={sourceCharacter?.slug ?? DEFAULT_CHARACTER_SLUG}
renewalPlan={selectedVipPlan}
renewalConsentSubjectId={userState.currentUser?.id || null}
/>
</div>
<SubscriptionRenewalConfirmationDialog
open={pendingVipPlan !== null}
plan={pendingVipPlan}
onCancel={() => setPendingVipPlanId(null)}
onConfirm={handleConfirmVipPlan}
/>
{showPaymentIssueDialog ? (
<SubscriptionPaymentIssueDialog
open
+2 -2
View File
@@ -13,11 +13,11 @@ export class AppConstants {
/** 会员服务协议文档链接 */
static readonly membershipAgreementUrl =
"https://www.banlv-ai.com/cozsweet/membership-agreement.html";
"/legal/vip-membership-benefits.html";
/** 自动续费服务协议文档链接 */
static readonly autoRenewalAgreementUrl =
"https://www.banlv-ai.com/cozsweet/auto-renewal-agreement.html";
"/legal/automatic-renewal.html";
/** 开发环境 APP 标题 */
static readonly appTitleDevelopment = "Develop";
@@ -0,0 +1,33 @@
export const AUTOMATIC_RENEWAL_AGREEMENT_VERSION = "2026-07-29";
const STORAGE_PREFIX = "cozsweet.automatic-renewal-acknowledged";
function storageKey(subjectId: string | null | undefined): string | null {
const normalized = subjectId?.trim();
if (!normalized) return null;
return `${STORAGE_PREFIX}:${AUTOMATIC_RENEWAL_AGREEMENT_VERSION}:${encodeURIComponent(normalized)}`;
}
export function hasAutomaticRenewalAcknowledgement(
subjectId: string | null | undefined,
): boolean {
const key = storageKey(subjectId);
if (!key || typeof window === "undefined") return false;
try {
return window.localStorage.getItem(key) === "confirmed";
} catch {
return false;
}
}
export function rememberAutomaticRenewalAcknowledgement(
subjectId: string | null | undefined,
): void {
const key = storageKey(subjectId);
if (!key || typeof window === "undefined") return;
try {
window.localStorage.setItem(key, "confirmed");
} catch {
// Storage can be unavailable in privacy-restricted in-app browsers.
}
}