Compare commits

...

11 Commits

Author SHA1 Message Date
Codex d01441b8c7 fix(ci): deploy frontend production as lzf
Docker Image / Build and Push Docker Image (push) Successful in 2m45s
2026-07-27 16:54:17 +08:00
Codex ddacd03601 test(release): align selected production e2e assertions 2026-07-27 16:40:52 +08:00
Codex 1b121a8ef8 test(chat): enforce locked image URL masking 2026-07-27 16:12:12 +08:00
Codex b7221f2f70 feat(subscription): separate selection from payment and add issue feedback
(cherry picked from commit fe9d31146b)
2026-07-27 16:12:12 +08:00
Codex 30f88d3a20 fix(external-entry): preserve legacy private room links 2026-07-27 16:11:24 +08:00
Codex 7b09a7f850 feat(chat): send idempotent client message ids 2026-07-27 16:11:24 +08:00
Codex 38a4645b9c feat(private-zone): add paid video moments 2026-07-27 16:11:24 +08:00
Codex 76bffc1a0d feat(chat): add support action cards and live entitlements 2026-07-27 16:11:23 +08:00
Codex 19b8fc51d6 feat(call): add streaming voice call experience 2026-07-27 16:11:23 +08:00
Codex 9fbf180df6 fix(ci): scope frontend image cleanup 2026-07-27 16:11:23 +08:00
Codex 6721b6eb43 feat(payment): support user-bound seven-discount offers 2026-07-27 16:11:22 +08:00
145 changed files with 5746 additions and 289 deletions
+13 -11
View File
@@ -152,12 +152,9 @@ jobs:
- name: Deploy image over SSH
env:
SSH_HOST: ${{ secrets.SSH_HOST }}
SSH_USER: ${{ secrets.SSH_USER }}
SSH_PORT: ${{ secrets.SSH_PORT }}
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
TEST_DEPLOY_DIR: ${{ secrets.TEST_DEPLOY_DIR }}
PROD_DEPLOY_DIR: ${{ secrets.PROD_DEPLOY_DIR }}
REGISTRY_HOST: ${{ secrets.REGISTRY_HOST }}
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
@@ -166,16 +163,18 @@ jobs:
case "$DEPLOY_ENV" in
test)
DEPLOY_DIR="${TEST_DEPLOY_DIR:-/opt/cozsweet-web-test}"
DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-test"
HOST_PORT="9135"
CONTAINER_NAME="cozsweet-web-test"
PROJECT_NAME="cozsweet-web-test"
SERVER_RETAIN_COUNT="1"
;;
prod)
DEPLOY_DIR="${PROD_DEPLOY_DIR:-/opt/cozsweet-web-prod}"
DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-prod"
HOST_PORT="9185"
CONTAINER_NAME="cozsweet-web-prod"
PROJECT_NAME="cozsweet-web-prod"
SERVER_RETAIN_COUNT="2"
;;
*)
echo "Unsupported deploy env: $DEPLOY_ENV" >&2
@@ -183,8 +182,11 @@ jobs:
;;
esac
DEPLOY_DIR="$DEPLOY_ROOT/current"
DEPLOY_SHARED_DIR="$DEPLOY_ROOT/shared"
REMOTE_ENV_FILE="$DEPLOY_SHARED_DIR/$NEXT_ENV_FILE"
DEPLOY_HOST="$SSH_HOST"
DEPLOY_USER="$SSH_USER"
DEPLOY_USER="lzf"
DEPLOY_PORT="${SSH_PORT:-22}"
DEPLOY_KEY="$SSH_PRIVATE_KEY"
DEPLOY_KNOWN_HOSTS="$SSH_KNOWN_HOSTS"
@@ -210,19 +212,19 @@ jobs:
SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o IdentitiesOnly=yes"
SCP_OPTS="-i $KEY_FILE -P $DEPLOY_PORT -o IdentitiesOnly=yes"
ssh $SSH_OPTS "$SSH_TARGET" "mkdir -p '$DEPLOY_DIR'"
ssh $SSH_OPTS "$SSH_TARGET" \
"mkdir -p '$DEPLOY_DIR' '$DEPLOY_SHARED_DIR' '$DEPLOY_ROOT/releases' '$DEPLOY_ROOT/backups' '$DEPLOY_ROOT/tmp' && chmod 700 '$DEPLOY_SHARED_DIR'"
scp $SCP_OPTS docker-compose.yml "$SSH_TARGET:$DEPLOY_DIR/docker-compose.yml"
scp $SCP_OPTS scripts/server/deploy-docker-image.sh "$SSH_TARGET:$DEPLOY_DIR/deploy-docker-image.sh"
scp $SCP_OPTS "$NEXT_ENV_FILE" "$SSH_TARGET:$DEPLOY_DIR/$NEXT_ENV_FILE"
scp $SCP_OPTS "$NEXT_ENV_FILE" "$SSH_TARGET:$REMOTE_ENV_FILE"
ssh $SSH_OPTS "$SSH_TARGET" "chmod 600 '$REMOTE_ENV_FILE'"
printf '%s' "$REGISTRY_PASSWORD" \
| ssh $SSH_OPTS "$SSH_TARGET" \
"docker login '$REGISTRY_HOST' -u '$REGISTRY_USERNAME' --password-stdin"
SERVER_RETAIN_COUNT="1"
ssh $SSH_OPTS "$SSH_TARGET" \
"cd '$DEPLOY_DIR' && chmod +x ./deploy-docker-image.sh && ./deploy-docker-image.sh '$IMAGE_VERSION_TAG' '$NEXT_ENV_FILE' '$HOST_PORT' '$CONTAINER_NAME' '$PROJECT_NAME' '$SERVER_RETAIN_COUNT'"
"cd '$DEPLOY_DIR' && chmod +x ./deploy-docker-image.sh && ./deploy-docker-image.sh '$IMAGE_VERSION_TAG' '$REMOTE_ENV_FILE' '$HOST_PORT' '$CONTAINER_NAME' '$PROJECT_NAME' '$SERVER_RETAIN_COUNT'"
- name: Purge Cloudflare cache
env:
+3 -1
View File
@@ -19,7 +19,7 @@ https://<APP_HOST>/external-entry?<参数>
| 参数 | 可选值或格式 | 用途 |
| --- | --- | --- |
| `target` | `chat``tip``private-zone` | 指定进入的页面;不传或值无效时进入聊天页。 |
| `target` | `chat``tip``private-zone` | 指定进入的页面;不传或值无效时进入聊天页。历史值 `private-room` 兼容进入 `private-zone`,新链接不得继续使用。 |
| `character` | `elio``maya``nayeli` | 指定角色;不传或值无效时使用 Elio。 |
| `psid` | string | 传入 Facebook Page-scoped User ID。 |
| `mode` | `promotion` | 开启聊天促销模式。 |
@@ -27,6 +27,8 @@ https://<APP_HOST>/external-entry?<参数>
`mode=promotion` 只有在 `target=chat` 且同时提供有效的 `promotion_type` 时生效。
标准私密空间参数是 `target=private-zone`。前端仅为已经发布的旧链接保留 `target=private-room` 兼容;`private_zone` 等其他拼写仍按无效目标处理并回退聊天页。
## PSID 与登录状态流程
PSID 保存、登录状态判断和 Facebook Identity 绑定逻辑见 [PSID 与登录状态流程图](./psid-login-flow.md)。
+56 -33
View File
@@ -1,43 +1,66 @@
# 外部入口链接清单
[返回外部入口接入说明](./README.md)
这份清单可以独立发送和直接点击。所有新链接统一使用标准参数 `target=private-zone`;历史参数 `target=private-room` 仅用于兼容已经发出的旧链接。
以下链接可以直接点击打开。PSID 示例统一使用 `27511427698460020`
## 使用规则
- `target=chat`:进入聊天页。
- `target=tip`:进入对应角色的打赏页。
- `target=private-zone`:进入对应角色的私密空间。
- `character` 可使用 `elio``maya``nayeli`;不传或值无效时使用 Elio。
- `mode=promotion` 只在 `target=chat``promotion_type``voice``image``private` 时生效。
- PSID 示例统一使用 `27511427698460020`;不要在入口中放登录 Token、Page Access Token 或 App Secret。
## 测试环境
| 入口 | 链接 |
| --- | --- |
| 普通聊天 | [打开普通聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat) |
| Maya 聊天 | [打开 Maya 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=maya) |
| Nayeli 聊天 | [打开 Nayeli 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=nayeli) |
| 携带 PSID 的聊天 | [打开 PSID 聊天示例](https://frontend-test.banlv-ai.com/external-entry?target=chat&psid=27511427698460020) |
| 语音促销 | [打开语音促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=voice) |
| 图片促销 | [打开图片促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=image) |
| 私密文本促销 | [打开私密文本促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=private) |
| 咖啡打赏 | [打开咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip) |
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=maya) |
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=nayeli) |
| 私密空间 | [打开私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone) |
| Maya 私密空间 | [打开 Maya 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=maya) |
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=nayeli) |
| 入口 | 可点击链接 | 预期落地页面 |
| --- | --- | --- |
| 普通聊天Elio | [打开普通聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat) | `/characters/elio/chat` |
| Maya 聊天 | [打开 Maya 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=maya) | `/characters/maya/chat` |
| Nayeli 聊天 | [打开 Nayeli 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=nayeli) | `/characters/nayeli/chat` |
| 携带 PSID 的 Elio 聊天 | [打开 PSID 聊天示例](https://frontend-test.banlv-ai.com/external-entry?target=chat&psid=27511427698460020) | `/characters/elio/chat` |
| 语音促销 | [打开语音促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=voice) | `/characters/elio/chat`,保存语音促销意图 |
| 图片促销 | [打开图片促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=image) | `/characters/elio/chat`,保存图片促销意图 |
| 私密文本促销 | [打开私密文本促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=private) | `/characters/elio/chat`,保存私密文本促销意图 |
| Elio 咖啡打赏 | [打开 Elio 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=elio) | `/characters/elio/tip` |
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=maya) | `/characters/maya/tip` |
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=nayeli) | `/characters/nayeli/tip` |
| Elio 私密空间 | [打开 Elio 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=elio) | `/characters/elio/private-zone` |
| Maya 私密空间 | [打开 Maya 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=maya) | `/characters/maya/private-zone` |
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=nayeli) | `/characters/nayeli/private-zone` |
## 旧链接兼容验证
以下链接仅用于验证已经发出的 `private-room` 旧链接仍能正确进入私密空间。新投放链接不要再使用这些地址。
| 旧入口 | 可点击链接 | 预期落地页面 |
| --- | --- | --- |
| Elio 旧私密空间 | [验证 Elio 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=elio) | `/characters/elio/private-zone` |
| Maya 旧私密空间 | [验证 Maya 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=maya) | `/characters/maya/private-zone` |
| Nayeli 旧私密空间 | [验证 Nayeli 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=nayeli) | `/characters/nayeli/private-zone` |
## 正式环境
| 入口 | 链接 |
| --- | --- |
| 普通聊天 | [打开普通聊天](https://cozsweet.com/external-entry?target=chat) |
| Maya 聊天 | [打开 Maya 聊天](https://cozsweet.com/external-entry?target=chat&character=maya) |
| Nayeli 聊天 | [打开 Nayeli 聊天](https://cozsweet.com/external-entry?target=chat&character=nayeli) |
| 携带 PSID 的聊天 | [打开 PSID 聊天示例](https://cozsweet.com/external-entry?target=chat&psid=27511427698460020) |
| 语音促销 | [打开语音促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=voice) |
| 图片促销 | [打开图片促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=image) |
| 私密文本促销 | [打开私密文本促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=private) |
| 咖啡打赏 | [打开咖啡打赏](https://cozsweet.com/external-entry?target=tip) |
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=maya) |
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=nayeli) |
| 私密空间 | [打开私密空间](https://cozsweet.com/external-entry?target=private-zone) |
| Maya 私密空间 | [打开 Maya 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=maya) |
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=nayeli) |
正式环境仅列标准链接,不再传播 `private-room` 旧参数。
如需在其他入口携带 PSID,在链接末尾追加 `&psid=27511427698460020`
| 入口 | 可点击链接 | 预期落地页面 |
| --- | --- | --- |
| 普通聊天(Elio | [打开普通聊天](https://cozsweet.com/external-entry?target=chat) | `/characters/elio/chat` |
| Maya 聊天 | [打开 Maya 聊天](https://cozsweet.com/external-entry?target=chat&character=maya) | `/characters/maya/chat` |
| Nayeli 聊天 | [打开 Nayeli 聊天](https://cozsweet.com/external-entry?target=chat&character=nayeli) | `/characters/nayeli/chat` |
| 携带 PSID 的 Elio 聊天 | [打开 PSID 聊天示例](https://cozsweet.com/external-entry?target=chat&psid=27511427698460020) | `/characters/elio/chat` |
| 语音促销 | [打开语音促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=voice) | `/characters/elio/chat`,保存语音促销意图 |
| 图片促销 | [打开图片促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=image) | `/characters/elio/chat`,保存图片促销意图 |
| 私密文本促销 | [打开私密文本促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=private) | `/characters/elio/chat`,保存私密文本促销意图 |
| Elio 咖啡打赏 | [打开 Elio 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=elio) | `/characters/elio/tip` |
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=maya) | `/characters/maya/tip` |
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=nayeli) | `/characters/nayeli/tip` |
| Elio 私密空间 | [打开 Elio 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=elio) | `/characters/elio/private-zone` |
| Maya 私密空间 | [打开 Maya 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=maya) | `/characters/maya/private-zone` |
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=nayeli) | `/characters/nayeli/private-zone` |
## 验收判断
打开入口后,浏览器地址最终应与“预期落地页面”一致。普通聊天和私密空间必须分别落在 `/chat``/private-zone`,不能再进入同一个页面。
如需在其他入口携带 PSID,在已有查询参数的链接末尾追加 `&psid=27511427698460020`
+15 -1
View File
@@ -61,7 +61,21 @@ export async function registerChatMocks(page: Page, options: ChatMockOptions, st
await route.fulfill({ status: 401, json: { message: "expired" } });
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,
reply: "You always know how to make me smile.",
+10
View File
@@ -4,6 +4,16 @@ import { apiEnvelope } from "../data/common";
import { createPaymentOrderResponse, paidPaymentOrderStatusResponse, paymentPlansResponse, tipPaymentPlansResponse, vipStatusResponse } from "../data/payment";
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/tip-plans**", async (route) => route.fulfill({ json: apiEnvelope(tipPaymentPlansResponse) }));
await page.route("**/api/payment/create-order", async (route) => route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) }));
+2 -2
View File
@@ -75,13 +75,13 @@ export const paidImageChatSendResponse = {
messageId: paidImageMessageId,
isGuest: true,
timestamp: 1_782_180_725_000,
image: { type: "elio_schedule", url: paidImageUrl },
image: { type: "elio_schedule", url: null },
lockDetail: { locked: true, showContent: true, showUpgrade: true, reason: "image", hint: "Activate VIP to unlock the full photo.", detail: null },
};
export function createPaidImageHistoryResponse(unlocked: boolean) {
return {
messages: [{ role: "assistant", type: "image", content: unlocked ? "" : paidImageChatSendResponse.reply, id: paidImageMessageId, created_at: "2026-06-30T00:00:00.000Z", audioUrl: null, image: { type: "elio_schedule", url: paidImageUrl }, lockDetail: unlocked ? { locked: false, showContent: true, showUpgrade: false, reason: null, hint: null, detail: null } : paidImageChatSendResponse.lockDetail }],
messages: [{ role: "assistant", type: "image", content: unlocked ? "" : paidImageChatSendResponse.reply, id: paidImageMessageId, created_at: "2026-06-30T00:00:00.000Z", audioUrl: null, image: { type: "elio_schedule", url: unlocked ? paidImageUrl : null }, lockDetail: unlocked ? { locked: false, showContent: true, showUpgrade: false, reason: null, hint: null, detail: null } : paidImageChatSendResponse.lockDetail }],
total: 1, limit: 50, offset: 0, isVip: unlocked, privateFreeLimit: 0, privateUsedToday: 0, privateCanViewFree: false,
};
}
+11 -1
View File
@@ -1,9 +1,19 @@
import { expect, type Page } from "@playwright/test";
export async function completeVipPayment(page: Page) {
const checkoutButton = page.getByRole("button", { name: "Pay and Top Up" });
await expect(checkoutButton).toBeDisabled();
await page.getByRole("button", { name: /Monthly,/i }).click();
const renewalDialog = page.getByRole("dialog", {
name: "Automatic Renewal Confirmation",
});
await expect(renewalDialog).toBeVisible();
await renewalDialog.getByRole("button", { name: "Confirm" }).click();
await expect(checkoutButton).toBeEnabled();
const createOrderRequestPromise = page.waitForRequest("**/api/payment/create-order");
const orderStatusRequestPromise = page.waitForRequest("**/api/payment/order-status**");
await page.getByRole("button", { name: /Pay and Activ/i }).click();
await checkoutButton.click();
const createOrderRequest = await createOrderRequestPromise;
expect(createOrderRequest.postDataJSON()).toMatchObject({ planId: "vip_monthly", payChannel: "stripe" });
await orderStatusRequestPromise;
@@ -4,6 +4,7 @@ import { mockCoreApis } from "@e2e/fixtures/api-mocks";
import {
clearBrowserState,
enterChatFromSplash,
expectAuthRedirectToVipChatSubscription,
} from "@e2e/fixtures/test-helpers";
test.beforeEach(async ({ baseURL, context, page }) => {
@@ -29,3 +30,26 @@ test("renders a backend commercial action and opens the private zone", async ({
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(/\/auth\?redirect=/);
expectAuthRedirectToVipChatSubscription(page);
const redirect = new URL(page.url()).searchParams.get("redirect");
const subscriptionUrl = new URL(redirect ?? "", "http://e2e.local");
expect(subscriptionUrl.searchParams.get("planId")).toBe("vip_annual");
expect(subscriptionUrl.searchParams.get("commercialOfferId")).toBe(
"13ec8a10-58d7-4d24-b66b-8db5699a1aa8",
);
});
@@ -26,7 +26,10 @@ test("guest unlocks a promoted image through email login and top-up", async ({
);
await expect(page).toHaveURL(defaultCharacterChatUrl);
const unlockButton = page.getByRole("button", {
const promotedImageCard = page
.getByRole("group", { name: "Locked private image" })
.last();
const unlockButton = promotedImageCard.getByRole("button", {
name: "Unlock private image",
});
await expect(unlockButton).toBeVisible({ timeout: 10_000 });
@@ -182,7 +182,7 @@ async function registerFavoriteMenuMocks(page: Page): Promise<void> {
function collectBrowserErrors(page: Page): string[] {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("pageerror", (error) => errors.push(error.stack ?? error.message));
page.on("console", (message) => {
if (message.type() === "error") errors.push(message.text());
});
@@ -193,7 +193,8 @@ function isFeatureRuntimeError(message: string): boolean {
const isKnownLocalPreviewDependencyError =
message.includes("[ApiLoggingInterceptor]") ||
message.includes("[next-auth][error][CLIENT_FETCH_ERROR]") ||
message.includes("[Result] Result.wrap caught exception");
message.includes("[Result] Result.wrap caught exception") ||
message.includes("Cannot read properties of undefined (reading 'waiting')");
return !isKnownLocalPreviewDependencyError;
}
+28 -1
View File
@@ -89,6 +89,13 @@ for (const character of characters) {
test(`${character.displayName} can open a character-scoped Private Zone`, async ({
page,
}) => {
const momentsRequest = page.waitForRequest((request) => {
const url = new URL(request.url());
return (
url.pathname === "/api/private-zone/posts" &&
url.searchParams.get("characterId") === character.id
);
});
const albumRequest = page.waitForRequest((request) => {
const url = new URL(request.url());
return (
@@ -99,7 +106,11 @@ for (const character of characters) {
await page.goto(`/characters/${character.slug}/private-zone`);
await albumRequest;
await Promise.all([momentsRequest, albumRequest]);
await expect(
page.getByRole("heading", { name: "Private moments" }),
).toBeVisible();
await page.getByRole("tab", { name: "Albums" }).click();
await expect(
page.getByRole("heading", { name: "Private albums" }),
).toBeVisible();
@@ -152,11 +163,27 @@ test("a real Private Zone request failure still offers Retry", async ({
await page.goto("/characters/maya/private-zone");
await page.getByRole("tab", { name: "Albums" }).click();
await expect(page.getByRole("button", { name: "Retry" })).toBeVisible();
await expect(page.getByRole("button", { name: "Refresh" })).toHaveCount(0);
});
async function registerMultiRoleCommercialMocks(page: Page): Promise<void> {
await page.route("**/api/private-zone/posts**", async (route) => {
const url = new URL(route.request().url());
const characterId = url.searchParams.get("characterId") ?? "elio";
await route.fulfill({
json: apiEnvelope({
characterId,
items: [],
nextCursor: null,
hasMore: false,
creditBalance: 1000,
currency: "credits",
}),
});
});
await page.route("**/api/private-zone/albums**", async (route) => {
const url = new URL(route.request().url());
const characterId = url.searchParams.get("characterId") ?? "elio";
+8 -20
View File
@@ -19,10 +19,6 @@ import {
switchToEmailSignIn,
} from "@e2e/fixtures/test-helpers";
const paidImageOverlayUrl = new RegExp(
`${defaultCharacterChatPath}\\?image=${encodeURIComponent(paidImageDisplayMessageId)}$`,
);
test.beforeEach(async ({ baseURL, context, page }) => {
await clearBrowserState(context, page, baseURL);
await mockCoreApis(page, {
@@ -48,26 +44,18 @@ test("guest can unlock a paid image after email login and subscription payment",
message: "给我发图片",
});
const paidImageButton = page.getByRole("button", {
name: "Open image in fullscreen",
const lockedImageCard = page.getByRole("group", {
name: "Locked private image",
}).last();
await expect(paidImageButton).toBeVisible();
await paidImageButton.click();
await expect(page).toHaveURL(paidImageOverlayUrl);
const lockedImageDialog = page.getByRole("dialog", {
name: "Locked fullscreen image",
});
await expect(lockedImageDialog).toBeVisible();
await lockedImageDialog
.getByRole("button", { name: "Unlock high-definition large image" })
await expect(lockedImageCard).toBeVisible();
await expect(lockedImageCard.locator("img")).toHaveCount(0);
await lockedImageCard
.getByRole("button", { name: "Unlock private image" })
.click();
await expect(page).toHaveURL(/\/auth\?redirect=/);
expect(new URL(page.url()).searchParams.get("redirect")).toBe(
`${defaultCharacterChatPath}?image=${encodeURIComponent(paidImageDisplayMessageId)}`,
defaultCharacterChatPath,
);
await switchToEmailSignIn(page);
@@ -75,7 +63,7 @@ test("guest can unlock a paid image after email login and subscription payment",
"**/api/chat/unlock-private",
);
await submitEmailLogin(page, {
expectedUrl: paidImageOverlayUrl,
expectedUrl: new RegExp(`${defaultCharacterChatPath}$`),
});
const unlockRequest = await unlockRequestPromise;
+146
View File
@@ -0,0 +1,146 @@
import { expect, test, type Page } from "@playwright/test";
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
import { apiEnvelope } from "@e2e/fixtures/data/common";
import {
clearBrowserState,
seedEmailSession,
} from "@e2e/fixtures/test-helpers";
const postId = "11111111-1111-1111-1111-111111111111";
let unlocked = false;
test.beforeEach(async ({ baseURL, context, page }) => {
unlocked = false;
await clearBrowserState(context, page, baseURL);
await mockCoreApis(page);
await registerPrivateZoneVideoMocks(page);
});
test("Private Zone defaults to Moments and reveals video only after one credit unlock", async ({
page,
}) => {
await seedEmailSession(page);
const listRequest = page.waitForRequest((request) => {
const url = new URL(request.url());
return (
url.pathname === "/api/private-zone/posts" &&
url.searchParams.get("characterId") === "maya-tan"
);
});
await page.goto("/characters/maya/private-zone");
await listRequest;
await expect(
page.getByRole("heading", { name: "Private moments" }),
).toBeVisible();
await expect(page.getByText("Only for you.")).toBeVisible();
await expect(page.locator("video")).toHaveCount(0);
await page.getByRole("button", { name: "Unlock for 100 credits" }).click();
const dialog = page.getByRole("alertdialog");
await expect(dialog).toContainText("100 credits");
const unlockRequest = page.waitForRequest(
`**/api/private-zone/posts/${postId}/unlock`,
);
await dialog.getByRole("button", { name: "Unlock", exact: true }).click();
expect((await unlockRequest).postDataJSON()).toEqual({ expectedCost: 100 });
const video = page.locator("video");
await expect(video).toHaveCount(1);
await expect(video.locator("source")).toHaveAttribute("src", /video\.mp4/);
await expect(page.getByRole("alertdialog")).toHaveCount(0);
});
test("Albums remain available behind the second tab", async ({ page }) => {
await seedEmailSession(page);
await page.goto("/characters/maya/private-zone");
await page.getByRole("tab", { name: "Albums" }).click();
await expect(
page.getByRole("heading", { name: "Private albums" }),
).toBeVisible();
await expect(page.getByText("Maya archive")).toBeVisible();
});
async function registerPrivateZoneVideoMocks(page: Page): Promise<void> {
await page.route("**/api/private-zone/posts**", async (route) => {
const url = new URL(route.request().url());
await route.fulfill({
json: apiEnvelope({
characterId: url.searchParams.get("characterId") ?? "maya-tan",
items: [videoPost(unlocked)],
nextCursor: null,
hasMore: false,
creditBalance: unlocked ? 150 : 250,
currency: "credits",
}),
});
});
// Playwright evaluates page routes in reverse registration order. Register
// the specific mutation last so the broader list route cannot intercept it.
await page.route("**/api/private-zone/posts/*/unlock", async (route) => {
unlocked = true;
await route.fulfill({
json: apiEnvelope({
postId,
reason: "ok",
unlocked: true,
creditsCharged: 100,
requiredCredits: 100,
currentCredits: 150,
shortfallCredits: 0,
creditBalance: 150,
post: videoPost(true),
}),
});
});
await page.route("**/api/private-zone/albums**", async (route) => {
await route.fulfill({
json: apiEnvelope({
items: [
{
albumId: "album-maya",
title: "Maya archive",
content: null,
previewText: "Private photos",
imageCount: 1,
images: [{ url: "/images/private-zone/banner/maya.png", locked: true, index: 0 }],
locked: true,
unlocked: false,
unlockCost: 80,
publishedAt: "2026-07-24T10:00:00+00:00",
lockDetail: { locked: true },
},
],
creditBalance: 250,
pendingImageCount: 0,
hasIncompleteContent: false,
}),
});
});
}
function videoPost(isUnlocked: boolean) {
return {
postId,
characterId: "maya-tan",
caption: "Only for you.",
posterUrl: "/images/private-zone/banner/maya.png",
mediaType: "video",
videoUrl: isUnlocked ? "/test-video.mp4?token=short" : null,
videoMimeType: "video/mp4",
videoSizeBytes: 1024,
durationSeconds: 18,
unlockCostCredits: 100,
currency: "credits",
locked: !isUnlocked,
unlocked: isUnlocked,
availableForNewUnlock: true,
publishedAt: "2026-07-24T10:00:00+00:00",
};
}
@@ -2,22 +2,16 @@ import { expect, test } from "@playwright/test";
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
import {
paidImageDisplayMessageId,
paidImageMessageId,
} from "@e2e/fixtures/test-data";
import {
clearBrowserState,
defaultCharacterChatPath,
dismissChatInterruptions,
expectInsufficientCreditsDialog,
expectVipChatSubscriptionUrl,
signInWithEmailAndOpenChat,
} from "@e2e/fixtures/test-helpers";
const paidImageOverlayUrl = new RegExp(
`${defaultCharacterChatPath}\\?image=${encodeURIComponent(paidImageDisplayMessageId)}$`,
);
test.beforeEach(async ({ baseURL, context, page }) => {
await clearBrowserState(context, page, baseURL);
await mockCoreApis(page, {
@@ -25,30 +19,23 @@ test.beforeEach(async ({ baseURL, context, page }) => {
});
});
test("user sees insufficient credits when unlocking a paid image from fullscreen and can navigate to subscription", async ({
test("user sees insufficient credits when unlocking from the locked image card and can navigate to subscription", async ({
page,
}) => {
await signInWithEmailAndOpenChat(page);
await dismissChatInterruptions(page);
const paidImageButton = page.getByRole("button", {
name: "Open image in fullscreen",
const lockedImageCard = page.getByRole("group", {
name: "Locked private image",
}).last();
await expect(paidImageButton).toBeVisible({ timeout: 10_000 });
await paidImageButton.click();
await expect(page).toHaveURL(paidImageOverlayUrl);
const lockedImageDialog = page.getByRole("dialog", {
name: "Locked fullscreen image",
});
await expect(lockedImageDialog).toBeVisible();
await expect(lockedImageCard).toBeVisible({ timeout: 10_000 });
await expect(lockedImageCard.locator("img")).toHaveCount(0);
const unlockRequestPromise = page.waitForRequest(
"**/api/chat/unlock-private",
);
await lockedImageDialog
.getByRole("button", { name: "Unlock high-definition large image" })
await lockedImageCard
.getByRole("button", { name: "Unlock private image" })
.click();
const unlockRequest = await unlockRequestPromise;
+1
View File
@@ -5,6 +5,7 @@ NEXTAUTH_URL=https://frontend-test.banlv-ai.com
NEXTAUTH_URL_INTERNAL=http://localhost:3000
NEXT_PUBLIC_API_BASE_URL=https://proapi.banlv-ai.com
NEXT_PUBLIC_WS_BASE_URL=wss://proapi.banlv-ai.com/ws
NEXT_PUBLIC_ENABLE_VOICE_CALL=false
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51Te8ybEJDtUGxQHo0UMySJ2hW0vVryynzllmIUI3UQdQCFgxNLci0Jmm2lQkRsTaIP7C7IQlFzfFyBJ5rOhr1ML800G8P8DF5R
NEXT_PUBLIC_API_CONNECT_TIMEOUT=30000
+1
View File
@@ -10,6 +10,7 @@ NEXT_PUBLIC_API_BASE_URL=https://api.banlv-ai.com
# WebSocket URL(生产环境)
NEXT_PUBLIC_WS_BASE_URL=wss://api.banlv-ai.com/ws
NEXT_PUBLIC_ENABLE_VOICE_CALL=false
# Stripe 支付(publishable key 可暴露在浏览器端)
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_51Te8ybEJDtUGxQHouKlEMfMuCZWifzlhBIReeKvANOtyCXS4zL0SMTWJXiFHPKz7azpF6OnIKXUPFSLs82fevVjr00w1bw5mvl
-2
View File
@@ -49,8 +49,6 @@ echo "=== compose project: $COMPOSE_PROJECT_NAME ==="
"${COMPOSE[@]}" up -d --remove-orphans --no-build web
"${COMPOSE[@]}" ps
docker image prune -f
prune_project_images() {
local retain_count="$1"
if ! [[ "$retain_count" =~ ^[0-9]+$ ]] || [ "$retain_count" -le 0 ]; then
+19
View File
@@ -22,6 +22,9 @@ export interface UsePaymentRouteFlowInput {
characterId?: string;
initialCategory?: string | null;
initialPlanId?: string | null;
commercialOfferId?: string | null;
resumeOrderId?: string | null;
chatActionId?: string | null;
}
export interface PaymentRouteFlow {
@@ -41,15 +44,21 @@ export function usePaymentRouteFlow({
characterId,
initialCategory = null,
initialPlanId = null,
commercialOfferId = null,
resumeOrderId = null,
chatActionId = null,
}: UsePaymentRouteFlowInput): PaymentRouteFlow {
const payment = usePaymentState();
const paymentDispatch = usePaymentDispatch();
const initializedCatalogKeyRef = useRef<string | null>(null);
const resumedOrderIdRef = useRef<string | null>(null);
const catalogKey = [
catalog,
characterId ?? "",
initialCategory ?? "",
initialPlanId ?? "",
commercialOfferId ?? "",
chatActionId ?? "",
].join(":");
usePendingPaymentOrderLifecycle({
@@ -69,16 +78,26 @@ export function usePaymentRouteFlow({
...(characterId ? { characterId } : {}),
...(initialCategory ? { category: initialCategory } : {}),
...(initialPlanId ? { planId: initialPlanId } : {}),
...(commercialOfferId ? { commercialOfferId } : {}),
...(chatActionId ? { chatActionId } : {}),
});
}, [
catalog,
catalogKey,
characterId,
commercialOfferId,
chatActionId,
initialCategory,
initialPlanId,
initialPayChannel,
paymentDispatch,
]);
useEffect(() => {
if (!resumeOrderId || resumedOrderIdRef.current === resumeOrderId) return;
resumedOrderIdRef.current = resumeOrderId;
paymentDispatch({ type: "PaymentReturned", orderId: resumeOrderId });
}, [paymentDispatch, resumeOrderId]);
return { payment, paymentDispatch };
}
@@ -0,0 +1,57 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { VoiceCallPlayer } from "@/app/call/voice-call-player";
describe("VoiceCallPlayer", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("schedules decoded sentence audio on one continuous Web Audio timeline", async () => {
const starts: number[] = [];
const sources: Array<{ onended: (() => void) | null }> = [];
const context = {
state: "running",
currentTime: 0,
destination: {},
resume: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
decodeAudioData: vi.fn(async () => ({ duration: 1 })),
createBufferSource: vi.fn(() => {
const source = {
buffer: null,
onended: null as (() => void) | null,
connect: vi.fn(),
disconnect: vi.fn(),
stop: vi.fn(),
start: vi.fn((at: number) => starts.push(at)),
};
sources.push(source);
return source;
}),
};
vi.stubGlobal("AudioContext", function AudioContextMock() {
return context;
});
const player = new VoiceCallPlayer();
const gaps: number[] = [];
player.onGap = (milliseconds) => gaps.push(milliseconds);
const meta = {
callId: "call-1",
turnId: "turn-1",
index: 0,
mimeType: "audio/mpeg",
byteLength: 3,
};
player.enqueue(meta, new Uint8Array([1, 2, 3]).buffer);
player.enqueue({ ...meta, index: 1 }, new Uint8Array([4, 5, 6]).buffer);
await vi.waitFor(() => expect(starts).toHaveLength(2));
expect(starts).toEqual([0.025, 1.025]);
expect(gaps).toEqual([0]);
expect(sources).toHaveLength(2);
player.dispose();
});
});
+8
View File
@@ -0,0 +1,8 @@
import { redirect } from "next/navigation";
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
import { getCharacterRoutes } from "@/router/routes";
export default function LegacyCallPage() {
redirect(getCharacterRoutes(DEFAULT_CHARACTER_SLUG).call);
}
+101
View File
@@ -0,0 +1,101 @@
import type { CallAudioChunkMeta } from "@/core/net/voice-call-transport";
export class VoiceCallPlayer {
private context: AudioContext | null = null;
private sources = new Set<AudioBufferSourceNode>();
private decodeChain: Promise<void> = Promise.resolve();
private scheduledUntil = 0;
private pendingDecodes = 0;
private generation = 0;
onPlaying: (() => void) | null = null;
onIdle: (() => void) | null = null;
onGap: ((milliseconds: number) => void) | null = null;
onError: ((error: Error) => void) | null = null;
get isPlaying(): boolean {
return this.sources.size > 0 || this.pendingDecodes > 0;
}
async prepare(): Promise<void> {
const context = this.getContext();
if (context.state === "suspended") await context.resume();
}
enqueue(_meta: CallAudioChunkMeta, bytes: ArrayBuffer): void {
const generation = this.generation;
this.pendingDecodes += 1;
this.decodeChain = this.decodeChain
.then(async () => {
const context = this.getContext();
if (context.state === "suspended") await context.resume();
const audioBuffer = await context.decodeAudioData(bytes.slice(0));
if (generation !== this.generation) return;
this.schedule(context, audioBuffer);
})
.catch((error: unknown) => {
this.onError?.(error instanceof Error ? error : new Error(String(error)));
})
.finally(() => {
this.pendingDecodes = Math.max(0, this.pendingDecodes - 1);
this.notifyIdleIfNeeded();
});
}
stop(): void {
this.generation += 1;
for (const source of this.sources) {
source.onended = null;
try {
source.stop();
} catch {
// 已自然结束的 source 无需重复停止。
}
source.disconnect();
}
this.sources.clear();
this.scheduledUntil = 0;
this.onIdle?.();
}
dispose(): void {
this.stop();
const context = this.context;
this.context = null;
if (context && context.state !== "closed") void context.close();
}
private getContext(): AudioContext {
if (!this.context || this.context.state === "closed") {
this.context = new AudioContext({ latencyHint: "interactive" });
}
return this.context;
}
private schedule(context: AudioContext, buffer: AudioBuffer): void {
const leadSeconds = 0.025;
const earliestStart = context.currentTime + leadSeconds;
const hadPreviousSegment = this.scheduledUntil > 0;
const startAt = Math.max(earliestStart, this.scheduledUntil);
if (hadPreviousSegment) {
this.onGap?.(Math.max(0, (startAt - this.scheduledUntil) * 1000));
}
const source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
this.sources.add(source);
this.scheduledUntil = startAt + buffer.duration;
source.onended = () => {
source.disconnect();
this.sources.delete(source);
this.notifyIdleIfNeeded();
};
source.start(startAt);
this.onPlaying?.();
}
private notifyIdleIfNeeded(): void {
if (this.sources.size || this.pendingDecodes) return;
this.scheduledUntil = 0;
this.onIdle?.();
}
}
+47
View File
@@ -0,0 +1,47 @@
.screen {
position: relative;
display: flex;
min-height: var(--app-viewport-height, 100dvh);
overflow: hidden;
flex-direction: column;
color: #fff;
background: #090810;
}
.background { object-fit: cover; opacity: .48; }
.scrim { position: absolute; inset: 0; background: radial-gradient(circle at 50% 32%, rgba(239,83,155,.18), transparent 36%), linear-gradient(180deg, rgba(9,8,16,.28), rgba(9,8,16,.94)); }
.header { position: relative; z-index: 1; display: flex; align-items: center; justify-content: space-between; padding: calc(18px + var(--app-safe-top, 0px)) 20px 12px; }
.iconButton { display: inline-flex; width: 42px; height: 42px; cursor: pointer; align-items: center; justify-content: center; border: 1px solid rgba(255,255,255,.16); border-radius: 999px; color: #fff; background: rgba(10,9,18,.55); backdrop-filter: blur(14px); }
.balances { display: flex; gap: 8px; font-size: 12px; font-weight: 650; }
.balances span { padding: 7px 10px; border: 1px solid rgba(255,255,255,.12); border-radius: 999px; background: rgba(10,9,18,.58); backdrop-filter: blur(14px); }
.content { position: relative; z-index: 1; display: flex; min-height: 0; flex: 1; flex-direction: column; align-items: center; justify-content: center; padding: 24px 28px; text-align: center; }
.avatarRing { position: relative; display: grid; width: 174px; height: 174px; place-items: center; border-radius: 50%; background: linear-gradient(135deg, rgba(255,255,255,.24), rgba(239,83,155,.42)); box-shadow: 0 28px 72px rgba(0,0,0,.42); transition: transform .25s ease, box-shadow .25s ease; }
.avatarRing::after { position: absolute; inset: -10px; border: 1px solid rgba(255,255,255,.16); border-radius: inherit; content: ""; }
.avatarRing.listening, .avatarRing.speaking { animation: callPulse 1.8s ease-in-out infinite; box-shadow: 0 0 0 12px rgba(239,83,155,.08), 0 28px 72px rgba(0,0,0,.42); }
.avatar { width: 158px; height: 158px; border: 4px solid rgba(9,8,16,.8); border-radius: 50%; object-fit: cover; }
.content h1 { margin: 30px 0 8px; font-size: clamp(27px, 7vw, 36px); letter-spacing: -.025em; }
.state { display: flex; min-height: 28px; align-items: center; gap: 7px; color: rgba(255,255,255,.78); font-size: 15px; }
.lowBalance { margin: 12px 0 0; padding: 7px 11px; border-radius: 999px; color: #ffd6e8; background: rgba(210,48,121,.2); font-size: 12px; }
.transcript { width: min(100%, 440px); min-height: 105px; margin-top: 24px; text-align: left; }
.transcript p { margin: 0 0 10px; padding: 11px 13px; border: 1px solid rgba(255,255,255,.09); border-radius: 15px; color: rgba(255,255,255,.9); background: rgba(14,12,24,.48); font-size: 14px; line-height: 1.45; backdrop-filter: blur(12px); }
.transcript span { display: block; margin-bottom: 4px; color: #f3a3c8; font-size: 11px; font-weight: 700; text-transform: uppercase; }
.error { max-width: 360px; margin: 8px 0 0; color: #ffc2ca; font-size: 13px; }
.footer { position: relative; z-index: 1; display: flex; flex-direction: column; align-items: center; padding: 10px 24px calc(24px + var(--app-safe-bottom, 0px)); }
.footer p { margin: 12px 0 0; color: rgba(255,255,255,.52); font-size: 12px; }
.startButton { display: inline-flex; min-width: 170px; cursor: pointer; align-items: center; justify-content: center; gap: 9px; border: 0; border-radius: 999px; padding: 15px 24px; color: #fff; background: linear-gradient(135deg, #ee579d, #ce357c); box-shadow: 0 16px 36px rgba(212,54,127,.32); font-size: 15px; font-weight: 750; }
.endButton { display: inline-flex; width: 66px; height: 66px; cursor: pointer; align-items: center; justify-content: center; border: 0; border-radius: 50%; color: #fff; background: #e24456; box-shadow: 0 15px 34px rgba(226,68,86,.34); }
.topUpBackdrop { position: absolute; z-index: 10; inset: 0; display: flex; align-items: flex-end; justify-content: center; padding: 18px; background: rgba(5,4,9,.68); backdrop-filter: blur(8px); }
.topUpDialog { width: min(100%, 460px); padding: 24px; border: 1px solid rgba(255,255,255,.12); border-radius: 24px; background: #17131f; box-shadow: 0 24px 70px rgba(0,0,0,.5); text-align: center; }
.topUpDialog h2 { margin: 0; font-size: 21px; }
.topUpDialog p { margin: 10px 0 20px; color: rgba(255,255,255,.66); font-size: 14px; line-height: 1.5; }
.topUpDialog button { width: 100%; cursor: pointer; border: 0; border-radius: 999px; padding: 13px 18px; color: #fff; background: #df478d; font-weight: 750; }
.topUpDialog .secondaryButton { margin-top: 8px; color: rgba(255,255,255,.72); background: transparent; }
@keyframes callPulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.025); } }
@media (max-height: 700px) {
.avatarRing { width: 138px; height: 138px; }
.avatar { width: 124px; height: 124px; }
.content h1 { margin-top: 20px; }
.transcript { min-height: 72px; margin-top: 16px; }
}
+280
View File
@@ -0,0 +1,280 @@
"use client";
import Image from "next/image";
import { useCallback, useEffect, useRef, useState } from "react";
import { Mic, PhoneOff, RotateCcw, Volume2, X } from "lucide-react";
import { MobileShell } from "@/app/_components/core";
import { getApiConfig } from "@/core/net/config/api_config";
import {
VoiceCallTransport,
type CallBillingStatusPayload,
} from "@/core/net/voice-call-transport";
import { VoiceCallAudioCapture } from "@/integrations/voice-call-audio";
import { getSessionAccessToken } from "@/lib/auth/auth_session";
import { useActiveCharacter, useActiveCharacterRoutes } from "@/providers/character-provider";
import { useAppNavigator } from "@/router/use-app-navigator";
import { VoiceCallPlayer } from "./voice-call-player";
import styles from "./voice-call-screen.module.css";
type CallUiState = "idle" | "connecting" | "listening" | "thinking" | "speaking" | "ended" | "error";
const STATE_COPY: Record<CallUiState, string> = {
idle: "Ready to call",
connecting: "Connecting…",
listening: "Listening…",
thinking: "Thinking…",
speaking: "Speaking…",
ended: "Call ended",
error: "Call unavailable",
};
async function getSessionToken(): Promise<string> {
const token = await getSessionAccessToken();
if (token) return token;
throw new Error("Please sign in before starting a call");
}
export function VoiceCallScreen() {
const character = useActiveCharacter();
const routes = useActiveCharacterRoutes();
const navigator = useAppNavigator();
const [uiState, setUiState] = useState<CallUiState>("idle");
const [userTranscript, setUserTranscript] = useState("");
const [aiTranscript, setAiTranscript] = useState("");
const [freeTurns, setFreeTurns] = useState(0);
const [balance, setBalance] = useState(0);
const [cost, setCost] = useState(2);
const [error, setError] = useState<string | null>(null);
const [showTopUp, setShowTopUp] = useState(false);
const transportRef = useRef<VoiceCallTransport | null>(null);
const captureRef = useRef<VoiceCallAudioCapture | null>(null);
const playerRef = useRef<VoiceCallPlayer | null>(null);
const callIdRef = useRef("");
const activeTurnRef = useRef("");
const reconnectTurnRef = useRef("");
const resumeVersionRef = useRef(0);
const endingRef = useRef(false);
const pendingTopUpRef = useRef(false);
const finishCall = useCallback((navigate = true) => {
if (endingRef.current) return;
endingRef.current = true;
captureRef.current?.dispose();
playerRef.current?.dispose();
if (callIdRef.current) transportRef.current?.endCall(callIdRef.current);
transportRef.current?.disconnect();
reconnectTurnRef.current = "";
resumeVersionRef.current = 0;
setUiState("ended");
if (navigate) navigator.push(routes.chat);
}, [navigator, routes.chat]);
const beginListening = useCallback((turnId: string) => {
const capture = captureRef.current;
const transport = transportRef.current;
const callId = callIdRef.current;
if (!capture || !transport || !callId || !turnId) return;
activeTurnRef.current = turnId;
reconnectTurnRef.current = turnId;
setUiState(playerRef.current?.isPlaying ? "speaking" : "listening");
const preRoll: ArrayBuffer[] = [];
let streamOpened = false;
capture.startTurn({
onChunk: (chunk) => {
if (streamOpened) {
transport.sendAudioChunk(chunk);
return;
}
preRoll.push(chunk);
if (preRoll.length > 5) preRoll.shift();
},
onSpeechStart: () => {
setError(null);
if (playerRef.current?.isPlaying) {
playerRef.current.stop();
transport.interrupt(callId);
}
streamOpened = transport.startAudio(
callId,
turnId,
capture.mimeType,
capture.sampleRate,
);
if (streamOpened) {
for (const chunk of preRoll) transport.sendAudioChunk(chunk);
preRoll.length = 0;
setUserTranscript("");
setAiTranscript("");
setUiState("listening");
}
},
onTurnEnd: (vadLatencyMs) => {
if (streamOpened) {
transport.endAudio(callId, turnId, vadLatencyMs);
setUiState("thinking");
}
},
onError: (captureError) => {
setError(captureError.message);
setUiState("error");
},
});
}, []);
const applyBilling = useCallback((status: CallBillingStatusPayload) => {
setBalance(status.creditBalance);
setFreeTurns(status.freeTurnsRemaining);
setCost(status.requiredCredits || 2);
if (status.canContinue && status.nextTurnId) {
beginListening(status.nextTurnId);
return;
}
captureRef.current?.stopTurn();
pendingTopUpRef.current = true;
if (!playerRef.current?.isPlaying) setShowTopUp(true);
}, [beginListening]);
const startCall = useCallback(async () => {
if (uiState !== "idle" && uiState !== "error") return;
endingRef.current = false;
pendingTopUpRef.current = false;
setError(null);
setUiState("connecting");
try {
const player = new VoiceCallPlayer();
playerRef.current = player;
const playerReady = player.prepare();
const capture = new VoiceCallAudioCapture();
await Promise.all([capture.prepare(), playerReady]);
captureRef.current = capture;
const token = await getSessionToken();
const transport = new VoiceCallTransport(getApiConfig().wsUrl, token);
transportRef.current = transport;
player.onPlaying = () => setUiState("speaking");
player.onIdle = () => {
if (pendingTopUpRef.current) setShowTopUp(true);
else if (activeTurnRef.current) setUiState("listening");
};
player.onError = (playbackError) => setError(playbackError.message);
player.onGap = (milliseconds) => {
transport.sendClientMetric("audioChunkGap", milliseconds);
};
transport.onOpen = () => {
if (!reconnectTurnRef.current) reconnectTurnRef.current = crypto.randomUUID();
transport.startCall(
character.id,
reconnectTurnRef.current,
resumeVersionRef.current || undefined,
);
};
transport.onReconnecting = () => {
capture.stopTurn();
player.stop();
callIdRef.current = "";
setUiState("connecting");
};
transport.onStarted = (started) => {
callIdRef.current = started.callId;
activeTurnRef.current = started.turnId;
reconnectTurnRef.current = started.turnId;
resumeVersionRef.current = started.resumeVersion;
setFreeTurns(started.freeTurnsRemaining);
setBalance(started.creditBalance);
setCost(started.costPerPaidTurn || 2);
beginListening(started.turnId);
};
transport.onState = setUiState;
transport.onTranscript = (text) => setUserTranscript(text);
transport.onAiSentence = (text) => {
setAiTranscript((current) => `${current}${current ? " " : ""}${text}`);
};
transport.onAudioChunk = (meta, bytes) => player.enqueue(meta, bytes);
transport.onBillingStatus = applyBilling;
transport.onEnded = () => setUiState("ended");
transport.onError = (code, message) => {
setError(message);
if (
activeTurnRef.current
&& (code === "CALL_TURN_FAILED" || code === "CALL_STT_FAILED")
) {
setUiState("listening");
} else {
setUiState("error");
}
};
transport.connect();
} catch (startError) {
captureRef.current?.dispose();
playerRef.current?.dispose();
setError(startError instanceof Error ? startError.message : String(startError));
setUiState("error");
}
}, [applyBilling, beginListening, character.id, uiState]);
useEffect(() => () => finishCall(false), [finishCall]);
const lowBalance = freeTurns === 0 && balance < cost * 2 && balance >= cost;
return (
<MobileShell background="#090810">
<main className={styles.screen}>
<Image src={character.assets.chatBackground} alt="" fill priority className={styles.background} />
<div className={styles.scrim} />
<header className={styles.header}>
<button type="button" className={styles.iconButton} onClick={() => finishCall()} aria-label="Close call">
<X size={22} aria-hidden="true" />
</button>
<div className={styles.balances}>
<span>{freeTurns} free</span>
<span>{balance} credits</span>
</div>
</header>
<section className={styles.content} aria-live="polite">
<div className={`${styles.avatarRing} ${styles[uiState]}`}>
<Image src={character.assets.avatar} alt={character.displayName} width={148} height={148} className={styles.avatar} priority />
</div>
<h1>{character.displayName}</h1>
<div className={styles.state}>
{uiState === "listening" ? <Mic size={18} aria-hidden="true" /> : null}
{uiState === "speaking" ? <Volume2 size={18} aria-hidden="true" /> : null}
<span>{STATE_COPY[uiState]}</span>
</div>
{lowBalance ? <p className={styles.lowBalance}>Your balance covers fewer than two paid turns.</p> : null}
<div className={styles.transcript}>
{userTranscript ? <p><span>You</span>{userTranscript}</p> : null}
{aiTranscript ? <p><span>{character.shortName}</span>{aiTranscript}</p> : null}
</div>
{error ? <p className={styles.error}>{error}</p> : null}
</section>
<footer className={styles.footer}>
{uiState === "idle" || uiState === "error" ? (
<button type="button" className={styles.startButton} onClick={() => void startCall()}>
{uiState === "error" ? <RotateCcw size={20} aria-hidden="true" /> : <Mic size={20} aria-hidden="true" />}
{uiState === "error" ? "Try again" : "Start call"}
</button>
) : (
<button type="button" className={styles.endButton} onClick={() => finishCall()} aria-label="End call">
<PhoneOff size={27} aria-hidden="true" />
</button>
)}
<p>Speak naturally you can interrupt at any time.</p>
</footer>
{showTopUp ? (
<div className={styles.topUpBackdrop} role="presentation">
<section className={styles.topUpDialog} role="dialog" aria-modal="true" aria-labelledby="call-topup-title">
<h2 id="call-topup-title">Not enough credits for another turn</h2>
<p>Your current reply has finished. Top up to keep the conversation going.</p>
<button type="button" onClick={() => navigator.openSubscription({ type: "topup", returnTo: "chat" })}>Top up credits</button>
<button type="button" className={styles.secondaryButton} onClick={() => finishCall()}>End call</button>
</section>
</div>
) : null}
</main>
</MobileShell>
);
}
@@ -0,0 +1,5 @@
import { VoiceCallScreen } from "@/app/call/voice-call-screen";
export default function CharacterCallPage() {
return <VoiceCallScreen />;
}
@@ -23,6 +23,7 @@ export default async function CharacterTipPage({
const initialPlanId = normalizeTipGiftParam(
getFirstPaymentSearchParam(query[TIP_GIFT_PLAN_ID_PARAM]),
);
const chatActionId = getFirstPaymentSearchParam(query.chatActionId);
return (
<TipScreen
@@ -30,6 +31,7 @@ export default async function CharacterTipPage({
initialPlanId={initialPlanId}
shouldResumePendingOrder={paymentReturn.shouldResumePendingOrder}
initialPayChannel={paymentReturn.initialPayChannel}
chatActionId={chatActionId}
/>
);
}
@@ -0,0 +1,110 @@
import { describe, expect, it, vi } from "vitest";
import type { ChatAction } from "@/data/schemas/chat";
import type { PaymentOrderStatusResponse } from "@/data/schemas/payment";
import {
resolveChatActionTarget,
type ChatActionNavigationContext,
} from "../chat-action-navigation";
const baseAction: ChatAction = {
actionId: "action-1",
kind: "support",
type: "openProfile",
copy: "Open it here.",
ctaLabel: "Open",
ruleId: null,
orderId: null,
};
function createContext(
order: Partial<PaymentOrderStatusResponse> = {},
): ChatActionNavigationContext {
const orderResponse: PaymentOrderStatusResponse = {
orderId: "order-1",
status: "pending",
orderType: "dol",
planId: "topup-100",
creditsAdded: 0,
...order,
};
return {
characterRoutes: {
splash: "/characters/elio/splash",
chat: "/characters/elio/chat",
call: "/characters/elio/call",
privateZone: "/characters/elio/private-zone",
tip: "/characters/elio/tip",
},
characterSlug: "elio",
profileUrl: "/profile?returnTo=chat",
feedbackUrl: "/feedback?returnTo=chat",
coinsRulesUrl: "/coins-rules?returnTo=chat",
getOrderStatus: vi.fn(async () => orderResponse),
};
}
describe("resolveChatActionTarget", () => {
it.each([
["giftOffer", "/characters/elio/tip?chatActionId=action-1"],
["privateAlbumOffer", "/characters/elio/private-zone"],
["openProfile", "/profile?returnTo=chat"],
["openWallet", "/profile?returnTo=chat"],
["openCoinsRules", "/coins-rules?returnTo=chat"],
["openFeedback", "/feedback?returnTo=chat"],
] as const)("maps %s to an allowlisted internal page", async (type, expected) => {
await expect(
resolveChatActionTarget({ ...baseAction, type }, createContext()),
).resolves.toBe(expected);
});
it("maps VIP and top-up actions to typed subscription routes", async () => {
await expect(
resolveChatActionTarget(
{ ...baseAction, kind: "commercial", type: "activateVip" },
createContext(),
),
).resolves.toBe(
"/subscription?type=vip&returnTo=chat&character=elio&chatActionId=action-1",
);
await expect(
resolveChatActionTarget(
{ ...baseAction, kind: "commercial", type: "topUp" },
createContext(),
),
).resolves.toBe(
"/subscription?type=topup&returnTo=chat&character=elio&chatActionId=action-1",
);
});
it("resumes a pending VIP order using its owned order id", async () => {
const action: ChatAction = {
...baseAction,
type: "resumePayment",
orderId: "order-1",
};
await expect(
resolveChatActionTarget(
action,
createContext({ orderType: "vip_monthly" }),
),
).resolves.toBe(
"/subscription?type=vip&returnTo=chat&character=elio&resumeOrderId=order-1",
);
});
it("does not resume an order that is no longer pending", async () => {
const action: ChatAction = {
...baseAction,
type: "resumePayment",
orderId: "order-1",
};
await expect(
resolveChatActionTarget(action, createContext({ status: "paid" })),
).resolves.toBe("/profile?returnTo=chat");
await expect(
resolveChatActionTarget(action, createContext({ status: "expired" })),
).resolves.toBe("/feedback?returnTo=chat");
});
});
+64
View File
@@ -0,0 +1,64 @@
import type { ChatAction } from "@/data/schemas/chat";
import type { PaymentOrderStatusResponse } from "@/data/schemas/payment";
import type { CharacterRoutes } from "@/router/routes";
import { appendRouteSearchParams, ROUTE_BUILDERS } from "@/router/routes";
export interface ChatActionNavigationContext {
characterRoutes: CharacterRoutes;
characterSlug: string;
profileUrl: string;
feedbackUrl: string;
coinsRulesUrl: string;
getOrderStatus: (orderId: string) => Promise<PaymentOrderStatusResponse>;
}
/** Resolve only application-owned, allowlisted destinations for a chat action. */
export async function resolveChatActionTarget(
action: ChatAction,
context: ChatActionNavigationContext,
): Promise<string> {
switch (action.type) {
case "giftOffer":
return appendRouteSearchParams(context.characterRoutes.tip, {
chatActionId: action.actionId,
});
case "privateAlbumOffer":
return context.characterRoutes.privateZone;
case "openProfile":
case "openWallet":
return context.profileUrl;
case "openCoinsRules":
return context.coinsRulesUrl;
case "activateVip":
return ROUTE_BUILDERS.subscription("vip", {
sourceCharacterSlug: context.characterSlug,
returnTo: "chat",
chatActionId: action.actionId,
});
case "topUp":
return ROUTE_BUILDERS.subscription("topup", {
sourceCharacterSlug: context.characterSlug,
returnTo: "chat",
chatActionId: action.actionId,
});
case "openFeedback":
return context.feedbackUrl;
case "resumePayment": {
if (!action.orderId) return context.feedbackUrl;
const order = await context.getOrderStatus(action.orderId);
if (order.status === "paid") return context.profileUrl;
if (order.status !== "pending") return context.feedbackUrl;
if (order.orderType === "tip") return context.characterRoutes.tip;
return ROUTE_BUILDERS.subscription(
order.orderType === "vip" || order.orderType.startsWith("vip_")
? "vip"
: "topup",
{
sourceCharacterSlug: context.characterSlug,
returnTo: "chat",
resumeOrderId: action.orderId,
},
);
}
}
}
+106 -3
View File
@@ -17,9 +17,14 @@ import { useCharacterCatalog } from "@/providers/character-catalog-provider";
import { clearPendingChatNavigation } from "@/lib/navigation/chat_unlock_session";
import { buildGlobalPageUrl } from "@/router/global-route-context";
import { resolveAuthenticatedNavigation } from "@/router/navigation-resolver";
import { getCharacterRoutes, ROUTES } from "@/router/routes";
import type { CommercialAction } from "@/data/schemas/chat";
import { getCharacterRoutes, ROUTE_BUILDERS, ROUTES } from "@/router/routes";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
import { paymentApi } from "@/data/services/api";
import { behaviorAnalytics } from "@/lib/analytics";
import {
recordChatActionEvent,
rememberChatActionArrival,
} from "@/lib/chat/chat_action_events";
import { MobileShell } from "@/app/_components/core";
@@ -47,6 +52,7 @@ import { useChatGuestLogin } from "./hooks/use-chat-guest-login";
import { useChatMessageLimitBanner } from "./hooks/use-chat-message-limit-banner";
import { useChatPromotionBootstrap } from "./hooks/use-chat-promotion-bootstrap";
import { useSplashLatestMessageSync } from "./hooks/use-splash-latest-message-sync";
import { resolveChatActionTarget } from "./chat-action-navigation";
const chatShellStyle = {
"--chat-message-font-size": "clamp(16px, 3.333vw, 18px)",
@@ -64,6 +70,14 @@ export function ChatScreen() {
ROUTES.profile,
characterRoutes.chat,
);
const feedbackUrl = buildGlobalPageUrl(
ROUTES.feedback,
characterRoutes.chat,
);
const coinsRulesUrl = buildGlobalPageUrl(
ROUTES.coinsRules,
characterRoutes.chat,
);
const searchParams = useSearchParams();
const state = useChatState();
const chatDispatch = useChatDispatch();
@@ -269,7 +283,7 @@ export function ChatScreen() {
router.push(characterRoutes.privateZone);
}
function handleCommercialAction(action: CommercialAction): void {
async function handleCommercialAction(action: CommercialAction): Promise<void> {
behaviorAnalytics.elementClick(
"chat.commercial_action.open",
action.ctaLabel,
@@ -281,6 +295,29 @@ export function ChatScreen() {
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(
action.target === "giftCatalog"
? characterRoutes.tip
@@ -301,6 +338,69 @@ export function ChatScreen() {
);
}
function handleChatActionViewed(action: ChatAction): void {
void recordChatActionEvent(action, state.characterId, "viewed").catch(
() => undefined,
);
}
async function handleChatAction(action: ChatAction): Promise<void> {
behaviorAnalytics.elementClick(
"chat.action.open",
action.ctaLabel,
{
actionId: action.actionId,
actionKind: action.kind,
actionType: action.type,
characterId: state.characterId,
ruleId: action.ruleId,
},
);
await recordChatActionEvent(
action,
state.characterId,
"opened",
).catch(() => undefined);
const targetUrl = await resolveChatActionTarget(action, {
characterRoutes,
characterSlug: character.slug,
profileUrl,
feedbackUrl,
coinsRulesUrl,
getOrderStatus: (orderId) => paymentApi.getOrderStatus(orderId),
});
const authenticatedTarget = resolveAuthenticatedNavigation({
loginStatus: authState.loginStatus,
targetUrl,
});
rememberChatActionArrival(
action,
state.characterId,
targetUrl,
);
router.push(authenticatedTarget);
}
function handleChatActionDismiss(action: ChatAction): void {
behaviorAnalytics.elementClick(
"chat.action.dismiss",
"Dismiss chat action",
{
actionId: action.actionId,
actionKind: action.kind,
actionType: action.type,
characterId: state.characterId,
ruleId: action.ruleId,
},
);
void recordChatActionEvent(
action,
state.characterId,
"dismissed",
).catch(() => undefined);
}
return (
<MobileShell>
<div
@@ -351,6 +451,9 @@ export function ChatScreen() {
onCharacterAvatarClick={handleOpenCharacterPrivateZone}
onCommercialAction={handleCommercialAction}
onCommercialActionDismiss={handleCommercialActionDismiss}
onChatActionViewed={handleChatActionViewed}
onChatAction={handleChatAction}
onChatActionDismiss={handleChatActionDismiss}
onLoadMoreHistory={() => {
chatDispatch({ type: "ChatLoadMoreHistoryRequested" });
}}
@@ -0,0 +1,67 @@
/* @vitest-environment jsdom */
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ChatActionCard } from "../chat-action-card";
describe("ChatActionCard", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("reports one view, opens the action and can be dismissed", async () => {
const onViewed = vi.fn();
const onActivate = vi.fn(async () => undefined);
const onDismiss = vi.fn();
const action = {
actionId: "action-1",
kind: "support" as const,
type: "openFeedback" as const,
copy: "Share the screenshot and approximate payment time here.",
ctaLabel: "Open Feedback",
ruleId: null,
orderId: null,
};
await act(async () => {
root.render(
<ChatActionCard
action={action}
onViewed={onViewed}
onActivate={onActivate}
onDismiss={onDismiss}
/>,
);
});
expect(onViewed).toHaveBeenCalledTimes(1);
expect(container.querySelector("[data-chat-action='openFeedback']"))
.not.toBeNull();
const openButton = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.includes("Open Feedback"),
);
await act(async () => openButton?.click());
expect(onActivate).toHaveBeenCalledWith(action);
const dismissButton = container.querySelector<HTMLButtonElement>(
'button[aria-label="Dismiss"]',
);
act(() => dismissButton?.click());
expect(onDismiss).toHaveBeenCalledWith(action);
expect(container.innerHTML).toBe("");
});
});
@@ -23,4 +23,23 @@ describe("CommercialActionCard", () => {
expect(html).toContain("Open private zone");
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");
});
});
@@ -0,0 +1,118 @@
"use client";
import { useEffect, useRef, useState } from "react";
import {
ArrowRight,
CircleDollarSign,
CircleHelp,
Gift,
Images,
LoaderCircle,
MessageSquareWarning,
UserRound,
WalletCards,
X,
type LucideIcon,
} from "lucide-react";
import type { ChatAction } from "@/data/schemas/chat";
import styles from "./chat-area.module.css";
const ACTION_ICONS: Record<ChatAction["type"], LucideIcon> = {
giftOffer: Gift,
privateAlbumOffer: Images,
openProfile: UserRound,
openWallet: WalletCards,
openCoinsRules: WalletCards,
activateVip: CircleDollarSign,
topUp: CircleDollarSign,
openFeedback: MessageSquareWarning,
resumePayment: CircleHelp,
};
export interface ChatActionCardProps {
action: ChatAction;
onViewed?: (action: ChatAction) => void;
onActivate?: (action: ChatAction) => void | Promise<void>;
onDismiss?: (action: ChatAction) => void;
}
export function ChatActionCard({
action,
onViewed,
onActivate,
onDismiss,
}: ChatActionCardProps) {
const [dismissed, setDismissed] = useState(false);
const [activating, setActivating] = useState(false);
const [activationError, setActivationError] = useState<string | null>(null);
const viewedActionIdRef = useRef<string | null>(null);
useEffect(() => {
if (viewedActionIdRef.current === action.actionId) return;
viewedActionIdRef.current = action.actionId;
onViewed?.(action);
}, [action, onViewed]);
if (dismissed) return null;
const Icon = ACTION_ICONS[action.type];
return (
<aside
className={styles.commercialAction}
aria-label={action.ctaLabel}
data-chat-action={action.type}
data-chat-action-kind={action.kind}
>
<div className={styles.commercialActionHeader}>
<Icon size={18} aria-hidden="true" />
<button
type="button"
className={styles.commercialActionDismiss}
title="Dismiss"
aria-label="Dismiss"
onClick={() => {
setDismissed(true);
onDismiss?.(action);
}}
>
<X size={16} aria-hidden="true" />
</button>
</div>
<p className={styles.commercialActionCopy}>{action.copy}</p>
{activationError ? (
<p className={styles.commercialActionError} role="alert">
{activationError}
</p>
) : null}
<button
type="button"
className={styles.commercialActionButton}
disabled={activating}
onClick={() => {
setActivating(true);
setActivationError(null);
void Promise.resolve(onActivate?.(action))
.catch(() =>
setActivationError(
"This option is unavailable right now. Please try again.",
),
)
.finally(() => setActivating(false));
}}
>
<span>{action.ctaLabel}</span>
{activating ? (
<LoaderCircle
className={styles.commercialActionSpinner}
size={17}
aria-hidden="true"
/>
) : (
<ArrowRight size={17} aria-hidden="true" />
)}
</button>
</aside>
);
}
@@ -189,6 +189,26 @@
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 {
max-width: var(--chat-bubble-max-width, 75%);
background: var(--color-bubble-ai, rgba(255, 255, 255, 0.08));
+17 -1
View File
@@ -24,7 +24,7 @@ import {
import { LoaderCircle } from "lucide-react";
import type { UiMessage } from "@/stores/chat/ui-message";
import type { CommercialAction } from "@/data/schemas/chat";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
import { usePullToRefresh } from "@/hooks/use-pull-to-refresh";
import {
@@ -64,6 +64,9 @@ export interface ChatAreaProps {
onCharacterAvatarClick?: () => void;
onCommercialAction?: (action: CommercialAction) => void;
onCommercialActionDismiss?: (action: CommercialAction) => void;
onChatActionViewed?: (action: ChatAction) => void;
onChatAction?: (action: ChatAction) => void | Promise<void>;
onChatActionDismiss?: (action: ChatAction) => void;
}
type ChatMessageAction = (
@@ -90,6 +93,9 @@ export function ChatArea({
onCharacterAvatarClick,
onCommercialAction,
onCommercialActionDismiss,
onChatActionViewed,
onChatAction,
onChatActionDismiss,
}: ChatAreaProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
@@ -264,6 +270,9 @@ export function ChatArea({
onCharacterAvatarClick,
onCommercialAction,
onCommercialActionDismiss,
onChatActionViewed,
onChatAction,
onChatActionDismiss,
)}
{isReplyingAI ? (
@@ -304,6 +313,9 @@ function renderMessagesWithDateHeaders(
onCharacterAvatarClick?: () => void,
onCommercialAction?: (action: CommercialAction) => void,
onCommercialActionDismiss?: (action: CommercialAction) => void,
onChatActionViewed?: (action: ChatAction) => void,
onChatAction?: (action: ChatAction) => void | Promise<void>,
onChatActionDismiss?: (action: ChatAction) => void,
) {
return buildChatRenderItems(messages, getMessageKey).map((item) =>
item.type === "date" ? (
@@ -324,6 +336,7 @@ function renderMessagesWithDateHeaders(
lockedPrivate={item.message.lockedPrivate}
privateMessageHint={item.message.privateMessageHint}
commercialAction={item.message.commercialAction}
chatAction={item.message.chatAction}
isUnlockingMessage={
isUnlockingMessage === true &&
item.message.displayId === unlockingMessageId
@@ -336,6 +349,9 @@ function renderMessagesWithDateHeaders(
onCharacterAvatarClick={onCharacterAvatarClick}
onCommercialAction={onCommercialAction}
onCommercialActionDismiss={onCommercialActionDismiss}
onChatActionViewed={onChatActionViewed}
onChatAction={onChatAction}
onChatActionDismiss={onChatActionDismiss}
/>
),
);
+20 -5
View File
@@ -5,7 +5,7 @@
* 顶部保持返回、首充优惠、收藏入口三段结构。
*/
import type { ReactNode } from "react";
import { Lock } from "lucide-react";
import { Lock, Phone } from "lucide-react";
import { BackButton } from "@/app/_components";
import { FavoriteEntryButton } from "@/app/_components/core";
@@ -27,6 +27,7 @@ export function ChatHeader({
const navigator = useAppNavigator();
const character = useActiveCharacter();
const characterRoutes = useActiveCharacterRoutes();
const voiceCallEnabled = process.env.NEXT_PUBLIC_ENABLE_VOICE_CALL === "true";
return (
<header className="flex shrink-0 flex-col items-stretch bg-transparent p-0">
@@ -58,10 +59,24 @@ export function ChatHeader({
<div className="flex min-w-0 justify-center">{offerBanner}</div>
<FavoriteEntryButton
characterSlug={character.slug}
tone="dark"
/>
<div className="flex items-center gap-2">
{voiceCallEnabled ? (
<button
type="button"
className="inline-flex size-(--responsive-icon-button-size,42px) cursor-pointer items-center justify-center rounded-full border border-[rgba(255,255,255,0.12)] bg-[rgba(13,11,20,0.7)] text-white shadow-[0_10px_24px_rgba(0,0,0,0.2)] backdrop-blur-md transition hover:bg-[rgba(28,24,39,0.82)] active:scale-96"
aria-label={`Call ${character.shortName}`}
data-analytics-key="chat.start_voice_call"
data-analytics-label="Start voice call"
onClick={() => navigator.push(characterRoutes.call)}
>
<Phone size={19} strokeWidth={2.3} aria-hidden="true" />
</button>
) : null}
<FavoriteEntryButton
characterSlug={character.slug}
tone="dark"
/>
</div>
</div>
</header>
);
@@ -1,7 +1,7 @@
"use client";
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";
@@ -9,7 +9,7 @@ import styles from "./chat-area.module.css";
export interface CommercialActionCardProps {
action: CommercialAction;
onActivate?: (action: CommercialAction) => void;
onActivate?: (action: CommercialAction) => void | Promise<void>;
onDismiss?: (action: CommercialAction) => void;
}
@@ -19,9 +19,16 @@ export function CommercialActionCard({
onDismiss,
}: CommercialActionCardProps) {
const [dismissed, setDismissed] = useState(false);
const [activating, setActivating] = useState(false);
const [activationError, setActivationError] = useState<string | null>(null);
if (dismissed) return null;
const Icon = action.type === "giftOffer" ? Gift : Images;
const Icon =
action.type === "giftOffer"
? Gift
: action.type === "discountOffer"
? BadgePercent
: Images;
return (
<aside
@@ -45,13 +52,29 @@ export function CommercialActionCard({
</button>
</div>
<p className={styles.commercialActionCopy}>{action.copy}</p>
{activationError ? (
<p className={styles.commercialActionError} role="alert">
{activationError}
</p>
) : null}
<button
type="button"
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>
<ArrowRight size={17} aria-hidden="true" />
{activating ? (
<LoaderCircle className={styles.commercialActionSpinner} size={17} aria-hidden="true" />
) : (
<ArrowRight size={17} aria-hidden="true" />
)}
</button>
</aside>
);
+1
View File
@@ -6,6 +6,7 @@ export * from "./ai-disclosure-banner";
export * from "./browser-hint-overlay";
export * from "./chat-area";
export * from "./commercial-action-card";
export * from "./chat-action-card";
export * from "./chat-header";
export * from "./chat-insufficient-credits-banner";
export * from "./chat-input-bar";
+13 -1
View File
@@ -9,7 +9,7 @@
* - 用户:[占位 spacer] [Content] [Avatar]
*/
import { useUserSelector } from "@/stores/user/user-context";
import type { CommercialAction } from "@/data/schemas/chat";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
import { MessageAvatar } from "./message-avatar";
import { MessageContent } from "./message-content";
@@ -29,6 +29,7 @@ export interface MessageBubbleProps {
lockedPrivate?: boolean | null;
privateMessageHint?: string | null;
commercialAction?: CommercialAction | null;
chatAction?: ChatAction | null;
isUnlockingMessage?: boolean;
onUnlockPrivateMessage?: ChatMessageAction;
onUnlockVoiceMessage?: ChatMessageAction;
@@ -38,6 +39,9 @@ export interface MessageBubbleProps {
onCharacterAvatarClick?: () => void;
onCommercialAction?: (action: CommercialAction) => void;
onCommercialActionDismiss?: (action: CommercialAction) => void;
onChatActionViewed?: (action: ChatAction) => void;
onChatAction?: (action: ChatAction) => void | Promise<void>;
onChatActionDismiss?: (action: ChatAction) => void;
}
type ChatMessageAction = (
@@ -59,6 +63,7 @@ export function MessageBubble({
lockedPrivate,
privateMessageHint,
commercialAction,
chatAction,
isUnlockingMessage,
onUnlockPrivateMessage,
onUnlockVoiceMessage,
@@ -68,6 +73,9 @@ export function MessageBubble({
onCharacterAvatarClick,
onCommercialAction,
onCommercialActionDismiss,
onChatActionViewed,
onChatAction,
onChatActionDismiss,
}: MessageBubbleProps) {
const avatarUrl = useUserSelector((state) => state.context.avatarUrl);
@@ -97,6 +105,7 @@ export function MessageBubble({
lockedPrivate={lockedPrivate}
privateMessageHint={privateMessageHint}
commercialAction={commercialAction}
chatAction={chatAction}
isUnlockingMessage={isUnlockingMessage}
onUnlockPrivateMessage={onUnlockPrivateMessage}
onUnlockVoiceMessage={onUnlockVoiceMessage}
@@ -104,6 +113,9 @@ export function MessageBubble({
onOpenImage={onOpenImage}
onCommercialAction={onCommercialAction}
onCommercialActionDismiss={onCommercialActionDismiss}
onChatActionViewed={onChatActionViewed}
onChatAction={onChatAction}
onChatActionDismiss={onChatActionDismiss}
/>
<div className={styles.bubbleAvatarSpacer} aria-hidden="true" />
</div>
+18 -2
View File
@@ -1,6 +1,7 @@
"use client";
import type { CommercialAction } from "@/data/schemas/chat";
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
import { ChatActionCard } from "./chat-action-card";
import { CommercialActionCard } from "./commercial-action-card";
import { ImageBubble } from "./image-bubble";
import { LockedImageMessageCard } from "./locked-image-message-card";
@@ -23,6 +24,7 @@ export interface MessageContentProps {
lockedPrivate?: boolean | null;
privateMessageHint?: string | null;
commercialAction?: CommercialAction | null;
chatAction?: ChatAction | null;
isUnlockingMessage?: boolean;
onUnlockPrivateMessage?: ChatMessageAction;
onUnlockVoiceMessage?: ChatMessageAction;
@@ -30,6 +32,9 @@ export interface MessageContentProps {
onOpenImage?: (displayMessageId: string) => void;
onCommercialAction?: (action: CommercialAction) => void;
onCommercialActionDismiss?: (action: CommercialAction) => void;
onChatActionViewed?: (action: ChatAction) => void;
onChatAction?: (action: ChatAction) => void | Promise<void>;
onChatActionDismiss?: (action: ChatAction) => void;
}
type ChatMessageAction = (
@@ -53,6 +58,7 @@ export function MessageContent({
lockedPrivate,
privateMessageHint,
commercialAction,
chatAction,
isUnlockingMessage,
onUnlockPrivateMessage,
onUnlockVoiceMessage,
@@ -60,6 +66,9 @@ export function MessageContent({
onOpenImage,
onCommercialAction,
onCommercialActionDismiss,
onChatActionViewed,
onChatAction,
onChatActionDismiss,
}: MessageContentProps) {
const hasImage = imageUrl != null && imageUrl.length > 0;
const hasAudio = audioUrl != null && audioUrl.length > 0;
@@ -134,7 +143,14 @@ export function MessageContent({
) : null}
</>
)}
{isFromAI && commercialAction ? (
{isFromAI && chatAction ? (
<ChatActionCard
action={chatAction}
onViewed={onChatActionViewed}
onActivate={onChatAction}
onDismiss={onChatActionDismiss}
/>
) : isFromAI && commercialAction ? (
<CommercialActionCard
action={commercialAction}
onActivate={onCommercialAction}
@@ -14,9 +14,20 @@ vi.mock("@/stores/auth/auth-context", () => ({
vi.mock("@/stores/user/user-context", () => ({
useUserDispatch: () => vi.fn(),
useUserState: () => ({
currentUser: {
dailyFreeChatLimit: 30,
dailyFreePrivateLimit: 2,
currentUser: null,
entitlements: {
quotas: {
normalChatFreeDaily: 47,
privateUnlockFreeDaily: 5,
},
costs: {
normal_message: 3,
private_message: 9,
voice_message: 11,
photo: 13,
private_album_10: 101,
private_album_20: 181,
},
},
}),
}));
@@ -31,5 +42,11 @@ describe("CoinsRulesScreen", () => {
expect(html).toContain(
'href="/profile?returnTo=%2Fcharacters%2Fmaya%2Fchat"',
);
expect(html).toContain("47 free messages daily");
expect(html).toContain("5 free private messages daily");
expect(html).toContain("3 coins / message");
expect(html).toContain("10 photos / 101 coins");
expect(html).not.toContain("30 free messages daily");
expect(html).not.toContain("2 free private messages daily");
});
});
+58 -22
View File
@@ -19,10 +19,6 @@ import {
import { useAuthState } from "@/stores/auth/auth-context";
import { useUserDispatch, useUserState } from "@/stores/user/user-context";
import {
FREE_PRIVATE_MESSAGE_DAILY_COUNT,
FREE_STANDARD_CHAT_DAILY_COUNT,
} from "./coins-rules.constants";
import styles from "./coins-rules-screen.module.css";
interface CoinRuleItem {
@@ -35,25 +31,44 @@ interface CoinRuleItem {
const formatDailyFreeMessages = (count: number, label: string): string =>
`${Math.max(0, Math.trunc(count))} free ${label} daily`;
const formatCoinCost = (cost: number | null, unit: string): string =>
cost === null
? "Current rate shown at unlock"
: `${Math.max(0, Math.trunc(cost))} coins / ${unit}`;
const createCoinRules = (
dailyFreeChatLimit: number,
dailyFreePrivateLimit: number,
dailyFreeChatLimit: number | null,
dailyFreePrivateLimit: number | null,
costs: {
normalMessage: number | null;
privateMessage: number | null;
voiceMessage: number | null;
photo: number | null;
privateAlbum10: number | null;
privateAlbum20: number | null;
},
): readonly CoinRuleItem[] => [
{
title: "Standard Chat",
cost: "2 coins / message",
free: formatDailyFreeMessages(dailyFreeChatLimit, "messages"),
cost: formatCoinCost(costs.normalMessage, "message"),
free:
dailyFreeChatLimit === null
? "Current daily allowance loads from your account"
: formatDailyFreeMessages(dailyFreeChatLimit, "messages"),
icon: MessageCircle,
},
{
title: "Private Chat",
cost: "10 coins / message",
free: formatDailyFreeMessages(dailyFreePrivateLimit, "private messages"),
cost: formatCoinCost(costs.privateMessage, "message"),
free:
dailyFreePrivateLimit === null
? "Current daily allowance loads from your account"
: formatDailyFreeMessages(dailyFreePrivateLimit, "private messages"),
icon: Sparkles,
},
{
title: "Voice Message",
cost: "20 coins / message",
cost: formatCoinCost(costs.voiceMessage, "message"),
icon: Mic2,
},
// {
@@ -63,17 +78,23 @@ const createCoinRules = (
// },
{
title: "Photo",
cost: "40 coins / photo",
cost: formatCoinCost(costs.photo, "photo"),
icon: ImageIcon,
},
{
title: "Private Album",
cost: "10 photos / 300 coins",
cost:
costs.privateAlbum10 === null
? "Current price shown in Private Zone"
: `10 photos / ${Math.max(0, Math.trunc(costs.privateAlbum10))} coins`,
icon: ImageIcon,
},
{
title: "Private Album",
cost: "20 photos / 600 coins",
cost:
costs.privateAlbum20 === null
? "Current price shown in Private Zone"
: `20 photos / ${Math.max(0, Math.trunc(costs.privateAlbum20))} coins`,
icon: ImageIcon,
},
] as const;
@@ -87,20 +108,35 @@ export function CoinsRulesScreen({ returnTo }: CoinsRulesScreenProps) {
const authState = useAuthState();
const userState = useUserState();
const userDispatch = useUserDispatch();
const entitlements = userState.entitlements;
const dailyFreeChatLimit =
userState.currentUser?.dailyFreeChatLimit ?? FREE_STANDARD_CHAT_DAILY_COUNT;
entitlements?.quotas.normalChatFreeDaily ??
userState.currentUser?.dailyFreeChatLimit ??
null;
const dailyFreePrivateLimit =
entitlements?.quotas.privateUnlockFreeDaily ??
userState.currentUser?.dailyFreePrivateLimit ??
FREE_PRIVATE_MESSAGE_DAILY_COUNT;
const standardChatLabel = formatDailyFreeMessages(
null;
const standardChatLabel =
dailyFreeChatLimit === null
? "the current daily allowance shown for your account"
: formatDailyFreeMessages(dailyFreeChatLimit, "messages");
const privateChatLabel =
dailyFreePrivateLimit === null
? "the current private allowance shown for your account"
: formatDailyFreeMessages(dailyFreePrivateLimit, "private messages");
const coinRules = createCoinRules(
dailyFreeChatLimit,
"messages",
);
const privateChatLabel = formatDailyFreeMessages(
dailyFreePrivateLimit,
"private messages",
{
normalMessage: entitlements?.costs.normal_message ?? null,
privateMessage: entitlements?.costs.private_message ?? null,
voiceMessage: entitlements?.costs.voice_message ?? null,
photo: entitlements?.costs.photo ?? null,
privateAlbum10: entitlements?.costs.private_album_10 ?? null,
privateAlbum20: entitlements?.costs.private_album_20 ?? null,
},
);
const coinRules = createCoinRules(dailyFreeChatLimit, dailyFreePrivateLimit);
useEffect(() => {
if (!authState.hasInitialized || authState.isLoading) return;
@@ -1,2 +0,0 @@
export const FREE_STANDARD_CHAT_DAILY_COUNT = 30;
export const FREE_PRIVATE_MESSAGE_DAILY_COUNT = 2;
+1
View File
@@ -6,6 +6,7 @@
* `/external-entry?target=chat&mode=promotion&promotion_type=voice`
* `/external-entry?target=chat&character=maya`
* `/external-entry?target=tip`
* `/external-entry?target=private-zone&character=nayeli`
*
* 页面不直接 `redirect()`,而是把数据交给 Client 组件先写入本地存储,
* 再通过 `router.replace()` 清理 URL 并跳转到最终页面。
@@ -0,0 +1,67 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { PrivateZoneVideoPostCard } from "../private-zone-video-post-card";
const basePost = {
postId: "11111111-1111-1111-1111-111111111111",
characterId: "maya-tan",
caption: "Only for you.",
posterUrl: "https://storage.example/poster.jpg?token=short",
mediaType: "video" as const,
videoUrl: null,
videoMimeType: "video/mp4",
videoSizeBytes: 1024,
durationSeconds: 18,
unlockCostCredits: 100,
currency: "credits" as const,
locked: true,
unlocked: false,
availableForNewUnlock: true,
publishedAt: "2026-07-24T10:00:00+00:00",
};
describe("PrivateZoneVideoPostCard", () => {
it("shows caption and poster but no video source while locked", () => {
const html = renderToStaticMarkup(
<PrivateZoneVideoPostCard
post={basePost}
displayName="Maya"
avatarUrl="/images/avatar.png"
index={0}
isUnlocking={false}
onUnlock={() => undefined}
onPlaybackError={() => undefined}
/>,
);
expect(html).toContain("Only for you.");
expect(html).toContain("poster.jpg");
expect(html).toContain("Unlock for 100 credits");
expect(html).not.toContain("<video");
});
it("renders an inline controlled video only after unlock", () => {
const html = renderToStaticMarkup(
<PrivateZoneVideoPostCard
post={{
...basePost,
locked: false,
unlocked: true,
videoUrl: "https://storage.example/video.mp4?token=short",
}}
displayName="Maya"
avatarUrl="/images/avatar.png"
index={0}
isUnlocking={false}
onUnlock={() => undefined}
onPlaybackError={() => undefined}
/>,
);
expect(html).toContain("<video");
expect(html).toContain("controls");
expect(html).toContain("playsInline");
expect(html).not.toContain("autoplay");
});
});
+2
View File
@@ -1,4 +1,6 @@
export * from "./private-album-card";
export * from "./private-album-gallery";
export * from "./private-zone-video-post-card";
export * from "./status-card";
export * from "./unlock-confirm-dialog";
export * from "./video-post-unlock-dialog";
@@ -0,0 +1,125 @@
import type { CSSProperties } from "react";
import { LockKeyhole, Play } from "lucide-react";
import { CharacterAvatar } from "@/app/_components";
import type { PrivateZoneVideoPost } from "@/data/schemas/private-zone";
import styles from "../private-zone-screen.module.css";
export interface PrivateZoneVideoPostCardProps {
post: PrivateZoneVideoPost;
displayName: string;
avatarUrl: string;
index: number;
isUnlocking: boolean;
onUnlock: () => void;
onPlaybackError: () => void;
}
export function PrivateZoneVideoPostCard({
post,
displayName,
avatarUrl,
index,
isUnlocking,
onUnlock,
onPlaybackError,
}: PrivateZoneVideoPostCardProps) {
return (
<article
className={styles.postCard}
style={{ "--reveal-index": index } as CSSProperties}
>
<header className={styles.postHeader}>
<div className={styles.postAuthor}>
<CharacterAvatar
src={avatarUrl}
alt=""
size={38}
imageSize={38}
className={styles.postAvatar}
/>
<div>
<p className={styles.authorName}>{displayName}</p>
<p className={styles.authorSubline}>Private moment</p>
</div>
</div>
<time className={styles.postTime}>{formatMomentTime(post.publishedAt)}</time>
</header>
{post.caption ? <p className={styles.postText}>{post.caption}</p> : null}
{post.unlocked && post.videoUrl ? (
<video
className={styles.momentVideo}
controls
playsInline
preload="metadata"
poster={post.posterUrl ?? undefined}
onError={onPlaybackError}
>
<source src={post.videoUrl} type={post.videoMimeType || "video/mp4"} />
Your browser cannot play this video.
</video>
) : (
<div className={styles.momentLockedMedia}>
{post.posterUrl ? (
// Signed private media URLs intentionally bypass Next image optimization.
// eslint-disable-next-line @next/next/no-img-element
<img
className={styles.momentPoster}
src={post.posterUrl}
alt="Private video cover"
/>
) : (
<div className={styles.momentPosterFallback}>
<Play size={34} aria-hidden="true" />
</div>
)}
<div className={styles.momentLockPanel}>
<span className={styles.momentLockIcon} aria-hidden="true">
<LockKeyhole size={18} />
</span>
<strong>Private video</strong>
<span>
{post.durationSeconds == null
? "Unlock to watch"
: `${formatDuration(post.durationSeconds)} · Unlock to watch`}
</span>
<button
type="button"
data-analytics-key="private_zone_video.unlock"
data-analytics-label="Unlock Private Zone video moment"
disabled={isUnlocking || !post.availableForNewUnlock}
onClick={onUnlock}
>
{isUnlocking
? "Unlocking..."
: post.availableForNewUnlock
? `Unlock for ${post.unlockCostCredits} credits`
: "No longer available"}
</button>
</div>
</div>
)}
</article>
);
}
function formatDuration(seconds: number): string {
const safe = Math.max(0, Math.round(seconds));
const minutes = Math.floor(safe / 60);
const remainder = String(safe % 60).padStart(2, "0");
return `${minutes}:${remainder}`;
}
function formatMomentTime(value: string): string {
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return "Just now";
const seconds = Math.max(0, Math.floor((Date.now() - parsed.getTime()) / 1000));
if (seconds < 60) return "Just now";
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
if (seconds < 604800) return `${Math.floor(seconds / 86400)}d`;
return parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
@@ -0,0 +1,54 @@
import type { PrivateZoneVideoPost } from "@/data/schemas/private-zone";
import styles from "../private-zone-screen.module.css";
export interface VideoPostUnlockDialogProps {
post: PrivateZoneVideoPost;
isUnlocking: boolean;
errorMessage: string | null;
onCancel: () => void;
onConfirm: () => void;
}
export function VideoPostUnlockDialog({
post,
isUnlocking,
errorMessage,
onCancel,
onConfirm,
}: VideoPostUnlockDialogProps) {
return (
<div className={styles.dialogOverlay} role="alertdialog" aria-modal="true">
<div className={styles.dialog}>
<h2 className={styles.dialogTitle}>Unlock this private video?</h2>
<p className={styles.dialogCopy}>
You&apos;ll use {post.unlockCostCredits} credits. The video stays in your
Private Zone after unlocking.
</p>
{errorMessage ? (
<p className={styles.dialogError}>{errorMessage}</p>
) : null}
<div className={styles.dialogActions}>
<button
type="button"
className={styles.dialogSecondary}
disabled={isUnlocking}
onClick={onCancel}
>
Cancel
</button>
<button
type="button"
data-analytics-key="private_zone_video.unlock_confirm"
data-analytics-label="Confirm Private Zone video unlock"
className={styles.dialogPrimary}
disabled={isUnlocking}
onClick={onConfirm}
>
{isUnlocking ? "Unlocking..." : "Unlock"}
</button>
</div>
</div>
</div>
);
}
@@ -215,6 +215,38 @@
box-shadow: 0 8px 18px rgba(131, 72, 85, 0.08);
}
.contentTabs {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
margin-bottom: 18px;
padding: 5px;
border: 1px solid rgba(255, 116, 159, 0.14);
border-radius: 999px;
background: rgba(255, 255, 255, 0.72);
box-shadow: 0 10px 24px rgba(131, 72, 85, 0.07);
}
.contentTab {
min-height: 42px;
padding: 0 16px;
border: 0;
border-radius: 999px;
background: transparent;
color: #8a7078;
cursor: pointer;
font: inherit;
font-size: 14px;
font-weight: 850;
transition: background 0.18s ease, color 0.18s ease, box-shadow 0.18s ease;
}
.contentTabActive {
background: linear-gradient(135deg, #ff7aa9, #ffad79);
color: #ffffff;
box-shadow: 0 8px 18px rgba(248, 77, 150, 0.2);
}
.timeline {
display: flex;
flex-direction: column;
@@ -263,6 +295,118 @@
margin: 0;
}
.momentVideo,
.momentLockedMedia {
width: 100%;
margin-top: 14px;
border-radius: clamp(18px, 4.815vw, 26px);
background: #161316;
box-shadow: 0 16px 34px rgba(34, 25, 29, 0.16);
}
.momentVideo {
display: block;
max-height: 68vh;
aspect-ratio: 9 / 12;
object-fit: contain;
}
.momentLockedMedia {
position: relative;
aspect-ratio: 9 / 12;
overflow: hidden;
}
.momentPoster,
.momentPosterFallback {
display: block;
width: 100%;
height: 100%;
}
.momentPoster {
object-fit: cover;
}
.momentPosterFallback {
display: grid;
place-items: center;
background:
radial-gradient(circle at 70% 15%, rgba(255, 179, 109, 0.34), transparent 42%),
linear-gradient(145deg, #4f4249, #211b20);
color: rgba(255, 255, 255, 0.78);
}
.momentLockPanel {
position: absolute;
right: 14px;
bottom: 14px;
left: 14px;
display: flex;
min-height: 164px;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 7px;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 22px;
background: rgba(23, 19, 23, 0.7);
color: #ffffff;
text-align: center;
backdrop-filter: blur(14px);
}
.momentLockIcon {
display: grid;
width: 38px;
height: 38px;
place-items: center;
border-radius: 999px;
background: rgba(255, 255, 255, 0.16);
}
.momentLockPanel strong {
font-size: 20px;
font-weight: 900;
}
.momentLockPanel span:not(.momentLockIcon) {
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
font-weight: 650;
}
.momentLockPanel button,
.loadMoreButton {
min-height: 44px;
padding: 0 22px;
border: 0;
border-radius: 999px;
cursor: pointer;
font: inherit;
font-size: 14px;
font-weight: 850;
}
.momentLockPanel button {
margin-top: 9px;
background: #ffffff;
color: #2c2227;
}
.momentLockPanel button:disabled {
cursor: wait;
opacity: 0.7;
}
.loadMoreButton {
display: block;
margin: 16px auto 0;
background: rgba(255, 93, 149, 0.12);
color: #a94c64;
}
.authorName {
color: #26191d;
font-size: clamp(14px, 3.333vw, 17px);
@@ -776,6 +920,9 @@
}
.primaryCta:focus-visible,
.contentTab:focus-visible,
.momentLockPanel button:focus-visible,
.loadMoreButton:focus-visible,
.lockedPreviewCta:focus-visible,
.mediaGridItem:focus-visible,
.galleryClose:focus-visible,
+199 -37
View File
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
@@ -18,17 +18,24 @@ import {
useActiveCharacterRoutes,
} from "@/providers/character-provider";
import { isPrivateAlbumLocked } from "@/lib/private-zone/private_album";
import { behaviorAnalytics } from "@/lib/analytics";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import {
usePrivateZoneDispatch,
usePrivateZoneState,
} from "@/stores/private-zone";
import {
usePrivateZonePostDispatch,
usePrivateZonePostState,
} from "@/stores/private-zone-posts";
import {
PrivateAlbumCard,
PrivateAlbumGallery,
PrivateZoneVideoPostCard,
StatusCard,
UnlockConfirmDialog,
VideoPostUnlockDialog,
} from "./components";
import styles from "./private-zone-screen.module.css";
import {
@@ -54,11 +61,16 @@ export function PrivateZoneScreen() {
const authDispatch = useAuthDispatch();
const state = usePrivateZoneState();
const dispatch = usePrivateZoneDispatch();
const postState = usePrivateZonePostState();
const postDispatch = usePrivateZonePostDispatch();
const [activeTab, setActiveTab] = useState<"moments" | "albums">("moments");
const openedGalleryInPageRef = useRef(false);
const previousPostLoginStatusRef = useRef(authState.loginStatus);
const galleryState = useMemo(
() => getPrivateAlbumGalleryState(searchParams),
[searchParams],
);
const visibleTab = galleryState ? "albums" : activeTab;
usePrivateZoneBootstrapFlow({
authDispatch,
@@ -74,6 +86,56 @@ export function PrivateZoneScreen() {
unlockPaywallRequest: state.unlockPaywallRequest,
});
usePrivateZoneUnlockSuccessRefresh(state.unlockSuccessNonce);
usePrivateZoneUnlockSuccessRefresh(postState.unlockSuccessNonce);
useEffect(() => {
if (!authState.hasInitialized || authState.isLoading) return;
if (authState.loginStatus === "notLoggedIn") return;
const previous = previousPostLoginStatusRef.current;
previousPostLoginStatusRef.current = authState.loginStatus;
if (postState.status === "idle") {
postDispatch({ type: "PrivateZonePostInit" });
return;
}
if (previous !== authState.loginStatus && postState.status !== "loading") {
postDispatch({ type: "PrivateZonePostRefresh" });
}
}, [
authState.hasInitialized,
authState.isLoading,
authState.loginStatus,
postDispatch,
postState.status,
]);
useEffect(() => {
const request = postState.unlockPaywallRequest;
if (!request) return;
if (isPrivateZoneAuthRequired(authState.loginStatus)) {
navigator.openAuth(characterRoutes.privateZone);
} else {
behaviorAnalytics.paywallShown({
entryPoint: "private_zone",
triggerReason: "insufficient_credits",
});
navigator.openSubscription({
type: "topup",
returnTo: "private-zone",
analytics: {
entryPoint: "private_zone",
triggerReason: "insufficient_credits",
},
});
}
postDispatch({ type: "PrivateZonePostUnlockPaywallConsumed" });
}, [
authState.loginStatus,
characterRoutes.privateZone,
navigator,
postDispatch,
postState.unlockPaywallRequest,
]);
const displayName = character.displayName;
const avatarUrl = character.assets.avatar;
@@ -86,6 +148,13 @@ export function PrivateZoneScreen() {
) ?? null,
[state.items, state.pendingConfirmAlbumId],
);
const pendingPost = useMemo(
() =>
postState.items.find(
(post) => post.postId === postState.pendingConfirmPostId,
) ?? null,
[postState.items, postState.pendingConfirmPostId],
);
const galleryAlbum = useMemo(
() =>
galleryState
@@ -157,6 +226,14 @@ export function PrivateZoneScreen() {
);
};
const handlePostUnlock = (postId: string) => {
if (isPrivateZoneAuthRequired(authState.loginStatus)) {
navigator.openAuth(characterRoutes.privateZone);
return;
}
postDispatch({ type: "PrivateZonePostUnlockRequested", postId });
};
const handleCloseGallery = () => {
if (openedGalleryInPageRef.current) {
openedGalleryInPageRef.current = false;
@@ -235,49 +312,116 @@ export function PrivateZoneScreen() {
</section>
<section className={styles.postsSection} aria-labelledby="posts-title">
<div className={styles.contentTabs} role="tablist" aria-label="Private Zone content">
<button
type="button"
role="tab"
aria-selected={visibleTab === "moments"}
className={`${styles.contentTab} ${visibleTab === "moments" ? styles.contentTabActive : ""}`}
onClick={() => setActiveTab("moments")}
>
Moments
</button>
<button
type="button"
role="tab"
aria-selected={visibleTab === "albums"}
className={`${styles.contentTab} ${visibleTab === "albums" ? styles.contentTabActive : ""}`}
onClick={() => setActiveTab("albums")}
>
Albums
</button>
</div>
<div className={styles.sectionHeader}>
<div>
<p className={styles.kicker}>Albums</p>
<p className={styles.kicker}>{visibleTab === "moments" ? "Moments" : "Albums"}</p>
<h2 id="posts-title" className={styles.sectionTitle}>
Private albums
{visibleTab === "moments" ? "Private moments" : "Private albums"}
</h2>
</div>
<span className={styles.postCount}>{state.items.length}</span>
<span className={styles.postCount}>
{visibleTab === "moments" ? postState.items.length : state.items.length}
</span>
</div>
{state.errorMessage ? (
<StatusCard
message={state.errorMessage}
actionLabel="Retry"
onAction={() => dispatch({ type: "PrivateZoneRefresh" })}
/>
) : null}
{state.isLoading && state.items.length === 0 ? (
<StatusCard message="Loading private albums..." />
) : null}
<div className={styles.timeline}>
{state.items.map((album, index) => (
<PrivateAlbumCard
key={album.albumId}
album={album}
displayName={displayName}
avatarUrl={avatarUrl}
index={index}
isUnlocking={state.unlockingAlbumId === album.albumId}
onOpenGallery={(imageIndex) =>
handleOpenGallery(album.albumId, imageIndex)
}
onUnlock={() =>
dispatch({
type: "PrivateZoneUnlockRequested",
albumId: album.albumId,
})
}
/>
))}
</div>
{visibleTab === "moments" ? (
<>
{postState.errorMessage ? (
<StatusCard
message={postState.errorMessage}
actionLabel="Retry"
onAction={() => postDispatch({ type: "PrivateZonePostRefresh" })}
/>
) : null}
{postState.isLoading && postState.items.length === 0 ? (
<StatusCard message="Loading private moments..." />
) : null}
{!postState.isLoading && !postState.errorMessage && postState.items.length === 0 ? (
<StatusCard message="No private moments yet." />
) : null}
<div className={styles.timeline}>
{postState.items.map((post, index) => (
<PrivateZoneVideoPostCard
key={post.postId}
post={post}
displayName={displayName}
avatarUrl={avatarUrl}
index={index}
isUnlocking={postState.unlockingPostId === post.postId}
onUnlock={() => handlePostUnlock(post.postId)}
onPlaybackError={() =>
postDispatch({ type: "PrivateZonePostRefresh" })
}
/>
))}
</div>
{postState.hasMore ? (
<button
type="button"
className={styles.loadMoreButton}
disabled={postState.isLoadingMore}
onClick={() => postDispatch({ type: "PrivateZonePostLoadMore" })}
>
{postState.isLoadingMore ? "Loading..." : "Load more"}
</button>
) : null}
</>
) : (
<>
{state.errorMessage ? (
<StatusCard
message={state.errorMessage}
actionLabel="Retry"
onAction={() => dispatch({ type: "PrivateZoneRefresh" })}
/>
) : null}
{state.isLoading && state.items.length === 0 ? (
<StatusCard message="Loading private albums..." />
) : null}
<div className={styles.timeline}>
{state.items.map((album, index) => (
<PrivateAlbumCard
key={album.albumId}
album={album}
displayName={displayName}
avatarUrl={avatarUrl}
index={index}
isUnlocking={state.unlockingAlbumId === album.albumId}
onOpenGallery={(imageIndex) =>
handleOpenGallery(album.albumId, imageIndex)
}
onUnlock={() =>
dispatch({
type: "PrivateZoneUnlockRequested",
albumId: album.albumId,
})
}
/>
))}
</div>
</>
)}
</section>
<AppBottomNav
@@ -309,6 +453,24 @@ export function PrivateZoneScreen() {
</div>
) : null}
{pendingPost ? (
<VideoPostUnlockDialog
post={pendingPost}
isUnlocking={postState.isUnlocking}
errorMessage={postState.unlockErrorMessage}
onCancel={() =>
postDispatch({ type: "PrivateZonePostUnlockCancelled" })
}
onConfirm={() =>
postDispatch({ type: "PrivateZonePostUnlockConfirmed" })
}
/>
) : postState.unlockErrorMessage ? (
<div className={styles.toast} role="status">
{postState.unlockErrorMessage}
</div>
) : null}
{galleryAlbum &&
galleryState &&
!isPrivateAlbumLocked(galleryAlbum) &&
@@ -0,0 +1,267 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
const payment = {
status: "ready",
plans: [
{
planId: "vip_monthly",
planName: "Monthly",
orderType: "vip_monthly",
vipDays: 30,
dolAmount: null,
amountCents: 1990,
originalAmountCents: 3990,
currency: "USD",
},
{
planId: "vip_quarterly",
planName: "Quarterly",
orderType: "vip_quarterly",
vipDays: 90,
dolAmount: null,
amountCents: 4990,
originalAmountCents: 6990,
currency: "USD",
},
{
planId: "coin_1000",
planName: "1000 Coins",
orderType: "coins_1000",
vipDays: null,
dolAmount: 1000,
amountCents: 990,
originalAmountCents: null,
currency: "USD",
},
],
isFirstRecharge: false,
commercialOffer: null,
selectedPlanId: "vip_monthly",
payChannel: "stripe" as const,
agreed: true,
currentOrderId: null,
isCreatingOrder: false,
isPollingOrder: false,
isLoadingPlans: false,
};
const paymentDispatch = vi.fn((event: { type: string; planId?: string }) => {
if (event.type === "PaymentPlanSelected" && event.planId) {
payment.selectedPlanId = event.planId;
}
});
return { payment, paymentDispatch, planClick: vi.fn() };
});
vi.mock("@/app/_components", () => ({
BackButton: () => <button type="button">Back</button>,
}));
vi.mock("@/app/_components/core", () => ({
MobileShell: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
vi.mock("@/app/_components/payment/payment-method-selector", () => ({
PaymentMethodSelector: () => <div>Payment methods</div>,
}));
vi.mock("@/app/_hooks/use-payment-method-selection", () => ({
usePaymentMethodSelection: () => undefined,
}));
vi.mock("@/app/_hooks/use-payment-plan-analytics", () => ({
usePaymentPlanAnalytics: () => undefined,
}));
vi.mock("@/hooks/use-has-hydrated", () => ({
useHasHydrated: () => true,
}));
vi.mock("@/stores/user/user-context", () => ({
useUserState: () => ({ currentUser: { countryCode: "ID" } }),
}));
vi.mock("@/lib/payment/payment_method", () => ({
getPaymentMethodConfig: () => ({
initialPayChannel: "stripe",
showPaymentMethodSelector: true,
ezpayDisplayName: "QRIS",
}),
}));
vi.mock("@/lib/analytics", () => ({
behaviorAnalytics: { planClick: mocks.planClick },
getDefaultPaymentAnalyticsContext: () => ({}),
}));
vi.mock("../use-subscription-payment-flow", () => ({
useSubscriptionPaymentFlow: () => ({
payment: mocks.payment,
paymentDispatch: mocks.paymentDispatch,
showPaymentSuccessDialog: false,
handleBackClick: vi.fn(),
handlePaymentSuccessClose: vi.fn(),
}),
}));
vi.mock("../components", () => ({
SubscriptionVipOfferSection: ({
plans,
onSelectPlan,
}: {
plans: Array<{ id: string }>;
onSelectPlan: (id: string) => void;
}) => (
<div>
{plans.map((plan) => (
<button key={plan.id} type="button" onClick={() => onSelectPlan(plan.id)}>
{plan.id}
</button>
))}
</div>
),
SubscriptionCoinsOfferSection: ({
plans,
onSelectPlan,
}: {
plans: Array<{ id: string }>;
onSelectPlan: (id: string) => void;
}) => (
<div>
{plans.map((plan) => (
<button key={plan.id} type="button" onClick={() => onSelectPlan(plan.id)}>
{plan.id}
</button>
))}
</div>
),
SubscriptionCheckoutButton: ({ disabled }: { disabled: boolean }) => (
<button type="button" data-testid="checkout" disabled={disabled}>
Pay and Top Up
</button>
),
SubscriptionRenewalConfirmationDialog: ({
open,
onCancel,
onConfirm,
}: {
open: boolean;
onCancel: () => void;
onConfirm: () => void;
}) =>
open ? (
<div role="dialog">
<button type="button" onClick={onCancel}>Cancel</button>
<button type="button" onClick={onConfirm}>Confirm</button>
</div>
) : null,
SubscriptionPaymentIssueDialog: () => null,
SubscriptionPaymentSuccessDialog: () => null,
}));
import { SubscriptionScreen } from "../subscription-screen";
describe("SubscriptionScreen payment selection flow", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
mocks.payment.selectedPlanId = "vip_monthly";
mocks.paymentDispatch.mockClear();
mocks.planClick.mockClear();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("confirms VIP selection before enabling the separate checkout button", () => {
act(() => root.render(<SubscriptionScreen />));
const checkout = container.querySelector<HTMLButtonElement>(
'[data-testid="checkout"]',
);
expect(checkout?.disabled).toBe(true);
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
act(() => clickButton(container, "Confirm"));
expect(mocks.paymentDispatch).toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "vip_monthly",
});
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
expect(checkout?.disabled).toBe(false);
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
act(() => clickButton(container, "vip_quarterly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
expect(mocks.payment.selectedPlanId).toBe("vip_monthly");
});
it("keeps the original selection when VIP confirmation is cancelled", () => {
act(() => root.render(<SubscriptionScreen />));
act(() => clickButton(container, "vip_quarterly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
act(() => clickButton(container, "Cancel"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.payment.selectedPlanId).toBe("vip_monthly");
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "vip_quarterly",
});
});
it("requires VIP confirmation again after the page is remounted", () => {
act(() => root.render(<SubscriptionScreen />));
act(() => clickButton(container, "vip_monthly"));
act(() => clickButton(container, "Confirm"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
act(() => root.unmount());
root = createRoot(container);
act(() => root.render(<SubscriptionScreen />));
act(() => clickButton(container, "vip_monthly"));
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
});
it("selects a coin package without showing the renewal dialog", () => {
act(() => root.render(<SubscriptionScreen />));
act(() => clickButton(container, "coin_1000"));
expect(container.querySelector('[role="dialog"]')).toBeNull();
expect(mocks.paymentDispatch).toHaveBeenCalledWith({
type: "PaymentPlanSelected",
planId: "coin_1000",
});
expect(mocks.paymentDispatch).not.toHaveBeenCalledWith(
expect.objectContaining({ type: "PaymentCreateOrderSubmitted" }),
);
});
});
function clickButton(root: ParentNode, label: string): void {
const button = Array.from(root.querySelectorAll("button")).find(
(item) => item.textContent?.trim() === label,
);
if (!button) throw new Error(`Expected ${label} button`);
button.click();
}
@@ -7,9 +7,11 @@ import {
} from "@/data/schemas/payment";
import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan,
getDefaultSubscriptionPlanId,
getFirstRechargeOfferView,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews,
toVipOfferPlanViews,
} from "../subscription-screen.helpers";
@@ -277,4 +279,86 @@ describe("subscription screen helpers", () => {
}),
).toBeNull();
});
it("requires confirmation for each unconfirmed VIP plan", () => {
const vipPlans = [
{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "",
},
{
id: "vip_quarterly",
title: "Quarterly",
price: "49.90",
currency: "usd",
originalPrice: "",
},
];
expect(
requiresVipPlanConfirmation({
planId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(true);
expect(
requiresVipPlanConfirmation({
planId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(["vip_monthly"]),
}),
).toBe(false);
expect(
requiresVipPlanConfirmation({
planId: "coin_1000",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
});
it("allows checkout only after the selected VIP plan is confirmed", () => {
const vipPlans = [
{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "",
},
];
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "vip_monthly",
vipPlans,
confirmedVipPlanIds: new Set(["vip_monthly"]),
}),
).toBe(true);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "coin_1000",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(true);
expect(
canCheckoutSubscriptionPlan({
selectedPlanId: "",
vipPlans,
confirmedVipPlanIds: new Set(),
}),
).toBe(false);
});
});
@@ -0,0 +1,224 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Result } from "@/utils/result";
import { SubscriptionPaymentIssueDialog } from "../subscription-payment-issue-dialog";
import { SubscriptionRenewalConfirmationDialog } from "../subscription-renewal-confirmation-dialog";
const mocks = vi.hoisted(() => ({
submitFeedback: vi.fn(),
}));
vi.mock("@/lib/feedback", () => ({
submitFeedback: mocks.submitFeedback,
}));
vi.mock("@/app/feedback/feedback-context", () => ({
createFeedbackContext: () => ({
appVersion: "test",
platform: "web",
browser: "Chrome",
viewport: "390x844@3",
}),
}));
describe("subscription payment dialogs", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
mocks.submitFeedback.mockReset();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
document.body.querySelectorAll('[role="dialog"]').forEach((node) => node.remove());
});
it("confirms a VIP plan without submitting payment", () => {
const onConfirm = vi.fn();
const onCancel = vi.fn();
act(() =>
root.render(
<SubscriptionRenewalConfirmationDialog
open
plan={{
id: "vip_monthly",
title: "Monthly",
price: "19.90",
currency: "usd",
originalPrice: "39.90",
}}
onCancel={onCancel}
onConfirm={onConfirm}
/>,
),
);
const dialog = document.body.querySelector('[role="dialog"]');
expect(dialog?.textContent).toContain("Automatic Renewal Confirmation");
expect(dialog?.textContent).toContain("Monthly");
expect(dialog?.textContent).toContain("19.90 usd");
expect(dialog?.querySelectorAll("a")).toHaveLength(2);
act(() => clickButton(dialog, "Confirm"));
expect(onConfirm).toHaveBeenCalledOnce();
expect(onCancel).not.toHaveBeenCalled();
});
it("submits Other as a Manager payment issue with one description field", async () => {
mocks.submitFeedback.mockResolvedValue(
Result.ok({ feedbackId: "feedback-payment-1" }),
);
const onClose = vi.fn();
const onSubmitted = vi.fn();
act(() =>
root.render(
<SubscriptionPaymentIssueDialog
open
subscriptionType="vip"
planId="vip_monthly"
orderId={null}
payChannel="ezpay"
countryCode="ID"
characterId="maya"
onClose={onClose}
onSubmitted={onSubmitted}
/>,
),
);
const other = document.body.querySelector<HTMLInputElement>(
'input[value="other"]',
);
expect(
Array.from(document.body.querySelectorAll<HTMLInputElement>('input[type="radio"]')).map(
(input) => input.parentElement?.textContent?.trim(),
),
).toEqual([
"Concerned about card information security",
"Insufficient card or wallet balance",
"No supported payment method available",
"Too expensive",
"Other",
]);
act(() => {
other?.click();
});
const textarea = document.body.querySelector("textarea");
expect(textarea?.getAttribute("placeholder")).toBe(
"Please describe the payment problem you encountered.",
);
act(() => setTextareaValue(textarea, "QRIS did not open correctly."));
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(mocks.submitFeedback).toHaveBeenCalledWith({
category: "payment",
content: "Payment issue: Other\nDetails: QRIS did not open correctly.",
context: {
appVersion: "test",
platform: "web",
browser: "Chrome",
viewport: "390x844@3",
sourcePage: "subscription",
paymentIssueReason: "other",
subscriptionType: "vip",
planId: "vip_monthly",
payChannel: "ezpay",
countryCode: "ID",
characterId: "maya",
},
images: [],
idempotencyKey: expect.stringMatching(/^payment_feedback_[A-Za-z0-9_-]+$/),
});
expect(onSubmitted).toHaveBeenCalledWith(
"Thanks. Your payment issue has been submitted.",
);
expect(onClose).toHaveBeenCalledOnce();
});
it("keeps a failed payment issue open and reuses its idempotency key for retry", async () => {
mocks.submitFeedback
.mockResolvedValueOnce(Result.err(new Error("backend unavailable")))
.mockResolvedValueOnce(Result.ok({ feedbackId: "feedback-payment-2" }));
const onClose = vi.fn();
act(() =>
root.render(
<SubscriptionPaymentIssueDialog
open
subscriptionType="topup"
planId="coin_1000"
orderId="pay_pending_1"
payChannel="stripe"
countryCode="US"
characterId="elio"
onClose={onClose}
onSubmitted={() => undefined}
/>,
),
);
const reason = document.body.querySelector<HTMLInputElement>(
'input[value="tooExpensive"]',
);
act(() => reason?.click());
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(document.body.textContent).toContain(
"Unable to submit. Please try again.",
);
expect(onClose).not.toHaveBeenCalled();
await act(async () => {
clickButton(document.body, "Submit");
await Promise.resolve();
await Promise.resolve();
});
expect(mocks.submitFeedback).toHaveBeenCalledTimes(2);
expect(mocks.submitFeedback.mock.calls[0]?.[0].idempotencyKey).toBe(
mocks.submitFeedback.mock.calls[1]?.[0].idempotencyKey,
);
expect(onClose).toHaveBeenCalledOnce();
});
});
function clickButton(root: ParentNode | null, label: string): void {
const button = Array.from(root?.querySelectorAll("button") ?? []).find(
(item) => item.textContent?.trim() === label,
);
if (!button) throw new Error(`Expected ${label} button`);
button.click();
}
function setTextareaValue(
element: HTMLTextAreaElement | null,
value: string,
): void {
if (!element) throw new Error("Expected textarea");
const setter = Object.getOwnPropertyDescriptor(
HTMLTextAreaElement.prototype,
"value",
)?.set;
setter?.call(element, value);
element.dispatchEvent(new Event("input", { bubbles: true }));
}
+2
View File
@@ -6,4 +6,6 @@ export * from "./subscription-checkout-button";
export * from "./subscription-coins-offer-section";
export * from "./subscription-cta-button";
export * from "./subscription-payment-success-dialog";
export * from "./subscription-payment-issue-dialog";
export * from "./subscription-renewal-confirmation-dialog";
export * from "./subscription-vip-offer-section";
@@ -19,7 +19,7 @@ import { SubscriptionCtaButton } from "./subscription-cta-button";
const log = new Logger("SubscriptionCheckoutButton");
export interface SubscriptionCheckoutButtonProps {
/** 是否可用(未选套餐 / 未勾选协议 → false */
/** 是否可用(未选套餐或 VIP 套餐尚未确认自动续费时为 false */
disabled?: boolean;
subscriptionType: "vip" | "topup";
returnTo?: SubscriptionReturnTo;
@@ -44,22 +44,13 @@ export function SubscriptionCheckoutButton({
subscriptionType,
});
const isLoading =
payment.isCreatingOrder ||
payment.isPollingOrder;
const readyLabel =
subscriptionType === "topup" ? "Pay and Top Up" : "Pay and Activiate";
const agreementLabel =
subscriptionType === "topup"
? "Confirm the agreement and Top Up"
: "Confirm the agreement and Activate";
const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
const readyLabel = "Pay and Top Up";
const label = payment.isPollingOrder
? "Processing payment..."
: payment.isCreatingOrder
? "Creating order..."
: payment.agreed
? readyLabel
: agreementLabel;
? "Processing payment..."
: payment.isCreatingOrder
? "Creating order..."
: readyLabel;
const handleClick = () => {
if (disabled || isLoading) return;
@@ -0,0 +1,187 @@
.scrim {
position: fixed;
inset: 0;
z-index: 90;
display: flex;
align-items: center;
justify-content: center;
padding:
calc(20px + var(--app-safe-top, 0px))
calc(16px + var(--app-safe-right, 0px))
calc(20px + var(--app-safe-bottom, 0px))
calc(16px + var(--app-safe-left, 0px));
}
.panel {
width: min(100%, 420px);
max-height: min(86dvh, 720px);
overflow-y: auto;
border: 1px solid rgba(255, 95, 174, 0.24);
border-radius: 24px;
background: #ffffff;
color: #23171d;
box-shadow: 0 28px 80px rgba(42, 20, 31, 0.3);
}
.content {
display: flex;
flex-direction: column;
gap: 16px;
padding: clamp(20px, 5vw, 28px);
}
.title {
margin: 0;
color: #23171d;
font-size: clamp(20px, 5vw, 24px);
font-weight: 900;
line-height: 1.2;
}
.description {
margin: 0;
color: #65545d;
font-size: 14px;
line-height: 1.65;
}
.link {
color: #db327f;
font-weight: 800;
text-decoration: underline;
text-underline-offset: 2px;
}
.reasonList {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding: 0;
border: 0;
}
.reasonOption {
display: flex;
min-height: 48px;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 11px 13px;
border: 1px solid #eadce3;
border-radius: 14px;
background: #fffafb;
color: #403139;
cursor: pointer;
font-size: 14px;
font-weight: 700;
line-height: 1.35;
}
.reasonOption:has(input:checked) {
border-color: #f657a0;
background: #fff0f7;
box-shadow: 0 0 0 2px rgba(246, 87, 160, 0.12);
}
.reasonOption input {
flex: 0 0 auto;
width: 20px;
height: 20px;
accent-color: #f657a0;
}
.field {
display: flex;
flex-direction: column;
gap: 8px;
color: #403139;
font-size: 14px;
font-weight: 800;
}
.field textarea {
width: 100%;
min-height: 112px;
resize: vertical;
border: 1px solid #dccbd4;
border-radius: 14px;
background: #ffffff;
color: #23171d;
padding: 12px;
font: inherit;
font-weight: 500;
line-height: 1.5;
}
.field textarea:focus-visible {
border-color: #f657a0;
outline: 2px solid rgba(246, 87, 160, 0.18);
}
.error {
margin: 0;
color: #b42318;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 2px;
}
.secondaryButton,
.primaryButton {
min-height: 46px;
border-radius: 999px;
padding: 10px 18px;
cursor: pointer;
font: inherit;
font-size: 15px;
font-weight: 900;
}
.secondaryButton {
border: 1px solid #d9c7d0;
background: #f7f1f4;
color: #55434c;
}
.primaryButton {
border: 0;
background: linear-gradient(135deg, #ff67b3 0%, #f657a0 100%);
color: #ffffff;
box-shadow: 0 8px 20px rgba(246, 87, 160, 0.26);
}
.secondaryButton:disabled,
.primaryButton:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.srOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 360px) {
.content {
padding: 18px;
}
.reasonOption {
font-size: 13px;
}
}
@@ -0,0 +1,215 @@
"use client";
import { type FormEvent, useMemo, useState } from "react";
import { ModalPortal } from "@/app/_components/core/modal-portal";
import { createFeedbackContext } from "@/app/feedback/feedback-context";
import type { PayChannel } from "@/data/schemas/payment";
import { submitFeedback } from "@/lib/feedback";
import type { SubscriptionType } from "../subscription-screen.helpers";
import styles from "./subscription-dialog.module.css";
const PAYMENT_ISSUE_REASONS = [
{
value: "cardSecurityConcern",
label: "Concerned about card information security",
},
{
value: "insufficientBalance",
label: "Insufficient card or wallet balance",
},
{
value: "unsupportedPaymentMethod",
label: "No supported payment method available",
},
{ value: "tooExpensive", label: "Too expensive" },
{ value: "other", label: "Other" },
] as const;
type PaymentIssueReason = (typeof PAYMENT_ISSUE_REASONS)[number]["value"];
const OTHER_DETAILS_MIN_LENGTH = 10;
const OTHER_DETAILS_MAX_LENGTH = 2000;
const SUCCESS_MESSAGE = "Thanks. Your payment issue has been submitted.";
const FAILURE_MESSAGE = "Unable to submit. Please try again.";
export interface SubscriptionPaymentIssueDialogProps {
open: boolean;
subscriptionType: SubscriptionType;
planId: string | null;
orderId: string | null;
payChannel: PayChannel;
countryCode?: string | null;
characterId: string;
onClose: () => void;
onSubmitted: (message: string) => void;
}
export function SubscriptionPaymentIssueDialog({
open,
subscriptionType,
planId,
orderId,
payChannel,
countryCode,
characterId,
onClose,
onSubmitted,
}: SubscriptionPaymentIssueDialogProps) {
const [reason, setReason] = useState<PaymentIssueReason | null>(null);
const [details, setDetails] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [idempotencyKey] = useState(createIdempotencyKey);
const normalizedDetails = details.trim();
const detailsError = useMemo(() => {
if (reason !== "other") return null;
if (normalizedDetails.length < OTHER_DETAILS_MIN_LENGTH) {
return `Please describe the issue in at least ${OTHER_DETAILS_MIN_LENGTH} characters.`;
}
if (normalizedDetails.length > OTHER_DETAILS_MAX_LENGTH) {
return `Your description cannot exceed ${OTHER_DETAILS_MAX_LENGTH} characters.`;
}
return null;
}, [normalizedDetails, reason]);
const canSubmit = reason !== null && detailsError === null && !isSubmitting;
const handleClose = () => {
if (isSubmitting) return;
onClose();
};
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!reason || !canSubmit) {
setErrorMessage(
detailsError ?? "Please select the payment problem you encountered.",
);
return;
}
const reasonLabel = PAYMENT_ISSUE_REASONS.find(
(item) => item.value === reason,
)?.label;
if (!reasonLabel) return;
setIsSubmitting(true);
setErrorMessage(null);
const result = await submitFeedback({
category: "payment",
content:
reason === "other"
? `Payment issue: Other\nDetails: ${normalizedDetails}`
: `Payment issue: ${reasonLabel}`,
context: {
...createFeedbackContext(),
sourcePage: "subscription",
paymentIssueReason: reason,
subscriptionType,
...(planId ? { planId } : {}),
...(orderId ? { orderId } : {}),
payChannel,
...(countryCode ? { countryCode } : {}),
characterId,
},
images: [],
idempotencyKey,
});
if (!result.success) {
setErrorMessage(FAILURE_MESSAGE);
setIsSubmitting(false);
return;
}
setIsSubmitting(false);
onSubmitted(SUCCESS_MESSAGE);
onClose();
};
return (
<ModalPortal
open={open}
onClose={handleClose}
scrimClassName={styles.scrim}
panelClassName={styles.panel}
scrimOpacity={0.56}
persistent={isSubmitting}
ariaLabel="What problem did you encounter?"
>
<form className={styles.content} onSubmit={handleSubmit}>
<h2 className={styles.title}>What problem did you encounter?</h2>
<fieldset className={styles.reasonList} disabled={isSubmitting}>
<legend className={styles.srOnly}>Payment problem</legend>
{PAYMENT_ISSUE_REASONS.map((item) => (
<label key={item.value} className={styles.reasonOption}>
<span>{item.label}</span>
<input
type="radio"
name="paymentIssueReason"
value={item.value}
checked={reason === item.value}
onChange={() => {
setReason(item.value);
setErrorMessage(null);
}}
/>
</label>
))}
</fieldset>
{reason === "other" ? (
<label className={styles.field}>
<span>Please describe the issue</span>
<textarea
value={details}
minLength={OTHER_DETAILS_MIN_LENGTH}
maxLength={OTHER_DETAILS_MAX_LENGTH}
rows={4}
disabled={isSubmitting}
placeholder="Please describe the payment problem you encountered."
onChange={(event) => {
setDetails(event.target.value);
setErrorMessage(null);
}}
/>
</label>
) : null}
{errorMessage ? (
<p className={styles.error} role="alert">
{errorMessage}
</p>
) : null}
<div className={styles.actions}>
<button
type="button"
className={styles.secondaryButton}
disabled={isSubmitting}
onClick={handleClose}
>
Cancel
</button>
<button
type="submit"
className={styles.primaryButton}
disabled={!canSubmit}
>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
</div>
</form>
</ModalPortal>
);
}
function createIdempotencyKey(): string {
const token =
typeof crypto !== "undefined" && "randomUUID" in crypto
? crypto.randomUUID()
: `${Date.now()}_${Math.random().toString(36).slice(2)}`;
return `payment_feedback_${token}`;
}
@@ -0,0 +1,83 @@
"use client";
import { ModalPortal } from "@/app/_components/core/modal-portal";
import { AppConstants } from "@/core/app_constants";
import type { VipOfferPlanView } from "./subscription-vip-offer-section";
import styles from "./subscription-dialog.module.css";
export interface SubscriptionRenewalConfirmationDialogProps {
open: boolean;
plan: VipOfferPlanView | null;
onCancel: () => void;
onConfirm: () => void;
}
export function SubscriptionRenewalConfirmationDialog({
open,
plan,
onCancel,
onConfirm,
}: SubscriptionRenewalConfirmationDialogProps) {
return (
<ModalPortal
open={open && plan !== null}
onClose={onCancel}
scrimClassName={styles.scrim}
panelClassName={styles.panel}
scrimOpacity={0.56}
ariaLabel="Automatic Renewal Confirmation"
>
{plan ? (
<div className={styles.content}>
<h2 className={styles.title}>Automatic Renewal Confirmation</h2>
<p className={styles.description}>
You selected the <strong>{plan.title}</strong> plan for{" "}
<strong>
{plan.price} {plan.currency}
</strong>
. It will renew automatically at the applicable renewal price until
you cancel.
</p>
<p className={styles.description}>
By confirming, you agree to the{" "}
<a
href={AppConstants.membershipAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.link}
>
VIP Membership Benefits Agreement
</a>{" "}
and{" "}
<a
href={AppConstants.autoRenewalAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.link}
>
Automatic Renewal Agreement
</a>
.
</p>
<div className={styles.actions}>
<button
type="button"
className={styles.secondaryButton}
onClick={onCancel}
>
Cancel
</button>
<button
type="button"
className={styles.primaryButton}
onClick={onConfirm}
>
Confirm
</button>
</div>
</div>
) : null}
</ModalPortal>
);
}
@@ -8,13 +8,15 @@
padding:
calc(var(--page-padding-y, 18px) + var(--app-safe-top, 0px))
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
calc(10px + var(--app-safe-bottom, 0px))
calc(104px + var(--app-safe-bottom, 0px))
calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
height: 40px;
}
@@ -22,6 +24,43 @@
display: inline-flex;
}
.paymentIssueButton {
border: 0;
background: transparent;
color: #b72f70;
cursor: pointer;
font: inherit;
font-size: var(--responsive-caption, 13px);
font-weight: 800;
text-decoration: underline;
text-underline-offset: 3px;
}
.paymentIssueButton:focus-visible {
border-radius: 6px;
outline: 2px solid #f657a0;
outline-offset: 3px;
}
.paymentIssueNotice {
position: fixed;
z-index: 80;
top: calc(68px + var(--app-safe-top, 0px));
left: 50%;
width: min(calc(100% - 40px), 500px);
margin: 0;
padding: 10px 12px;
border: 1px solid rgba(39, 174, 96, 0.3);
border-radius: 14px;
background: rgba(236, 253, 245, 0.96);
color: #166534;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
transform: translateX(-50%);
box-shadow: 0 12px 30px rgba(22, 101, 52, 0.12);
}
.firstRechargeBanner {
display: flex;
align-items: center;
@@ -129,24 +168,23 @@
}
.ctaSlot {
margin-top: var(--page-section-gap-lg, 22px);
}
.agreementSlot {
margin-top: var(--spacing-md);
padding: 0 var(--spacing-xs);
}
.agreementLabel {
font-size: var(--responsive-micro, 12px);
}
.agreementLink {
color: var(--color-auth-text-primary);
font-weight: 700;
text-decoration: none;
}
.agreementLink:hover {
text-decoration: underline;
position: fixed;
z-index: 40;
right: 50%;
bottom: 0;
width: min(100%, var(--app-max-width, 540px));
padding:
12px
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
calc(12px + var(--app-safe-bottom, 0px))
calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
border-top: 1px solid rgba(246, 87, 160, 0.14);
background: linear-gradient(
180deg,
rgba(255, 255, 255, 0.72) 0%,
rgba(255, 249, 252, 0.98) 35%
);
box-shadow: 0 -12px 30px rgba(87, 35, 59, 0.1);
backdrop-filter: blur(16px);
transform: translateX(50%);
}
+10
View File
@@ -32,6 +32,12 @@ export default async function SubscriptionPage({
const sourceCharacterSlug =
getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ??
DEFAULT_CHARACTER_SLUG;
const initialPlanId = getFirstPaymentSearchParam(query.planId);
const commercialOfferId = getFirstPaymentSearchParam(
query.commercialOfferId,
);
const resumeOrderId = getFirstPaymentSearchParam(query.resumeOrderId);
const chatActionId = getFirstPaymentSearchParam(query.chatActionId);
const analyticsContext = parsePaymentAnalyticsContext({
entryPoint: getFirstPaymentSearchParam(
query[PAYMENT_ANALYTICS_ENTRY_PARAM],
@@ -50,6 +56,10 @@ export default async function SubscriptionPage({
initialPayChannel={paymentReturn.initialPayChannel}
analyticsContext={analyticsContext}
sourceCharacterSlug={sourceCharacterSlug}
initialPlanId={initialPlanId}
commercialOfferId={commercialOfferId}
resumeOrderId={resumeOrderId}
chatActionId={chatActionId}
/>
);
}
@@ -105,6 +105,30 @@ export function findSelectedSubscriptionPlan(input: {
return plans.find((plan) => plan.id === input.selectedPlanId) ?? null;
}
export function requiresVipPlanConfirmation(input: {
planId: string;
vipPlans: readonly VipOfferPlanView[];
confirmedVipPlanIds: ReadonlySet<string>;
}): boolean {
return (
input.vipPlans.some((plan) => plan.id === input.planId) &&
!input.confirmedVipPlanIds.has(input.planId)
);
}
export function canCheckoutSubscriptionPlan(input: {
selectedPlanId: string;
vipPlans: readonly VipOfferPlanView[];
confirmedVipPlanIds: ReadonlySet<string>;
}): boolean {
if (!input.selectedPlanId) return false;
return !requiresVipPlanConfirmation({
planId: input.selectedPlanId,
vipPlans: input.vipPlans,
confirmedVipPlanIds: input.confirmedVipPlanIds,
});
}
export function getDefaultSubscriptionPlanId(input: {
canSubscribeVip: boolean;
selectedPlanId: string;
+116 -35
View File
@@ -1,12 +1,11 @@
"use client";
import { useEffect, useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import { BackButton } from "@/app/_components";
import { Checkbox, MobileShell } from "@/app/_components/core";
import { MobileShell } from "@/app/_components/core";
import { PaymentMethodSelector } from "@/app/_components/payment/payment-method-selector";
import { usePaymentMethodSelection } from "@/app/_hooks/use-payment-method-selection";
import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics";
import { AppConstants } from "@/core/app_constants";
import type { PayChannel } from "@/data/schemas/payment";
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
@@ -21,14 +20,18 @@ import { useUserState } from "@/stores/user/user-context";
import {
SubscriptionCheckoutButton,
SubscriptionCoinsOfferSection,
SubscriptionPaymentIssueDialog,
SubscriptionPaymentSuccessDialog,
SubscriptionRenewalConfirmationDialog,
SubscriptionVipOfferSection,
} from "./components";
import styles from "./components/subscription-screen.module.css";
import {
canCheckoutSubscriptionPlan,
findSelectedSubscriptionPlan,
getFirstRechargeOfferView,
getDefaultSubscriptionPlanId,
requiresVipPlanConfirmation,
toCoinsOfferPlanViews,
toVipOfferPlanViews,
type SubscriptionType,
@@ -44,6 +47,10 @@ export interface SubscriptionScreenProps {
initialPayChannel?: PayChannel | null;
analyticsContext?: PaymentAnalyticsContext;
sourceCharacterSlug?: string;
initialPlanId?: string | null;
commercialOfferId?: string | null;
resumeOrderId?: string | null;
chatActionId?: string | null;
}
export function SubscriptionScreen({
@@ -53,7 +60,19 @@ export function SubscriptionScreen({
initialPayChannel = null,
analyticsContext: providedAnalyticsContext,
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
initialPlanId = null,
commercialOfferId = null,
resumeOrderId = null,
chatActionId = null,
}: SubscriptionScreenProps) {
const [confirmedVipPlanIds, setConfirmedVipPlanIds] = useState<
ReadonlySet<string>
>(() => new Set());
const [pendingVipPlanId, setPendingVipPlanId] = useState<string | null>(null);
const [showPaymentIssueDialog, setShowPaymentIssueDialog] = useState(false);
const [paymentIssueNotice, setPaymentIssueNotice] = useState<string | null>(
null,
);
const userState = useUserState();
const countryCode = userState.currentUser?.countryCode;
const paymentMethodConfig = getPaymentMethodConfig({
@@ -72,6 +91,10 @@ export function SubscriptionScreen({
returnTo,
sourceCharacterSlug,
initialPayChannel: paymentMethodConfig.initialPayChannel,
initialPlanId,
commercialOfferId,
resumeOrderId,
chatActionId,
});
const canSubscribeVip = subscriptionType === "vip";
const analyticsContext =
@@ -122,15 +145,48 @@ export function SubscriptionScreen({
const isPaymentBusy =
payment.isCreatingOrder ||
payment.isPollingOrder;
const selectedPlanIsVip = vipOfferPlans.some(
(plan) => plan.id === payment.selectedPlanId,
);
const canActivate =
selectedPlan !== null && payment.agreed && !isPaymentBusy;
selectedPlan !== null &&
canCheckoutSubscriptionPlan({
selectedPlanId: payment.selectedPlanId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
}) &&
!isPaymentBusy;
const pendingVipPlan =
vipOfferPlans.find((plan) => plan.id === pendingVipPlanId) ?? null;
const handleSelectPlan = (planId: string) => {
const plan = payment.plans.find((item) => item.planId === planId);
if (plan) behaviorAnalytics.planClick(plan, analyticsContext);
if (
requiresVipPlanConfirmation({
planId,
vipPlans: vipOfferPlans,
confirmedVipPlanIds,
})
) {
setPendingVipPlanId(planId);
return;
}
paymentDispatch({ type: "PaymentPlanSelected", planId });
};
const handleConfirmVipPlan = () => {
if (!pendingVipPlanId) return;
const planId = pendingVipPlanId;
setConfirmedVipPlanIds((current) => {
const next = new Set(current);
next.add(planId);
return next;
});
paymentDispatch({ type: "PaymentPlanSelected", planId });
setPendingVipPlanId(null);
};
const handlePaymentMethodChange = (payChannel: PayChannel) => {
paymentDispatch({
type: "PaymentPayChannelChanged",
@@ -183,8 +239,24 @@ export function SubscriptionScreen({
variant="soft"
analyticsKey="subscription.back"
/>
<button
type="button"
className={styles.paymentIssueButton}
onClick={() => {
setPaymentIssueNotice(null);
setShowPaymentIssueDialog(true);
}}
>
Payment issue?
</button>
</header>
{paymentIssueNotice ? (
<p className={styles.paymentIssueNotice} role="status">
{paymentIssueNotice}
</p>
) : null}
{firstRechargeOffer ? (
<section
className={styles.firstRechargeBanner}
@@ -209,6 +281,22 @@ export function SubscriptionScreen({
</section>
) : 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}>
{canSubscribeVip ? (
<SubscriptionVipOfferSection
@@ -243,39 +331,32 @@ export function SubscriptionScreen({
/>
</div>
<div className={styles.agreementSlot}>
<Checkbox
checked={payment.agreed}
onChange={(agreed) =>
paymentDispatch({
type: "PaymentAgreementChanged",
agreed,
})
}
label={
<span className={styles.agreementLabel}>
I agree to the{" "}
<a
href={AppConstants.membershipAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.agreementLink}
>
VIP Membership Benefits Agreement
</a>{" "}
and{" "}
<a
href={AppConstants.autoRenewalAgreementUrl}
target="_blank"
rel="noreferrer"
className={styles.agreementLink}
>
Automatic renewal Agreement
</a>
</span>
<SubscriptionRenewalConfirmationDialog
open={pendingVipPlan !== null}
plan={pendingVipPlan}
onCancel={() => setPendingVipPlanId(null)}
onConfirm={handleConfirmVipPlan}
/>
{showPaymentIssueDialog ? (
<SubscriptionPaymentIssueDialog
open
subscriptionType={
selectedPlan
? selectedPlanIsVip
? "vip"
: "topup"
: subscriptionType
}
planId={selectedPlan?.id ?? null}
orderId={payment.currentOrderId}
payChannel={payment.payChannel}
countryCode={countryCode}
characterId={sourceCharacterSlug}
onClose={() => setShowPaymentIssueDialog(false)}
onSubmitted={setPaymentIssueNotice}
/>
</div>
) : null}
<SubscriptionPaymentSuccessDialog
open={showPaymentSuccessDialog}
@@ -20,6 +20,10 @@ export interface UseSubscriptionPaymentFlowInput {
returnTo: SubscriptionReturnTo;
initialPayChannel: PayChannel;
sourceCharacterSlug?: string;
initialPlanId?: string | null;
commercialOfferId?: string | null;
resumeOrderId?: string | null;
chatActionId?: string | null;
}
export function useSubscriptionPaymentFlow({
@@ -28,12 +32,20 @@ export function useSubscriptionPaymentFlow({
returnTo,
initialPayChannel,
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
initialPlanId = null,
commercialOfferId = null,
resumeOrderId = null,
chatActionId = null,
}: UseSubscriptionPaymentFlowInput) {
const router = useRouter();
const { payment, paymentDispatch } = usePaymentRouteFlow({
initialPayChannel,
paymentType: subscriptionType,
shouldResumePendingOrder,
initialPlanId,
commercialOfferId,
resumeOrderId,
chatActionId,
});
const successDialogShownOrderRef = useRef<string | null>(null);
const [showPaymentSuccessDialog, setShowPaymentSuccessDialog] =
@@ -358,6 +358,7 @@ function makePaymentState(
giftProducts: [giftProduct],
selectedGiftCategory: giftCategory.category,
isFirstRecharge: false,
commercialOffer: null,
selectedPlanId: giftPlan.planId,
payChannel: "stripe",
autoRenew: false,
+3
View File
@@ -39,6 +39,7 @@ export interface TipScreenProps {
initialPlanId?: string | null;
shouldResumePendingOrder?: boolean;
initialPayChannel?: PayChannel | null;
chatActionId?: string | null;
}
export function TipScreen({
@@ -46,6 +47,7 @@ export function TipScreen({
initialPlanId = null,
shouldResumePendingOrder = false,
initialPayChannel = null,
chatActionId = null,
}: TipScreenProps) {
const character = useActiveCharacter();
const characterRoutes = useActiveCharacterRoutes();
@@ -63,6 +65,7 @@ export function TipScreen({
initialPayChannel: paymentMethodConfig.initialPayChannel,
paymentType: "tip",
shouldResumePendingOrder,
chatActionId,
});
const selectedCategory =
@@ -0,0 +1,139 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { VoiceCallTransport } from "@/core/net/voice-call-transport";
class FakeWebSocket {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSED = 3;
readyState = FakeWebSocket.CONNECTING;
binaryType = "blob";
sent: unknown[] = [];
onopen: (() => void) | null = null;
onmessage: ((event: { data: unknown }) => void) | null = null;
onclose: ((event: { code: number; reason: string; wasClean: boolean }) => void) | null = null;
onerror: (() => void) | null = null;
constructor(readonly url: string) {}
send(data: unknown) { this.sent.push(data); }
close() { this.readyState = FakeWebSocket.CLOSED; }
open() { this.readyState = FakeWebSocket.OPEN; this.onopen?.(); }
receive(data: unknown) { this.onmessage?.({ data }); }
}
describe("VoiceCallTransport", () => {
let sockets: FakeWebSocket[];
beforeEach(() => {
sockets = [];
});
afterEach(() => {
vi.useRealTimers();
});
function create() {
return new VoiceCallTransport("wss://api.example/ws", "secret-token", {
webSocketFactory: (url) => {
const socket = new FakeWebSocket(url);
sockets.push(socket);
return socket as unknown as WebSocket;
},
});
}
it("uploads 100-200ms chunks as binary frames instead of base64 JSON", () => {
const transport = create();
transport.connect();
sockets[0].open();
transport.startCall("elio", "turn-1");
transport.startAudio("call-1", "turn-1", "audio/webm;codecs=opus", 48000);
const frame = new Uint8Array([1, 2, 3]).buffer;
transport.sendAudioChunk(frame);
transport.endAudio("call-1", "turn-1");
expect(JSON.parse(sockets[0].sent[0] as string)).toMatchObject({
type: "call_start",
protocolVersion: 2,
characterId: "elio",
turnId: "turn-1",
});
expect(JSON.parse(sockets[0].sent[1] as string)).toMatchObject({
type: "call_audio_start",
encoding: "opus",
});
expect(sockets[0].sent[2]).toBe(frame);
expect(JSON.parse(sockets[0].sent[3] as string).type).toBe("call_audio_end");
});
it("associates the next binary payload with its JSON audio metadata", () => {
const transport = create();
const received = vi.fn();
transport.onAudioChunk = received;
transport.connect();
sockets[0].open();
sockets[0].receive(JSON.stringify({
type: "call_audio_chunk_start",
protocolVersion: 2,
callId: "call-1",
turnId: "turn-1",
index: 0,
mimeType: "audio/mpeg",
byteLength: 3,
}));
const bytes = new Uint8Array([4, 5, 6]).buffer;
sockets[0].receive(bytes);
expect(received).toHaveBeenCalledWith(
expect.objectContaining({ turnId: "turn-1", index: 0, mimeType: "audio/mpeg" }),
bytes,
);
});
it("surfaces billing fields without treating a normal charge as an error", () => {
const transport = create();
const billing = vi.fn();
transport.onBillingStatus = billing;
transport.connect();
sockets[0].open();
sockets[0].receive(JSON.stringify({
type: "call_billing_status",
status: "settled",
creditsCharged: 2,
creditBalance: 8,
requiredCredits: 2,
shortfallCredits: 0,
canContinue: true,
nextTurnId: "turn-2",
}));
expect(billing).toHaveBeenCalledWith(expect.objectContaining({
creditsCharged: 2,
creditBalance: 8,
canContinue: true,
nextTurnId: "turn-2",
}));
});
it("starts a reconnect attempt within the two-second release gate", () => {
vi.useFakeTimers();
const transport = create();
const reconnecting = vi.fn();
transport.onReconnecting = reconnecting;
transport.connect();
sockets[0].open();
sockets[0].onclose?.({ code: 1006, reason: "network", wasClean: false });
expect(reconnecting).toHaveBeenCalledWith(400);
vi.advanceTimersByTime(400);
expect(sockets).toHaveLength(2);
sockets[1].open();
expect(JSON.parse(sockets[1].sent[0] as string)).toMatchObject({
type: "call_client_metric",
name: "reconnectLatency",
milliseconds: 400,
});
transport.disconnect();
});
});
+16 -2
View File
@@ -14,8 +14,11 @@ import { AppEnvUtil } from "@/utils/app-env";
import { Logger } from "@/utils/logger";
import {
CommercialActionSchema,
ChatActionSchema,
type ChatAction,
type CommercialAction,
} from "@/data/schemas/chat";
import { createClientMessageId } from "@/lib/chat/client_message_id";
const log = new Logger("ChatWebSocket");
const RECONNECT_DELAY_MS = 3000;
@@ -45,6 +48,7 @@ export class ChatWebSocket {
onImage: ((url: string) => void) | null = null;
onPaywallStatus: ((payload: PaywallStatusPayload) => void) | null = null;
onCommercialAction: ((action: CommercialAction) => void) | null = null;
onChatAction: ((action: ChatAction) => void) | null = null;
onError: ((errorMessage: string) => void) | null = null;
constructor(
@@ -98,8 +102,11 @@ export class ChatWebSocket {
}
}
sendMessage(content: string): boolean {
const payload = { type: "message", content };
sendMessage(
content: string,
clientMessageId: string = createClientMessageId(),
): boolean {
const payload = { type: "message", content, clientMessageId };
if (!this.isConnected) {
logWebSocketWarn("→ WS SEND SKIPPED: socket is not open", payload);
return false;
@@ -151,6 +158,8 @@ export class ChatWebSocket {
ctaLabel?: string;
target?: string;
ruleId?: string;
kind?: string;
orderId?: string | null;
};
};
try {
@@ -195,6 +204,11 @@ export class ChatWebSocket {
if (action.success) this.onCommercialAction?.(action.data);
break;
}
case "chat_action": {
const action = ChatActionSchema.safeParse(payload.data);
if (action.success) this.onChatAction?.(action.data);
break;
}
case "error":
this.onError?.(payload.error ?? "Unknown error");
break;
+210
View File
@@ -0,0 +1,210 @@
import { Logger } from "@/utils/logger";
const log = new Logger("VoiceCallTransport");
const PROTOCOL_VERSION = 2 as const;
const WS_OPEN = 1;
const WS_CLOSING = 2;
export interface CallStartedPayload {
callId: string;
turnId: string;
characterId: string;
costPerPaidTurn: number;
freeTurnsRemaining: number;
creditBalance: number;
canContinue: boolean;
resumeVersion: number;
}
export interface CallBillingStatusPayload {
callId?: string;
turnId?: string;
nextTurnId?: string;
status: string;
creditsCharged: number;
creditBalance: number;
freeTurnsRemaining: number;
requiredCredits: number;
shortfallCredits: number;
canContinue: boolean;
}
export interface CallAudioChunkMeta {
callId: string;
turnId: string;
index: number;
mimeType: string;
byteLength: number;
}
export interface VoiceCallTransportOptions {
webSocketFactory?: (url: string) => WebSocket;
reconnectBaseMs?: number;
}
export class VoiceCallTransport {
private socket: WebSocket | null = null;
private disposed = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempt = 0;
private disconnectedAt = 0;
private pendingAudioMeta: CallAudioChunkMeta | null = null;
private readonly factory: (url: string) => WebSocket;
private readonly reconnectBaseMs: number;
onOpen: (() => void) | null = null;
onReconnecting: ((delayMs: number) => void) | null = null;
onStarted: ((payload: CallStartedPayload) => void) | null = null;
onState: ((state: "listening" | "thinking" | "speaking") => void) | null = null;
onTranscript: ((text: string, final: boolean) => void) | null = null;
onAiSentence: ((text: string, index: number) => void) | null = null;
onBillingStatus: ((payload: CallBillingStatusPayload) => void) | null = null;
onAudioChunk: ((meta: CallAudioChunkMeta, bytes: ArrayBuffer) => void) | null = null;
onInterrupted: (() => void) | null = null;
onEnded: (() => void) | null = null;
onError: ((code: string, message: string) => void) | null = null;
constructor(
private readonly serverUrl: string,
private readonly token: string,
options: VoiceCallTransportOptions = {},
) {
this.factory = options.webSocketFactory ?? ((url) => new WebSocket(url));
this.reconnectBaseMs = options.reconnectBaseMs ?? 400;
}
get isConnected(): boolean {
return this.socket?.readyState === WS_OPEN;
}
connect(): void {
if (this.disposed || (this.socket && this.socket.readyState < WS_CLOSING)) return;
const separator = this.serverUrl.includes("?") ? "&" : "?";
const url = `${this.serverUrl}${separator}token=${encodeURIComponent(this.token)}`;
const socket = this.factory(url);
socket.binaryType = "arraybuffer";
this.socket = socket;
socket.onopen = () => {
this.reconnectAttempt = 0;
if (this.disconnectedAt) {
this.sendClientMetric("reconnectLatency", Date.now() - this.disconnectedAt);
this.disconnectedAt = 0;
}
this.onOpen?.();
};
socket.onmessage = (event) => this.handleMessage(event.data);
socket.onerror = () => this.onError?.("CALL_NETWORK_ERROR", "通话网络连接异常");
socket.onclose = () => {
this.socket = null;
this.disconnectedAt = Date.now();
if (!this.disposed) this.scheduleReconnect();
};
}
startCall(characterId: string, turnId: string, resumeVersion?: number): boolean {
return this.sendJson({
type: "call_start", protocolVersion: PROTOCOL_VERSION, characterId, turnId,
...(resumeVersion ? { resumeVersion } : {}),
});
}
startAudio(callId: string, turnId: string, mimeType: string, sampleRate: number): boolean {
return this.sendJson({
type: "call_audio_start", protocolVersion: PROTOCOL_VERSION,
callId, turnId, encoding: "opus", mimeType, sampleRate,
});
}
sendAudioChunk(bytes: ArrayBuffer): boolean {
if (!this.isConnected) return false;
this.socket?.send(bytes);
return true;
}
endAudio(callId: string, turnId: string, vadLatency = 0): boolean {
return this.sendJson({
type: "call_audio_end", protocolVersion: PROTOCOL_VERSION, callId, turnId,
vadLatency,
});
}
sendClientMetric(name: "audioChunkGap" | "reconnectLatency", milliseconds: number): boolean {
return this.sendJson({
type: "call_client_metric",
protocolVersion: PROTOCOL_VERSION,
name,
milliseconds: Math.max(0, Math.min(60_000, milliseconds)),
});
}
interrupt(callId: string): boolean {
return this.sendJson({
type: "call_interrupt", protocolVersion: PROTOCOL_VERSION, callId,
});
}
endCall(callId: string): boolean {
return this.sendJson({
type: "call_end", protocolVersion: PROTOCOL_VERSION, callId,
});
}
disconnect(): void {
this.disposed = true;
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
this.socket?.close();
this.socket = null;
}
private sendJson(payload: Record<string, unknown>): boolean {
if (!this.isConnected) return false;
this.socket?.send(JSON.stringify(payload));
return true;
}
private scheduleReconnect(): void {
const delayMs = Math.min(1600, this.reconnectBaseMs * 2 ** this.reconnectAttempt);
this.reconnectAttempt += 1;
this.onReconnecting?.(delayMs);
this.reconnectTimer = setTimeout(() => this.connect(), delayMs);
}
private handleMessage(data: unknown): void {
if (data instanceof ArrayBuffer) {
const meta = this.pendingAudioMeta;
this.pendingAudioMeta = null;
if (meta && meta.byteLength === data.byteLength) this.onAudioChunk?.(meta, data);
else if (meta) this.onError?.("CALL_AUDIO_FRAME_INVALID", "通话音频帧不完整");
return;
}
if (typeof data !== "string") return;
let payload: Record<string, unknown>;
try {
payload = JSON.parse(data) as Record<string, unknown>;
} catch (error) {
log.warn("Ignored malformed call event", error);
return;
}
const type = String(payload.type ?? "");
if (type === "call_started") {
this.onStarted?.(payload as unknown as CallStartedPayload);
} else if (type === "call_state") {
this.onState?.(String(payload.state) as "listening" | "thinking" | "speaking");
} else if (type === "call_stt_partial" || type === "call_stt_final") {
this.onTranscript?.(String(payload.text ?? ""), type === "call_stt_final");
} else if (type === "call_ai_sentence") {
this.onAiSentence?.(String(payload.text ?? ""), Number(payload.index ?? 0));
} else if (type === "call_billing_status") {
this.onBillingStatus?.(payload as unknown as CallBillingStatusPayload);
} else if (type === "call_audio_chunk_start") {
this.pendingAudioMeta = payload as unknown as CallAudioChunkMeta;
} else if (type === "call_interrupted") {
this.onInterrupted?.();
} else if (type === "call_ended") {
this.onEnded?.();
} else if (type === "call_error") {
this.onError?.(String(payload.errorCode ?? "CALL_ERROR"), String(payload.message ?? "通话失败"));
}
}
}
@@ -10,7 +10,7 @@
"timestamp": 1782180725000,
"image": {
"type": "elio_schedule",
"url": "https://cdn.cozsweet.com/mock/chat/elio-schedule-locked.jpg"
"url": null
},
"lockDetail": {
"locked": true,
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from "vitest";
import { ChatRemoteDataSource } from "../chat_remote_data_source";
import { SendMessageRequestSchema } from "@/data/schemas/chat";
describe("chat send clientMessageId", () => {
it("keeps legacy requests compatible but validates an explicit UUID", () => {
expect(
SendMessageRequestSchema.parse({ characterId: "elio", message: "hello" })
.clientMessageId,
).toBeUndefined();
expect(() =>
SendMessageRequestSchema.parse({
characterId: "elio",
message: "hello",
clientMessageId: "not-a-uuid",
}),
).toThrow();
});
it("adds one UUID before the HTTP client owns any retry", async () => {
const sendMessage = vi.fn().mockResolvedValue({
reply: "hi",
messageId: "server-message-1",
image: { type: null, url: null },
lockDetail: { locked: false, reason: null },
});
const source = new ChatRemoteDataSource({ sendMessage } as never);
await source.sendMessage("elio", "hello");
const request = sendMessage.mock.calls[0][0];
expect(request.clientMessageId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
});
it("reuses an explicitly supplied key for a protocol fallback", async () => {
const sendMessage = vi.fn().mockResolvedValue({
reply: "hi",
messageId: "server-message-1",
image: { type: null, url: null },
lockDetail: { locked: false, reason: null },
});
const source = new ChatRemoteDataSource({ sendMessage } as never);
const clientMessageId = "11111111-1111-4111-8111-111111111111";
await source.sendMessage("elio", "hello", { clientMessageId, useWebSocket: false });
await source.sendMessage("elio", "hello", { clientMessageId, useWebSocket: true });
expect(sendMessage.mock.calls.map(([request]) => request.clientMessageId)).toEqual([
clientMessageId,
clientMessageId,
]);
});
});
@@ -9,6 +9,33 @@ import type { PaymentApi } from "@/data/services/api";
import { Result } from "@/utils/result";
describe("PaymentRepository", () => {
it("forwards chat action attribution only in the owned order request", async () => {
const createOrder = vi.fn().mockResolvedValue({
orderId: "pay_xxx",
payParams: null,
});
const repository = new PaymentRepository({
createOrder,
} as unknown as PaymentApi);
const result = await repository.createOrder(
"vip_monthly",
"stripe",
true,
undefined,
undefined,
"019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
);
expect(createOrder).toHaveBeenCalledWith({
planId: "vip_monthly",
payChannel: "stripe",
autoRenew: true,
chatActionId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
});
expect(Result.isOk(result)).toBe(true);
});
it("loads a character gift catalog without adapting product metadata", async () => {
const catalog = GiftProductsResponseSchema.parse({
characterId: "elio",
@@ -17,6 +17,7 @@ import {
} from "@/data/schemas/chat";
import type { ChatApi } from "@/data/services/api";
import { Result } from "@/utils/result";
import { createClientMessageId } from "@/lib/chat/client_message_id";
export class ChatRemoteDataSource {
constructor(private readonly api: ChatApi) {}
@@ -29,6 +30,7 @@ export class ChatRemoteDataSource {
return Result.wrap(async () => {
const request = SendMessageRequestSchema.parse({
characterId,
clientMessageId: options?.clientMessageId ?? createClientMessageId(),
message,
...(options?.imageId ? { imageId: options.imageId } : {}),
...(options?.imageThumbUrl
@@ -49,6 +49,8 @@ export interface ChatRequestOptions {
}
export interface ChatSendOptions extends ChatRequestOptions {
/** 同一次逻辑发送在重试或 HTTP/WS 切换时必须复用。 */
clientMessageId?: string;
imageId?: string;
imageThumbUrl?: string;
imageMediumUrl?: string;
@@ -9,4 +9,5 @@ export * from "./ifeedback_repository";
export * from "./imetrics_repository";
export * from "./ipayment_repository";
export * from "./iprivate_zone_repository";
export * from "./iprivate_zone_post_repository";
export * from "./iuser_repository";
@@ -13,7 +13,7 @@ import type { Result } from "@/utils/result";
export interface IPaymentRepository {
/** 获取套餐列表。 */
getPlans(): Promise<Result<PaymentPlansResponse>>;
getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>>;
/** 获取本地缓存套餐列表。 */
getCachedPlans(): Promise<Result<PaymentPlansResponse | null>>;
@@ -30,6 +30,8 @@ export interface IPaymentRepository {
payChannel: PayChannel,
autoRenew: boolean,
recipientCharacterId?: string,
commercialOfferId?: string,
chatActionId?: string,
): Promise<Result<CreatePaymentOrderResponse>>;
/** 查询支付订单状态。 */
@@ -0,0 +1,21 @@
import type {
PrivateZonePostsResponse,
PrivateZonePostUnlockResponse,
} from "@/data/schemas/private-zone";
import type { Result } from "@/utils/result";
export interface GetPrivateZonePostsInput {
characterId: string;
limit?: number;
cursor?: string | null;
}
export interface IPrivateZonePostRepository {
getPosts(
input: GetPrivateZonePostsInput,
): Promise<Result<PrivateZonePostsResponse>>;
unlockPost(
postId: string,
expectedCost: number,
): Promise<Result<PrivateZonePostUnlockResponse>>;
}
+7 -3
View File
@@ -24,10 +24,10 @@ export class PaymentRepository implements IPaymentRepository {
constructor(private readonly api: PaymentApi) {}
/** 获取套餐列表。 */
async getPlans(): Promise<Result<PaymentPlansResponse>> {
async getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>> {
return Result.wrap(async () => {
const response = await this.api.getPlans();
await PaymentPlansStorage.setPlans(response);
const response = await this.api.getPlans(commercialOfferId);
if (!commercialOfferId) await PaymentPlansStorage.setPlans(response);
return response;
});
}
@@ -62,12 +62,16 @@ export class PaymentRepository implements IPaymentRepository {
payChannel: PayChannel,
autoRenew: boolean,
recipientCharacterId?: string,
commercialOfferId?: string,
chatActionId?: string,
): Promise<Result<CreatePaymentOrderResponse>> {
const request = CreatePaymentOrderRequestSchema.parse({
planId,
payChannel,
autoRenew,
...(recipientCharacterId ? { recipientCharacterId } : {}),
...(commercialOfferId ? { commercialOfferId } : {}),
...(chatActionId ? { chatActionId } : {}),
});
return Result.wrap(() => this.api.createOrder(request));
}
@@ -0,0 +1,43 @@
import type {
GetPrivateZonePostsInput,
IPrivateZonePostRepository,
} from "@/data/repositories/interfaces";
import {
UnlockPrivateZonePostRequestSchema,
type PrivateZonePostsResponse,
type PrivateZonePostUnlockResponse,
} from "@/data/schemas/private-zone";
import {
PrivateZonePostApi,
privateZonePostApi,
} from "@/data/services/api/private_zone_post_api";
import { Result } from "@/utils/result";
import { createLazySingleton } from "./lazy_singleton";
export class PrivateZonePostRepository implements IPrivateZonePostRepository {
constructor(private readonly api: PrivateZonePostApi) {}
getPosts(
input: GetPrivateZonePostsInput,
): Promise<Result<PrivateZonePostsResponse>> {
return Result.wrap(() => this.api.getPosts(input));
}
unlockPost(
postId: string,
expectedCost: number,
): Promise<Result<PrivateZonePostUnlockResponse>> {
return Result.wrap(() =>
this.api.unlockPost(
postId,
UnlockPrivateZonePostRequestSchema.parse({ expectedCost }),
),
);
}
}
export const getPrivateZonePostRepository =
createLazySingleton<IPrivateZonePostRepository>(
() => new PrivateZonePostRepository(privateZonePostApi),
);
@@ -0,0 +1,68 @@
import { describe, expect, it } from "vitest";
import {
ChatActionEventRequestSchema,
ChatActionSchema,
} from "@/data/schemas/chat";
describe("ChatActionSchema", () => {
it("accepts a support action without an order", () => {
expect(
ChatActionSchema.parse({
actionId: "action-1",
kind: "support",
type: "openFeedback",
copy: "Send the screenshot and approximate payment time here.",
ctaLabel: "Open Feedback",
ruleId: null,
orderId: null,
}),
).toMatchObject({ type: "openFeedback", orderId: null });
});
it("requires orderId only for resumePayment", () => {
expect(() =>
ChatActionSchema.parse({
actionId: "action-2",
kind: "support",
type: "resumePayment",
copy: "You can continue the pending order here.",
ctaLabel: "Continue",
ruleId: null,
orderId: null,
}),
).toThrow();
expect(() =>
ChatActionSchema.parse({
actionId: "action-3",
kind: "support",
type: "openWallet",
copy: "Open your wallet.",
ctaLabel: "Open Wallet",
ruleId: null,
orderId: "order-not-allowed",
}),
).toThrow();
});
});
describe("ChatActionEventRequestSchema", () => {
it("requires a UUID event id and an allowlisted event type", () => {
expect(
ChatActionEventRequestSchema.parse({
eventId: "4b223884-02ec-4fd2-aacf-e84ee8ca3adb",
actionId: "action-1",
characterId: "elio",
eventType: "arrived",
}),
).toMatchObject({ eventType: "arrived" });
expect(() =>
ChatActionEventRequestSchema.parse({
eventId: "not-a-uuid",
actionId: "action-1",
characterId: "elio",
eventType: "clicked",
}),
).toThrow();
});
});
+75
View File
@@ -0,0 +1,75 @@
import { z } from "zod";
export const ChatActionTypeSchema = z.enum([
"giftOffer",
"privateAlbumOffer",
"openProfile",
"openWallet",
"openCoinsRules",
"activateVip",
"topUp",
"openFeedback",
"resumePayment",
]);
export const ChatActionSchema = z
.object({
actionId: z.string().min(1),
kind: z.enum(["support", "commercial"]),
type: ChatActionTypeSchema,
copy: z.string().min(1),
ctaLabel: z.string().min(1),
ruleId: z.string().min(1).nullable(),
orderId: z.string().min(1).nullable(),
})
.superRefine((action, context) => {
if (action.type === "resumePayment" && action.orderId === null) {
context.addIssue({
code: "custom",
path: ["orderId"],
message: "orderId is required for resumePayment",
});
}
if (action.type !== "resumePayment" && action.orderId !== null) {
context.addIssue({
code: "custom",
path: ["orderId"],
message: "orderId is only allowed for resumePayment",
});
}
})
.readonly();
export const ChatActionEventTypeSchema = z.enum([
"viewed",
"opened",
"dismissed",
"arrived",
]);
export const ChatActionEventRequestSchema = z
.object({
eventId: z.uuid(),
actionId: z.string().min(1),
characterId: z.string().min(1),
eventType: ChatActionEventTypeSchema,
})
.readonly();
export const ChatActionEventResponseSchema = z
.object({
eventId: z.uuid(),
actionId: z.string().min(1),
eventType: ChatActionEventTypeSchema,
duplicate: z.boolean(),
})
.readonly();
export type ChatAction = z.output<typeof ChatActionSchema>;
export type ChatActionEventType = z.output<typeof ChatActionEventTypeSchema>;
export type ChatActionEventRequest = z.input<
typeof ChatActionEventRequestSchema
>;
export type ChatActionEventResponse = z.output<
typeof ChatActionEventResponseSchema
>;
+1
View File
@@ -7,6 +7,7 @@ export * from "./chat_media";
export * from "./chat_message";
export * from "./opening_message";
export * from "./chat_payloads";
export * from "./chat_action";
export * from "./request/send_message_request";
export * from "./request/unlock_history_request";
export * from "./request/unlock_private_request";
@@ -9,6 +9,7 @@ import { booleanOrFalse } from "../../nullable-defaults";
export const SendMessageRequestSchema = z
.object({
characterId: z.string().min(1),
clientMessageId: z.uuid().optional(),
message: z.string().max(4000).optional(),
imageId: z.string().min(1).optional(),
imageThumbUrl: z.string().min(1).optional(),
@@ -11,14 +11,15 @@ import {
stringOrEmpty,
} from "../../nullable-defaults";
import { ChatImageSchema, ChatLockDetailSchema } from "../chat_payloads";
import { ChatActionSchema } from "../chat_action";
export const CommercialActionSchema = z
.object({
actionId: z.string().min(1),
type: z.enum(["giftOffer", "privateAlbumOffer"]),
type: z.enum(["giftOffer", "privateAlbumOffer", "discountOffer"]),
copy: 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),
})
.readonly();
@@ -41,6 +42,7 @@ export const ChatSendResponseSchema = z
requiredCredits: numberOrZero,
shortfallCredits: numberOrZero,
commercialAction: CommercialActionSchema.nullish().default(null),
chatAction: ChatActionSchema.nullish().default(null),
})
.readonly();
@@ -12,6 +12,14 @@ export interface FeedbackContext {
platform: string;
browser: string;
viewport: string;
sourcePage?: string;
paymentIssueReason?: string;
subscriptionType?: string;
planId?: string;
orderId?: string;
payChannel?: string;
countryCode?: string;
characterId?: string;
}
export interface SubmitFeedbackInput {
@@ -19,4 +27,5 @@ export interface SubmitFeedbackInput {
content: string;
context: FeedbackContext;
images: readonly File[];
idempotencyKey?: string;
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { CreatePaymentOrderRequestSchema } from "@/data/schemas/payment";
describe("CreatePaymentOrderRequestSchema", () => {
const baseRequest = {
planId: "vip_monthly",
payChannel: "stripe",
autoRenew: true,
} as const;
it("accepts a UUID chatActionId for funnel attribution", () => {
expect(
CreatePaymentOrderRequestSchema.parse({
...baseRequest,
chatActionId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
}),
).toMatchObject({
...baseRequest,
chatActionId: "019c8f8d-17d3-7a42-b1cc-b6927b1927d5",
});
});
it("rejects a non-UUID chatActionId", () => {
expect(() =>
CreatePaymentOrderRequestSchema.parse({
...baseRequest,
chatActionId: "action-1",
}),
).toThrow();
});
});
@@ -75,6 +75,8 @@ describe("PaymentPlan", () => {
mostPopular: true,
firstRechargeDiscountPercent: null,
promotionType: null,
commercialOfferId: null,
commercialDiscountPercent: null,
});
});
@@ -190,6 +192,45 @@ describe("PaymentPlansResponse", () => {
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", () => {
+1
View File
@@ -8,6 +8,7 @@ export * from "./gift_product";
export * from "./request/create_payment_order_request";
export * from "./request/tip_message_request";
export * from "./response/create_payment_order_response";
export * from "./response/commercial_offer_response";
export * from "./response/gift_products_response";
export * from "./response/payment_order_status_response";
export * from "./response/payment_plans_response";
+2
View File
@@ -25,6 +25,8 @@ export const PaymentPlanSchema = z
mostPopular: booleanOrFalse,
firstRechargeDiscountPercent: numberOrNull,
promotionType: stringOrNull,
commercialOfferId: stringOrNull,
commercialDiscountPercent: numberOrNull,
})
.readonly();
@@ -11,6 +11,8 @@ export const CreatePaymentOrderRequestSchema = z
payChannel: PayChannelSchema,
autoRenew: z.boolean(),
recipientCharacterId: z.string().min(1).optional(),
commercialOfferId: z.string().min(1).optional(),
chatActionId: z.uuid().optional(),
})
.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 "./commercial_offer_response";
export * from "./gift_products_response";
export * from "./payment_order_status_response";
export * from "./payment_plans_response";
@@ -20,10 +20,24 @@ export const FirstRechargeOfferSchema = z
})
.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
.object({
isFirstRecharge: booleanOrFalse,
firstRechargeOffer: schemaOrNull(FirstRechargeOfferSchema),
commercialOffer: schemaOrNull(CommercialOfferSummarySchema),
plans: arrayOrEmpty(PaymentPlanSchema),
})
.readonly();
@@ -35,7 +49,9 @@ export type PaymentPlansResponseData = z.output<
typeof PaymentPlansResponseSchema
>;
export type FirstRechargeOfferData = z.output<typeof FirstRechargeOfferSchema>;
export type CommercialOfferSummaryData = z.output<typeof CommercialOfferSummarySchema>;
export type FirstRechargeOffer = FirstRechargeOfferData;
export type CommercialOfferSummary = CommercialOfferSummaryData;
export type PaymentPlansResponse = PaymentPlansResponseData;
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import {
PrivateZonePostUnlockResponseSchema,
PrivateZonePostsResponseSchema,
} from "@/data/schemas/private-zone";
const post = {
postId: "11111111-1111-1111-1111-111111111111",
characterId: "maya-tan",
caption: "Only for you.",
posterUrl: "https://storage.example/poster.jpg?token=short",
mediaType: "video",
videoUrl: null,
videoMimeType: "video/mp4",
videoSizeBytes: 1024,
durationSeconds: 18,
unlockCostCredits: 100,
currency: "credits",
locked: true,
unlocked: false,
availableForNewUnlock: true,
publishedAt: "2026-07-24T10:00:00+00:00",
};
describe("Private Zone video post schema", () => {
it("parses a locked post without inventing a video URL", () => {
const response = PrivateZonePostsResponseSchema.parse({
characterId: "maya-tan",
items: [post],
nextCursor: null,
hasMore: false,
creditBalance: 250,
currency: "credits",
});
expect(response.items[0].videoUrl).toBeNull();
expect(response.items[0].posterUrl).toContain("poster.jpg");
expect(response.items[0].unlockCostCredits).toBe(100);
});
it("parses cost changes and insufficient-credit details", () => {
const changed = PrivateZonePostUnlockResponseSchema.parse({
postId: post.postId,
reason: "cost_changed",
unlocked: false,
creditsCharged: 0,
requiredCredits: 150,
creditBalance: 250,
post: { ...post, unlockCostCredits: 150 },
});
const insufficient = PrivateZonePostUnlockResponseSchema.parse({
postId: post.postId,
reason: "insufficient_credits",
unlocked: false,
creditsCharged: 0,
requiredCredits: 100,
currentCredits: 40,
shortfallCredits: 60,
creditBalance: 40,
post,
});
expect(changed.post?.unlockCostCredits).toBe(150);
expect(insufficient.shortfallCredits).toBe(60);
});
});
+1
View File
@@ -3,6 +3,7 @@
*/
export * from "./private_album";
export * from "./private_zone_post";
export * from "./request/unlock_private_album_request";
export * from "./response/private_album_unlock_response";
export * from "./response/private_albums_response";
@@ -0,0 +1,82 @@
import { z } from "zod";
import {
arrayOrEmpty,
booleanOrFalse,
booleanOrTrue,
numberOrNull,
numberOrZero,
schemaOrNull,
stringOrEmpty,
stringOrNull,
} from "../nullable-defaults";
export const PrivateZoneVideoPostSchema = z
.object({
postId: stringOrEmpty,
characterId: stringOrEmpty,
caption: stringOrEmpty,
posterUrl: stringOrNull,
mediaType: z.literal("video").default("video"),
videoUrl: stringOrNull,
videoMimeType: stringOrEmpty,
videoSizeBytes: numberOrZero,
durationSeconds: numberOrNull,
unlockCostCredits: numberOrZero,
currency: z.literal("credits").default("credits"),
locked: booleanOrFalse,
unlocked: booleanOrFalse,
availableForNewUnlock: booleanOrTrue,
publishedAt: stringOrEmpty,
})
.readonly();
export const PrivateZonePostsResponseSchema = z
.object({
characterId: stringOrEmpty,
items: arrayOrEmpty(PrivateZoneVideoPostSchema),
nextCursor: stringOrNull,
hasMore: booleanOrFalse,
creditBalance: numberOrZero,
currency: z.literal("credits").default("credits"),
})
.readonly();
export const PrivateZonePostUnlockReasonSchema = z.enum([
"ok",
"already_unlocked",
"insufficient_credits",
"cost_changed",
"unavailable",
"deduct_failed",
"not_found",
]);
export const PrivateZonePostUnlockResponseSchema = z
.object({
postId: stringOrEmpty,
reason: PrivateZonePostUnlockReasonSchema.or(stringOrEmpty),
unlocked: booleanOrFalse,
creditsCharged: numberOrZero,
requiredCredits: numberOrZero,
currentCredits: numberOrZero,
shortfallCredits: numberOrZero,
creditBalance: numberOrZero,
post: schemaOrNull(PrivateZoneVideoPostSchema),
})
.readonly();
export const UnlockPrivateZonePostRequestSchema = z
.object({
expectedCost: z.number().int().min(1),
})
.readonly();
export type PrivateZoneVideoPost = z.output<typeof PrivateZoneVideoPostSchema>;
export type PrivateZonePostsResponse = z.output<typeof PrivateZonePostsResponseSchema>;
export type PrivateZonePostUnlockResponse = z.output<
typeof PrivateZonePostUnlockResponseSchema
>;
export type UnlockPrivateZonePostRequest = z.output<
typeof UnlockPrivateZonePostRequestSchema
>;
@@ -134,11 +134,26 @@ describe("User", () => {
photo: 40,
},
},
voiceCallBilling: {
enabled: true,
protocolVersion: 2,
chargeMode: "per_turn",
sharesNormalChatFreeDaily: true,
freeTurnsDaily: 30,
costPerPaidTurn: 2,
usageType: "voice_call_turn",
legacyMinuteCostUsed: false,
},
});
expect(entitlements.isVip).toBe(true);
expect(entitlements.creditBalance).toBe(120);
expect(entitlements.historyUnlock.costs.photo).toBe(40);
expect(entitlements.voiceCallBilling).toMatchObject({
protocolVersion: 2,
chargeMode: "per_turn",
costPerPaidTurn: 2,
});
});
it("defaults nullable entitlement sections through schema helpers", () => {
@@ -49,6 +49,17 @@ const HISTORY_UNLOCK_DEFAULTS = {
costs: HISTORY_UNLOCK_COSTS_DEFAULTS,
} as const;
const VOICE_CALL_BILLING_DEFAULTS = {
enabled: false,
protocolVersion: 2,
chargeMode: "per_turn",
sharesNormalChatFreeDaily: true,
freeTurnsDaily: 0,
costPerPaidTurn: 0,
usageType: "voice_call_turn",
legacyMinuteCostUsed: false,
} as const;
export const UserEntitlementsPolicySchema = z
.object({
membershipState: stringOrEmpty,
@@ -105,6 +116,20 @@ export const UserEntitlementsHistoryUnlockSchema = z
.passthrough()
.readonly();
export const VoiceCallBillingSchema = z
.object({
enabled: booleanOrFalse,
protocolVersion: numberOrZero,
chargeMode: stringOrEmpty,
sharesNormalChatFreeDaily: booleanOrFalse,
freeTurnsDaily: numberOrZero,
costPerPaidTurn: numberOrZero,
usageType: stringOrEmpty,
legacyMinuteCostUsed: booleanOrFalse,
})
.passthrough()
.readonly();
export const UserEntitlementsSchema = z
.object({
userId: stringOrEmpty,
@@ -120,6 +145,10 @@ export const UserEntitlementsSchema = z
UserEntitlementsHistoryUnlockSchema,
HISTORY_UNLOCK_DEFAULTS,
),
voiceCallBilling: schemaOr(
VoiceCallBillingSchema,
VOICE_CALL_BILLING_DEFAULTS,
),
})
.readonly();
@@ -6,7 +6,7 @@ import { ApiPath } from "../api_path";
describe("ApiPath contract source", () => {
it("uses the shared contract path for every static operation", () => {
const staticOperations = Object.entries(apiContract).filter(
([operationId]) => operationId !== "privateZoneAlbumUnlock",
([, operation]) => !operation.path.includes("{"),
);
for (const [operationId, operation] of staticOperations) {
@@ -21,4 +21,10 @@ describe("ApiPath contract source", () => {
"/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",
);
});
});
@@ -32,12 +32,17 @@ describe("FeedbackApi", () => {
viewport: "392x760@2.75",
},
images: [image],
idempotencyKey: "payment_feedback_123",
});
expect(response).toEqual({ feedbackId: "feedback-123" });
expect(httpClientMock).toHaveBeenCalledWith(
"/api/feedback",
expect.objectContaining({ method: "POST", body: expect.any(FormData) }),
expect.objectContaining({
method: "POST",
body: expect.any(FormData),
headers: { "Idempotency-Key": "payment_feedback_123" },
}),
);
const body = httpClientMock.mock.calls[0][1].body as FormData;
expect(body.get("category")).toBe("problem");
@@ -60,6 +60,26 @@ describe("multi-character API contract", () => {
});
});
it("reports an idempotent chat action event", async () => {
const body = {
eventId: "4b223884-02ec-4fd2-aacf-e84ee8ca3adb",
actionId: "action-1",
characterId: CHARACTER_ID,
eventType: "opened" as const,
};
httpClientMock.mockResolvedValue({
success: true,
data: { ...body, duplicate: false },
});
await new ChatApi().recordActionEvent(body);
expect(httpClientMock).toHaveBeenCalledWith("/api/chat/action-events", {
method: "POST",
body,
});
});
it("persists the character opening message with the canonical contract", async () => {
httpClientMock.mockResolvedValue({
success: true,
@@ -81,4 +81,38 @@ describe("PaymentApi", () => {
});
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" },
});
});
});
+4
View File
@@ -17,13 +17,17 @@
"paymentPlans": { "method": "get", "path": "/api/payment/plans" },
"paymentGiftProducts": { "method": "get", "path": "/api/payment/gift-products" },
"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" },
"chatActionEvents": { "method": "post", "path": "/api/chat/action-events" },
"chatOpeningMessage": { "method": "post", "path": "/api/chat/opening-message" },
"chatHistory": { "method": "get", "path": "/api/chat/history" },
"chatUnlockPrivate": { "method": "post", "path": "/api/chat/unlock-private" },
"chatUnlockHistory": { "method": "post", "path": "/api/chat/unlock-history" },
"privateZoneAlbums": { "method": "get", "path": "/api/private-zone/albums" },
"privateZoneAlbumUnlock": { "method": "post", "path": "/api/private-zone/albums/{albumId}/unlock" },
"privateZonePosts": { "method": "get", "path": "/api/private-zone/posts" },
"privateZonePostUnlock": { "method": "post", "path": "/api/private-zone/posts/{postId}/unlock" },
"metricsPwaEvent": { "method": "post", "path": "/api/metrics/pwa/event" },
"reportUserInfo": { "method": "post", "path": "/api/data/report-user-info" },
"feedback": { "method": "post", "path": "/api/feedback" },

Some files were not shown because too many files have changed in this diff Show More