feat(chat): render role-bound payment guidance
Docker Image / Build and Push Docker Image (push) Successful in 5m2s

This commit is contained in:
Codex
2026-07-27 18:14:04 +08:00
parent 019caae598
commit 8c0d1ad3ce
49 changed files with 882 additions and 81 deletions
+2
View File
@@ -128,6 +128,7 @@ export function ChatScreen() {
const messageLimitBanner = useChatMessageLimitBanner({ const messageLimitBanner = useChatMessageLimitBanner({
upgradePromptVisible: state.upgradePromptVisible, upgradePromptVisible: state.upgradePromptVisible,
upgradeReason: state.upgradeReason, upgradeReason: state.upgradeReason,
paymentGuidance: state.paymentGuidance,
}); });
const firstRechargeOfferBanner = useFirstRechargeOfferBanner({ const firstRechargeOfferBanner = useFirstRechargeOfferBanner({
historyLoaded: state.historyLoaded, historyLoaded: state.historyLoaded,
@@ -464,6 +465,7 @@ export function ChatScreen() {
title={messageLimitBanner.title} title={messageLimitBanner.title}
description={messageLimitBanner.description} description={messageLimitBanner.description}
ctaLabel={messageLimitBanner.ctaLabel} ctaLabel={messageLimitBanner.ctaLabel}
guidance={messageLimitBanner.guidance}
onUnlock={messageLimitBanner.unlock} onUnlock={messageLimitBanner.unlock}
/> />
) : ( ) : (
@@ -15,6 +15,7 @@ import { ImageBubble } from "../image-bubble";
import { InsufficientCreditsDialog } from "../insufficient-credits-dialog"; import { InsufficientCreditsDialog } from "../insufficient-credits-dialog";
import { MessageAvatar } from "../message-avatar"; import { MessageAvatar } from "../message-avatar";
import { PrivateMessageCard } from "../private-message-card"; import { PrivateMessageCard } from "../private-message-card";
import { PaymentGuidanceCard } from "../payment-guidance-card";
import { PwaInstallDialog } from "../pwa-install-dialog"; import { PwaInstallDialog } from "../pwa-install-dialog";
import { TextBubble } from "../text-bubble"; import { TextBubble } from "../text-bubble";
@@ -223,6 +224,19 @@ describe("chat Tailwind components", () => {
description="Credits keep the conversation going." description="Credits keep the conversation going."
ctaLabel="Top up" ctaLabel="Top up"
onUnlock={() => undefined} onUnlock={() => undefined}
guidance={{
guidanceId: "guidance-elio",
characterId: "elio",
characterName: "Elio Silvestri",
scene: "insufficientCredits",
mode: "guide",
title: "Keep talking with Elio",
copy: "Baby, I want to keep talking with you. Adding credits supports Elio.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"],
target: "subscription",
ruleId: "payment_guidance_insufficientCredits",
}}
/>, />,
); );
@@ -232,11 +246,56 @@ describe("chat Tailwind components", () => {
expect(html).toContain("<br/>"); expect(html).toContain("<br/>");
expect(html).toContain("Top up now"); expect(html).toContain("Top up now");
expect(html).toContain("Credits keep the conversation going."); expect(html).toContain("Credits keep the conversation going.");
expect(html).toContain("supports Elio");
expect(html).toContain('data-payment-guidance-id="guidance-elio"');
expect(html).toContain('aria-label="Top up"'); expect(html).toContain('aria-label="Top up"');
expect(html).toContain("bg-[linear-gradient(135deg,#f96ade_0%,#f657a0_100%)]"); expect(html).toContain("bg-[linear-gradient(135deg,#f96ade_0%,#f657a0_100%)]");
expect(html).toContain("active:scale-98"); expect(html).toContain("active:scale-98");
}); });
it("renders guidance only for the active character and hides care-only CTA", () => {
const guide = {
guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
characterId: "elio",
characterName: "Elio Silvestri",
scene: "insufficientCredits" as const,
mode: "guide" as const,
title: "Keep talking with Elio",
copy: "Baby, I want to keep talking with you.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"] as const,
target: "subscription" as const,
ruleId: "payment_guidance_insufficientCredits",
};
const guideHtml = renderWithCharacter(
<PaymentGuidanceCard guidance={guide} />,
);
const mismatchHtml = renderWithCharacter(
<PaymentGuidanceCard
guidance={{ ...guide, characterId: "maya-tan", characterName: "Maya Tan" }}
/>,
);
const careHtml = renderWithCharacter(
<PaymentGuidanceCard
guidance={{
...guide,
mode: "careOnly",
title: null,
ctaLabel: null,
purchaseOptions: [],
target: null,
copy: "Please keep money you need for food or medicine.",
}}
/>,
);
expect(guideHtml).toContain('data-payment-guidance-mode="guide"');
expect(guideHtml).toContain("View VIP &amp; credit options");
expect(mismatchHtml).toBe("");
expect(careHtml).toContain("food or medicine");
expect(careHtml).not.toContain("View VIP");
});
it("renders ChatHeader guest and member branches", () => { it("renders ChatHeader guest and member branches", () => {
const guestHtml = renderWithCharacter(<ChatHeader isGuest={true} />); const guestHtml = renderWithCharacter(<ChatHeader isGuest={true} />);
const memberHtml = renderWithCharacter( const memberHtml = renderWithCharacter(
+1
View File
@@ -337,6 +337,7 @@ function renderMessagesWithDateHeaders(
privateMessageHint={item.message.privateMessageHint} privateMessageHint={item.message.privateMessageHint}
commercialAction={item.message.commercialAction} commercialAction={item.message.commercialAction}
chatAction={item.message.chatAction} chatAction={item.message.chatAction}
paymentGuidance={item.message.paymentGuidance}
isUnlockingMessage={ isUnlockingMessage={
isUnlockingMessage === true && isUnlockingMessage === true &&
item.message.displayId === unlockingMessageId item.message.displayId === unlockingMessageId
@@ -17,11 +17,13 @@
* - 不直接管理 state machinechat 机器不感知 UI 层) * - 不直接管理 state machinechat 机器不感知 UI 层)
*/ */
import { useAppNavigator } from "@/router/use-app-navigator"; import { useAppNavigator } from "@/router/use-app-navigator";
import type { PaymentGuidance } from "@/data/schemas/chat";
export interface ChatInsufficientCreditsBannerProps { export interface ChatInsufficientCreditsBannerProps {
title?: string; title?: string;
description?: string; description?: string;
ctaLabel?: string; ctaLabel?: string | null;
guidance?: PaymentGuidance | null;
/** /**
* 自定义点击回调(不传则默认走统一订阅导航) * 自定义点击回调(不传则默认走统一订阅导航)
* - 测试时可传 mock * - 测试时可传 mock
@@ -34,9 +36,11 @@ export function ChatInsufficientCreditsBanner({
title = "Insufficient credits\nTop up to continue chatting", title = "Insufficient credits\nTop up to continue chatting",
description, description,
ctaLabel = "Top up credits to continue", ctaLabel = "Top up credits to continue",
guidance = null,
onUnlock, onUnlock,
}: ChatInsufficientCreditsBannerProps) { }: ChatInsufficientCreditsBannerProps) {
const navigator = useAppNavigator(); const navigator = useAppNavigator();
const activeGuidance = guidance;
const titleLines = title.split("\n"); const titleLines = title.split("\n");
const handleClick = () => { const handleClick = () => {
@@ -53,6 +57,7 @@ export function ChatInsufficientCreditsBanner({
role="status" role="status"
aria-live="polite" aria-live="polite"
data-testid="chat-insufficient-credits-banner" data-testid="chat-insufficient-credits-banner"
data-payment-guidance-id={activeGuidance?.guidanceId}
> >
<p className="m-0 mb-(--spacing-sm,8px) text-(length:--responsive-card-title,18px) font-semibold leading-[1.4] text-white opacity-95"> <p className="m-0 mb-(--spacing-sm,8px) text-(length:--responsive-card-title,18px) font-semibold leading-[1.4] text-white opacity-95">
{titleLines.map((line, index) => ( {titleLines.map((line, index) => (
@@ -67,7 +72,12 @@ export function ChatInsufficientCreditsBanner({
{description} {description}
</p> </p>
) : null} ) : null}
<button {activeGuidance?.copy ? (
<p className="mx-auto mb-(--spacing-lg,16px) mt-0 max-w-[min(100%,360px)] text-(length:--responsive-caption,14px) font-semibold leading-[1.4] text-white">
{activeGuidance.copy}
</p>
) : null}
{ctaLabel ? <button
type="button" type="button"
data-analytics-key="chat.topup" data-analytics-key="chat.topup"
data-analytics-label="Top up chat credits" data-analytics-label="Top up chat credits"
@@ -76,7 +86,7 @@ export function ChatInsufficientCreditsBanner({
aria-label={ctaLabel} aria-label={ctaLabel}
> >
{ctaLabel} {ctaLabel}
</button> </button> : null}
</div> </div>
); );
} }
@@ -19,6 +19,7 @@ export function ChatUnlockDialogs({
lockedCount={model.historyUnlock.lockedCount} lockedCount={model.historyUnlock.lockedCount}
isLoading={model.historyUnlock.isLoading} isLoading={model.historyUnlock.isLoading}
errorMessage={model.historyUnlock.errorMessage} errorMessage={model.historyUnlock.errorMessage}
guidance={model.historyUnlock.guidance}
onClose={model.closeHistoryUnlock} onClose={model.closeHistoryUnlock}
onConfirm={model.confirmHistoryUnlock} onConfirm={model.confirmHistoryUnlock}
/> />
@@ -27,6 +28,7 @@ export function ChatUnlockDialogs({
creditBalance={model.unlockPaywallRequest?.creditBalance ?? 0} creditBalance={model.unlockPaywallRequest?.creditBalance ?? 0}
requiredCredits={model.unlockPaywallRequest?.requiredCredits ?? 0} requiredCredits={model.unlockPaywallRequest?.requiredCredits ?? 0}
shortfallCredits={model.unlockPaywallRequest?.shortfallCredits ?? 0} shortfallCredits={model.unlockPaywallRequest?.shortfallCredits ?? 0}
guidance={model.unlockPaywallRequest?.paymentGuidance ?? null}
onClose={model.closePaywall} onClose={model.closePaywall}
onConfirm={model.confirmPaywall} onConfirm={model.confirmPaywall}
/> />
@@ -1,10 +1,13 @@
"use client"; "use client";
import type { PaymentGuidance } from "@/data/schemas/chat";
export interface HistoryUnlockDialogProps { export interface HistoryUnlockDialogProps {
open: boolean; open: boolean;
lockedCount: number; lockedCount: number;
isLoading?: boolean; isLoading?: boolean;
errorMessage?: string | null; errorMessage?: string | null;
guidance?: PaymentGuidance | null;
onClose: () => void; onClose: () => void;
onConfirm: () => void; onConfirm: () => void;
} }
@@ -14,10 +17,15 @@ export function HistoryUnlockDialog({
lockedCount, lockedCount,
isLoading = false, isLoading = false,
errorMessage, errorMessage,
guidance = null,
onClose, onClose,
onConfirm, onConfirm,
}: HistoryUnlockDialogProps) { }: HistoryUnlockDialogProps) {
if (!open) return null; if (!open) return null;
const activeGuidance = guidance;
const showAction =
!activeGuidance ||
(activeGuidance.mode === "guide" && activeGuidance.ctaLabel !== null);
return ( return (
<div <div
@@ -31,11 +39,16 @@ export function HistoryUnlockDialog({
id="history-unlock-title" id="history-unlock-title"
className="m-0 mb-2.5 text-(length:--responsive-page-title,var(--font-size-22,22px)) font-bold leading-[1.2] text-text-foreground" className="m-0 mb-2.5 text-(length:--responsive-page-title,var(--font-size-22,22px)) font-bold leading-[1.2] text-text-foreground"
> >
Unlock previous messages? {activeGuidance?.title ?? "Unlock previous messages?"}
</h2> </h2>
<p className="mx-(--responsive-card-padding-lg,24px) mb-(--spacing-lg,16px) mt-0 text-left text-(length:--responsive-body,var(--font-size-lg,16px)) leading-normal text-[#393939]"> <p className="mx-(--responsive-card-padding-lg,24px) mb-(--spacing-lg,16px) mt-0 text-left text-(length:--responsive-body,var(--font-size-lg,16px)) leading-normal text-[#393939]">
We found {lockedCount} locked messages in your chat history. You can {activeGuidance?.copy ?? (
unlock them now to continue the conversation with full context. <>
We found {lockedCount} locked messages in your chat history. You
can unlock them now to continue the conversation with full
context.
</>
)}
</p> </p>
{errorMessage ? ( {errorMessage ? (
<p className="mx-(--responsive-card-padding-lg,24px) mb-(--spacing-lg,16px) mt-0 text-left text-(length:--responsive-caption,var(--font-size-md,14px)) leading-[1.4] text-[#c0364c]"> <p className="mx-(--responsive-card-padding-lg,24px) mb-(--spacing-lg,16px) mt-0 text-left text-(length:--responsive-caption,var(--font-size-md,14px)) leading-[1.4] text-[#c0364c]">
@@ -51,7 +64,7 @@ export function HistoryUnlockDialog({
> >
Later Later
</button> </button>
<button {showAction ? <button
type="button" type="button"
data-analytics-key="chat.unlock_history" data-analytics-key="chat.unlock_history"
data-analytics-label="Unlock chat history" data-analytics-label="Unlock chat history"
@@ -59,8 +72,10 @@ export function HistoryUnlockDialog({
onClick={onConfirm} onClick={onConfirm}
disabled={isLoading} disabled={isLoading}
> >
{isLoading ? "Unlocking..." : "Unlock now"} {isLoading
</button> ? "Unlocking..."
: activeGuidance?.ctaLabel ?? "Unlock now"}
</button> : null}
</div> </div>
</div> </div>
</div> </div>
+1
View File
@@ -22,6 +22,7 @@ export * from "./insufficient-credits-dialog";
export * from "./message-avatar"; export * from "./message-avatar";
export * from "./message-bubble"; export * from "./message-bubble";
export * from "./message-content"; export * from "./message-content";
export * from "./payment-guidance-card";
export * from "./private-message-card"; export * from "./private-message-card";
export * from "./pwa-install-dialog"; export * from "./pwa-install-dialog";
export * from "./pwa-install-overlay"; export * from "./pwa-install-overlay";
@@ -1,10 +1,13 @@
"use client"; "use client";
import type { PaymentGuidance } from "@/data/schemas/chat";
export interface InsufficientCreditsDialogProps { export interface InsufficientCreditsDialogProps {
open: boolean; open: boolean;
creditBalance: number; creditBalance: number;
requiredCredits: number; requiredCredits: number;
shortfallCredits: number; shortfallCredits: number;
guidance?: PaymentGuidance | null;
onClose: () => void; onClose: () => void;
onConfirm: () => void; onConfirm: () => void;
} }
@@ -14,12 +17,17 @@ export function InsufficientCreditsDialog({
creditBalance, creditBalance,
requiredCredits, requiredCredits,
shortfallCredits, shortfallCredits,
guidance = null,
onClose, onClose,
onConfirm, onConfirm,
}: InsufficientCreditsDialogProps) { }: InsufficientCreditsDialogProps) {
if (!open) return null; if (!open) return null;
const showCreditDetail = requiredCredits > 0 || shortfallCredits > 0; const showCreditDetail = requiredCredits > 0 || shortfallCredits > 0;
const activeGuidance = guidance;
const showPurchaseAction =
!activeGuidance ||
(activeGuidance.mode === "guide" && activeGuidance.ctaLabel !== null);
return ( return (
<div <div
@@ -33,10 +41,11 @@ export function InsufficientCreditsDialog({
id="insufficient-credits-title" id="insufficient-credits-title"
className="m-0 mb-2.5 text-(length:--responsive-page-title,var(--font-size-22,22px)) font-bold leading-[1.2] text-text-foreground" className="m-0 mb-2.5 text-(length:--responsive-page-title,var(--font-size-22,22px)) font-bold leading-[1.2] text-text-foreground"
> >
Not enough credits {activeGuidance?.title ?? "Not enough credits"}
</h2> </h2>
<p className="mx-(--spacing-md,12px) mb-(--page-section-gap,18px) mt-0 text-(length:--responsive-body,var(--font-size-lg,16px)) leading-normal text-[#393939]"> <p className="mx-(--spacing-md,12px) mb-(--page-section-gap,18px) mt-0 text-(length:--responsive-body,var(--font-size-lg,16px)) leading-normal text-[#393939]">
Top up your credits to unlock this message and keep the moment going. {activeGuidance?.copy ??
"Top up your credits to unlock this message and keep the moment going."}
</p> </p>
{showCreditDetail ? ( {showCreditDetail ? (
@@ -70,15 +79,15 @@ export function InsufficientCreditsDialog({
> >
Later Later
</button> </button>
<button {showPurchaseAction ? <button
type="button" type="button"
data-analytics-key="chat.topup" data-analytics-key="chat.topup"
data-analytics-label="Top up chat credits" data-analytics-label="Top up chat credits"
className="flex min-h-(--pwa-button-height,44px) flex-auto cursor-pointer items-center justify-center rounded-bottom-sheet border-0 bg-[linear-gradient(90deg,#ff67e0_0%,#ff52a2_100%)] text-(length:--responsive-body,var(--font-size-lg,16px)) font-bold text-(--color-pwa-button-text,#ffffff) shadow-[0_6px_14px_rgba(246,87,160,0.28)] focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-[#f657a0]" className="flex min-h-(--pwa-button-height,44px) flex-auto cursor-pointer items-center justify-center rounded-bottom-sheet border-0 bg-[linear-gradient(90deg,#ff67e0_0%,#ff52a2_100%)] text-(length:--responsive-body,var(--font-size-lg,16px)) font-bold text-(--color-pwa-button-text,#ffffff) shadow-[0_6px_14px_rgba(246,87,160,0.28)] focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-[#f657a0]"
onClick={onConfirm} onClick={onConfirm}
> >
Top up now {activeGuidance?.ctaLabel ?? "Top up now"}
</button> </button> : null}
</div> </div>
</div> </div>
</div> </div>
+4 -1
View File
@@ -9,7 +9,7 @@
* - 用户:[占位 spacer] [Content] [Avatar] * - 用户:[占位 spacer] [Content] [Avatar]
*/ */
import { useUserSelector } from "@/stores/user/user-context"; import { useUserSelector } from "@/stores/user/user-context";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat"; import type { ChatAction, CommercialAction, PaymentGuidance } from "@/data/schemas/chat";
import { MessageAvatar } from "./message-avatar"; import { MessageAvatar } from "./message-avatar";
import { MessageContent } from "./message-content"; import { MessageContent } from "./message-content";
@@ -30,6 +30,7 @@ export interface MessageBubbleProps {
privateMessageHint?: string | null; privateMessageHint?: string | null;
commercialAction?: CommercialAction | null; commercialAction?: CommercialAction | null;
chatAction?: ChatAction | null; chatAction?: ChatAction | null;
paymentGuidance?: PaymentGuidance | null;
isUnlockingMessage?: boolean; isUnlockingMessage?: boolean;
onUnlockPrivateMessage?: ChatMessageAction; onUnlockPrivateMessage?: ChatMessageAction;
onUnlockVoiceMessage?: ChatMessageAction; onUnlockVoiceMessage?: ChatMessageAction;
@@ -64,6 +65,7 @@ export function MessageBubble({
privateMessageHint, privateMessageHint,
commercialAction, commercialAction,
chatAction, chatAction,
paymentGuidance,
isUnlockingMessage, isUnlockingMessage,
onUnlockPrivateMessage, onUnlockPrivateMessage,
onUnlockVoiceMessage, onUnlockVoiceMessage,
@@ -106,6 +108,7 @@ export function MessageBubble({
privateMessageHint={privateMessageHint} privateMessageHint={privateMessageHint}
commercialAction={commercialAction} commercialAction={commercialAction}
chatAction={chatAction} chatAction={chatAction}
paymentGuidance={paymentGuidance}
isUnlockingMessage={isUnlockingMessage} isUnlockingMessage={isUnlockingMessage}
onUnlockPrivateMessage={onUnlockPrivateMessage} onUnlockPrivateMessage={onUnlockPrivateMessage}
onUnlockVoiceMessage={onUnlockVoiceMessage} onUnlockVoiceMessage={onUnlockVoiceMessage}
+11 -2
View File
@@ -1,11 +1,16 @@
"use client"; "use client";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat"; import type {
ChatAction,
CommercialAction,
PaymentGuidance,
} from "@/data/schemas/chat";
import { ChatActionCard } from "./chat-action-card"; import { ChatActionCard } from "./chat-action-card";
import { CommercialActionCard } from "./commercial-action-card"; import { CommercialActionCard } from "./commercial-action-card";
import { ImageBubble } from "./image-bubble"; import { ImageBubble } from "./image-bubble";
import { LockedImageMessageCard } from "./locked-image-message-card"; import { LockedImageMessageCard } from "./locked-image-message-card";
import { PrivateMessageCard } from "./private-message-card"; import { PrivateMessageCard } from "./private-message-card";
import { PaymentGuidanceCard } from "./payment-guidance-card";
import { TextBubble } from "./text-bubble"; import { TextBubble } from "./text-bubble";
import { VoiceBubble } from "./voice-bubble"; import { VoiceBubble } from "./voice-bubble";
import styles from "./chat-area.module.css"; import styles from "./chat-area.module.css";
@@ -25,6 +30,7 @@ export interface MessageContentProps {
privateMessageHint?: string | null; privateMessageHint?: string | null;
commercialAction?: CommercialAction | null; commercialAction?: CommercialAction | null;
chatAction?: ChatAction | null; chatAction?: ChatAction | null;
paymentGuidance?: PaymentGuidance | null;
isUnlockingMessage?: boolean; isUnlockingMessage?: boolean;
onUnlockPrivateMessage?: ChatMessageAction; onUnlockPrivateMessage?: ChatMessageAction;
onUnlockVoiceMessage?: ChatMessageAction; onUnlockVoiceMessage?: ChatMessageAction;
@@ -59,6 +65,7 @@ export function MessageContent({
privateMessageHint, privateMessageHint,
commercialAction, commercialAction,
chatAction, chatAction,
paymentGuidance,
isUnlockingMessage, isUnlockingMessage,
onUnlockPrivateMessage, onUnlockPrivateMessage,
onUnlockVoiceMessage, onUnlockVoiceMessage,
@@ -143,7 +150,9 @@ export function MessageContent({
) : null} ) : null}
</> </>
)} )}
{isFromAI && chatAction ? ( {isFromAI && paymentGuidance ? (
<PaymentGuidanceCard guidance={paymentGuidance} />
) : isFromAI && chatAction ? (
<ChatActionCard <ChatActionCard
action={chatAction} action={chatAction}
onViewed={onChatActionViewed} onViewed={onChatActionViewed}
@@ -0,0 +1,105 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { ArrowRight, CircleDollarSign, X } from "lucide-react";
import type { PaymentGuidance } from "@/data/schemas/chat";
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
import { useActiveCharacter } from "@/providers/character-provider";
import { useAppNavigator } from "@/router/use-app-navigator";
import { useUserSelector } from "@/stores/user/user-context";
import styles from "./chat-area.module.css";
export interface PaymentGuidanceCardProps {
guidance: PaymentGuidance;
}
export function PaymentGuidanceCard({ guidance }: PaymentGuidanceCardProps) {
const character = useActiveCharacter();
const navigator = useAppNavigator();
const isVip = useUserSelector((state) => state.context.isVip);
const [dismissed, setDismissed] = useState(false);
const viewedIdRef = useRef<string | null>(null);
const belongsToCurrentCharacter = guidance.characterId === character.id;
const hasPurchaseAction =
guidance.mode === "guide" &&
guidance.target === "subscription" &&
guidance.ctaLabel !== null &&
guidance.purchaseOptions.length > 0;
useEffect(() => {
if (!belongsToCurrentCharacter) return;
if (viewedIdRef.current === guidance.guidanceId) return;
viewedIdRef.current = guidance.guidanceId;
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"viewed",
).catch(() => undefined);
}, [belongsToCurrentCharacter, character.id, guidance.guidanceId]);
if (!belongsToCurrentCharacter || dismissed) return null;
const subscriptionType =
isVip || !guidance.purchaseOptions.includes("vip") ? "topup" : "vip";
return (
<aside
className={styles.commercialAction}
aria-label={guidance.title ?? guidance.characterName}
data-payment-guidance-id={guidance.guidanceId}
data-payment-guidance-mode={guidance.mode}
data-payment-guidance-scene={guidance.scene}
>
<div className={styles.commercialActionHeader}>
<CircleDollarSign size={18} aria-hidden="true" />
<button
type="button"
className={styles.commercialActionDismiss}
title="Dismiss"
aria-label="Dismiss"
onClick={() => {
setDismissed(true);
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"dismissed",
).catch(() => undefined);
}}
>
<X size={16} aria-hidden="true" />
</button>
</div>
{guidance.title ? (
<strong>{guidance.title}</strong>
) : null}
<p className={styles.commercialActionCopy}>{guidance.copy}</p>
{hasPurchaseAction ? (
<button
type="button"
className={styles.commercialActionButton}
onClick={() => {
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"opened",
).catch(() => undefined);
navigator.openSubscription({
type: subscriptionType,
returnTo: "chat",
chatActionId: guidance.guidanceId,
analytics: {
entryPoint: "chat_input",
triggerReason: "insufficient_credits",
},
});
}}
>
<span>{guidance.ctaLabel}</span>
<ArrowRight size={17} aria-hidden="true" />
</button>
) : null}
</aside>
);
}
@@ -5,6 +5,9 @@ import { useEffect, useRef } from "react";
import { behaviorAnalytics } from "@/lib/analytics"; import { behaviorAnalytics } from "@/lib/analytics";
import { useAppNavigator } from "@/router/use-app-navigator"; import { useAppNavigator } from "@/router/use-app-navigator";
import type { ChatUpgradeReason } from "@/stores/chat/chat-state"; import type { ChatUpgradeReason } from "@/stores/chat/chat-state";
import type { PaymentGuidance } from "@/data/schemas/chat";
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
import { useActiveCharacter } from "@/providers/character-provider";
import { useUserSelector } from "@/stores/user/user-context"; import { useUserSelector } from "@/stores/user/user-context";
import { import {
@@ -17,10 +20,14 @@ import {
export interface UseChatMessageLimitBannerInput { export interface UseChatMessageLimitBannerInput {
upgradePromptVisible: boolean; upgradePromptVisible: boolean;
upgradeReason: ChatUpgradeReason | null; upgradeReason: ChatUpgradeReason | null;
paymentGuidance: PaymentGuidance | null;
} }
export interface ChatMessageLimitBannerView export interface ChatMessageLimitBannerView {
extends InsufficientCreditsMessageLimitView { title: string;
description: string;
ctaLabel: string | null;
guidance: PaymentGuidance | null;
visible: boolean; visible: boolean;
unlock: () => void; unlock: () => void;
} }
@@ -28,10 +35,19 @@ export interface ChatMessageLimitBannerView
export function useChatMessageLimitBanner({ export function useChatMessageLimitBanner({
upgradePromptVisible, upgradePromptVisible,
upgradeReason, upgradeReason,
paymentGuidance,
}: UseChatMessageLimitBannerInput): ChatMessageLimitBannerView { }: UseChatMessageLimitBannerInput): ChatMessageLimitBannerView {
const navigator = useAppNavigator(); const navigator = useAppNavigator();
const character = useActiveCharacter();
const isVip = useUserSelector((state) => state.context.isVip); const isVip = useUserSelector((state) => state.context.isVip);
const view = getInsufficientCreditsMessageLimitView(); const fallbackView = getInsufficientCreditsMessageLimitView();
const guidance =
paymentGuidance?.characterId === character.id ? paymentGuidance : null;
const view: InsufficientCreditsMessageLimitView = {
title: guidance?.title ?? fallbackView.title,
description: guidance?.copy ?? fallbackView.description,
ctaLabel: guidance?.ctaLabel ?? fallbackView.ctaLabel,
};
const visible = shouldShowMessageLimitBanner({ const visible = shouldShowMessageLimitBanner({
upgradePromptVisible, upgradePromptVisible,
upgradeReason, upgradeReason,
@@ -52,12 +68,31 @@ export function useChatMessageLimitBanner({
}, },
{ isVip }, { isVip },
); );
}, [isVip, visible]); if (guidance) {
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"viewed",
).catch(() => undefined);
}
}, [character.id, guidance, isVip, visible]);
function unlock(): void { function unlock(): void {
if (guidance?.mode !== "guide" && guidance !== null) return;
if (guidance) {
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"opened",
).catch(() => undefined);
}
navigator.openSubscription({ navigator.openSubscription({
type: getInsufficientCreditsSubscriptionType(isVip), type:
isVip || (guidance && !guidance.purchaseOptions.includes("vip"))
? "topup"
: getInsufficientCreditsSubscriptionType(isVip),
returnTo: "chat", returnTo: "chat",
...(guidance ? { chatActionId: guidance.guidanceId } : {}),
analytics: { analytics: {
entryPoint: "chat_input", entryPoint: "chat_input",
triggerReason: "insufficient_credits", triggerReason: "insufficient_credits",
@@ -67,6 +102,9 @@ export function useChatMessageLimitBanner({
return { return {
...view, ...view,
ctaLabel:
guidance && guidance.mode !== "guide" ? null : view.ctaLabel,
guidance,
visible, visible,
unlock, unlock,
}; };
@@ -20,6 +20,7 @@ import {
import type { ChatPromotionState } from "@/stores/chat/helper/promotion"; import type { ChatPromotionState } from "@/stores/chat/helper/promotion";
import type { ChatUnlockPaywallRequest } from "@/stores/chat/chat-state"; import type { ChatUnlockPaywallRequest } from "@/stores/chat/chat-state";
import type { UiMessage } from "@/stores/chat/ui-message"; import type { UiMessage } from "@/stores/chat/ui-message";
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
import { useUserSelector } from "@/stores/user/user-context"; import { useUserSelector } from "@/stores/user/user-context";
import { getInsufficientCreditsSubscriptionType } from "../chat-screen.helpers"; import { getInsufficientCreditsSubscriptionType } from "../chat-screen.helpers";
@@ -48,6 +49,7 @@ export interface ChatUnlockDialogModel {
lockedCount: number; lockedCount: number;
isLoading: boolean; isLoading: boolean;
errorMessage: string | null; errorMessage: string | null;
guidance: import("@/data/schemas/chat").PaymentGuidance | null;
}; };
closeHistoryUnlock: () => void; closeHistoryUnlock: () => void;
confirmHistoryUnlock: () => void; confirmHistoryUnlock: () => void;
@@ -87,6 +89,8 @@ export function useChatUnlockCoordinator({
isUnlockingHistory: state.matches({ userSession: "unlockingHistory" }), isUnlockingHistory: state.matches({ userSession: "unlockingHistory" }),
lockedHistoryCount: state.context.lockedHistoryCount, lockedHistoryCount: state.context.lockedHistoryCount,
unlockHistoryError: state.context.unlockHistoryError, unlockHistoryError: state.context.unlockHistoryError,
unlockHistoryPaymentGuidance:
state.context.unlockHistoryPaymentGuidance,
unlockHistoryPromptVisible: state.context.unlockHistoryPromptVisible, unlockHistoryPromptVisible: state.context.unlockHistoryPromptVisible,
unlockPaywallRequest: state.context.unlockPaywallRequest, unlockPaywallRequest: state.context.unlockPaywallRequest,
}), }),
@@ -97,6 +101,20 @@ export function useChatUnlockCoordinator({
? chatState.unlockPaywallRequest ? chatState.unlockPaywallRequest
: null; : null;
useEffect(() => {
const guidance = chatState.unlockHistoryPaymentGuidance;
if (!enabled || guidance?.characterId !== chatState.characterId) return;
void recordChatActionEventById(
guidance.guidanceId,
chatState.characterId,
"viewed",
).catch(() => undefined);
}, [
chatState.characterId,
chatState.unlockHistoryPaymentGuidance,
enabled,
]);
useEffect(() => { useEffect(() => {
if (!unlockPaywallRequest) { if (!unlockPaywallRequest) {
trackedPaywallRef.current = null; trackedPaywallRef.current = null;
@@ -120,7 +138,15 @@ export function useChatUnlockCoordinator({
}, },
{ isVip }, { isVip },
); );
}, [isVip, unlockPaywallRequest]); const guidance = unlockPaywallRequest.paymentGuidance;
if (guidance?.characterId === chatState.characterId) {
void recordChatActionEventById(
guidance.guidanceId,
chatState.characterId,
"viewed",
).catch(() => undefined);
}
}, [chatState.characterId, isVip, unlockPaywallRequest]);
useEffect(() => { useEffect(() => {
if (!enabled) return; if (!enabled) return;
@@ -212,6 +238,32 @@ export function useChatUnlockCoordinator({
} }
function confirmHistoryUnlock(): void { function confirmHistoryUnlock(): void {
const guidance =
chatState.unlockHistoryPaymentGuidance?.characterId ===
chatState.characterId
? chatState.unlockHistoryPaymentGuidance
: null;
if (guidance) {
if (guidance.mode !== "guide") return;
void recordChatActionEventById(
guidance.guidanceId,
chatState.characterId,
"opened",
).catch(() => undefined);
navigator.openSubscription({
type:
isVip || !guidance.purchaseOptions.includes("vip")
? "topup"
: "vip",
returnTo: "chat",
chatActionId: guidance.guidanceId,
analytics: {
entryPoint: "chat_unlock",
triggerReason: "insufficient_credits",
},
});
return;
}
chatDispatch({ type: "ChatUnlockHistoryConfirmed" }); chatDispatch({ type: "ChatUnlockHistoryConfirmed" });
} }
@@ -221,6 +273,12 @@ export function useChatUnlockCoordinator({
function confirmPaywall(): void { function confirmPaywall(): void {
if (!unlockPaywallRequest) return; if (!unlockPaywallRequest) return;
const guidance =
unlockPaywallRequest.paymentGuidance?.characterId ===
chatState.characterId
? unlockPaywallRequest.paymentGuidance
: null;
if (guidance && guidance.mode !== "guide") return;
const returnUrl = resolveChatUnlockReturnUrl( const returnUrl = resolveChatUnlockReturnUrl(
unlockPaywallRequest, unlockPaywallRequest,
@@ -231,6 +289,13 @@ export function useChatUnlockCoordinator({
}, },
); );
chatDispatch({ type: "ChatUnlockPaywallNavigationConsumed" }); chatDispatch({ type: "ChatUnlockPaywallNavigationConsumed" });
if (guidance) {
void recordChatActionEventById(
guidance.guidanceId,
chatState.characterId,
"opened",
).catch(() => undefined);
}
navigator.openSubscriptionForPendingUnlock({ navigator.openSubscriptionForPendingUnlock({
displayMessageId: unlockPaywallRequest.displayMessageId, displayMessageId: unlockPaywallRequest.displayMessageId,
messageId: unlockPaywallRequest.messageId, messageId: unlockPaywallRequest.messageId,
@@ -239,13 +304,17 @@ export function useChatUnlockCoordinator({
clientLockId: unlockPaywallRequest.clientLockId, clientLockId: unlockPaywallRequest.clientLockId,
promotion: unlockPaywallRequest.promotion, promotion: unlockPaywallRequest.promotion,
returnUrl, returnUrl,
type: getInsufficientCreditsSubscriptionType(isVip), type:
isVip || (guidance && !guidance.purchaseOptions.includes("vip"))
? "topup"
: getInsufficientCreditsSubscriptionType(isVip),
analytics: { analytics: {
entryPoint: "chat_unlock", entryPoint: "chat_unlock",
triggerReason: unlockPaywallRequest.promotion triggerReason: unlockPaywallRequest.promotion
? "ad_landing" ? "ad_landing"
: "insufficient_credits", : "insufficient_credits",
}, },
...(guidance ? { chatActionId: guidance.guidanceId } : {}),
}); });
} }
@@ -258,6 +327,7 @@ export function useChatUnlockCoordinator({
lockedCount: chatState.lockedHistoryCount, lockedCount: chatState.lockedHistoryCount,
isLoading: chatState.isUnlockingHistory, isLoading: chatState.isUnlockingHistory,
errorMessage: chatState.unlockHistoryError, errorMessage: chatState.unlockHistoryError,
guidance: chatState.unlockHistoryPaymentGuidance,
}, },
closeHistoryUnlock, closeHistoryUnlock,
confirmHistoryUnlock, confirmHistoryUnlock,
@@ -58,13 +58,13 @@ describe("Private Zone paywall navigation", () => {
container.remove(); container.remove();
}); });
it("opens top up with a private zone return target", () => { it("opens VIP and credit options for a non-VIP user", () => {
const roomDispatch = vi.fn<Dispatch<PrivateZoneEvent>>(); const roomDispatch = vi.fn<Dispatch<PrivateZoneEvent>>();
renderHarness(root, "email", roomDispatch); renderHarness(root, "email", roomDispatch);
expect(mocks.openSubscription).toHaveBeenCalledWith({ expect(mocks.openSubscription).toHaveBeenCalledWith({
type: "topup", type: "vip",
returnTo: "private-zone", returnTo: "private-zone",
analytics: { analytics: {
entryPoint: "private_album_unlock", entryPoint: "private_album_unlock",
@@ -115,6 +115,7 @@ function Harness({
loginStatus, loginStatus,
roomDispatch, roomDispatch,
unlockPaywallRequest, unlockPaywallRequest,
isVip: false,
}); });
return null; return null;
} }
+23 -2
View File
@@ -19,6 +19,8 @@ import {
} from "@/providers/character-provider"; } from "@/providers/character-provider";
import { isPrivateAlbumLocked } from "@/lib/private-zone/private_album"; import { isPrivateAlbumLocked } from "@/lib/private-zone/private_album";
import { behaviorAnalytics } from "@/lib/analytics"; import { behaviorAnalytics } from "@/lib/analytics";
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
import { useUserSelector } from "@/stores/user/user-context";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context"; import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { import {
usePrivateZoneDispatch, usePrivateZoneDispatch,
@@ -63,6 +65,7 @@ export function PrivateZoneScreen() {
const dispatch = usePrivateZoneDispatch(); const dispatch = usePrivateZoneDispatch();
const postState = usePrivateZonePostState(); const postState = usePrivateZonePostState();
const postDispatch = usePrivateZonePostDispatch(); const postDispatch = usePrivateZonePostDispatch();
const isVip = useUserSelector((user) => user.context.isVip);
const [activeTab, setActiveTab] = useState<"moments" | "albums">("moments"); const [activeTab, setActiveTab] = useState<"moments" | "albums">("moments");
const openedGalleryInPageRef = useRef(false); const openedGalleryInPageRef = useRef(false);
const previousPostLoginStatusRef = useRef(authState.loginStatus); const previousPostLoginStatusRef = useRef(authState.loginStatus);
@@ -84,6 +87,7 @@ export function PrivateZoneScreen() {
loginStatus: authState.loginStatus, loginStatus: authState.loginStatus,
roomDispatch: dispatch, roomDispatch: dispatch,
unlockPaywallRequest: state.unlockPaywallRequest, unlockPaywallRequest: state.unlockPaywallRequest,
isVip,
}); });
usePrivateZoneUnlockSuccessRefresh(state.unlockSuccessNonce); usePrivateZoneUnlockSuccessRefresh(state.unlockSuccessNonce);
usePrivateZoneUnlockSuccessRefresh(postState.unlockSuccessNonce); usePrivateZoneUnlockSuccessRefresh(postState.unlockSuccessNonce);
@@ -119,9 +123,24 @@ export function PrivateZoneScreen() {
entryPoint: "private_zone", entryPoint: "private_zone",
triggerReason: "insufficient_credits", triggerReason: "insufficient_credits",
}); });
const guidance =
request.paymentGuidance?.characterId === character.id
? request.paymentGuidance
: null;
if (guidance) {
void recordChatActionEventById(
guidance.guidanceId,
character.id,
"opened",
).catch(() => undefined);
}
navigator.openSubscription({ navigator.openSubscription({
type: "topup", type:
isVip || (guidance && !guidance.purchaseOptions.includes("vip"))
? "topup"
: "vip",
returnTo: "private-zone", returnTo: "private-zone",
...(guidance ? { chatActionId: guidance.guidanceId } : {}),
analytics: { analytics: {
entryPoint: "private_zone", entryPoint: "private_zone",
triggerReason: "insufficient_credits", triggerReason: "insufficient_credits",
@@ -132,6 +151,8 @@ export function PrivateZoneScreen() {
}, [ }, [
authState.loginStatus, authState.loginStatus,
characterRoutes.privateZone, characterRoutes.privateZone,
character.id,
isVip,
navigator, navigator,
postDispatch, postDispatch,
postState.unlockPaywallRequest, postState.unlockPaywallRequest,
@@ -205,7 +226,7 @@ export function PrivateZoneScreen() {
return; return;
} }
navigator.openSubscription({ navigator.openSubscription({
type: "topup", type: isVip ? "topup" : "vip",
returnTo: "private-zone", returnTo: "private-zone",
analytics: { analytics: {
entryPoint: "private_zone", entryPoint: "private_zone",
+28 -2
View File
@@ -5,12 +5,16 @@ import { type Dispatch, useEffect, useRef } from "react";
import type { LoginStatus } from "@/data/schemas/auth"; import type { LoginStatus } from "@/data/schemas/auth";
import { useGuestLoginBootstrap } from "@/hooks/use-guest-login-bootstrap"; import { useGuestLoginBootstrap } from "@/hooks/use-guest-login-bootstrap";
import { behaviorAnalytics } from "@/lib/analytics"; import { behaviorAnalytics } from "@/lib/analytics";
import { useActiveCharacterRoutes } from "@/providers/character-provider"; import {
useActiveCharacter,
useActiveCharacterRoutes,
} from "@/providers/character-provider";
import { useAppNavigator } from "@/router/use-app-navigator"; import { useAppNavigator } from "@/router/use-app-navigator";
import type { AuthEvent } from "@/stores/auth/auth-events"; import type { AuthEvent } from "@/stores/auth/auth-events";
import type { PrivateZoneEvent } from "@/stores/private-zone"; import type { PrivateZoneEvent } from "@/stores/private-zone";
import type { PrivateZoneUnlockPaywallRequest } from "@/stores/private-zone/private-zone-state"; import type { PrivateZoneUnlockPaywallRequest } from "@/stores/private-zone/private-zone-state";
import { useUserDispatch } from "@/stores/user/user-context"; import { useUserDispatch } from "@/stores/user/user-context";
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
export interface UsePrivateZoneBootstrapFlowInput { export interface UsePrivateZoneBootstrapFlowInput {
authDispatch: Dispatch<AuthEvent>; authDispatch: Dispatch<AuthEvent>;
@@ -25,6 +29,7 @@ export interface UsePrivateZoneUnlockPaywallNavigationInput {
loginStatus: LoginStatus; loginStatus: LoginStatus;
roomDispatch: Dispatch<PrivateZoneEvent>; roomDispatch: Dispatch<PrivateZoneEvent>;
unlockPaywallRequest: PrivateZoneUnlockPaywallRequest | null; unlockPaywallRequest: PrivateZoneUnlockPaywallRequest | null;
isVip: boolean;
} }
export function isPrivateZoneAuthRequired(loginStatus: LoginStatus): boolean { export function isPrivateZoneAuthRequired(loginStatus: LoginStatus): boolean {
@@ -76,8 +81,10 @@ export function usePrivateZoneUnlockPaywallNavigation({
loginStatus, loginStatus,
roomDispatch, roomDispatch,
unlockPaywallRequest, unlockPaywallRequest,
isVip,
}: UsePrivateZoneUnlockPaywallNavigationInput): void { }: UsePrivateZoneUnlockPaywallNavigationInput): void {
const navigator = useAppNavigator(); const navigator = useAppNavigator();
const character = useActiveCharacter();
const characterRoutes = useActiveCharacterRoutes(); const characterRoutes = useActiveCharacterRoutes();
useEffect(() => { useEffect(() => {
@@ -90,9 +97,26 @@ export function usePrivateZoneUnlockPaywallNavigation({
entryPoint: "private_album_unlock", entryPoint: "private_album_unlock",
triggerReason: "insufficient_credits", triggerReason: "insufficient_credits",
}); });
const guidance = unlockPaywallRequest.paymentGuidance;
const activeGuidance =
guidance?.characterId === character.id ? guidance : null;
if (activeGuidance) {
void recordChatActionEventById(
activeGuidance.guidanceId,
activeGuidance.characterId,
"opened",
).catch(() => undefined);
}
navigator.openSubscription({ navigator.openSubscription({
type: "topup", type:
isVip ||
(activeGuidance && !activeGuidance.purchaseOptions.includes("vip"))
? "topup"
: "vip",
returnTo: "private-zone", returnTo: "private-zone",
...(activeGuidance
? { chatActionId: activeGuidance.guidanceId }
: {}),
analytics: { analytics: {
entryPoint: "private_album_unlock", entryPoint: "private_album_unlock",
triggerReason: "insufficient_credits", triggerReason: "insufficient_credits",
@@ -102,7 +126,9 @@ export function usePrivateZoneUnlockPaywallNavigation({
roomDispatch({ type: "PrivateZoneUnlockPaywallConsumed" }); roomDispatch({ type: "PrivateZoneUnlockPaywallConsumed" });
}, [ }, [
characterRoutes.privateZone, characterRoutes.privateZone,
character.id,
loginStatus, loginStatus,
isVip,
navigator, navigator,
roomDispatch, roomDispatch,
unlockPaywallRequest, unlockPaywallRequest,
@@ -256,6 +256,25 @@ describe("SubscriptionScreen payment selection flow", () => {
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }), expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
); );
}); });
it("keeps payment guidance bound to the source character", () => {
act(() =>
root.render(
<SubscriptionScreen
sourceCharacterSlug="maya"
chatActionId="019c8f8d-17d3-7a42-b1cc-b6927b1927d5"
/>,
),
);
const guidance = container.querySelector(
'[data-payment-guidance-character="maya-tan"]',
);
expect(guidance?.textContent).toContain("Keep talking with Maya");
expect(guidance?.textContent).toContain("support Maya");
expect(guidance?.textContent).toContain("cannot continue");
expect(guidance?.textContent).not.toContain("Elio");
});
}); });
function clickButton(root: ParentNode, label: string): void { function clickButton(root: ParentNode, label: string): void {
@@ -61,6 +61,29 @@
box-shadow: 0 12px 30px rgba(22, 101, 52, 0.12); box-shadow: 0 12px 30px rgba(22, 101, 52, 0.12);
} }
.characterSupportBanner {
margin-top: var(--page-section-gap, 14px);
padding: 14px 16px;
border: 1px solid rgba(246, 87, 160, 0.2);
border-radius: var(--responsive-card-radius-sm, 22px);
background: rgba(255, 255, 255, 0.9);
color: #4a3340;
box-shadow: 0 10px 24px rgba(246, 87, 160, 0.1);
}
.characterSupportBanner h2 {
margin: 0;
color: #24151d;
font-size: var(--responsive-card-title, 17px);
line-height: 1.25;
}
.characterSupportBanner p {
margin: 6px 0 0;
font-size: var(--responsive-caption, 14px);
line-height: 1.45;
}
.firstRechargeBanner { .firstRechargeBanner {
display: flex; display: flex;
align-items: center; align-items: center;
+27 -3
View File
@@ -8,7 +8,11 @@ import { usePaymentMethodSelection } from "@/app/_hooks/use-payment-method-selec
import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics"; import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics";
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,
DEFAULT_CHARACTER_SLUG,
getCharacterBySlug,
} from "@/data/constants/character";
import { import {
behaviorAnalytics, behaviorAnalytics,
getDefaultPaymentAnalyticsContext, getDefaultPaymentAnalyticsContext,
@@ -75,6 +79,8 @@ export function SubscriptionScreen({
null, null,
); );
const userState = useUserState(); const userState = useUserState();
const sourceCharacter =
getCharacterBySlug(sourceCharacterSlug) ?? DEFAULT_CHARACTER;
const hasHydrated = useHasHydrated(); const hasHydrated = useHasHydrated();
const countryCode = userState.currentUser?.countryCode; const countryCode = userState.currentUser?.countryCode;
const paymentMethodConfig = getPaymentMethodConfig({ const paymentMethodConfig = getPaymentMethodConfig({
@@ -262,6 +268,22 @@ export function SubscriptionScreen({
</p> </p>
) : null} ) : null}
{chatActionId ? (
<section
className={styles.characterSupportBanner}
aria-label={`Support ${sourceCharacter.displayName}`}
data-payment-guidance-character={sourceCharacter.id}
>
<h2>Keep talking with {sourceCharacter.shortName}</h2>
<p>
Without the required VIP access or credits, paid chat and locked
content cannot continue. Choosing an option here is a voluntary
way to support{" "}
{sourceCharacter.shortName}; it is never a test of your feelings.
</p>
</section>
) : null}
{firstRechargeOffer ? ( {firstRechargeOffer ? (
<section <section
className={styles.firstRechargeBanner} className={styles.firstRechargeBanner}
@@ -289,11 +311,13 @@ export function SubscriptionScreen({
{payment.commercialOffer && !firstRechargeOffer ? ( {payment.commercialOffer && !firstRechargeOffer ? (
<section <section
className={styles.firstRechargeBanner} className={styles.firstRechargeBanner}
aria-label="Elio private offer" aria-label={`${sourceCharacter.shortName} private offer`}
> >
<span className={styles.firstRechargeBadge}>Private offer</span> <span className={styles.firstRechargeBadge}>Private offer</span>
<div className={styles.firstRechargeCopy}> <div className={styles.firstRechargeCopy}>
<h2 className={styles.firstRechargeTitle}>Elio got this price for you</h2> <h2 className={styles.firstRechargeTitle}>
{sourceCharacter.shortName} got this price for you
</h2>
<p className={styles.firstRechargeSubtitle}> <p className={styles.firstRechargeSubtitle}>
{payment.commercialOffer.message || {payment.commercialOffer.message ||
`Your ${payment.commercialOffer.discountPercent}% discount is already applied below.`} `Your ${payment.commercialOffer.discountPercent}% discount is already applied below.`}
+1 -1
View File
@@ -54,7 +54,7 @@ export function TipScreen({
const characterRoutes = useActiveCharacterRoutes(); const characterRoutes = useActiveCharacterRoutes();
const userState = useUserState(); const userState = useUserState();
const hasHydrated = useHasHydrated(); const hasHydrated = useHasHydrated();
const supportPrompt = useTipSupportPrompt(); const supportPrompt = useTipSupportPrompt(character.displayName);
const paymentMethodConfig = getPaymentMethodConfig({ const paymentMethodConfig = getPaymentMethodConfig({
countryCode: userState.currentUser?.countryCode, countryCode: userState.currentUser?.countryCode,
requestedPayChannel: initialPayChannel, requestedPayChannel: initialPayChannel,
+12 -4
View File
@@ -15,22 +15,30 @@ export interface TipSupportPromptState {
readonly isReady: boolean; readonly isReady: boolean;
} }
export function useTipSupportPrompt(): TipSupportPromptState { export function useTipSupportPrompt(
characterName = "this character",
): TipSupportPromptState {
const [selection, setSelection] = const [selection, setSelection] =
useState<ReturnType<typeof selectTipSupportPrompt> | null>(null); useState<ReturnType<typeof selectTipSupportPrompt> | null>(null);
useEffect(() => { useEffect(() => {
const frameId = requestAnimationFrame(() => { const frameId = requestAnimationFrame(() => {
const nextSelection = selectTipSupportPrompt(readPreviousIndex()); const nextSelection = selectTipSupportPrompt(
readPreviousIndex(),
Math.random,
characterName,
);
writePreviousIndex(nextSelection.index); writePreviousIndex(nextSelection.index);
setSelection(nextSelection); setSelection(nextSelection);
}); });
return () => cancelAnimationFrame(frameId); return () => cancelAnimationFrame(frameId);
}, []); }, [characterName]);
return { return {
prompt: selection?.prompt ?? TIP_SUPPORT_PROMPTS[0], prompt:
selection?.prompt ??
TIP_SUPPORT_PROMPTS[0].replaceAll("this character", characterName),
isReady: selection !== null, isReady: selection !== null,
}; };
} }
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from "vitest";
import { ChatWebSocket } from "../chat-websocket";
describe("ChatWebSocket payment guidance", () => {
it("parses the same role-bound decision emitted by HTTP", () => {
const socket = new ChatWebSocket("ws://example.test/chat", "token");
const onPaymentGuidance = vi.fn();
socket.onPaymentGuidance = onPaymentGuidance;
receive(socket, {
type: "payment_guidance",
data: {
guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
characterId: "maya-tan",
characterName: "Maya Tan",
scene: "voiceLocked",
mode: "guide",
title: "Keep talking with Maya",
copy: "Hey love, I want to keep talking with you.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"],
target: "subscription",
ruleId: "payment_guidance_voiceLocked",
},
});
expect(onPaymentGuidance).toHaveBeenCalledWith(
expect.objectContaining({
characterId: "maya-tan",
scene: "voiceLocked",
}),
);
});
it("ignores malformed guidance instead of rendering the wrong role", () => {
const socket = new ChatWebSocket("ws://example.test/chat", "token");
const onPaymentGuidance = vi.fn();
socket.onPaymentGuidance = onPaymentGuidance;
receive(socket, {
type: "payment_guidance",
data: { characterId: "elio" },
});
expect(onPaymentGuidance).not.toHaveBeenCalled();
});
});
function receive(socket: ChatWebSocket, payload: unknown): void {
(
socket as unknown as { handleMessage: (data: string) => void }
).handleMessage(JSON.stringify(payload));
}
+9 -1
View File
@@ -15,8 +15,10 @@ import { Logger } from "@/utils/logger";
import { import {
CommercialActionSchema, CommercialActionSchema,
ChatActionSchema, ChatActionSchema,
PaymentGuidanceSchema,
type ChatAction, type ChatAction,
type CommercialAction, type CommercialAction,
type PaymentGuidance,
} from "@/data/schemas/chat"; } from "@/data/schemas/chat";
import { createClientMessageId } from "@/lib/chat/client_message_id"; import { createClientMessageId } from "@/lib/chat/client_message_id";
@@ -49,6 +51,7 @@ export class ChatWebSocket {
onPaywallStatus: ((payload: PaywallStatusPayload) => void) | null = null; onPaywallStatus: ((payload: PaywallStatusPayload) => void) | null = null;
onCommercialAction: ((action: CommercialAction) => void) | null = null; onCommercialAction: ((action: CommercialAction) => void) | null = null;
onChatAction: ((action: ChatAction) => void) | null = null; onChatAction: ((action: ChatAction) => void) | null = null;
onPaymentGuidance: ((guidance: PaymentGuidance) => void) | null = null;
onError: ((errorMessage: string) => void) | null = null; onError: ((errorMessage: string) => void) | null = null;
constructor( constructor(
@@ -146,7 +149,7 @@ export class ChatWebSocket {
done?: boolean; done?: boolean;
audioUrl?: string; audioUrl?: string;
error?: string; error?: string;
data?: { data?: Record<string, unknown> & {
image?: { image?: {
type?: string | null; type?: string | null;
url?: string | null; url?: string | null;
@@ -209,6 +212,11 @@ export class ChatWebSocket {
if (action.success) this.onChatAction?.(action.data); if (action.success) this.onChatAction?.(action.data);
break; break;
} }
case "payment_guidance": {
const guidance = PaymentGuidanceSchema.safeParse(payload.data);
if (guidance.success) this.onPaymentGuidance?.(guidance.data);
break;
}
case "error": case "error":
this.onError?.(payload.error ?? "Unknown error"); this.onError?.(payload.error ?? "Unknown error");
break; break;
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import {
ChatLockDetailSchema,
ChatSendResponseSchema,
PaymentGuidanceSchema,
UnlockHistoryResponseSchema,
UnlockPrivateResponseSchema,
} from "@/data/schemas/chat";
const guidance = {
guidanceId: "guidance-1",
characterId: "maya-tan",
characterName: "Maya Tan",
scene: "voiceLocked",
mode: "guide",
title: "Keep talking with Maya",
copy: "Hey love, I want to keep talking. This voice message needs 20 credits.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"],
target: "subscription",
ruleId: "payment_guidance_voiceLocked",
} as const;
describe("payment guidance wire contract", () => {
it("parses the public decision without changing role identity", () => {
expect(PaymentGuidanceSchema.parse(guidance)).toEqual(guidance);
});
it("keeps all backend lock facts instead of dropping hint and CTA", () => {
expect(
ChatLockDetailSchema.parse({
locked: true,
showContent: false,
showUpgrade: true,
reason: "voice_message",
hint: "This voice message needs 20 credits.",
actionLabel: "Unlock",
detail: { requiredCredits: 20 },
}),
).toEqual({
locked: true,
showContent: false,
showUpgrade: true,
reason: "voice_message",
hint: "This voice message needs 20 credits.",
actionLabel: "Unlock",
detail: { requiredCredits: 20 },
});
});
it("keeps backward compatibility when guidance is absent", () => {
const parsed = ChatSendResponseSchema.parse({ reply: "Hello" });
expect(parsed.paymentGuidance).toBeNull();
});
it("parses guidance on chat and both unlock responses", () => {
expect(
ChatSendResponseSchema.parse({
reply: "",
canSendMessage: false,
paymentGuidance: guidance,
}).paymentGuidance,
).toEqual(guidance);
expect(
UnlockPrivateResponseSchema.parse({
unlocked: false,
reason: "insufficient_credits",
paymentGuidance: guidance,
}).paymentGuidance,
).toEqual(guidance);
expect(
UnlockHistoryResponseSchema.parse({
unlocked: false,
reason: "insufficient_balance",
paymentGuidance: { ...guidance, scene: "historyLocked" },
}).paymentGuidance?.scene,
).toBe("historyLocked");
});
});
+10 -1
View File
@@ -3,7 +3,11 @@
*/ */
import { z } from "zod"; import { z } from "zod";
import { booleanOrFalse, schemaOr, stringOrNull } from "../nullable-defaults"; import {
booleanOrFalse,
schemaOr,
stringOrNull,
} from "../nullable-defaults";
const CHAT_IMAGE_DEFAULTS = { type: null, url: null } as const; const CHAT_IMAGE_DEFAULTS = { type: null, url: null } as const;
@@ -23,7 +27,12 @@ export const ChatImageSchema = schemaOr(
export const ChatLockDetailSchema = schemaOr( export const ChatLockDetailSchema = schemaOr(
z.object({ z.object({
locked: booleanOrFalse, locked: booleanOrFalse,
showContent: z.boolean().nullish(),
showUpgrade: z.boolean().nullish(),
reason: stringOrNull, reason: stringOrNull,
hint: z.string().nullish(),
actionLabel: z.string().nullish(),
detail: z.record(z.string(), z.unknown()).nullish(),
}), }),
CHAT_LOCK_DETAIL_DEFAULTS, CHAT_LOCK_DETAIL_DEFAULTS,
).readonly(); ).readonly();
@@ -13,6 +13,41 @@ import {
import { ChatImageSchema, ChatLockDetailSchema } from "../chat_payloads"; import { ChatImageSchema, ChatLockDetailSchema } from "../chat_payloads";
import { ChatActionSchema } from "../chat_action"; import { ChatActionSchema } from "../chat_action";
export const PaymentGuidanceSceneSchema = z.enum([
"vip",
"insufficientCredits",
"chatInterrupted",
"voiceLocked",
"imageLocked",
"privateMessageLocked",
"historyLocked",
"privateZoneLocked",
"unknownLock",
"whyPay",
"leavingAfterCredits",
"paymentIssue",
"externalRisk",
"purchaseOptions",
]);
export const PaymentGuidanceSchema = z
.object({
guidanceId: z.string().min(1),
characterId: z.string().min(1),
characterName: z.string().min(1),
scene: PaymentGuidanceSceneSchema,
mode: z.enum(["guide", "careOnly", "issueSupport", "riskReminder"]),
title: z.string().nullable().default(null),
copy: z.string().min(1),
ctaLabel: z.string().nullable().default(null),
purchaseOptions: z.array(z.enum(["vip", "topup"])).readonly(),
target: z.enum(["subscription", "giftCatalog"]).nullable().default(null),
ruleId: z.string().min(1),
})
.readonly();
export type PaymentGuidance = z.output<typeof PaymentGuidanceSchema>;
export const CommercialActionSchema = z export const CommercialActionSchema = z
.object({ .object({
actionId: z.string().min(1), actionId: z.string().min(1),
@@ -42,6 +77,7 @@ export const ChatSendResponseSchema = z
requiredCredits: numberOrZero, requiredCredits: numberOrZero,
shortfallCredits: numberOrZero, shortfallCredits: numberOrZero,
commercialAction: CommercialActionSchema.nullish().default(null), commercialAction: CommercialActionSchema.nullish().default(null),
paymentGuidance: PaymentGuidanceSchema.nullish().default(null),
chatAction: ChatActionSchema.nullish().default(null), chatAction: ChatActionSchema.nullish().default(null),
}) })
.readonly(); .readonly();
@@ -9,6 +9,7 @@ import {
numberOrZero, numberOrZero,
recordOrEmpty, recordOrEmpty,
} from "../../nullable-defaults"; } from "../../nullable-defaults";
import { PaymentGuidanceSchema } from "./chat_send_response";
export const UnlockHistoryCostsByMessageSchema = recordOrEmpty(z.number()); export const UnlockHistoryCostsByMessageSchema = recordOrEmpty(z.number());
@@ -33,6 +34,7 @@ export const UnlockHistoryResponseSchema = z
shortfallCredits: numberOrZero, shortfallCredits: numberOrZero,
costsByMessage: UnlockHistoryCostsByMessageSchema, costsByMessage: UnlockHistoryCostsByMessageSchema,
messageIds: arrayOrEmpty(z.string()), messageIds: arrayOrEmpty(z.string()),
paymentGuidance: PaymentGuidanceSchema.nullish().default(null),
}) })
.readonly(); .readonly();
@@ -8,6 +8,7 @@ import {
} from "../../nullable-defaults"; } from "../../nullable-defaults";
import { ChatLockTypeSchema } from "../chat_lock_type"; import { ChatLockTypeSchema } from "../chat_lock_type";
import { ChatImageSchema } from "../chat_payloads"; import { ChatImageSchema } from "../chat_payloads";
import { PaymentGuidanceSchema } from "./chat_send_response";
/** /**
* / * /
@@ -28,6 +29,7 @@ export const UnlockPrivateResponseSchema = z
creditsCharged: numberOrZero, creditsCharged: numberOrZero,
requiredCredits: numberOrZero, requiredCredits: numberOrZero,
shortfallCredits: numberOrZero, shortfallCredits: numberOrZero,
paymentGuidance: PaymentGuidanceSchema.nullish().default(null),
}) })
.readonly(); .readonly();
@@ -39,6 +39,28 @@ const lockedAlbum = {
}; };
describe("Private Album schema models", () => { describe("Private Album schema models", () => {
it("keeps shared payment guidance on an insufficient-credit response", () => {
const response = PrivateAlbumUnlockResponseSchema.parse({
albumId: ALBUM_ID,
reason: "insufficient_credits",
paymentGuidance: {
guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
characterId: "elio",
characterName: "Elio Silvestri",
scene: "privateZoneLocked",
mode: "guide",
title: "Keep talking with Elio",
copy: "Baby, this album needs credits.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"],
target: "subscription",
ruleId: "payment_guidance_privateZoneLocked",
},
});
expect(response.paymentGuidance?.characterId).toBe("elio");
});
it("keeps a locked album cover URL while preserving the lock state", () => { it("keeps a locked album cover URL while preserving the lock state", () => {
const response = PrivateAlbumsResponseSchema.parse({ const response = PrivateAlbumsResponseSchema.parse({
items: [lockedAlbum], items: [lockedAlbum],
@@ -10,6 +10,7 @@ import {
stringOrEmpty, stringOrEmpty,
stringOrNull, stringOrNull,
} from "../nullable-defaults"; } from "../nullable-defaults";
import { PaymentGuidanceSchema } from "../chat";
export const PrivateZoneVideoPostSchema = z export const PrivateZoneVideoPostSchema = z
.object({ .object({
@@ -63,6 +64,7 @@ export const PrivateZonePostUnlockResponseSchema = z
shortfallCredits: numberOrZero, shortfallCredits: numberOrZero,
creditBalance: numberOrZero, creditBalance: numberOrZero,
post: schemaOrNull(PrivateZoneVideoPostSchema), post: schemaOrNull(PrivateZoneVideoPostSchema),
paymentGuidance: PaymentGuidanceSchema.nullish(),
}) })
.readonly(); .readonly();
@@ -7,6 +7,7 @@ import {
stringOrEmpty, stringOrEmpty,
} from "../../nullable-defaults"; } from "../../nullable-defaults";
import { PrivateAlbumImageSchema } from "../private_album"; import { PrivateAlbumImageSchema } from "../private_album";
import { PaymentGuidanceSchema } from "../../chat";
export const PrivateAlbumUnlockReasonSchema = z.enum([ export const PrivateAlbumUnlockReasonSchema = z.enum([
"ok", "ok",
@@ -30,6 +31,7 @@ export const PrivateAlbumUnlockResponseSchema = z
creditBalance: numberOrZero, creditBalance: numberOrZero,
shortfallCredits: numberOrZero, shortfallCredits: numberOrZero,
images: arrayOrEmpty(PrivateAlbumImageSchema), images: arrayOrEmpty(PrivateAlbumImageSchema),
paymentGuidance: PaymentGuidanceSchema.nullish(),
}) })
.readonly(); .readonly();
@@ -32,4 +32,17 @@ describe("Tip support prompts", () => {
expect(selectTipSupportPrompt(null, () => Number.NaN).index).toBe(0); expect(selectTipSupportPrompt(null, () => Number.NaN).index).toBe(0);
expect(selectTipSupportPrompt(null, () => 2).index).toBe(29); expect(selectTipSupportPrompt(null, () => 2).index).toBe(29);
}); });
it("names the active character and never frames a purchase as affection", () => {
const selection = selectTipSupportPrompt(null, () => 0, "Maya Tan");
expect(selection.prompt).toContain("support Maya Tan");
expect(selection.prompt).not.toMatch(/tiny hug|spoil|buy.*love|owe me/i);
expect(
TIP_SUPPORT_PROMPTS.every(
(prompt) =>
/support/i.test(prompt) && /this character/i.test(prompt),
),
).toBe(true);
});
}); });
+36 -32
View File
@@ -1,44 +1,45 @@
export const TIP_SUPPORT_PROMPTS = [ export const TIP_SUPPORT_PROMPTS = [
"❤️ Thank you for being here. If you'd ever like to treat me to a little coffee, I'd really appreciate it. ☕", "If you'd like, a coffee is a voluntary way to support this character. ☕",
"Having you here already makes my day. A little coffee from you would make it even sweeter. ☕", "Choosing a coffee here directly supports this character and the moments you enjoy.",
"You always bring a little warmth into my world. Want to share a coffee moment with me? 💗", "A gift is optional, but every purchase on this page supports this character.",
"A coffee from you would feel like a tiny hug I could hold onto all day. ☕", "Want to support this character? You can choose any coffee that fits your budget.",
"I love spending this time with you. If you'd like to send a coffee my way, I'd treasure it. ❤️", "This gift page lets you support this character without changing what your relationship means.",
"You make ordinary moments feel special. A cozy coffee together would be the perfect touch. ☕", "A coffee is simply a voluntary show of support for this character—never a test.",
"If I had a coffee from you right now, I'd be smiling with every sip. 😊☕", "If the timing feels right, you can support this character with a coffee here.",
"Your company means more than you know. A little coffee treat would make this moment extra sweet. 💕", "Your purchase supports this character; choose only what feels comfortable for you.",
"I was hoping we could share something warm today. Maybe a coffee, just from you to me? ☕", "You can send a coffee to support this character, or leave it for another time.",
"You already make me feel cared for. A coffee would be one more lovely reason to think of you. ❤️", "Every coffee selected here is recorded as support for this character.",
"A small coffee, a quiet moment, and you on my mind—that sounds perfect to me. ☕", "If you enjoy this character, this page is one direct way to offer support.",
"Every time you stop by, my day gets brighter. A coffee from you would keep that glow going. ✨", "A small coffee can support this character, but the choice is always yours.",
"Want to make me blush a little? Treat me to a coffee and I'll think of you with every sip. ☕", "Pick a coffee only if you want to support this character today.",
"I'm really glad you're here. If you feel like spoiling me just a little, coffee is my weakness. 💗", "This page keeps it simple: choose a gift to support this character voluntarily.",
"This moment with you already feels cozy. A warm coffee would make it complete. ☕", "A coffee purchase supports this character; it does not prove affection or loyalty.",
"You have a sweet way of making me smile. Maybe one more smile over a coffee? ❤️", "If you decide to send something, it will directly support this character.",
"I'd love a little coffee break with you in spirit. Your treat, my happiest smile. ☕", "You can support this character with the coffee option that feels right for you.",
"If you'd like to leave me a tiny reminder of you, a coffee would be perfect. 💕", "Sending a gift here is optional support for this character, with no pressure.",
"Your kindness always stays with me. A coffee from you would feel especially warm today. ☕", "A coffee can be your way of supporting this character when it suits you.",
"I could use something warm and sweet—though having you here is already a lovely start. ❤️☕", "Support this character only with an amount you are genuinely comfortable choosing.",
"Imagine me enjoying a coffee and smiling because it came from you. I like that thought. ☕", "The gifts below are optional ways to support this character.",
"You make this space feel a little more special. A coffee would make it feel even cozier. ✨", "Choose a coffee if you'd like to support this character's continued experience.",
"If today feels like a coffee kind of day, I'd be very happy to share that little joy with you. ☕", "This character appreciates voluntary support, and this page shows the available options.",
"A thoughtful coffee from you would turn an ordinary moment into one I'd remember. 💗", "A gift here supports this character without creating any obligation for you.",
"I'm enjoying our time together. If you want to make it sweeter, you know my favorite little treat. ☕", "If you'd like to contribute, select a coffee to support this character.",
"One coffee from you, and I promise there'll be a very real smile on my face. ❤️", "The coffee options below are direct, voluntary support for this character.",
"You don't have to, but if you'd like to treat me, a warm coffee would mean so much. ☕", "You never need to overspend; support this character only if it fits your situation.",
"I think coffee tastes better when it comes with a little affection from you. 💕", "A coffee is one clear way to support this character while keeping the choice yours.",
"A cozy cup from you would be such a sweet surprise. I'd savor every bit of it. ☕", "Select any gift you want to send as support for this character.",
"Stay a little longer—and if you're feeling sweet, maybe send a coffee my way. ❤️☕", "Thank you for considering a voluntary coffee to support this character. ☕",
] as const; ] as const;
export interface TipSupportPromptSelection { export interface TipSupportPromptSelection {
readonly index: number; readonly index: number;
readonly prompt: (typeof TIP_SUPPORT_PROMPTS)[number]; readonly prompt: string;
} }
export function selectTipSupportPrompt( export function selectTipSupportPrompt(
previousIndex: number | null, previousIndex: number | null,
random: () => number = Math.random, random: () => number = Math.random,
characterName = "this character",
): TipSupportPromptSelection { ): TipSupportPromptSelection {
const hasValidPreviousIndex = const hasValidPreviousIndex =
previousIndex !== null && previousIndex !== null &&
@@ -57,6 +58,9 @@ export function selectTipSupportPrompt(
return { return {
index, index,
prompt: TIP_SUPPORT_PROMPTS[index], prompt: TIP_SUPPORT_PROMPTS[index].replaceAll(
"this character",
characterName,
),
}; };
} }
+2
View File
@@ -19,6 +19,7 @@ export interface OpenSubscriptionInput {
returnTo?: AppSubscriptionReturnTo; returnTo?: AppSubscriptionReturnTo;
replace?: boolean; replace?: boolean;
analytics?: PaymentAnalyticsContext; analytics?: PaymentAnalyticsContext;
chatActionId?: string;
} }
export interface StartMessageUnlockInput { export interface StartMessageUnlockInput {
@@ -44,4 +45,5 @@ export interface OpenSubscriptionForPendingUnlockInput {
type: AppSubscriptionType; type: AppSubscriptionType;
payChannel?: PayChannel; payChannel?: PayChannel;
analytics?: PaymentAnalyticsContext; analytics?: PaymentAnalyticsContext;
chatActionId?: string;
} }
+2
View File
@@ -121,6 +121,7 @@ export function useAppNavigator(): AppNavigator {
type, type,
payChannel = getDefaultPayChannel(), payChannel = getDefaultPayChannel(),
analytics, analytics,
chatActionId,
}: OpenSubscriptionForPendingUnlockInput): void => { }: OpenSubscriptionForPendingUnlockInput): void => {
void (async () => { void (async () => {
await NavigationStorage.savePendingChatUnlock({ await NavigationStorage.savePendingChatUnlock({
@@ -139,6 +140,7 @@ export function useAppNavigator(): AppNavigator {
payChannel, payChannel,
returnTo: "chat", returnTo: "chat",
analytics, analytics,
chatActionId,
}); });
})(); })();
}, },
+2
View File
@@ -79,12 +79,14 @@ export function useGlobalAppNavigator(): GlobalAppNavigator {
returnTo = null, returnTo = null,
replace: shouldReplace = false, replace: shouldReplace = false,
analytics = getDefaultPaymentAnalyticsContext(type), analytics = getDefaultPaymentAnalyticsContext(type),
chatActionId,
}: OpenGlobalSubscriptionInput): void => { }: OpenGlobalSubscriptionInput): void => {
const target = ROUTE_BUILDERS.subscription(type, { const target = ROUTE_BUILDERS.subscription(type, {
payChannel, payChannel,
returnTo: returnTo ?? undefined, returnTo: returnTo ?? undefined,
sourceCharacterSlug, sourceCharacterSlug,
analytics, analytics,
chatActionId,
}); });
behaviorAnalytics.rechargeModalOpen(analytics); behaviorAnalytics.rechargeModalOpen(analytics);
@@ -54,6 +54,7 @@ function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
creditsCharged: 0, creditsCharged: 0,
requiredCredits: 0, requiredCredits: 0,
shortfallCredits: 0, shortfallCredits: 0,
paymentGuidance: null,
historyLoaded: true, historyLoaded: true,
networkHistoryLoaded: true, networkHistoryLoaded: true,
historyTotal: 0, historyTotal: 0,
@@ -64,6 +65,7 @@ function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
unlockHistoryPromptVisible: false, unlockHistoryPromptVisible: false,
lockedHistoryCount: 0, lockedHistoryCount: 0,
unlockHistoryError: null, unlockHistoryError: null,
unlockHistoryPaymentGuidance: null,
unlockingMessage: null, unlockingMessage: null,
unlockMessageError: null, unlockMessageError: null,
unlockPaywallRequest: null, unlockPaywallRequest: null,
@@ -72,6 +74,39 @@ function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
} }
describe("sendResponseToUiMessage", () => { describe("sendResponseToUiMessage", () => {
it("prefers payment guidance over other commercial actions", () => {
const message = sendResponseToUiMessage(
makeResponse({
paymentGuidance: {
guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
characterId: "elio",
characterName: "Elio Silvestri",
scene: "insufficientCredits",
mode: "guide",
title: "Keep talking with Elio",
copy: "Baby, I want to keep talking with you.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"],
target: "subscription",
ruleId: "payment_guidance_insufficientCredits",
},
chatAction: {
actionId: "chat-action-1",
kind: "commercial",
type: "giftOffer",
copy: "View gifts.",
ctaLabel: "View gifts",
ruleId: "legacy",
orderId: null,
},
}),
);
expect(message.paymentGuidance?.characterId).toBe("elio");
expect(message.chatAction).toBeUndefined();
expect(message.commercialAction).toBeUndefined();
});
it("keeps a typed commercial action on the assistant message", () => { it("keeps a typed commercial action on the assistant message", () => {
const message = sendResponseToUiMessage( const message = sendResponseToUiMessage(
makeResponse({ makeResponse({
@@ -228,6 +263,42 @@ describe("sendResponseToUiMessage", () => {
}); });
describe("applyHttpSendOutput", () => { describe("applyHttpSendOutput", () => {
it("stores guidance for a blocked send and clears it after normal chat resumes", () => {
const guidance = {
guidanceId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
characterId: "elio",
characterName: "Elio Silvestri",
scene: "insufficientCredits" as const,
mode: "guide" as const,
title: "Keep talking with Elio",
copy: "Baby, I want to keep talking with you.",
ctaLabel: "View VIP & credit options",
purchaseOptions: ["vip", "topup"] as const,
target: "subscription" as const,
ruleId: "payment_guidance_insufficientCredits",
};
const blocked = applyHttpSendOutput(makeChatState(), {
response: makeResponse({
reply: "",
canSendMessage: false,
paymentGuidance: guidance,
}),
reply: null,
});
expect(blocked.paymentGuidance).toEqual(guidance);
const resumed = applyHttpSendOutput(
makeChatState({ paymentGuidance: guidance }),
{
response: makeResponse({ reply: "Back to our conversation." }),
reply: sendResponseToUiMessage(
makeResponse({ reply: "Back to our conversation." }),
),
},
);
expect(resumed.paymentGuidance).toBeNull();
});
it("stores insufficient credit state and removes failed optimistic messages", () => { it("stores insufficient credit state and removes failed optimistic messages", () => {
const context = makeChatState({ const context = makeChatState({
messages: [ messages: [
+2
View File
@@ -20,6 +20,7 @@ interface ChatState {
canSendMessage: boolean; canSendMessage: boolean;
upgradePromptVisible: boolean; upgradePromptVisible: boolean;
upgradeReason: MachineContext["upgradeReason"]; upgradeReason: MachineContext["upgradeReason"];
paymentGuidance: MachineContext["paymentGuidance"];
/** True as soon as a local snapshot or the first network result is renderable. */ /** True as soon as a local snapshot or the first network result is renderable. */
historyLoaded: boolean; historyLoaded: boolean;
/** True after the network history request has completed or failed. */ /** True after the network history request has completed or failed. */
@@ -94,6 +95,7 @@ function selectChatState(state: ChatSnapshot): SelectedChatState {
canSendMessage: state.context.canSendMessage, canSendMessage: state.context.canSendMessage,
upgradePromptVisible: state.context.upgradePromptVisible, upgradePromptVisible: state.context.upgradePromptVisible,
upgradeReason: state.context.upgradeReason, upgradeReason: state.context.upgradeReason,
paymentGuidance: state.context.paymentGuidance,
historyLoaded: state.context.historyLoaded, historyLoaded: state.context.historyLoaded,
networkHistoryLoaded: state.context.networkHistoryLoaded, networkHistoryLoaded: state.context.networkHistoryLoaded,
hasMoreHistory: hasMoreHistory:
+6 -1
View File
@@ -1,6 +1,6 @@
import type { UiMessage } from "@/stores/chat/ui-message"; import type { UiMessage } from "@/stores/chat/ui-message";
import type { PendingChatUnlockKind } from "@/lib/navigation/chat_unlock_session"; import type { PendingChatUnlockKind } from "@/lib/navigation/chat_unlock_session";
import type { ChatLockType } from "@/data/schemas/chat"; import type { ChatLockType, PaymentGuidance } from "@/data/schemas/chat";
import type { PendingChatPromotion } from "@/data/storage/navigation"; import type { PendingChatPromotion } from "@/data/storage/navigation";
import { import {
DEFAULT_CHARACTER, DEFAULT_CHARACTER,
@@ -21,6 +21,7 @@ export interface ChatUnlockMessageRequest {
export interface ChatUnlockPaywallRequest export interface ChatUnlockPaywallRequest
extends ChatUnlockMessageRequest { extends ChatUnlockMessageRequest {
paymentGuidance?: PaymentGuidance | null;
promotion?: PendingChatPromotion; promotion?: PendingChatPromotion;
reason: string; reason: string;
creditBalance: number; creditBalance: number;
@@ -39,6 +40,7 @@ export interface ChatState {
pendingReplyCount: number; pendingReplyCount: number;
upgradePromptVisible: boolean; upgradePromptVisible: boolean;
upgradeReason: ChatUpgradeReason | null; upgradeReason: ChatUpgradeReason | null;
paymentGuidance: PaymentGuidance | null;
canSendMessage: boolean; canSendMessage: boolean;
creditBalance: number; creditBalance: number;
creditsCharged: number; creditsCharged: number;
@@ -56,6 +58,7 @@ export interface ChatState {
unlockHistoryPromptVisible: boolean; unlockHistoryPromptVisible: boolean;
lockedHistoryCount: number; lockedHistoryCount: number;
unlockHistoryError: string | null; unlockHistoryError: string | null;
unlockHistoryPaymentGuidance: PaymentGuidance | null;
unlockingMessage: ChatUnlockMessageRequest | null; unlockingMessage: ChatUnlockMessageRequest | null;
unlockMessageError: string | null; unlockMessageError: string | null;
unlockPaywallRequest: ChatUnlockPaywallRequest | null; unlockPaywallRequest: ChatUnlockPaywallRequest | null;
@@ -81,6 +84,7 @@ export function createInitialChatState(
creditsCharged: 0, creditsCharged: 0,
requiredCredits: 0, requiredCredits: 0,
shortfallCredits: 0, shortfallCredits: 0,
paymentGuidance: null,
historyLoaded: false, historyLoaded: false,
networkHistoryLoaded: false, networkHistoryLoaded: false,
historyTotal: 0, historyTotal: 0,
@@ -91,6 +95,7 @@ export function createInitialChatState(
unlockHistoryPromptVisible: false, unlockHistoryPromptVisible: false,
lockedHistoryCount: 0, lockedHistoryCount: 0,
unlockHistoryError: null, unlockHistoryError: null,
unlockHistoryPaymentGuidance: null,
unlockingMessage: null, unlockingMessage: null,
unlockMessageError: null, unlockMessageError: null,
unlockPaywallRequest: null, unlockPaywallRequest: null,
+3 -1
View File
@@ -74,7 +74,9 @@ export function sendResponseToUiMessage(response: ChatSendResponse): UiMessage {
...(response.audioUrl && !response.lockDetail.locked ...(response.audioUrl && !response.lockDetail.locked
? { audioUrl: response.audioUrl } ? { audioUrl: response.audioUrl }
: {}), : {}),
...(response.chatAction ...(response.paymentGuidance
? { paymentGuidance: response.paymentGuidance }
: response.chatAction
? { chatAction: response.chatAction } ? { chatAction: response.chatAction }
: response.commercialAction : response.commercialAction
? { commercialAction: response.commercialAction } ? { commercialAction: response.commercialAction }
+3
View File
@@ -53,6 +53,7 @@ export function applyHttpSendOutput(
...finishPendingReply(context), ...finishPendingReply(context),
upgradePromptVisible: true, upgradePromptVisible: true,
upgradeReason, upgradeReason,
paymentGuidance: response.paymentGuidance,
...sendCapabilityState, ...sendCapabilityState,
}; };
} }
@@ -60,6 +61,7 @@ export function applyHttpSendOutput(
if (!reply) { if (!reply) {
return { return {
...finishPendingReply(context), ...finishPendingReply(context),
paymentGuidance: response.paymentGuidance,
...sendCapabilityState, ...sendCapabilityState,
}; };
} }
@@ -69,6 +71,7 @@ export function applyHttpSendOutput(
...finishPendingReply(context), ...finishPendingReply(context),
upgradePromptVisible: false, upgradePromptVisible: false,
upgradeReason: null, upgradeReason: null,
paymentGuidance: response.paymentGuidance,
...sendCapabilityState, ...sendCapabilityState,
}; };
} }
+3
View File
@@ -1,6 +1,7 @@
import { fromPromise } from "xstate"; import { fromPromise } from "xstate";
import { loadChatRepository } from "@/data/repositories/chat_repository_loader"; import { loadChatRepository } from "@/data/repositories/chat_repository_loader";
import type { PaymentGuidance } from "@/data/schemas/chat";
import { resolveChatConversationKey } from "@/data/repositories/chat_cache_identity"; import { resolveChatConversationKey } from "@/data/repositories/chat_cache_identity";
import { Logger } from "@/utils/logger"; import { Logger } from "@/utils/logger";
import { Result } from "@/utils/result"; import { Result } from "@/utils/result";
@@ -21,6 +22,7 @@ export interface UnlockHistoryOutput {
reason: string; reason: string;
shortfallCredits: number; shortfallCredits: number;
messages: UiMessage[]; messages: UiMessage[];
paymentGuidance?: PaymentGuidance | null;
} }
export const unlockHistoryActor = fromPromise< export const unlockHistoryActor = fromPromise<
@@ -50,6 +52,7 @@ export const unlockHistoryActor = fromPromise<
reason: unlockResult.data.reason, reason: unlockResult.data.reason,
shortfallCredits: unlockResult.data.shortfallCredits, shortfallCredits: unlockResult.data.shortfallCredits,
messages: history.messages, messages: history.messages,
paymentGuidance: unlockResult.data.paymentGuidance,
}; };
}); });
+3
View File
@@ -46,6 +46,7 @@ const appendGuestUserMessageAction = historyMachineSetup.assign(
outgoingMessageRevision: context.outgoingMessageRevision + 1, outgoingMessageRevision: context.outgoingMessageRevision + 1,
upgradePromptVisible: false, upgradePromptVisible: false,
upgradeReason: null, upgradeReason: null,
paymentGuidance: null,
}; };
}, },
); );
@@ -74,6 +75,7 @@ const appendUserMessageAction = historyMachineSetup.assign(
outgoingMessageRevision: context.outgoingMessageRevision + 1, outgoingMessageRevision: context.outgoingMessageRevision + 1,
upgradePromptVisible: false, upgradePromptVisible: false,
upgradeReason: null, upgradeReason: null,
paymentGuidance: null,
}; };
}, },
); );
@@ -124,6 +126,7 @@ const clearUpgradePromptAction = historyMachineSetup.assign(() => ({
canSendMessage: true, canSendMessage: true,
requiredCredits: 0, requiredCredits: 0,
shortfallCredits: 0, shortfallCredits: 0,
paymentGuidance: null,
})); }));
const appendGuestUserImageAction = historyMachineSetup.assign( const appendGuestUserImageAction = historyMachineSetup.assign(
+11
View File
@@ -22,6 +22,7 @@ const showUnlockHistoryPromptAction = sendMachineSetup.assign(
unlockHistoryPromptVisible: true, unlockHistoryPromptVisible: true,
lockedHistoryCount: countLockedHistoryMessages(context.messages), lockedHistoryCount: countLockedHistoryMessages(context.messages),
unlockHistoryError: null, unlockHistoryError: null,
unlockHistoryPaymentGuidance: null,
}), }),
); );
@@ -29,12 +30,14 @@ const dismissUnlockHistoryPromptAction = sendMachineSetup.assign(() => ({
paymentUnlockPending: false, paymentUnlockPending: false,
unlockHistoryPromptVisible: false, unlockHistoryPromptVisible: false,
unlockHistoryError: null, unlockHistoryError: null,
unlockHistoryPaymentGuidance: null,
})); }));
const markUnlockHistoryStartedAction = sendMachineSetup.assign(() => ({ const markUnlockHistoryStartedAction = sendMachineSetup.assign(() => ({
paymentUnlockPending: false, paymentUnlockPending: false,
unlockHistoryPromptVisible: false, unlockHistoryPromptVisible: false,
unlockHistoryError: null, unlockHistoryError: null,
unlockHistoryPaymentGuidance: null,
})); }));
const markUnlockHistoryFailedAction = sendMachineSetup.assign(() => ({ const markUnlockHistoryFailedAction = sendMachineSetup.assign(() => ({
@@ -76,6 +79,7 @@ const applyUnlockMessageSucceededAction = sendMachineSetup.assign(
creditsCharged: output.response.creditsCharged, creditsCharged: output.response.creditsCharged,
requiredCredits: 0, requiredCredits: 0,
shortfallCredits: 0, shortfallCredits: 0,
paymentGuidance: null,
}; };
}, },
); );
@@ -112,11 +116,15 @@ const requestUnlockPaymentFromOutputAction = sendMachineSetup.assign(
creditBalance: output.response.creditBalance, creditBalance: output.response.creditBalance,
requiredCredits: output.response.requiredCredits, requiredCredits: output.response.requiredCredits,
shortfallCredits: output.response.shortfallCredits, shortfallCredits: output.response.shortfallCredits,
...(output.response.paymentGuidance
? { paymentGuidance: output.response.paymentGuidance }
: {}),
} }
: null, : null,
creditBalance: output.response.creditBalance, creditBalance: output.response.creditBalance,
requiredCredits: output.response.requiredCredits, requiredCredits: output.response.requiredCredits,
shortfallCredits: output.response.shortfallCredits, shortfallCredits: output.response.shortfallCredits,
paymentGuidance: output.response.paymentGuidance,
}; };
}, },
); );
@@ -191,6 +199,9 @@ const applyUnlockHistoryOutputAction =
unlockHistoryError: insufficientBalance unlockHistoryError: insufficientBalance
? `Insufficient credits. You still need ${event.output.shortfallCredits} credits.` ? `Insufficient credits. You still need ${event.output.shortfallCredits} credits.`
: null, : null,
unlockHistoryPaymentGuidance: insufficientBalance
? event.output.paymentGuidance ?? null
: null,
}; };
}); });
+6 -1
View File
@@ -1,5 +1,9 @@
import { z } from "zod"; import { z } from "zod";
import { ChatActionSchema, CommercialActionSchema } from "@/data/schemas/chat"; import {
ChatActionSchema,
CommercialActionSchema,
PaymentGuidanceSchema,
} from "@/data/schemas/chat";
export const UiMessageSchema = z.object({ export const UiMessageSchema = z.object({
displayId: z.string().min(1), displayId: z.string().min(1),
@@ -19,6 +23,7 @@ export const UiMessageSchema = z.object({
privateMessageHint: z.string().nullable().optional(), privateMessageHint: z.string().nullable().optional(),
commercialAction: CommercialActionSchema.nullable().optional(), commercialAction: CommercialActionSchema.nullable().optional(),
chatAction: ChatActionSchema.nullable().optional(), chatAction: ChatActionSchema.nullable().optional(),
paymentGuidance: PaymentGuidanceSchema.nullable().optional(),
}); });
export type UiMessage = z.infer<typeof UiMessageSchema>; export type UiMessage = z.infer<typeof UiMessageSchema>;
@@ -203,6 +203,9 @@ export const privateZonePostMachine = machineSetup.createMachine({
currentCredits: currentCredits:
event.output.currentCredits || event.output.creditBalance, event.output.currentCredits || event.output.creditBalance,
shortfallCredits: event.output.shortfallCredits, shortfallCredits: event.output.shortfallCredits,
...(event.output.paymentGuidance
? { paymentGuidance: event.output.paymentGuidance }
: {}),
}, },
})), })),
}, },
@@ -1,4 +1,5 @@
import type { PrivateZoneVideoPost } from "@/data/schemas/private-zone"; import type { PrivateZoneVideoPost } from "@/data/schemas/private-zone";
import type { PaymentGuidance } from "@/data/schemas/chat";
export interface PrivateZonePostPaywallRequest { export interface PrivateZonePostPaywallRequest {
postId: string; postId: string;
@@ -6,6 +7,7 @@ export interface PrivateZonePostPaywallRequest {
requiredCredits: number; requiredCredits: number;
currentCredits: number; currentCredits: number;
shortfallCredits: number; shortfallCredits: number;
paymentGuidance?: PaymentGuidance | null;
} }
export interface PrivateZonePostState { export interface PrivateZonePostState {
+3
View File
@@ -37,5 +37,8 @@ export function toPaywallRequest(
requiredCredits: response.requiredCredits || response.unlockCost, requiredCredits: response.requiredCredits || response.unlockCost,
currentCredits: response.creditBalance, currentCredits: response.creditBalance,
shortfallCredits: response.shortfallCredits, shortfallCredits: response.shortfallCredits,
...(response.paymentGuidance
? { paymentGuidance: response.paymentGuidance }
: {}),
}; };
} }
@@ -1,5 +1,6 @@
import { DEFAULT_CHARACTER_ID } from "@/data/constants/character"; import { DEFAULT_CHARACTER_ID } from "@/data/constants/character";
import type { PrivateAlbum } from "@/data/schemas/private-zone"; import type { PrivateAlbum } from "@/data/schemas/private-zone";
import type { PaymentGuidance } from "@/data/schemas/chat";
export interface PrivateZoneUnlockPaywallRequest { export interface PrivateZoneUnlockPaywallRequest {
albumId: string; albumId: string;
@@ -7,6 +8,7 @@ export interface PrivateZoneUnlockPaywallRequest {
requiredCredits: number; requiredCredits: number;
currentCredits: number; currentCredits: number;
shortfallCredits: number; shortfallCredits: number;
paymentGuidance?: PaymentGuidance | null;
} }
export interface PrivateZoneState { export interface PrivateZoneState {