feat(payment): support user-bound seven-discount offers
Docker Image / Build and Push Docker Image (push) Successful in 1m55s
Docker Image / Build and Push Docker Image (push) Successful in 1m55s
This commit is contained in:
@@ -61,7 +61,21 @@ export async function registerChatMocks(page: Page, options: ChatMockOptions, st
|
|||||||
await route.fulfill({ status: 401, json: { message: "expired" } });
|
await route.fulfill({ status: 401, json: { message: "expired" } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const response = message.includes("private album offer test")
|
const response = message.includes("discount offer test")
|
||||||
|
? {
|
||||||
|
...chatSendResponse,
|
||||||
|
reply: "I know you're thinking carefully about the price.",
|
||||||
|
messageId: "discount-action-message",
|
||||||
|
commercialAction: {
|
||||||
|
actionId: "13ec8a10-58d7-4d24-b66b-8db5699a1aa8",
|
||||||
|
type: "discountOffer",
|
||||||
|
copy: "Want me to ask for my best private offer?",
|
||||||
|
ctaLabel: "Yes, ask for me",
|
||||||
|
target: "discountConsent",
|
||||||
|
ruleId: "discount_after_price_objection",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: message.includes("private album offer test")
|
||||||
? {
|
? {
|
||||||
...chatSendResponse,
|
...chatSendResponse,
|
||||||
reply: "You always know how to make me smile.",
|
reply: "You always know how to make me smile.",
|
||||||
|
|||||||
@@ -4,6 +4,16 @@ import { apiEnvelope } from "../data/common";
|
|||||||
import { createPaymentOrderResponse, paidPaymentOrderStatusResponse, paymentPlansResponse, tipPaymentPlansResponse, vipStatusResponse } from "../data/payment";
|
import { createPaymentOrderResponse, paidPaymentOrderStatusResponse, paymentPlansResponse, tipPaymentPlansResponse, vipStatusResponse } from "../data/payment";
|
||||||
|
|
||||||
export async function registerPaymentMocks(page: Page) {
|
export async function registerPaymentMocks(page: Page) {
|
||||||
|
await page.route("**/api/payment/commercial-offers/*/accept", async (route) => route.fulfill({ json: apiEnvelope({
|
||||||
|
commercialOfferId: "13ec8a10-58d7-4d24-b66b-8db5699a1aa8",
|
||||||
|
planId: "vip_annual",
|
||||||
|
subscriptionType: "vip",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-24T08:00:00+00:00",
|
||||||
|
message: "I got it for you.",
|
||||||
|
promotionType: "commercial_seven_discount",
|
||||||
|
}) }));
|
||||||
await page.route("**/api/payment/plans**", async (route) => route.fulfill({ json: apiEnvelope(paymentPlansResponse) }));
|
await page.route("**/api/payment/plans**", async (route) => route.fulfill({ json: apiEnvelope(paymentPlansResponse) }));
|
||||||
await page.route("**/api/payment/tip-plans**", async (route) => route.fulfill({ json: apiEnvelope(tipPaymentPlansResponse) }));
|
await page.route("**/api/payment/tip-plans**", async (route) => route.fulfill({ json: apiEnvelope(tipPaymentPlansResponse) }));
|
||||||
await page.route("**/api/payment/create-order", async (route) => route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) }));
|
await page.route("**/api/payment/create-order", async (route) => route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) }));
|
||||||
|
|||||||
@@ -29,3 +29,21 @@ test("renders a backend commercial action and opens the private zone", async ({
|
|||||||
|
|
||||||
await expect(page).toHaveURL(/\/characters\/elio\/private-zone$/);
|
await expect(page).toHaveURL(/\/characters\/elio\/private-zone$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("asks for consent before opening a user-bound discount plan", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await enterChatFromSplash(page);
|
||||||
|
|
||||||
|
const input = page.getByRole("textbox", { name: "Message" });
|
||||||
|
await input.fill("discount offer test");
|
||||||
|
await input.press("Enter");
|
||||||
|
|
||||||
|
const offer = page.getByLabel("Yes, ask for me");
|
||||||
|
await expect(offer).toContainText("Want me to ask for my best private offer?");
|
||||||
|
await offer.getByRole("button", { name: "Yes, ask for me" }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(
|
||||||
|
/\/subscription\?type=vip.*planId=vip_annual.*commercialOfferId=13ec8a10/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ export interface UsePaymentRouteFlowInput {
|
|||||||
characterId?: string;
|
characterId?: string;
|
||||||
initialCategory?: string | null;
|
initialCategory?: string | null;
|
||||||
initialPlanId?: string | null;
|
initialPlanId?: string | null;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PaymentRouteFlow {
|
export interface PaymentRouteFlow {
|
||||||
@@ -41,6 +42,7 @@ export function usePaymentRouteFlow({
|
|||||||
characterId,
|
characterId,
|
||||||
initialCategory = null,
|
initialCategory = null,
|
||||||
initialPlanId = null,
|
initialPlanId = null,
|
||||||
|
commercialOfferId = null,
|
||||||
}: UsePaymentRouteFlowInput): PaymentRouteFlow {
|
}: UsePaymentRouteFlowInput): PaymentRouteFlow {
|
||||||
const payment = usePaymentState();
|
const payment = usePaymentState();
|
||||||
const paymentDispatch = usePaymentDispatch();
|
const paymentDispatch = usePaymentDispatch();
|
||||||
@@ -50,6 +52,7 @@ export function usePaymentRouteFlow({
|
|||||||
characterId ?? "",
|
characterId ?? "",
|
||||||
initialCategory ?? "",
|
initialCategory ?? "",
|
||||||
initialPlanId ?? "",
|
initialPlanId ?? "",
|
||||||
|
commercialOfferId ?? "",
|
||||||
].join(":");
|
].join(":");
|
||||||
|
|
||||||
usePendingPaymentOrderLifecycle({
|
usePendingPaymentOrderLifecycle({
|
||||||
@@ -69,11 +72,13 @@ export function usePaymentRouteFlow({
|
|||||||
...(characterId ? { characterId } : {}),
|
...(characterId ? { characterId } : {}),
|
||||||
...(initialCategory ? { category: initialCategory } : {}),
|
...(initialCategory ? { category: initialCategory } : {}),
|
||||||
...(initialPlanId ? { planId: initialPlanId } : {}),
|
...(initialPlanId ? { planId: initialPlanId } : {}),
|
||||||
|
...(commercialOfferId ? { commercialOfferId } : {}),
|
||||||
});
|
});
|
||||||
}, [
|
}, [
|
||||||
catalog,
|
catalog,
|
||||||
catalogKey,
|
catalogKey,
|
||||||
characterId,
|
characterId,
|
||||||
|
commercialOfferId,
|
||||||
initialCategory,
|
initialCategory,
|
||||||
initialPlanId,
|
initialPlanId,
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ import { useCharacterCatalog } from "@/providers/character-catalog-provider";
|
|||||||
import { clearPendingChatNavigation } from "@/lib/navigation/chat_unlock_session";
|
import { clearPendingChatNavigation } from "@/lib/navigation/chat_unlock_session";
|
||||||
import { buildGlobalPageUrl } from "@/router/global-route-context";
|
import { buildGlobalPageUrl } from "@/router/global-route-context";
|
||||||
import { resolveAuthenticatedNavigation } from "@/router/navigation-resolver";
|
import { resolveAuthenticatedNavigation } from "@/router/navigation-resolver";
|
||||||
import { getCharacterRoutes, ROUTES } from "@/router/routes";
|
import { getCharacterRoutes, ROUTE_BUILDERS, ROUTES } from "@/router/routes";
|
||||||
import type { CommercialAction } from "@/data/schemas/chat";
|
import type { CommercialAction } from "@/data/schemas/chat";
|
||||||
|
import { paymentApi } from "@/data/services/api";
|
||||||
import { behaviorAnalytics } from "@/lib/analytics";
|
import { behaviorAnalytics } from "@/lib/analytics";
|
||||||
|
|
||||||
import { MobileShell } from "@/app/_components/core";
|
import { MobileShell } from "@/app/_components/core";
|
||||||
@@ -252,7 +253,7 @@ export function ChatScreen() {
|
|||||||
router.push(characterRoutes.privateZone);
|
router.push(characterRoutes.privateZone);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCommercialAction(action: CommercialAction): void {
|
async function handleCommercialAction(action: CommercialAction): Promise<void> {
|
||||||
behaviorAnalytics.elementClick(
|
behaviorAnalytics.elementClick(
|
||||||
"chat.commercial_action.open",
|
"chat.commercial_action.open",
|
||||||
action.ctaLabel,
|
action.ctaLabel,
|
||||||
@@ -264,6 +265,29 @@ export function ChatScreen() {
|
|||||||
target: action.target,
|
target: action.target,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
if (action.target === "discountConsent") {
|
||||||
|
const offer = await paymentApi.acceptCommercialOffer(action.actionId);
|
||||||
|
behaviorAnalytics.elementClick(
|
||||||
|
"chat.commercial_action.accepted",
|
||||||
|
action.ctaLabel,
|
||||||
|
{
|
||||||
|
actionId: action.actionId,
|
||||||
|
actionType: action.type,
|
||||||
|
characterId: state.characterId,
|
||||||
|
planId: offer.planId,
|
||||||
|
discountPercent: offer.discountPercent,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
router.push(
|
||||||
|
ROUTE_BUILDERS.subscription(offer.subscriptionType, {
|
||||||
|
sourceCharacterSlug: character.slug,
|
||||||
|
returnTo: "chat",
|
||||||
|
planId: offer.planId,
|
||||||
|
commercialOfferId: offer.commercialOfferId,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
router.push(
|
router.push(
|
||||||
action.target === "giftCatalog"
|
action.target === "giftCatalog"
|
||||||
? characterRoutes.tip
|
? characterRoutes.tip
|
||||||
|
|||||||
@@ -23,4 +23,23 @@ describe("CommercialActionCard", () => {
|
|||||||
expect(html).toContain("Open private zone");
|
expect(html).toContain("Open private zone");
|
||||||
expect(html).toContain('aria-label="Dismiss offer"');
|
expect(html).toContain('aria-label="Dismiss offer"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("renders a consent-first discount action without a checkout URL", () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<CommercialActionCard
|
||||||
|
action={{
|
||||||
|
actionId: "offer-1",
|
||||||
|
type: "discountOffer",
|
||||||
|
copy: "Want me to ask for my best private offer?",
|
||||||
|
ctaLabel: "Yes, ask for me",
|
||||||
|
target: "discountConsent",
|
||||||
|
ruleId: "discount_after_price_objection",
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(html).toContain('data-commercial-action="discountOffer"');
|
||||||
|
expect(html).toContain("Yes, ask for me");
|
||||||
|
expect(html).not.toContain("/subscription");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -189,6 +189,26 @@
|
|||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.commercialActionButton:disabled {
|
||||||
|
cursor: wait;
|
||||||
|
opacity: 0.72;
|
||||||
|
}
|
||||||
|
|
||||||
|
.commercialActionError {
|
||||||
|
margin: -4px 0 10px;
|
||||||
|
color: #ffb4ab;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.commercialActionSpinner {
|
||||||
|
animation: commercial-action-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes commercial-action-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
.bubbleAi {
|
.bubbleAi {
|
||||||
max-width: var(--chat-bubble-max-width, 75%);
|
max-width: var(--chat-bubble-max-width, 75%);
|
||||||
background: var(--color-bubble-ai, rgba(255, 255, 255, 0.08));
|
background: var(--color-bubble-ai, rgba(255, 255, 255, 0.08));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { ArrowRight, Gift, Images, X } from "lucide-react";
|
import { ArrowRight, BadgePercent, Gift, Images, LoaderCircle, X } from "lucide-react";
|
||||||
|
|
||||||
import type { CommercialAction } from "@/data/schemas/chat";
|
import type { CommercialAction } from "@/data/schemas/chat";
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ import styles from "./chat-area.module.css";
|
|||||||
|
|
||||||
export interface CommercialActionCardProps {
|
export interface CommercialActionCardProps {
|
||||||
action: CommercialAction;
|
action: CommercialAction;
|
||||||
onActivate?: (action: CommercialAction) => void;
|
onActivate?: (action: CommercialAction) => void | Promise<void>;
|
||||||
onDismiss?: (action: CommercialAction) => void;
|
onDismiss?: (action: CommercialAction) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -19,9 +19,16 @@ export function CommercialActionCard({
|
|||||||
onDismiss,
|
onDismiss,
|
||||||
}: CommercialActionCardProps) {
|
}: CommercialActionCardProps) {
|
||||||
const [dismissed, setDismissed] = useState(false);
|
const [dismissed, setDismissed] = useState(false);
|
||||||
|
const [activating, setActivating] = useState(false);
|
||||||
|
const [activationError, setActivationError] = useState<string | null>(null);
|
||||||
if (dismissed) return null;
|
if (dismissed) return null;
|
||||||
|
|
||||||
const Icon = action.type === "giftOffer" ? Gift : Images;
|
const Icon =
|
||||||
|
action.type === "giftOffer"
|
||||||
|
? Gift
|
||||||
|
: action.type === "discountOffer"
|
||||||
|
? BadgePercent
|
||||||
|
: Images;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
@@ -45,13 +52,29 @@ export function CommercialActionCard({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<p className={styles.commercialActionCopy}>{action.copy}</p>
|
<p className={styles.commercialActionCopy}>{action.copy}</p>
|
||||||
|
{activationError ? (
|
||||||
|
<p className={styles.commercialActionError} role="alert">
|
||||||
|
{activationError}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={styles.commercialActionButton}
|
className={styles.commercialActionButton}
|
||||||
onClick={() => onActivate?.(action)}
|
disabled={activating}
|
||||||
|
onClick={() => {
|
||||||
|
setActivating(true);
|
||||||
|
setActivationError(null);
|
||||||
|
void Promise.resolve(onActivate?.(action))
|
||||||
|
.catch(() => setActivationError("This private offer is unavailable right now. Please try again."))
|
||||||
|
.finally(() => setActivating(false));
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<span>{action.ctaLabel}</span>
|
<span>{action.ctaLabel}</span>
|
||||||
|
{activating ? (
|
||||||
|
<LoaderCircle className={styles.commercialActionSpinner} size={17} aria-hidden="true" />
|
||||||
|
) : (
|
||||||
<ArrowRight size={17} aria-hidden="true" />
|
<ArrowRight size={17} aria-hidden="true" />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ export default async function SubscriptionPage({
|
|||||||
const sourceCharacterSlug =
|
const sourceCharacterSlug =
|
||||||
getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ??
|
getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ??
|
||||||
DEFAULT_CHARACTER_SLUG;
|
DEFAULT_CHARACTER_SLUG;
|
||||||
|
const initialPlanId = getFirstPaymentSearchParam(query.planId);
|
||||||
|
const commercialOfferId = getFirstPaymentSearchParam(
|
||||||
|
query.commercialOfferId,
|
||||||
|
);
|
||||||
const analyticsContext = parsePaymentAnalyticsContext({
|
const analyticsContext = parsePaymentAnalyticsContext({
|
||||||
entryPoint: getFirstPaymentSearchParam(
|
entryPoint: getFirstPaymentSearchParam(
|
||||||
query[PAYMENT_ANALYTICS_ENTRY_PARAM],
|
query[PAYMENT_ANALYTICS_ENTRY_PARAM],
|
||||||
@@ -50,6 +54,8 @@ export default async function SubscriptionPage({
|
|||||||
initialPayChannel={paymentReturn.initialPayChannel}
|
initialPayChannel={paymentReturn.initialPayChannel}
|
||||||
analyticsContext={analyticsContext}
|
analyticsContext={analyticsContext}
|
||||||
sourceCharacterSlug={sourceCharacterSlug}
|
sourceCharacterSlug={sourceCharacterSlug}
|
||||||
|
initialPlanId={initialPlanId}
|
||||||
|
commercialOfferId={commercialOfferId}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ export interface SubscriptionScreenProps {
|
|||||||
initialPayChannel?: PayChannel | null;
|
initialPayChannel?: PayChannel | null;
|
||||||
analyticsContext?: PaymentAnalyticsContext;
|
analyticsContext?: PaymentAnalyticsContext;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string;
|
||||||
|
initialPlanId?: string | null;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SubscriptionScreen({
|
export function SubscriptionScreen({
|
||||||
@@ -54,6 +56,8 @@ export function SubscriptionScreen({
|
|||||||
initialPayChannel = null,
|
initialPayChannel = null,
|
||||||
analyticsContext: providedAnalyticsContext,
|
analyticsContext: providedAnalyticsContext,
|
||||||
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
||||||
|
initialPlanId = null,
|
||||||
|
commercialOfferId = null,
|
||||||
}: SubscriptionScreenProps) {
|
}: SubscriptionScreenProps) {
|
||||||
const userState = useUserState();
|
const userState = useUserState();
|
||||||
const hasHydrated = useHasHydrated();
|
const hasHydrated = useHasHydrated();
|
||||||
@@ -77,6 +81,8 @@ export function SubscriptionScreen({
|
|||||||
returnTo,
|
returnTo,
|
||||||
sourceCharacterSlug,
|
sourceCharacterSlug,
|
||||||
initialPayChannel: paymentMethodConfig.initialPayChannel,
|
initialPayChannel: paymentMethodConfig.initialPayChannel,
|
||||||
|
initialPlanId,
|
||||||
|
commercialOfferId,
|
||||||
});
|
});
|
||||||
const canSubscribeVip = subscriptionType === "vip";
|
const canSubscribeVip = subscriptionType === "vip";
|
||||||
const analyticsContext =
|
const analyticsContext =
|
||||||
@@ -214,6 +220,22 @@ export function SubscriptionScreen({
|
|||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{payment.commercialOffer && !firstRechargeOffer ? (
|
||||||
|
<section
|
||||||
|
className={styles.firstRechargeBanner}
|
||||||
|
aria-label="Elio private offer"
|
||||||
|
>
|
||||||
|
<span className={styles.firstRechargeBadge}>Private offer</span>
|
||||||
|
<div className={styles.firstRechargeCopy}>
|
||||||
|
<h2 className={styles.firstRechargeTitle}>Elio got this price for you</h2>
|
||||||
|
<p className={styles.firstRechargeSubtitle}>
|
||||||
|
{payment.commercialOffer.message ||
|
||||||
|
`Your ${payment.commercialOffer.discountPercent}% discount is already applied below.`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className={styles.offerStack}>
|
<div className={styles.offerStack}>
|
||||||
{canSubscribeVip ? (
|
{canSubscribeVip ? (
|
||||||
<SubscriptionVipOfferSection
|
<SubscriptionVipOfferSection
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ export interface UseSubscriptionPaymentFlowInput {
|
|||||||
returnTo: SubscriptionReturnTo;
|
returnTo: SubscriptionReturnTo;
|
||||||
initialPayChannel: PayChannel;
|
initialPayChannel: PayChannel;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string;
|
||||||
|
initialPlanId?: string | null;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSubscriptionPaymentFlow({
|
export function useSubscriptionPaymentFlow({
|
||||||
@@ -28,12 +30,16 @@ export function useSubscriptionPaymentFlow({
|
|||||||
returnTo,
|
returnTo,
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
||||||
|
initialPlanId = null,
|
||||||
|
commercialOfferId = null,
|
||||||
}: UseSubscriptionPaymentFlowInput) {
|
}: UseSubscriptionPaymentFlowInput) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { payment, paymentDispatch } = usePaymentRouteFlow({
|
const { payment, paymentDispatch } = usePaymentRouteFlow({
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
paymentType: subscriptionType,
|
paymentType: subscriptionType,
|
||||||
shouldResumePendingOrder,
|
shouldResumePendingOrder,
|
||||||
|
initialPlanId,
|
||||||
|
commercialOfferId,
|
||||||
});
|
});
|
||||||
const successDialogShownOrderRef = useRef<string | null>(null);
|
const successDialogShownOrderRef = useRef<string | null>(null);
|
||||||
const [showPaymentSuccessDialog, setShowPaymentSuccessDialog] =
|
const [showPaymentSuccessDialog, setShowPaymentSuccessDialog] =
|
||||||
|
|||||||
@@ -358,6 +358,7 @@ function makePaymentState(
|
|||||||
giftProducts: [giftProduct],
|
giftProducts: [giftProduct],
|
||||||
selectedGiftCategory: giftCategory.category,
|
selectedGiftCategory: giftCategory.category,
|
||||||
isFirstRecharge: false,
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: null,
|
||||||
selectedPlanId: giftPlan.planId,
|
selectedPlanId: giftPlan.planId,
|
||||||
payChannel: "stripe",
|
payChannel: "stripe",
|
||||||
autoRenew: false,
|
autoRenew: false,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import type { Result } from "@/utils/result";
|
|||||||
|
|
||||||
export interface IPaymentRepository {
|
export interface IPaymentRepository {
|
||||||
/** 获取套餐列表。 */
|
/** 获取套餐列表。 */
|
||||||
getPlans(): Promise<Result<PaymentPlansResponse>>;
|
getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>>;
|
||||||
|
|
||||||
/** 获取本地缓存套餐列表。 */
|
/** 获取本地缓存套餐列表。 */
|
||||||
getCachedPlans(): Promise<Result<PaymentPlansResponse | null>>;
|
getCachedPlans(): Promise<Result<PaymentPlansResponse | null>>;
|
||||||
@@ -30,6 +30,7 @@ export interface IPaymentRepository {
|
|||||||
payChannel: PayChannel,
|
payChannel: PayChannel,
|
||||||
autoRenew: boolean,
|
autoRenew: boolean,
|
||||||
recipientCharacterId?: string,
|
recipientCharacterId?: string,
|
||||||
|
commercialOfferId?: string,
|
||||||
): Promise<Result<CreatePaymentOrderResponse>>;
|
): Promise<Result<CreatePaymentOrderResponse>>;
|
||||||
|
|
||||||
/** 查询支付订单状态。 */
|
/** 查询支付订单状态。 */
|
||||||
|
|||||||
@@ -24,10 +24,10 @@ export class PaymentRepository implements IPaymentRepository {
|
|||||||
constructor(private readonly api: PaymentApi) {}
|
constructor(private readonly api: PaymentApi) {}
|
||||||
|
|
||||||
/** 获取套餐列表。 */
|
/** 获取套餐列表。 */
|
||||||
async getPlans(): Promise<Result<PaymentPlansResponse>> {
|
async getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>> {
|
||||||
return Result.wrap(async () => {
|
return Result.wrap(async () => {
|
||||||
const response = await this.api.getPlans();
|
const response = await this.api.getPlans(commercialOfferId);
|
||||||
await PaymentPlansStorage.setPlans(response);
|
if (!commercialOfferId) await PaymentPlansStorage.setPlans(response);
|
||||||
return response;
|
return response;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -62,12 +62,14 @@ export class PaymentRepository implements IPaymentRepository {
|
|||||||
payChannel: PayChannel,
|
payChannel: PayChannel,
|
||||||
autoRenew: boolean,
|
autoRenew: boolean,
|
||||||
recipientCharacterId?: string,
|
recipientCharacterId?: string,
|
||||||
|
commercialOfferId?: string,
|
||||||
): Promise<Result<CreatePaymentOrderResponse>> {
|
): Promise<Result<CreatePaymentOrderResponse>> {
|
||||||
const request = CreatePaymentOrderRequestSchema.parse({
|
const request = CreatePaymentOrderRequestSchema.parse({
|
||||||
planId,
|
planId,
|
||||||
payChannel,
|
payChannel,
|
||||||
autoRenew,
|
autoRenew,
|
||||||
...(recipientCharacterId ? { recipientCharacterId } : {}),
|
...(recipientCharacterId ? { recipientCharacterId } : {}),
|
||||||
|
...(commercialOfferId ? { commercialOfferId } : {}),
|
||||||
});
|
});
|
||||||
return Result.wrap(() => this.api.createOrder(request));
|
return Result.wrap(() => this.api.createOrder(request));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,10 +15,10 @@ import { ChatImageSchema, ChatLockDetailSchema } from "../chat_payloads";
|
|||||||
export const CommercialActionSchema = z
|
export const CommercialActionSchema = z
|
||||||
.object({
|
.object({
|
||||||
actionId: z.string().min(1),
|
actionId: z.string().min(1),
|
||||||
type: z.enum(["giftOffer", "privateAlbumOffer"]),
|
type: z.enum(["giftOffer", "privateAlbumOffer", "discountOffer"]),
|
||||||
copy: z.string().min(1),
|
copy: z.string().min(1),
|
||||||
ctaLabel: z.string().min(1),
|
ctaLabel: z.string().min(1),
|
||||||
target: z.enum(["giftCatalog", "privateZone"]),
|
target: z.enum(["giftCatalog", "privateZone", "discountConsent"]),
|
||||||
ruleId: z.string().min(1),
|
ruleId: z.string().min(1),
|
||||||
})
|
})
|
||||||
.readonly();
|
.readonly();
|
||||||
|
|||||||
@@ -75,6 +75,8 @@ describe("PaymentPlan", () => {
|
|||||||
mostPopular: true,
|
mostPopular: true,
|
||||||
firstRechargeDiscountPercent: null,
|
firstRechargeDiscountPercent: null,
|
||||||
promotionType: null,
|
promotionType: null,
|
||||||
|
commercialOfferId: null,
|
||||||
|
commercialDiscountPercent: null,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -190,6 +192,45 @@ describe("PaymentPlansResponse", () => {
|
|||||||
discountPercent: 0,
|
discountPercent: 0,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("parses one user-bound commercial offer and its discounted plan", () => {
|
||||||
|
const response = PaymentPlansResponseSchema.parse({
|
||||||
|
commercialOffer: {
|
||||||
|
enabled: true,
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
planId: "vip_annual",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-24T08:00:00+00:00",
|
||||||
|
triggerReason: "price_objection",
|
||||||
|
message: "I got this private price for you.",
|
||||||
|
},
|
||||||
|
plans: [
|
||||||
|
{
|
||||||
|
planId: "vip_annual",
|
||||||
|
planName: "Annual VIP",
|
||||||
|
orderType: "vip_annual",
|
||||||
|
vipDays: 365,
|
||||||
|
dolAmount: null,
|
||||||
|
creditBalance: 9000,
|
||||||
|
amountCents: 12593,
|
||||||
|
originalAmountCents: 17990,
|
||||||
|
dailyPriceCents: 34,
|
||||||
|
currency: "USD",
|
||||||
|
promotionType: "commercial_seven_discount",
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
commercialDiscountPercent: 30,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.commercialOffer?.commercialOfferId).toBe("offer-1");
|
||||||
|
expect(response.plans[0]).toMatchObject({
|
||||||
|
planId: "vip_annual",
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
commercialDiscountPercent: 30,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("GiftProductsResponse", () => {
|
describe("GiftProductsResponse", () => {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export * from "./gift_product";
|
|||||||
export * from "./request/create_payment_order_request";
|
export * from "./request/create_payment_order_request";
|
||||||
export * from "./request/tip_message_request";
|
export * from "./request/tip_message_request";
|
||||||
export * from "./response/create_payment_order_response";
|
export * from "./response/create_payment_order_response";
|
||||||
|
export * from "./response/commercial_offer_response";
|
||||||
export * from "./response/gift_products_response";
|
export * from "./response/gift_products_response";
|
||||||
export * from "./response/payment_order_status_response";
|
export * from "./response/payment_order_status_response";
|
||||||
export * from "./response/payment_plans_response";
|
export * from "./response/payment_plans_response";
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ export const PaymentPlanSchema = z
|
|||||||
mostPopular: booleanOrFalse,
|
mostPopular: booleanOrFalse,
|
||||||
firstRechargeDiscountPercent: numberOrNull,
|
firstRechargeDiscountPercent: numberOrNull,
|
||||||
promotionType: stringOrNull,
|
promotionType: stringOrNull,
|
||||||
|
commercialOfferId: stringOrNull,
|
||||||
|
commercialDiscountPercent: numberOrNull,
|
||||||
})
|
})
|
||||||
.readonly();
|
.readonly();
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export const CreatePaymentOrderRequestSchema = z
|
|||||||
payChannel: PayChannelSchema,
|
payChannel: PayChannelSchema,
|
||||||
autoRenew: z.boolean(),
|
autoRenew: z.boolean(),
|
||||||
recipientCharacterId: z.string().min(1).optional(),
|
recipientCharacterId: z.string().min(1).optional(),
|
||||||
|
commercialOfferId: z.string().min(1).optional(),
|
||||||
})
|
})
|
||||||
.readonly();
|
.readonly();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const CommercialOfferResponseSchema = z
|
||||||
|
.object({
|
||||||
|
commercialOfferId: z.string().min(1),
|
||||||
|
planId: z.string().min(1),
|
||||||
|
subscriptionType: z.enum(["vip", "topup"]),
|
||||||
|
discountPercent: z.number().int().min(0).max(100),
|
||||||
|
pricePercent: z.number().int().min(0).max(100),
|
||||||
|
expiresAt: z.string().min(1),
|
||||||
|
message: z.string().min(1),
|
||||||
|
promotionType: z.string().min(1),
|
||||||
|
})
|
||||||
|
.readonly();
|
||||||
|
|
||||||
|
export type CommercialOfferResponse = z.output<
|
||||||
|
typeof CommercialOfferResponseSchema
|
||||||
|
>;
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export * from "./create_payment_order_response";
|
export * from "./create_payment_order_response";
|
||||||
|
export * from "./commercial_offer_response";
|
||||||
export * from "./gift_products_response";
|
export * from "./gift_products_response";
|
||||||
export * from "./payment_order_status_response";
|
export * from "./payment_order_status_response";
|
||||||
export * from "./payment_plans_response";
|
export * from "./payment_plans_response";
|
||||||
|
|||||||
@@ -20,10 +20,24 @@ export const FirstRechargeOfferSchema = z
|
|||||||
})
|
})
|
||||||
.readonly();
|
.readonly();
|
||||||
|
|
||||||
|
export const CommercialOfferSummarySchema = z
|
||||||
|
.object({
|
||||||
|
enabled: booleanOrFalse,
|
||||||
|
commercialOfferId: z.string().min(1),
|
||||||
|
planId: z.string().min(1),
|
||||||
|
discountPercent: numberOrZero,
|
||||||
|
pricePercent: numberOrZero,
|
||||||
|
expiresAt: z.string().min(1),
|
||||||
|
triggerReason: stringOrEmpty,
|
||||||
|
message: stringOrEmpty,
|
||||||
|
})
|
||||||
|
.readonly();
|
||||||
|
|
||||||
export const PaymentPlansResponseSchema = z
|
export const PaymentPlansResponseSchema = z
|
||||||
.object({
|
.object({
|
||||||
isFirstRecharge: booleanOrFalse,
|
isFirstRecharge: booleanOrFalse,
|
||||||
firstRechargeOffer: schemaOrNull(FirstRechargeOfferSchema),
|
firstRechargeOffer: schemaOrNull(FirstRechargeOfferSchema),
|
||||||
|
commercialOffer: schemaOrNull(CommercialOfferSummarySchema),
|
||||||
plans: arrayOrEmpty(PaymentPlanSchema),
|
plans: arrayOrEmpty(PaymentPlanSchema),
|
||||||
})
|
})
|
||||||
.readonly();
|
.readonly();
|
||||||
@@ -35,7 +49,9 @@ export type PaymentPlansResponseData = z.output<
|
|||||||
typeof PaymentPlansResponseSchema
|
typeof PaymentPlansResponseSchema
|
||||||
>;
|
>;
|
||||||
export type FirstRechargeOfferData = z.output<typeof FirstRechargeOfferSchema>;
|
export type FirstRechargeOfferData = z.output<typeof FirstRechargeOfferSchema>;
|
||||||
|
export type CommercialOfferSummaryData = z.output<typeof CommercialOfferSummarySchema>;
|
||||||
|
|
||||||
export type FirstRechargeOffer = FirstRechargeOfferData;
|
export type FirstRechargeOffer = FirstRechargeOfferData;
|
||||||
|
export type CommercialOfferSummary = CommercialOfferSummaryData;
|
||||||
|
|
||||||
export type PaymentPlansResponse = PaymentPlansResponseData;
|
export type PaymentPlansResponse = PaymentPlansResponseData;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { ApiPath } from "../api_path";
|
|||||||
describe("ApiPath contract source", () => {
|
describe("ApiPath contract source", () => {
|
||||||
it("uses the shared contract path for every static operation", () => {
|
it("uses the shared contract path for every static operation", () => {
|
||||||
const staticOperations = Object.entries(apiContract).filter(
|
const staticOperations = Object.entries(apiContract).filter(
|
||||||
([operationId]) => operationId !== "privateZoneAlbumUnlock",
|
([, operation]) => !operation.path.includes("{"),
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const [operationId, operation] of staticOperations) {
|
for (const [operationId, operation] of staticOperations) {
|
||||||
@@ -21,4 +21,10 @@ describe("ApiPath contract source", () => {
|
|||||||
"/api/private-zone/albums/album%2Fid%201/unlock",
|
"/api/private-zone/albums/album%2Fid%201/unlock",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("fills and encodes the commercial offer path parameter", () => {
|
||||||
|
expect(ApiPath.paymentCommercialOfferAccept("offer/id 1")).toBe(
|
||||||
|
"/api/payment/commercial-offers/offer%2Fid%201/accept",
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -81,4 +81,38 @@ describe("PaymentApi", () => {
|
|||||||
});
|
});
|
||||||
expect(response.message).toBe("Thank you for the thoughtful gift.");
|
expect(response.message).toBe("Thank you for the thoughtful gift.");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("accepts a server-issued offer before opening the subscription page", async () => {
|
||||||
|
httpClientMock.mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
planId: "vip_annual",
|
||||||
|
subscriptionType: "vip",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-24T08:00:00+00:00",
|
||||||
|
message: "I got it for you.",
|
||||||
|
promotionType: "commercial_seven_discount",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await new PaymentApi().acceptCommercialOffer("offer-1");
|
||||||
|
|
||||||
|
expect(httpClientMock).toHaveBeenCalledWith(
|
||||||
|
"/api/payment/commercial-offers/offer-1/accept",
|
||||||
|
{ method: "POST" },
|
||||||
|
);
|
||||||
|
expect(response.discountPercent).toBe(30);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requests an offer-scoped plan catalog without changing the public call", async () => {
|
||||||
|
httpClientMock.mockResolvedValue({ success: true, data: { plans: [] } });
|
||||||
|
|
||||||
|
await new PaymentApi().getPlans("offer-1");
|
||||||
|
|
||||||
|
expect(httpClientMock).toHaveBeenCalledWith("/api/payment/plans", {
|
||||||
|
query: { commercialOfferId: "offer-1" },
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
"paymentPlans": { "method": "get", "path": "/api/payment/plans" },
|
"paymentPlans": { "method": "get", "path": "/api/payment/plans" },
|
||||||
"paymentGiftProducts": { "method": "get", "path": "/api/payment/gift-products" },
|
"paymentGiftProducts": { "method": "get", "path": "/api/payment/gift-products" },
|
||||||
"paymentTipMessage": { "method": "post", "path": "/api/payment/tip-message" },
|
"paymentTipMessage": { "method": "post", "path": "/api/payment/tip-message" },
|
||||||
|
"paymentCommercialOfferAccept": { "method": "post", "path": "/api/payment/commercial-offers/{offerId}/accept" },
|
||||||
"chatSend": { "method": "post", "path": "/api/chat/send" },
|
"chatSend": { "method": "post", "path": "/api/chat/send" },
|
||||||
"chatOpeningMessage": { "method": "post", "path": "/api/chat/opening-message" },
|
"chatOpeningMessage": { "method": "post", "path": "/api/chat/opening-message" },
|
||||||
"chatHistory": { "method": "get", "path": "/api/chat/history" },
|
"chatHistory": { "method": "get", "path": "/api/chat/history" },
|
||||||
|
|||||||
@@ -66,6 +66,14 @@ export class ApiPath {
|
|||||||
/** 获取已支付礼物订单的角色感谢文案 */
|
/** 获取已支付礼物订单的角色感谢文案 */
|
||||||
static readonly paymentTipMessage = apiContract.paymentTipMessage.path;
|
static readonly paymentTipMessage = apiContract.paymentTipMessage.path;
|
||||||
|
|
||||||
|
/** 接受角色发放的用户专属优惠 */
|
||||||
|
static paymentCommercialOfferAccept(offerId: string): string {
|
||||||
|
return apiContract.paymentCommercialOfferAccept.path.replace(
|
||||||
|
"{offerId}",
|
||||||
|
encodeURIComponent(offerId),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ============ 聊天相关 ============
|
// ============ 聊天相关 ============
|
||||||
/** 发送消息 */
|
/** 发送消息 */
|
||||||
static readonly chatSend = apiContract.chatSend.path;
|
static readonly chatSend = apiContract.chatSend.path;
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
CreatePaymentOrderRequest,
|
CreatePaymentOrderRequest,
|
||||||
CreatePaymentOrderResponse,
|
CreatePaymentOrderResponse,
|
||||||
CreatePaymentOrderResponseSchema,
|
CreatePaymentOrderResponseSchema,
|
||||||
|
CommercialOfferResponse,
|
||||||
|
CommercialOfferResponseSchema,
|
||||||
GiftProductsResponse,
|
GiftProductsResponse,
|
||||||
GiftProductsResponseSchema,
|
GiftProductsResponseSchema,
|
||||||
PaymentOrderStatusResponse,
|
PaymentOrderStatusResponse,
|
||||||
@@ -24,13 +26,26 @@ import { ApiEnvelope, unwrap } from "./response_helper";
|
|||||||
|
|
||||||
export class PaymentApi {
|
export class PaymentApi {
|
||||||
/** 获取 VIP 与 Top-up 套餐列表。 */
|
/** 获取 VIP 与 Top-up 套餐列表。 */
|
||||||
async getPlans(): Promise<PaymentPlansResponse> {
|
async getPlans(commercialOfferId?: string): Promise<PaymentPlansResponse> {
|
||||||
const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans);
|
const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans, {
|
||||||
|
...(commercialOfferId ? { query: { commercialOfferId } } : {}),
|
||||||
|
});
|
||||||
return PaymentPlansResponseSchema.parse(
|
return PaymentPlansResponseSchema.parse(
|
||||||
unwrap(env) as Record<string, unknown>,
|
unwrap(env) as Record<string, unknown>,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 用户确认后激活一份后端签发的专属优惠。 */
|
||||||
|
async acceptCommercialOffer(offerId: string): Promise<CommercialOfferResponse> {
|
||||||
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
ApiPath.paymentCommercialOfferAccept(offerId),
|
||||||
|
{ method: "POST" },
|
||||||
|
);
|
||||||
|
return CommercialOfferResponseSchema.parse(
|
||||||
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** 一次获取当前角色的完整礼物目录。 */
|
/** 一次获取当前角色的完整礼物目录。 */
|
||||||
async getGiftProducts(characterId: string): Promise<GiftProductsResponse> {
|
async getGiftProducts(characterId: string): Promise<GiftProductsResponse> {
|
||||||
const env = await httpClient<ApiEnvelope<unknown>>(
|
const env = await httpClient<ApiEnvelope<unknown>>(
|
||||||
|
|||||||
@@ -66,6 +66,19 @@ describe("navigation resolver", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the user-bound offer and server-selected plan in the subscription URL", () => {
|
||||||
|
expect(
|
||||||
|
ROUTE_BUILDERS.subscription("vip", {
|
||||||
|
returnTo: "chat",
|
||||||
|
sourceCharacterSlug: "elio",
|
||||||
|
planId: "vip_annual",
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
}),
|
||||||
|
).toBe(
|
||||||
|
"/subscription?type=vip&returnTo=chat&character=elio&planId=vip_annual&commercialOfferId=offer-1",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("allows not logged in users to enter chat for guest bootstrap", () => {
|
it("allows not logged in users to enter chat for guest bootstrap", () => {
|
||||||
expect(
|
expect(
|
||||||
resolveRouteGuardRedirect({
|
resolveRouteGuardRedirect({
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ export const ROUTE_BUILDERS = {
|
|||||||
returnTo?: Exclude<AppSubscriptionReturnTo, null>;
|
returnTo?: Exclude<AppSubscriptionReturnTo, null>;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string;
|
||||||
analytics?: PaymentAnalyticsContext;
|
analytics?: PaymentAnalyticsContext;
|
||||||
|
planId?: string;
|
||||||
|
commercialOfferId?: string;
|
||||||
} = {},
|
} = {},
|
||||||
): `/subscription?${string}` => {
|
): `/subscription?${string}` => {
|
||||||
const params = new URLSearchParams({ type });
|
const params = new URLSearchParams({ type });
|
||||||
@@ -90,6 +92,10 @@ export const ROUTE_BUILDERS = {
|
|||||||
if (options.sourceCharacterSlug) {
|
if (options.sourceCharacterSlug) {
|
||||||
params.set("character", options.sourceCharacterSlug);
|
params.set("character", options.sourceCharacterSlug);
|
||||||
}
|
}
|
||||||
|
if (options.planId) params.set("planId", options.planId);
|
||||||
|
if (options.commercialOfferId) {
|
||||||
|
params.set("commercialOfferId", options.commercialOfferId);
|
||||||
|
}
|
||||||
if (options.analytics) {
|
if (options.analytics) {
|
||||||
params.set(
|
params.set(
|
||||||
PAYMENT_ANALYTICS_ENTRY_PARAM,
|
PAYMENT_ANALYTICS_ENTRY_PARAM,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import type { PaymentPlanCatalog } from "@/stores/payment/payment-state";
|
|||||||
|
|
||||||
export interface PaymentPlansActorInput {
|
export interface PaymentPlansActorInput {
|
||||||
catalog: PaymentPlanCatalog;
|
catalog: PaymentPlanCatalog;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateOrderInput {
|
export interface CreateOrderInput {
|
||||||
@@ -26,6 +27,7 @@ export interface CreateOrderInput {
|
|||||||
payChannel: PayChannel;
|
payChannel: PayChannel;
|
||||||
autoRenew: boolean;
|
autoRenew: boolean;
|
||||||
recipientCharacterId?: string;
|
recipientCharacterId?: string;
|
||||||
|
commercialOfferId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CreateOrderSpy = (input: CreateOrderInput) => void;
|
export type CreateOrderSpy = (input: CreateOrderInput) => void;
|
||||||
|
|||||||
@@ -81,6 +81,30 @@ describe("payment order flow", () => {
|
|||||||
actor.stop();
|
actor.stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("carries the server-issued commercial offer into order creation", async () => {
|
||||||
|
const createOrderSpy = vi.fn<CreateOrderSpy>();
|
||||||
|
const actor = createActor(
|
||||||
|
createTestPaymentMachine({ createOrderSpy }),
|
||||||
|
).start();
|
||||||
|
actor.send({
|
||||||
|
type: "PaymentInit",
|
||||||
|
planId: "vip_monthly",
|
||||||
|
commercialOfferId: "offer-user-bound-1",
|
||||||
|
});
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||||
|
|
||||||
|
actor.send({ type: "PaymentCreateOrderSubmitted" });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("paid"));
|
||||||
|
|
||||||
|
expect(createOrderSpy).toHaveBeenCalledWith({
|
||||||
|
planId: "vip_monthly",
|
||||||
|
payChannel: "stripe",
|
||||||
|
autoRenew: true,
|
||||||
|
commercialOfferId: "offer-user-bound-1",
|
||||||
|
});
|
||||||
|
actor.stop();
|
||||||
|
});
|
||||||
|
|
||||||
it("loads a stable Tip message after payment and clears it on reset", async () => {
|
it("loads a stable Tip message after payment and clears it on reset", async () => {
|
||||||
const loadTipMessage = vi.fn();
|
const loadTipMessage = vi.fn();
|
||||||
const actor = createActor(
|
const actor = createActor(
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export function hydratePlansResponseState(
|
|||||||
selectedPlanId: string,
|
selectedPlanId: string,
|
||||||
): Pick<
|
): Pick<
|
||||||
PaymentState,
|
PaymentState,
|
||||||
"plans" | "isFirstRecharge" | "selectedPlanId" | "autoRenew" | "errorMessage"
|
"plans" | "isFirstRecharge" | "commercialOffer" | "selectedPlanId" | "autoRenew" | "errorMessage"
|
||||||
> {
|
> {
|
||||||
const plans = normalizeFirstRechargePlans(
|
const plans = normalizeFirstRechargePlans(
|
||||||
response.plans,
|
response.plans,
|
||||||
@@ -61,6 +61,7 @@ export function hydratePlansResponseState(
|
|||||||
return {
|
return {
|
||||||
...hydratePlansState(plans, selectedPlanId),
|
...hydratePlansState(plans, selectedPlanId),
|
||||||
isFirstRecharge: response.isFirstRecharge,
|
isFirstRecharge: response.isFirstRecharge,
|
||||||
|
commercialOffer: response.commercialOffer,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +90,7 @@ export function refreshPlansResponseState(
|
|||||||
selectedPlanId: string,
|
selectedPlanId: string,
|
||||||
): Pick<
|
): Pick<
|
||||||
PaymentState,
|
PaymentState,
|
||||||
"plans" | "isFirstRecharge" | "selectedPlanId" | "autoRenew" | "errorMessage"
|
"plans" | "isFirstRecharge" | "commercialOffer" | "selectedPlanId" | "autoRenew" | "errorMessage"
|
||||||
> {
|
> {
|
||||||
const plans = normalizeFirstRechargePlans(
|
const plans = normalizeFirstRechargePlans(
|
||||||
response.plans,
|
response.plans,
|
||||||
@@ -98,6 +99,7 @@ export function refreshPlansResponseState(
|
|||||||
return {
|
return {
|
||||||
...refreshPlansState(plans, selectedPlanId),
|
...refreshPlansState(plans, selectedPlanId),
|
||||||
isFirstRecharge: response.isFirstRecharge,
|
isFirstRecharge: response.isFirstRecharge,
|
||||||
|
commercialOffer: response.commercialOffer,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export const createPaymentOrderActor = fromPromise<
|
|||||||
payChannel: PayChannel;
|
payChannel: PayChannel;
|
||||||
autoRenew: boolean;
|
autoRenew: boolean;
|
||||||
recipientCharacterId?: string;
|
recipientCharacterId?: string;
|
||||||
|
commercialOfferId?: string;
|
||||||
}
|
}
|
||||||
>(async ({ input }) => {
|
>(async ({ input }) => {
|
||||||
const result = await getPaymentRepository().createOrder(
|
const result = await getPaymentRepository().createOrder(
|
||||||
@@ -22,6 +23,7 @@ export const createPaymentOrderActor = fromPromise<
|
|||||||
input.payChannel,
|
input.payChannel,
|
||||||
input.autoRenew,
|
input.autoRenew,
|
||||||
input.recipientCharacterId,
|
input.recipientCharacterId,
|
||||||
|
input.commercialOfferId,
|
||||||
);
|
);
|
||||||
if (Result.isErr(result)) throw result.error;
|
if (Result.isErr(result)) throw result.error;
|
||||||
return result.data;
|
return result.data;
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import type { PaymentPlanCatalog } from "../../payment-state";
|
|||||||
|
|
||||||
export const loadCachedPaymentPlansActor = fromPromise<
|
export const loadCachedPaymentPlansActor = fromPromise<
|
||||||
PaymentPlansResponse | null,
|
PaymentPlansResponse | null,
|
||||||
{ catalog: PaymentPlanCatalog }
|
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null }
|
||||||
>(async ({ input }) => {
|
>(async ({ input }) => {
|
||||||
if (input.catalog === "tip") return null;
|
if (input.catalog === "tip" || input.commercialOfferId) return null;
|
||||||
const result = await getPaymentRepository().getCachedPlans();
|
const result = await getPaymentRepository().getCachedPlans();
|
||||||
if (Result.isErr(result)) throw result.error;
|
if (Result.isErr(result)) throw result.error;
|
||||||
return result.data;
|
return result.data;
|
||||||
@@ -18,13 +18,13 @@ export const loadCachedPaymentPlansActor = fromPromise<
|
|||||||
|
|
||||||
export const refreshPaymentPlansActor = fromPromise<
|
export const refreshPaymentPlansActor = fromPromise<
|
||||||
PaymentPlansResponse,
|
PaymentPlansResponse,
|
||||||
{ catalog: PaymentPlanCatalog }
|
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null }
|
||||||
>(async ({ input }) => {
|
>(async ({ input }) => {
|
||||||
const paymentRepo = getPaymentRepository();
|
const paymentRepo = getPaymentRepository();
|
||||||
if (input.catalog === "tip") {
|
if (input.catalog === "tip") {
|
||||||
throw new Error("Gift catalogs must use the gift products actor.");
|
throw new Error("Gift catalogs must use the gift products actor.");
|
||||||
}
|
}
|
||||||
const result = await paymentRepo.getPlans();
|
const result = await paymentRepo.getPlans(input.commercialOfferId ?? undefined);
|
||||||
if (Result.isErr(result)) throw result.error;
|
if (Result.isErr(result)) throw result.error;
|
||||||
return result.data;
|
return result.data;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -35,24 +35,30 @@ function initializeCatalogState(
|
|||||||
planCatalog === "tip" &&
|
planCatalog === "tip" &&
|
||||||
((event.category ?? null) !== context.selectedGiftCategory ||
|
((event.category ?? null) !== context.selectedGiftCategory ||
|
||||||
(event.planId ?? null) !== (context.selectedPlanId || null));
|
(event.planId ?? null) !== (context.selectedPlanId || null));
|
||||||
|
const commercialOfferId =
|
||||||
|
planCatalog === "default" ? (event.commercialOfferId ?? null) : null;
|
||||||
|
const offerChanged = commercialOfferId !== context.commercialOfferId;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
planCatalog,
|
planCatalog,
|
||||||
...(event.payChannel ? { payChannel: event.payChannel } : {}),
|
...(event.payChannel ? { payChannel: event.payChannel } : {}),
|
||||||
giftCharacterId,
|
giftCharacterId,
|
||||||
|
commercialOfferId,
|
||||||
requestedGiftCategory:
|
requestedGiftCategory:
|
||||||
planCatalog === "tip" ? (event.category ?? null) : null,
|
planCatalog === "tip" ? (event.category ?? null) : null,
|
||||||
requestedGiftPlanId:
|
requestedGiftPlanId:
|
||||||
planCatalog === "tip" ? (event.planId ?? null) : null,
|
planCatalog === "tip" ? (event.planId ?? null) : null,
|
||||||
...(catalogChanged || characterChanged || selectionChanged
|
...(catalogChanged || characterChanged || selectionChanged || offerChanged
|
||||||
? {
|
? {
|
||||||
...resetOrderState(),
|
...resetOrderState(),
|
||||||
plans: [],
|
plans: [],
|
||||||
giftCategories: [],
|
giftCategories: [],
|
||||||
giftProducts: [],
|
giftProducts: [],
|
||||||
selectedGiftCategory: null,
|
selectedGiftCategory: null,
|
||||||
selectedPlanId: "",
|
selectedPlanId:
|
||||||
|
planCatalog === "default" ? (event.planId ?? "") : "",
|
||||||
isFirstRecharge: false,
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: null,
|
||||||
autoRenew: planCatalog !== "tip",
|
autoRenew: planCatalog !== "tip",
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
@@ -207,7 +213,10 @@ export const loadingCachedPlansState =
|
|||||||
catalogMachineSetup.createStateConfig({
|
catalogMachineSetup.createStateConfig({
|
||||||
invoke: {
|
invoke: {
|
||||||
src: "loadCachedPlans",
|
src: "loadCachedPlans",
|
||||||
input: ({ context }) => ({ catalog: context.planCatalog }),
|
input: ({ context }) => ({
|
||||||
|
catalog: context.planCatalog,
|
||||||
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
}),
|
||||||
onDone: [
|
onDone: [
|
||||||
{
|
{
|
||||||
guard: ({ event }) => (event.output?.plans.length ?? 0) > 0,
|
guard: ({ event }) => (event.output?.plans.length ?? 0) > 0,
|
||||||
@@ -223,7 +232,10 @@ export const loadingCachedPlansState =
|
|||||||
export const loadingPlansState = catalogMachineSetup.createStateConfig({
|
export const loadingPlansState = catalogMachineSetup.createStateConfig({
|
||||||
invoke: {
|
invoke: {
|
||||||
src: "refreshPlans",
|
src: "refreshPlans",
|
||||||
input: ({ context }) => ({ catalog: context.planCatalog }),
|
input: ({ context }) => ({
|
||||||
|
catalog: context.planCatalog,
|
||||||
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
}),
|
||||||
onDone: {
|
onDone: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
actions: hydratePlansAction,
|
actions: hydratePlansAction,
|
||||||
@@ -238,7 +250,10 @@ export const loadingPlansState = catalogMachineSetup.createStateConfig({
|
|||||||
export const refreshingPlansState = catalogMachineSetup.createStateConfig({
|
export const refreshingPlansState = catalogMachineSetup.createStateConfig({
|
||||||
invoke: {
|
invoke: {
|
||||||
src: "refreshPlans",
|
src: "refreshPlans",
|
||||||
input: ({ context }) => ({ catalog: context.planCatalog }),
|
input: ({ context }) => ({
|
||||||
|
catalog: context.planCatalog,
|
||||||
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
}),
|
||||||
onDone: {
|
onDone: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
actions: refreshPlansAction,
|
actions: refreshPlansAction,
|
||||||
|
|||||||
@@ -195,6 +195,9 @@ const creatingOrderState = paymentMachineSetup.createStateConfig({
|
|||||||
event.recipientCharacterId
|
event.recipientCharacterId
|
||||||
? { recipientCharacterId: event.recipientCharacterId }
|
? { recipientCharacterId: event.recipientCharacterId }
|
||||||
: {}),
|
: {}),
|
||||||
|
...(context.commercialOfferId
|
||||||
|
? { commercialOfferId: context.commercialOfferId }
|
||||||
|
: {}),
|
||||||
}),
|
}),
|
||||||
onDone: {
|
onDone: {
|
||||||
target: "pollingOrder",
|
target: "pollingOrder",
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export interface PaymentContextState {
|
|||||||
giftProducts: MachineContext["giftProducts"];
|
giftProducts: MachineContext["giftProducts"];
|
||||||
selectedGiftCategory: string | null;
|
selectedGiftCategory: string | null;
|
||||||
isFirstRecharge: MachineContext["isFirstRecharge"];
|
isFirstRecharge: MachineContext["isFirstRecharge"];
|
||||||
|
commercialOffer: MachineContext["commercialOffer"];
|
||||||
selectedPlanId: string;
|
selectedPlanId: string;
|
||||||
payChannel: MachineContext["payChannel"];
|
payChannel: MachineContext["payChannel"];
|
||||||
autoRenew: boolean;
|
autoRenew: boolean;
|
||||||
@@ -74,6 +75,7 @@ function selectPaymentState(state: PaymentSnapshot): PaymentContextState {
|
|||||||
giftProducts: state.context.giftProducts,
|
giftProducts: state.context.giftProducts,
|
||||||
selectedGiftCategory: state.context.selectedGiftCategory,
|
selectedGiftCategory: state.context.selectedGiftCategory,
|
||||||
isFirstRecharge: state.context.isFirstRecharge,
|
isFirstRecharge: state.context.isFirstRecharge,
|
||||||
|
commercialOffer: state.context.commercialOffer,
|
||||||
selectedPlanId: state.context.selectedPlanId,
|
selectedPlanId: state.context.selectedPlanId,
|
||||||
payChannel: state.context.payChannel,
|
payChannel: state.context.payChannel,
|
||||||
autoRenew: state.context.autoRenew,
|
autoRenew: state.context.autoRenew,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export type PaymentEvent =
|
|||||||
characterId?: string;
|
characterId?: string;
|
||||||
category?: string | null;
|
category?: string | null;
|
||||||
planId?: string | null;
|
planId?: string | null;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
}
|
}
|
||||||
| { type: "PaymentPlanSelected"; planId: string }
|
| { type: "PaymentPlanSelected"; planId: string }
|
||||||
| { type: "PaymentPayChannelChanged"; payChannel: PayChannel }
|
| { type: "PaymentPayChannelChanged"; payChannel: PayChannel }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type {
|
|||||||
PayChannel,
|
PayChannel,
|
||||||
PaymentOrderStatus,
|
PaymentOrderStatus,
|
||||||
PaymentPlan,
|
PaymentPlan,
|
||||||
|
CommercialOfferSummary,
|
||||||
TipMessageResponse,
|
TipMessageResponse,
|
||||||
} from "@/data/schemas/payment";
|
} from "@/data/schemas/payment";
|
||||||
|
|
||||||
@@ -20,6 +21,8 @@ export interface PaymentState {
|
|||||||
requestedGiftCategory: string | null;
|
requestedGiftCategory: string | null;
|
||||||
requestedGiftPlanId: string | null;
|
requestedGiftPlanId: string | null;
|
||||||
isFirstRecharge: boolean;
|
isFirstRecharge: boolean;
|
||||||
|
commercialOfferId: string | null;
|
||||||
|
commercialOffer: CommercialOfferSummary | null;
|
||||||
selectedPlanId: string;
|
selectedPlanId: string;
|
||||||
payChannel: PayChannel;
|
payChannel: PayChannel;
|
||||||
autoRenew: boolean;
|
autoRenew: boolean;
|
||||||
@@ -45,6 +48,8 @@ export const initialState: PaymentState = {
|
|||||||
requestedGiftCategory: null,
|
requestedGiftCategory: null,
|
||||||
requestedGiftPlanId: null,
|
requestedGiftPlanId: null,
|
||||||
isFirstRecharge: false,
|
isFirstRecharge: false,
|
||||||
|
commercialOfferId: null,
|
||||||
|
commercialOffer: null,
|
||||||
selectedPlanId: "",
|
selectedPlanId: "",
|
||||||
payChannel: "stripe",
|
payChannel: "stripe",
|
||||||
autoRenew: true,
|
autoRenew: true,
|
||||||
|
|||||||
Reference in New Issue
Block a user