feat(subscription): separate selection from payment and add issue feedback

(cherry picked from commit fe9d31146b)
This commit is contained in:
Codex
2026-07-27 11:35:28 +08:00
parent 30f88d3a20
commit b7221f2f70
14 changed files with 1258 additions and 73 deletions
@@ -0,0 +1,267 @@
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(() => {
const payment = {
status: "ready",
plans: [
{
planId: "vip_monthly",
planName: "Monthly",
orderType: "vip_monthly",
vipDays: 30,
dolAmount: null,
amountCents: 1990,
originalAmountCents: 3990,
currency: "USD",
},
{
planId: "vip_quarterly",
planName: "Quarterly",
orderType: "vip_quarterly",
vipDays: 90,
dolAmount: null,
amountCents: 4990,
originalAmountCents: 6990,
currency: "USD",
},
{
planId: "coin_1000",
planName: "1000 Coins",
orderType: "coins_1000",
vipDays: null,
dolAmount: 1000,
amountCents: 990,
originalAmountCents: null,
currency: "USD",
},
],
isFirstRecharge: false,
commercialOffer: null,
selectedPlanId: "vip_monthly",
payChannel: "stripe" as const,
agreed: true,
currentOrderId: null,
isCreatingOrder: false,
isPollingOrder: false,
isLoadingPlans: false,
};
const paymentDispatch = vi.fn((event: { type: string; planId?: string }) => {
if (event.type === "PaymentPlanSelected" && event.planId) {
payment.selectedPlanId = event.planId;
}
});
return { payment, paymentDispatch, planClick: vi.fn() };
});
vi.mock("@/app/_components", () => ({
BackButton: () => <button type="button">Back</button>,
}));
vi.mock("@/app/_components/core", () => ({
MobileShell: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("@/app/_components/payment/payment-method-selector", () => ({
PaymentMethodSelector: () => <div>Payment methods</div>,
}));
vi.mock("@/app/_hooks/use-payment-method-selection", () => ({
usePaymentMethodSelection: () => undefined,
}));
vi.mock("@/app/_hooks/use-payment-plan-analytics", () => ({
usePaymentPlanAnalytics: () => undefined,
}));
vi.mock("@/hooks/use-has-hydrated", () => ({
useHasHydrated: () => true,
}));
vi.mock("@/stores/user/user-context", () => ({
useUserState: () => ({ currentUser: { countryCode: "ID" } }),
}));
vi.mock("@/lib/payment/payment_method", () => ({
getPaymentMethodConfig: () => ({
initialPayChannel: "stripe",
showPaymentMethodSelector: true,
ezpayDisplayName: "QRIS",
}),
}));
vi.mock("@/lib/analytics", () => ({
behaviorAnalytics: { planClick: mocks.planClick },
getDefaultPaymentAnalyticsContext: () => ({}),
}));
vi.mock("../use-subscription-payment-flow", () => ({
useSubscriptionPaymentFlow: () => ({
payment: mocks.payment,
paymentDispatch: mocks.paymentDispatch,
showPaymentSuccessDialog: false,
handleBackClick: vi.fn(),
handlePaymentSuccessClose: vi.fn(),
}),
}));
vi.mock("../components", () => ({
SubscriptionVipOfferSection: ({
plans,
onSelectPlan,
}: {
plans: Array<{ id: string }>;
onSelectPlan: (id: string) => void;
}) => (
<div>
{plans.map((plan) => (
<button key={plan.id} type="button" onClick={() => onSelectPlan(plan.id)}>
{plan.id}
</button>
))}
</div>
),
SubscriptionCoinsOfferSection: ({
plans,
onSelectPlan,
}: {
plans: Array<{ id: string }>;
onSelectPlan: (id: string) => void;
}) => (
<div>
{plans.map((plan) => (
<button key={plan.id} type="button" onClick={() => onSelectPlan(plan.id)}>
{plan.id}
</button>
))}
</div>
),
SubscriptionCheckoutButton: ({ disabled }: { disabled: boolean }) => (
<button type="button" data-testid="checkout" 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,
}));
import { SubscriptionScreen } from "../subscription-screen";
describe("SubscriptionScreen payment selection flow", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
mocks.payment.selectedPlanId = "vip_monthly";
mocks.paymentDispatch.mockClear();
mocks.planClick.mockClear();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("confirms VIP selection before enabling the separate checkout button", () => {
act(() => root.render(<SubscriptionScreen />));
const checkout = container.querySelector<HTMLButtonElement>(
'[data-testid="checkout"]',
);
expect(checkout?.disabled).toBe(true);
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 />));
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({
type: "PaymentPlanSelected",
planId: "vip_quarterly",
});
});
it("requires VIP confirmation again after the page is remounted", () => {
act(() => root.render(<SubscriptionScreen />));
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 />));
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 />));
act(() => clickButton(container, "coin_1000"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.paymentDispatch).toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "coin_1000",
});
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
});
});
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();
}
@@ -7,9 +7,11 @@ import {
} from "@/data/schemas/payment"; } from "@/data/schemas/payment";
import { import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan, findSelectedSubscriptionPlan,
getDefaultSubscriptionPlanId, getDefaultSubscriptionPlanId,
getFirstRechargeOfferView, getFirstRechargeOfferView,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews, toCoinsOfferPlanViews,
toVipOfferPlanViews, toVipOfferPlanViews,
} from "../subscription-screen.helpers"; } from "../subscription-screen.helpers";
@@ -277,4 +279,86 @@ describe("subscription screen helpers", () => {
}), }),
).toBeNull(); ).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,224 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Result } from "@/utils/result";
import { SubscriptionPaymentIssueDialog } from "../subscription-payment-issue-dialog";
import { SubscriptionRenewalConfirmationDialog } from "../subscription-renewal-confirmation-dialog";
const mocks = vi.hoisted(() => ({
submitFeedback: vi.fn(),
}));
vi.mock("@/lib/feedback", () => ({
submitFeedback: mocks.submitFeedback,
}));
vi.mock("@/app/feedback/feedback-context", () => ({
createFeedbackContext: () => ({
appVersion: "test",
platform: "web",
browser: "Chrome",
viewport: "390x844@3",
}),
}));
describe("subscription payment dialogs", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
mocks.submitFeedback.mockReset();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
document.body.querySelectorAll('[role="dialog"]').forEach((node) => node.remove());
});
it("confirms a VIP plan without submitting payment", () => {
const onConfirm = vi.fn();
const onCancel = vi.fn();
act(() =>
root.render(
<SubscriptionRenewalConfirmationDialog
open
plan={{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "39.90",
}}
onCancel={onCancel}
onConfirm={onConfirm}
/>,
),
);
const dialog = document.body.querySelector('[role="dialog"]');
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);
act(() => clickButton(dialog, "Confirm"));
expect(onConfirm).toHaveBeenCalledOnce();
expect(onCancel).not.toHaveBeenCalled();
});
it("submits Other as a Manager payment issue with one description field", async () => {
mocks.submitFeedback.mockResolvedValue(
Result.ok({ feedbackId: "feedback-payment-1" }),
);
const onClose = vi.fn();
const onSubmitted = vi.fn();
act(() =>
root.render(
<SubscriptionPaymentIssueDialog
open
subscriptionType="vip"
planId="vip_monthly"
orderId={null}
payChannel="ezpay"
countryCode="ID"
characterId="maya"
onClose={onClose}
onSubmitted={onSubmitted}
/>,
),
);
const other = document.body.querySelector<HTMLInputElement>(
'input[value="other"]',
);
expect(
Array.from(document.body.querySelectorAll<HTMLInputElement>('input[type="radio"]')).map(
(input) => input.parentElement?.textContent?.trim(),
),
).toEqual([
"Concerned about card information security",
"Insufficient card or wallet balance",
"No supported payment method available",
"Too expensive",
"Other",
]);
act(() => {
other?.click();
});
const textarea = document.body.querySelector("textarea");
expect(textarea?.getAttribute("placeholder")).toBe(
"Please describe the payment problem you encountered.",
);
act(() => setTextareaValue(textarea, "QRIS did not open correctly."));
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(mocks.submitFeedback).toHaveBeenCalledWith({
category: "payment",
content: "Payment issue: Other\nDetails: QRIS did not open correctly.",
context: {
appVersion: "test",
platform: "web",
browser: "Chrome",
viewport: "390x844@3",
sourcePage: "subscription",
paymentIssueReason: "other",
subscriptionType: "vip",
planId: "vip_monthly",
payChannel: "ezpay",
countryCode: "ID",
characterId: "maya",
},
images: [],
idempotencyKey: expect.stringMatching(/^payment_feedback_[A-Za-z0-9_-]+$/),
});
expect(onSubmitted).toHaveBeenCalledWith(
"Thanks. Your payment issue has been submitted.",
);
expect(onClose).toHaveBeenCalledOnce();
});
it("keeps a failed payment issue open and reuses its idempotency key for retry", async () => {
mocks.submitFeedback
.mockResolvedValueOnce(Result.err(new Error("backend unavailable")))
.mockResolvedValueOnce(Result.ok({ feedbackId: "feedback-payment-2" }));
const onClose = vi.fn();
act(() =>
root.render(
<SubscriptionPaymentIssueDialog
open
subscriptionType="topup"
planId="coin_1000"
orderId="pay_pending_1"
payChannel="stripe"
countryCode="US"
characterId="elio"
onClose={onClose}
onSubmitted={() => undefined}
/>,
),
);
const reason = document.body.querySelector<HTMLInputElement>(
'input[value="tooExpensive"]',
);
act(() => reason?.click());
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(document.body.textContent).toContain(
"Unable to submit. Please try again.",
);
expect(onClose).not.toHaveBeenCalled();
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(mocks.submitFeedback).toHaveBeenCalledTimes(2);
expect(mocks.submitFeedback.mock.calls[0]?.[0].idempotencyKey).toBe(
mocks.submitFeedback.mock.calls[1]?.[0].idempotencyKey,
);
expect(onClose).toHaveBeenCalledOnce();
});
});
function clickButton(root: ParentNode | null, 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();
}
function setTextareaValue(
element: HTMLTextAreaElement | null,
value: string,
): void {
if (!element) throw new Error("Expected textarea");
const setter = Object.getOwnPropertyDescriptor(
HTMLTextAreaElement.prototype,
"value",
)?.set;
setter?.call(element, value);
element.dispatchEvent(new Event("input", { bubbles: true }));
}
+2
View File
@@ -6,4 +6,6 @@ export * from "./subscription-checkout-button";
export * from "./subscription-coins-offer-section"; export * from "./subscription-coins-offer-section";
export * from "./subscription-cta-button"; export * from "./subscription-cta-button";
export * from "./subscription-payment-success-dialog"; export * from "./subscription-payment-success-dialog";
export * from "./subscription-payment-issue-dialog";
export * from "./subscription-renewal-confirmation-dialog";
export * from "./subscription-vip-offer-section"; export * from "./subscription-vip-offer-section";
@@ -19,7 +19,7 @@ import { SubscriptionCtaButton } from "./subscription-cta-button";
const log = new Logger("SubscriptionCheckoutButton"); const log = new Logger("SubscriptionCheckoutButton");
export interface SubscriptionCheckoutButtonProps { export interface SubscriptionCheckoutButtonProps {
/** 是否可用(未选套餐 / 未勾选协议 → false */ /** 是否可用(未选套餐或 VIP 套餐尚未确认自动续费时为 false */
disabled?: boolean; disabled?: boolean;
subscriptionType: "vip" | "topup"; subscriptionType: "vip" | "topup";
returnTo?: SubscriptionReturnTo; returnTo?: SubscriptionReturnTo;
@@ -44,22 +44,13 @@ export function SubscriptionCheckoutButton({
subscriptionType, subscriptionType,
}); });
const isLoading = const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
payment.isCreatingOrder || const readyLabel = "Pay and Top Up";
payment.isPollingOrder;
const readyLabel =
subscriptionType === "topup" ? "Pay and Top Up" : "Pay and Activiate";
const agreementLabel =
subscriptionType === "topup"
? "Confirm the agreement and Top Up"
: "Confirm the agreement and Activate";
const label = payment.isPollingOrder const label = payment.isPollingOrder
? "Processing payment..." ? "Processing payment..."
: payment.isCreatingOrder : payment.isCreatingOrder
? "Creating order..." ? "Creating order..."
: payment.agreed : readyLabel;
? readyLabel
: agreementLabel;
const handleClick = () => { const handleClick = () => {
if (disabled || isLoading) return; if (disabled || isLoading) return;
@@ -0,0 +1,187 @@
.scrim {
position: fixed;
inset: 0;
z-index: 90;
display: flex;
align-items: center;
justify-content: center;
padding:
calc(20px + var(--app-safe-top, 0px))
calc(16px + var(--app-safe-right, 0px))
calc(20px + var(--app-safe-bottom, 0px))
calc(16px + var(--app-safe-left, 0px));
}
.panel {
width: min(100%, 420px);
max-height: min(86dvh, 720px);
overflow-y: auto;
border: 1px solid rgba(255, 95, 174, 0.24);
border-radius: 24px;
background: #ffffff;
color: #23171d;
box-shadow: 0 28px 80px rgba(42, 20, 31, 0.3);
}
.content {
display: flex;
flex-direction: column;
gap: 16px;
padding: clamp(20px, 5vw, 28px);
}
.title {
margin: 0;
color: #23171d;
font-size: clamp(20px, 5vw, 24px);
font-weight: 900;
line-height: 1.2;
}
.description {
margin: 0;
color: #65545d;
font-size: 14px;
line-height: 1.65;
}
.link {
color: #db327f;
font-weight: 800;
text-decoration: underline;
text-underline-offset: 2px;
}
.reasonList {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding: 0;
border: 0;
}
.reasonOption {
display: flex;
min-height: 48px;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 11px 13px;
border: 1px solid #eadce3;
border-radius: 14px;
background: #fffafb;
color: #403139;
cursor: pointer;
font-size: 14px;
font-weight: 700;
line-height: 1.35;
}
.reasonOption:has(input:checked) {
border-color: #f657a0;
background: #fff0f7;
box-shadow: 0 0 0 2px rgba(246, 87, 160, 0.12);
}
.reasonOption input {
flex: 0 0 auto;
width: 20px;
height: 20px;
accent-color: #f657a0;
}
.field {
display: flex;
flex-direction: column;
gap: 8px;
color: #403139;
font-size: 14px;
font-weight: 800;
}
.field textarea {
width: 100%;
min-height: 112px;
resize: vertical;
border: 1px solid #dccbd4;
border-radius: 14px;
background: #ffffff;
color: #23171d;
padding: 12px;
font: inherit;
font-weight: 500;
line-height: 1.5;
}
.field textarea:focus-visible {
border-color: #f657a0;
outline: 2px solid rgba(246, 87, 160, 0.18);
}
.error {
margin: 0;
color: #b42318;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 2px;
}
.secondaryButton,
.primaryButton {
min-height: 46px;
border-radius: 999px;
padding: 10px 18px;
cursor: pointer;
font: inherit;
font-size: 15px;
font-weight: 900;
}
.secondaryButton {
border: 1px solid #d9c7d0;
background: #f7f1f4;
color: #55434c;
}
.primaryButton {
border: 0;
background: linear-gradient(135deg, #ff67b3 0%, #f657a0 100%);
color: #ffffff;
box-shadow: 0 8px 20px rgba(246, 87, 160, 0.26);
}
.secondaryButton:disabled,
.primaryButton:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.srOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 360px) {
.content {
padding: 18px;
}
.reasonOption {
font-size: 13px;
}
}
@@ -0,0 +1,215 @@
"use client";
import { type FormEvent, useMemo, useState } from "react";
import { ModalPortal } from "@/app/_components/core/modal-portal";
import { createFeedbackContext } from "@/app/feedback/feedback-context";
import type { PayChannel } from "@/data/schemas/payment";
import { submitFeedback } from "@/lib/feedback";
import type { SubscriptionType } from "../subscription-screen.helpers";
import styles from "./subscription-dialog.module.css";
const PAYMENT_ISSUE_REASONS = [
{
value: "cardSecurityConcern",
label: "Concerned about card information security",
},
{
value: "insufficientBalance",
label: "Insufficient card or wallet balance",
},
{
value: "unsupportedPaymentMethod",
label: "No supported payment method available",
},
{ value: "tooExpensive", label: "Too expensive" },
{ value: "other", label: "Other" },
] as const;
type PaymentIssueReason = (typeof PAYMENT_ISSUE_REASONS)[number]["value"];
const OTHER_DETAILS_MIN_LENGTH = 10;
const OTHER_DETAILS_MAX_LENGTH = 2000;
const SUCCESS_MESSAGE = "Thanks. Your payment issue has been submitted.";
const FAILURE_MESSAGE = "Unable to submit. Please try again.";
export interface SubscriptionPaymentIssueDialogProps {
open: boolean;
subscriptionType: SubscriptionType;
planId: string | null;
orderId: string | null;
payChannel: PayChannel;
countryCode?: string | null;
characterId: string;
onClose: () => void;
onSubmitted: (message: string) => void;
}
export function SubscriptionPaymentIssueDialog({
open,
subscriptionType,
planId,
orderId,
payChannel,
countryCode,
characterId,
onClose,
onSubmitted,
}: SubscriptionPaymentIssueDialogProps) {
const [reason, setReason] = useState<PaymentIssueReason | null>(null);
const [details, setDetails] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [idempotencyKey] = useState(createIdempotencyKey);
const normalizedDetails = details.trim();
const detailsError = useMemo(() => {
if (reason !== "other") return null;
if (normalizedDetails.length < OTHER_DETAILS_MIN_LENGTH) {
return `Please describe the issue in at least ${OTHER_DETAILS_MIN_LENGTH} characters.`;
}
if (normalizedDetails.length > OTHER_DETAILS_MAX_LENGTH) {
return `Your description cannot exceed ${OTHER_DETAILS_MAX_LENGTH} characters.`;
}
return null;
}, [normalizedDetails, reason]);
const canSubmit = reason !== null && detailsError === null && !isSubmitting;
const handleClose = () => {
if (isSubmitting) return;
onClose();
};
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!reason || !canSubmit) {
setErrorMessage(
detailsError ?? "Please select the payment problem you encountered.",
);
return;
}
const reasonLabel = PAYMENT_ISSUE_REASONS.find(
(item) => item.value === reason,
)?.label;
if (!reasonLabel) return;
setIsSubmitting(true);
setErrorMessage(null);
const result = await submitFeedback({
category: "payment",
content:
reason === "other"
? `Payment issue: Other\nDetails: ${normalizedDetails}`
: `Payment issue: ${reasonLabel}`,
context: {
...createFeedbackContext(),
sourcePage: "subscription",
paymentIssueReason: reason,
subscriptionType,
...(planId ? { planId } : {}),
...(orderId ? { orderId } : {}),
payChannel,
...(countryCode ? { countryCode } : {}),
characterId,
},
images: [],
idempotencyKey,
});
if (!result.success) {
setErrorMessage(FAILURE_MESSAGE);
setIsSubmitting(false);
return;
}
setIsSubmitting(false);
onSubmitted(SUCCESS_MESSAGE);
onClose();
};
return (
<ModalPortal
open={open}
onClose={handleClose}
scrimClassName={styles.scrim}
panelClassName={styles.panel}
scrimOpacity={0.56}
persistent={isSubmitting}
ariaLabel="What problem did you encounter?"
>
<form className={styles.content} onSubmit={handleSubmit}>
<h2 className={styles.title}>What problem did you encounter?</h2>
<fieldset className={styles.reasonList} disabled={isSubmitting}>
<legend className={styles.srOnly}>Payment problem</legend>
{PAYMENT_ISSUE_REASONS.map((item) => (
<label key={item.value} className={styles.reasonOption}>
<span>{item.label}</span>
<input
type="radio"
name="paymentIssueReason"
value={item.value}
checked={reason === item.value}
onChange={() => {
setReason(item.value);
setErrorMessage(null);
}}
/>
</label>
))}
</fieldset>
{reason === "other" ? (
<label className={styles.field}>
<span>Please describe the issue</span>
<textarea
value={details}
minLength={OTHER_DETAILS_MIN_LENGTH}
maxLength={OTHER_DETAILS_MAX_LENGTH}
rows={4}
disabled={isSubmitting}
placeholder="Please describe the payment problem you encountered."
onChange={(event) => {
setDetails(event.target.value);
setErrorMessage(null);
}}
/>
</label>
) : null}
{errorMessage ? (
<p className={styles.error} role="alert">
{errorMessage}
</p>
) : null}
<div className={styles.actions}>
<button
type="button"
className={styles.secondaryButton}
disabled={isSubmitting}
onClick={handleClose}
>
Cancel
</button>
<button
type="submit"
className={styles.primaryButton}
disabled={!canSubmit}
>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
</div>
</form>
</ModalPortal>
);
}
function createIdempotencyKey(): string {
const token =
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `${Date.now()}_${Math.random().toString(36).slice(2)}`;
return `payment_feedback_${token}`;
}
@@ -0,0 +1,83 @@
"use client";
import { ModalPortal } from "@/app/_components/core/modal-portal";
import { AppConstants } from "@/core/app_constants";
import type { VipOfferPlanView } from "./subscription-vip-offer-section";
import styles from "./subscription-dialog.module.css";
export interface SubscriptionRenewalConfirmationDialogProps {
open: boolean;
plan: VipOfferPlanView | null;
onCancel: () => void;
onConfirm: () => void;
}
export function SubscriptionRenewalConfirmationDialog({
open,
plan,
onCancel,
onConfirm,
}: SubscriptionRenewalConfirmationDialogProps) {
return (
<ModalPortal
open={open && plan !== null}
onClose={onCancel}
scrimClassName={styles.scrim}
panelClassName={styles.panel}
scrimOpacity={0.56}
ariaLabel="Automatic Renewal Confirmation"
>
{plan ? (
<div className={styles.content}>
<h2 className={styles.title}>Automatic Renewal Confirmation</h2>
<p className={styles.description}>
You selected the <strong>{plan.title}</strong> plan for{" "}
<strong>
{plan.price} {plan.currency}
</strong>
. It will renew automatically at the applicable renewal price until
you cancel.
</p>
<p className={styles.description}>
By confirming, you agree to the{" "}
<a
href={AppConstants.membershipAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.link}
>
VIP Membership Benefits Agreement
</a>{" "}
and{" "}
<a
href={AppConstants.autoRenewalAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.link}
>
Automatic Renewal Agreement
</a>
.
</p>
<div className={styles.actions}>
<button
type="button"
className={styles.secondaryButton}
onClick={onCancel}
>
Cancel
</button>
<button
type="button"
className={styles.primaryButton}
onClick={onConfirm}
>
Confirm
</button>
</div>
</div>
) : null}
</ModalPortal>
);
}
@@ -8,13 +8,15 @@
padding: padding:
calc(var(--page-padding-y, 18px) + var(--app-safe-top, 0px)) calc(var(--page-padding-y, 18px) + var(--app-safe-top, 0px))
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px)) calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
calc(10px + var(--app-safe-bottom, 0px)) calc(104px + var(--app-safe-bottom, 0px))
calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px)); calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
} }
.header { .header {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between;
gap: 12px;
height: 40px; height: 40px;
} }
@@ -22,6 +24,43 @@
display: inline-flex; display: inline-flex;
} }
.paymentIssueButton {
border: 0;
background: transparent;
color: #b72f70;
cursor: pointer;
font: inherit;
font-size: var(--responsive-caption, 13px);
font-weight: 800;
text-decoration: underline;
text-underline-offset: 3px;
}
.paymentIssueButton:focus-visible {
border-radius: 6px;
outline: 2px solid #f657a0;
outline-offset: 3px;
}
.paymentIssueNotice {
position: fixed;
z-index: 80;
top: calc(68px + var(--app-safe-top, 0px));
left: 50%;
width: min(calc(100% - 40px), 500px);
margin: 0;
padding: 10px 12px;
border: 1px solid rgba(39, 174, 96, 0.3);
border-radius: 14px;
background: rgba(236, 253, 245, 0.96);
color: #166534;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
transform: translateX(-50%);
box-shadow: 0 12px 30px rgba(22, 101, 52, 0.12);
}
.firstRechargeBanner { .firstRechargeBanner {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -129,24 +168,23 @@
} }
.ctaSlot { .ctaSlot {
margin-top: var(--page-section-gap-lg, 22px); position: fixed;
} z-index: 40;
right: 50%;
.agreementSlot { bottom: 0;
margin-top: var(--spacing-md); width: min(100%, var(--app-max-width, 540px));
padding: 0 var(--spacing-xs); padding:
} 12px
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
.agreementLabel { calc(12px + var(--app-safe-bottom, 0px))
font-size: var(--responsive-micro, 12px); calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
} border-top: 1px solid rgba(246, 87, 160, 0.14);
background: linear-gradient(
.agreementLink { 180deg,
color: var(--color-auth-text-primary); rgba(255, 255, 255, 0.72) 0%,
font-weight: 700; rgba(255, 249, 252, 0.98) 35%
text-decoration: none; );
} box-shadow: 0 -12px 30px rgba(87, 35, 59, 0.1);
backdrop-filter: blur(16px);
.agreementLink:hover { transform: translateX(50%);
text-decoration: underline;
} }
@@ -105,6 +105,30 @@ export function findSelectedSubscriptionPlan(input: {
return plans.find((plan) => plan.id === input.selectedPlanId) ?? null; 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: { export function getDefaultSubscriptionPlanId(input: {
canSubscribeVip: boolean; canSubscribeVip: boolean;
selectedPlanId: string; selectedPlanId: string;
+89 -36
View File
@@ -1,12 +1,11 @@
"use client"; "use client";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo, useState } from "react";
import { BackButton } from "@/app/_components"; import { BackButton } from "@/app/_components";
import { Checkbox, MobileShell } from "@/app/_components/core"; import { MobileShell } from "@/app/_components/core";
import { PaymentMethodSelector } from "@/app/_components/payment/payment-method-selector"; import { PaymentMethodSelector } from "@/app/_components/payment/payment-method-selector";
import { usePaymentMethodSelection } from "@/app/_hooks/use-payment-method-selection"; import { usePaymentMethodSelection } from "@/app/_hooks/use-payment-method-selection";
import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics"; import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics";
import { AppConstants } from "@/core/app_constants";
import type { PayChannel } from "@/data/schemas/payment"; import type { PayChannel } from "@/data/schemas/payment";
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit"; import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character"; import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
@@ -21,14 +20,18 @@ import { useUserState } from "@/stores/user/user-context";
import { import {
SubscriptionCheckoutButton, SubscriptionCheckoutButton,
SubscriptionCoinsOfferSection, SubscriptionCoinsOfferSection,
SubscriptionPaymentIssueDialog,
SubscriptionPaymentSuccessDialog, SubscriptionPaymentSuccessDialog,
SubscriptionRenewalConfirmationDialog,
SubscriptionVipOfferSection, SubscriptionVipOfferSection,
} from "./components"; } from "./components";
import styles from "./components/subscription-screen.module.css"; import styles from "./components/subscription-screen.module.css";
import { import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan, findSelectedSubscriptionPlan,
getFirstRechargeOfferView, getFirstRechargeOfferView,
getDefaultSubscriptionPlanId, getDefaultSubscriptionPlanId,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews, toCoinsOfferPlanViews,
toVipOfferPlanViews, toVipOfferPlanViews,
type SubscriptionType, type SubscriptionType,
@@ -62,6 +65,14 @@ export function SubscriptionScreen({
resumeOrderId = null, resumeOrderId = null,
chatActionId = null, chatActionId = null,
}: SubscriptionScreenProps) { }: 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,
);
const userState = useUserState(); const userState = useUserState();
const countryCode = userState.currentUser?.countryCode; const countryCode = userState.currentUser?.countryCode;
const paymentMethodConfig = getPaymentMethodConfig({ const paymentMethodConfig = getPaymentMethodConfig({
@@ -134,15 +145,48 @@ export function SubscriptionScreen({
const isPaymentBusy = const isPaymentBusy =
payment.isCreatingOrder || payment.isCreatingOrder ||
payment.isPollingOrder; payment.isPollingOrder;
const selectedPlanIsVip = vipOfferPlans.some(
(plan) => plan.id === payment.selectedPlanId,
);
const canActivate = const canActivate =
selectedPlan !== null && payment.agreed && !isPaymentBusy; selectedPlan !== null &&
canCheckoutSubscriptionPlan({
selectedPlanId: payment.selectedPlanId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
}) &&
!isPaymentBusy;
const pendingVipPlan =
vipOfferPlans.find((plan) => plan.id === pendingVipPlanId) ?? null;
const handleSelectPlan = (planId: string) => { const handleSelectPlan = (planId: string) => {
const plan = payment.plans.find((item) => item.planId === planId); const plan = payment.plans.find((item) => item.planId === planId);
if (plan) behaviorAnalytics.planClick(plan, analyticsContext); if (plan) behaviorAnalytics.planClick(plan, analyticsContext);
if (
requiresVipPlanConfirmation({
planId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
})
) {
setPendingVipPlanId(planId);
return;
}
paymentDispatch({ type: "PaymentPlanSelected", planId }); 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) => { const handlePaymentMethodChange = (payChannel: PayChannel) => {
paymentDispatch({ paymentDispatch({
type: "PaymentPayChannelChanged", type: "PaymentPayChannelChanged",
@@ -195,8 +239,24 @@ export function SubscriptionScreen({
variant="soft" variant="soft"
analyticsKey="subscription.back" analyticsKey="subscription.back"
/> />
<button
type="button"
className={styles.paymentIssueButton}
onClick={() => {
setPaymentIssueNotice(null);
setShowPaymentIssueDialog(true);
}}
>
Payment issue?
</button>
</header> </header>
{paymentIssueNotice ? (
<p className={styles.paymentIssueNotice} role="status">
{paymentIssueNotice}
</p>
) : null}
{firstRechargeOffer ? ( {firstRechargeOffer ? (
<section <section
className={styles.firstRechargeBanner} className={styles.firstRechargeBanner}
@@ -271,39 +331,32 @@ export function SubscriptionScreen({
/> />
</div> </div>
<div className={styles.agreementSlot}> <SubscriptionRenewalConfirmationDialog
<Checkbox open={pendingVipPlan !== null}
checked={payment.agreed} plan={pendingVipPlan}
onChange={(agreed) => onCancel={() => setPendingVipPlanId(null)}
paymentDispatch({ onConfirm={handleConfirmVipPlan}
type: "PaymentAgreementChanged",
agreed,
})
}
label={
<span className={styles.agreementLabel}>
I agree to the{" "}
<a
href={AppConstants.membershipAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.agreementLink}
>
VIP Membership Benefits Agreement
</a>{" "}
and{" "}
<a
href={AppConstants.autoRenewalAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.agreementLink}
>
Automatic renewal Agreement
</a>
</span>
}
/> />
</div>
{showPaymentIssueDialog ? (
<SubscriptionPaymentIssueDialog
open
subscriptionType={
selectedPlan
? selectedPlanIsVip
? "vip"
: "topup"
: subscriptionType
}
planId={selectedPlan?.id ?? null}
orderId={payment.currentOrderId}
payChannel={payment.payChannel}
countryCode={countryCode}
characterId={sourceCharacterSlug}
onClose={() => setShowPaymentIssueDialog(false)}
onSubmitted={setPaymentIssueNotice}
/>
) : null}
<SubscriptionPaymentSuccessDialog <SubscriptionPaymentSuccessDialog
open={showPaymentSuccessDialog} open={showPaymentSuccessDialog}
@@ -12,6 +12,14 @@ export interface FeedbackContext {
platform: string; platform: string;
browser: string; browser: string;
viewport: string; viewport: string;
sourcePage?: string;
paymentIssueReason?: string;
subscriptionType?: string;
planId?: string;
orderId?: string;
payChannel?: string;
countryCode?: string;
characterId?: string;
} }
export interface SubmitFeedbackInput { export interface SubmitFeedbackInput {
@@ -19,4 +27,5 @@ export interface SubmitFeedbackInput {
content: string; content: string;
context: FeedbackContext; context: FeedbackContext;
images: readonly File[]; images: readonly File[];
idempotencyKey?: string;
} }
@@ -32,12 +32,17 @@ describe("FeedbackApi", () => {
viewport: "392x760@2.75", viewport: "392x760@2.75",
}, },
images: [image], images: [image],
idempotencyKey: "payment_feedback_123",
}); });
expect(response).toEqual({ feedbackId: "feedback-123" }); expect(response).toEqual({ feedbackId: "feedback-123" });
expect(httpClientMock).toHaveBeenCalledWith( expect(httpClientMock).toHaveBeenCalledWith(
"/api/feedback", "/api/feedback",
expect.objectContaining({ method: "POST", body: expect.any(FormData) }), expect.objectContaining({
method: "POST",
body: expect.any(FormData),
headers: { "Idempotency-Key": "payment_feedback_123" },
}),
); );
const body = httpClientMock.mock.calls[0][1].body as FormData; const body = httpClientMock.mock.calls[0][1].body as FormData;
expect(body.get("category")).toBe("problem"); expect(body.get("category")).toBe("problem");
+3
View File
@@ -19,6 +19,9 @@ export class FeedbackApi {
const envelope = await httpClient<ApiEnvelope<unknown>>(ApiPath.feedback, { const envelope = await httpClient<ApiEnvelope<unknown>>(ApiPath.feedback, {
method: "POST", method: "POST",
body, body,
...(input.idempotencyKey
? { headers: { "Idempotency-Key": input.idempotencyKey } }
: {}),
}); });
return FeedbackSubmitResponseSchema.parse(unwrap(envelope)); return FeedbackSubmitResponseSchema.parse(unwrap(envelope));
} }