Compare commits
26 Commits
pre
...
d01441b8c7
| Author | SHA1 | Date | |
|---|---|---|---|
| d01441b8c7 | |||
| ddacd03601 | |||
| 1b121a8ef8 | |||
| b7221f2f70 | |||
| 30f88d3a20 | |||
| 7b09a7f850 | |||
| 38a4645b9c | |||
| 76bffc1a0d | |||
| 19b8fc51d6 | |||
| 9fbf180df6 | |||
| 6721b6eb43 | |||
| 64ba720121 | |||
| b04ef58855 | |||
| 606e6d60ff | |||
| c659c5fc3f | |||
| 537a0a2c36 | |||
| b1f52c68e8 | |||
| 3c7b0c30e0 | |||
| 469512df18 | |||
| 318e4991be | |||
| 2d432e5367 | |||
| d6f104ee3f | |||
| 9ca56c2a04 | |||
| 4639acf232 | |||
| bdd53a6ea1 | |||
| fb9e30cfd1 |
@@ -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:
|
||||
|
||||
@@ -6,10 +6,12 @@ ENV PNPM_HOME=/pnpm
|
||||
ENV PNPM_STORE_PATH=/pnpm/store
|
||||
ENV PATH=$PNPM_HOME:$PATH
|
||||
|
||||
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||
|
||||
RUN apk add --no-cache libc6-compat \
|
||||
&& corepack enable \
|
||||
&& corepack prepare pnpm@10.30.3 --activate \
|
||||
&& pnpm config set store-dir "$PNPM_STORE_PATH"
|
||||
&& npm install --global "pnpm@10.30.3" --registry="$NPM_REGISTRY" \
|
||||
&& pnpm config set store-dir "$PNPM_STORE_PATH" \
|
||||
&& pnpm config set registry "$NPM_REGISTRY"
|
||||
|
||||
FROM base AS deps
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
|
||||
@@ -25,9 +25,9 @@
|
||||
"./src/data/schemas/payment",
|
||||
"./src/data/schemas/payment/request",
|
||||
"./src/data/schemas/payment/response",
|
||||
"./src/data/schemas/private-zoom",
|
||||
"./src/data/schemas/private-zoom/request",
|
||||
"./src/data/schemas/private-zoom/response",
|
||||
"./src/data/schemas/private-zone",
|
||||
"./src/data/schemas/private-zone/request",
|
||||
"./src/data/schemas/private-zone/response",
|
||||
"./src/data/schemas/user",
|
||||
"./src/data/storage/app",
|
||||
"./src/data/storage/auth",
|
||||
|
||||
@@ -63,7 +63,7 @@ Authorization: Bearer <TOKEN>
|
||||
2. `isActive=true`;
|
||||
3. `capabilities.chat=true`。
|
||||
|
||||
服务端目录决定角色是否可聊天及排序;本地目录继续提供 slug、图片、文案和 Tip 能力。`privateZoom` 只有在本地能力和服务端 `privateContent` 同时开启时可用。
|
||||
服务端目录决定角色是否可聊天及排序;本地目录继续提供 slug、图片、文案和 Tip 能力。`privateZone` 只有在本地能力和服务端 `privateContent` 同时开启时可用。
|
||||
|
||||
远端目录返回前,生产环境只使用 Elio 作为临时目录;非生产环境可使用完整本地目录。远端目录加载成功后,以合并结果为准。
|
||||
|
||||
@@ -72,7 +72,7 @@ Authorization: Bearer <TOKEN>
|
||||
```text
|
||||
/characters/{slug}/splash
|
||||
/characters/{slug}/chat
|
||||
/characters/{slug}/private-zoom
|
||||
/characters/{slug}/private-zone
|
||||
/characters/{slug}/tip
|
||||
```
|
||||
|
||||
@@ -81,11 +81,11 @@ Authorization: Bearer <TOKEN>
|
||||
```text
|
||||
/splash -> /characters/elio/splash
|
||||
/chat -> /characters/elio/chat
|
||||
/private-zoom -> /characters/elio/private-zoom
|
||||
/private-zone -> /characters/elio/private-zone
|
||||
/tip -> /characters/elio/tip
|
||||
```
|
||||
|
||||
Chat Provider 以 `characterId` 为边界,路由角色变化时创建新的 Actor。Private Zoom 的角色边界由 [Private Zoom 权威协议](./FRONTEND_PRIVATE_ZOOM_API.md) 定义。
|
||||
Chat Provider 以 `characterId` 为边界,路由角色变化时创建新的 Actor。Private Zone 的角色边界由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||
|
||||
## 3. Chat HTTP 协议
|
||||
|
||||
@@ -308,7 +308,7 @@ conversationKey = {ownerKey}::character:{encodeURIComponent(characterId)}
|
||||
|
||||
## 7. 关联业务边界
|
||||
|
||||
- Private Zoom 的相册、解锁、Gallery 和支付回跳由 [Private Zoom 权威协议](./FRONTEND_PRIVATE_ZOOM_API.md) 定义。
|
||||
- Private Zone 的相册、解锁、Gallery 和支付回跳由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||
- Tip 的角色归属、订单轮询和支付回跳由 [Payment 权威协议](./FRONTEND_PAYMENT_API.md) 定义;Chat 只保存解锁所需的原角色回跳地址。
|
||||
- 登录、支付和解锁回跳保存原角色动态 URL,不能降级为通用 `/chat`。
|
||||
- Analytics 可以使用 `characterId`,聊天正文不属于路由或身份协议的一部分。
|
||||
|
||||
@@ -224,7 +224,7 @@ payChannel = ezpay
|
||||
subscriptionType = vip | topup | tip
|
||||
giftCategory(仅 Tip,可空)
|
||||
giftPlanId(仅 Tip,可空)
|
||||
returnTo = chat | private-zoom | profile(可选)
|
||||
returnTo = chat | private-zone | profile(可选)
|
||||
characterSlug(可选)
|
||||
createdAt
|
||||
```
|
||||
@@ -238,7 +238,7 @@ Tip -> /characters/{slug}/tip?category=...&planId=...&payChannel=ezpay&
|
||||
|
||||
恢复页面只接受与当前 `paymentType` 相同的待处理订单。带有 `paymentReturn=1` 时派发 `PaymentReturned` 并继续轮询;普通进入支付页时会清理同类型的旧待处理订单。订单进入 paid、failed 或 expired 后清理持久化记录。缺少 Gift 字段的旧记录由最新目录默认选择第一件商品,不再读取 `coffee_type`。
|
||||
|
||||
无效或未知 `characterSlug` 回退到默认角色 slug。有效角色回跳必须保留原角色,不能统一返回 Elio。`returnTo=private-zoom` 的最终页面行为由 [Private Zoom 权威协议](./FRONTEND_PRIVATE_ZOOM_API.md) 定义。
|
||||
无效或未知 `characterSlug` 回退到默认角色 slug。有效角色回跳必须保留原角色,不能统一返回 Elio。`returnTo=private-zone` 的最终页面行为由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||
|
||||
## 8. 成功后的跨域同步
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# CozSweet Private Zoom 权威协议
|
||||
# CozSweet Private Zone 权威协议
|
||||
|
||||
## 1. 状态与范围
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
| 边界 | 实现位置 |
|
||||
| --- | --- |
|
||||
| API 路径与方法 | `src/data/services/api/api_contract.json` |
|
||||
| 请求与响应字段 | `src/data/schemas/private-zoom` |
|
||||
| API 与 Repository | `src/data/services/api/private_zoom_api.ts`、`src/data/repositories/private_zoom_repository.ts` |
|
||||
| Private Zoom 状态机 | `src/stores/private-zoom` |
|
||||
| 页面、Gallery 与导航 | `src/app/private-zoom` |
|
||||
| 角色 Provider | `src/providers/private-zoom-route-provider.tsx` |
|
||||
| 请求与响应字段 | `src/data/schemas/private-zone` |
|
||||
| API 与 Repository | `src/data/services/api/private_zone_api.ts`、`src/data/repositories/private_zone_repository.ts` |
|
||||
| Private Zone 状态机 | `src/stores/private-zone` |
|
||||
| 页面、Gallery 与导航 | `src/app/private-zone` |
|
||||
| 角色 Provider | `src/providers/private-zone-route-provider.tsx` |
|
||||
|
||||
修改上述实现时必须在同一变更中更新本文,不能再新增按相册列表、解锁或 Gallery 拆分的并行协议。
|
||||
|
||||
@@ -22,13 +22,13 @@
|
||||
标准路由:
|
||||
|
||||
```text
|
||||
/characters/{characterSlug}/private-zoom
|
||||
/characters/{characterSlug}/private-zone
|
||||
```
|
||||
|
||||
旧地址保留为默认角色重定向,并保留查询参数:
|
||||
|
||||
```text
|
||||
/private-zoom -> /characters/elio/private-zoom
|
||||
/private-zone -> /characters/elio/private-zone
|
||||
```
|
||||
|
||||
URL 使用角色 `slug`,API 和 Actor 使用角色业务 `id`:
|
||||
@@ -39,14 +39,14 @@ URL 使用角色 `slug`,API 和 Actor 使用角色业务 `id`:
|
||||
| `maya-tan` | `maya` |
|
||||
| `nayeli-cervantes` | `nayeli` |
|
||||
|
||||
角色必须同时存在于本地目录且 `capabilities.privateZoom=true`。该能力由本地配置和角色目录响应的 `privateContent` 共同决定;能力关闭或 slug 未知时路由返回 Not Found。
|
||||
角色必须同时存在于本地目录且 `capabilities.privateZone=true`。该能力由本地配置和角色目录响应的 `privateContent` 共同决定;能力关闭或 slug 未知时路由返回 Not Found。
|
||||
|
||||
`PrivateZoomProvider` 以 `characterId` 为输入和 React key。切换角色会销毁旧 Actor 并创建空状态,不能复用上一角色的相册、余额或解锁请求。
|
||||
`PrivateZoneProvider` 以 `characterId` 为输入和 React key。切换角色会销毁旧 Actor 并创建空状态,不能复用上一角色的相册、余额或解锁请求。
|
||||
|
||||
## 3. 相册列表
|
||||
|
||||
```http
|
||||
GET <API_BASE_URL>/api/private-zoom/albums?characterId=maya-tan&limit=20
|
||||
GET <API_BASE_URL>/api/private-zone/albums?characterId=maya-tan&limit=20
|
||||
Authorization: Bearer <TOKEN>
|
||||
```
|
||||
|
||||
@@ -55,7 +55,7 @@ Authorization: Bearer <TOKEN>
|
||||
| `characterId` | 是 | 当前角色业务 ID |
|
||||
| `limit` | 否 | 当前固定为 20 |
|
||||
|
||||
前端当前只加载第一页,不实现 Private Zoom 分页,也不把相册列表写入本地缓存。初始化、手动刷新或登录身份变化时重新请求网络。
|
||||
前端当前只加载第一页,不实现 Private Zone 分页,也不把相册列表写入本地缓存。初始化、手动刷新或登录身份变化时重新请求网络。
|
||||
|
||||
标准响应数据:
|
||||
|
||||
@@ -105,7 +105,7 @@ album.locked || !album.unlocked || album.lockDetail.locked
|
||||
用户点击锁定相册后,前端先展示确认 Dialog。只有待确认 `albumId` 仍存在于当前 Actor 的 `items` 中,才会发起请求。
|
||||
|
||||
```http
|
||||
POST <API_BASE_URL>/api/private-zoom/albums/{albumId}/unlock
|
||||
POST <API_BASE_URL>/api/private-zone/albums/{albumId}/unlock
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer <TOKEN>
|
||||
```
|
||||
@@ -177,25 +177,25 @@ Schema 同时允许未知字符串,未知失败原因使用通用错误文案
|
||||
|
||||
## 5. 身份与支付导航
|
||||
|
||||
Private Zoom 初始化会复用 Guest 登录引导。Auth 尚未初始化或正在加载时不请求列表;`notLoggedIn` 完成 Guest bootstrap 后再进入列表加载。Guest 和正式用户都可以读取后端允许的相册列表。
|
||||
Private Zone 初始化会复用 Guest 登录引导。Auth 尚未初始化或正在加载时不请求列表;`notLoggedIn` 完成 Guest bootstrap 后再进入列表加载。Guest 和正式用户都可以读取后端允许的相册列表。
|
||||
|
||||
积分不足生成 Paywall 请求后:
|
||||
|
||||
| 当前身份 | 导航 |
|
||||
| --- | --- |
|
||||
| Guest 或 Not Logged In | 打开 Auth,redirect 为当前角色 Private Zoom |
|
||||
| 已认证用户 | 打开 Top-up,`returnTo=private-zoom`,保留当前角色来源 |
|
||||
| Guest 或 Not Logged In | 打开 Auth,redirect 为当前角色 Private Zone |
|
||||
| 已认证用户 | 打开 Top-up,`returnTo=private-zone`,保留当前角色来源 |
|
||||
|
||||
Paywall 导航发起后立即消费当前请求,避免 React 重渲染重复导航。支付回跳和订单恢复遵循 [Payment 权威协议](./FRONTEND_PAYMENT_API.md)。
|
||||
|
||||
解锁成功后 `unlockSuccessNonce` 递增,页面桥接到 `UserFetch`,刷新当前积分和权益。Private Zoom 不自行修改 User Store 余额。
|
||||
解锁成功后 `unlockSuccessNonce` 递增,页面桥接到 `UserFetch`,刷新当前积分和权益。Private Zone 不自行修改 User Store 余额。
|
||||
|
||||
## 6. Gallery URL 协议
|
||||
|
||||
解锁相册使用查询参数打开页内 Gallery:
|
||||
|
||||
```text
|
||||
/characters/{slug}/private-zoom?album={albumId}&image={zeroBasedIndex}
|
||||
/characters/{slug}/private-zone?album={albumId}&image={zeroBasedIndex}
|
||||
```
|
||||
|
||||
解析规则:
|
||||
@@ -208,7 +208,7 @@ Paywall 导航发起后立即消费当前请求,避免 React 重渲染重复
|
||||
|
||||
任一条件不满足时,页面通过 replace 删除 `album` 和 `image`,并保留其他查询参数。
|
||||
|
||||
页面内点击九宫格缩略图时,Gallery 从该图片的后端数组原始索引打开。关闭操作优先使用浏览器 back;直接刷新或外部分享 Gallery URL 时,关闭操作使用 replace 返回当前角色 Private Zoom。
|
||||
页面内点击九宫格缩略图时,Gallery 从该图片的后端数组原始索引打开。关闭操作优先使用浏览器 back;直接刷新或外部分享 Gallery URL 时,关闭操作使用 replace 返回当前角色 Private Zone。
|
||||
|
||||
Gallery 只浏览 `locked=false` 且 URL 非空的图片,但 URL 中的 `image` 仍使用原始数组索引。横向拖动时图片跟随指针,达到视口宽度 18%(最低 56px),或达到 0.45px/ms 且至少移动 24px 时切换;首尾越界拖动使用 0.28 阻尼且不循环。松手后使用 240ms 横向吸附动画,键盘方向键和左右按钮复用相同切换逻辑。Escape 关闭;`prefers-reduced-motion` 下取消吸附过渡。
|
||||
|
||||
@@ -222,17 +222,17 @@ Gallery 只浏览 `locked=false` 且 URL 非空的图片,但 URL 中的 `image
|
||||
- 超过 9 张时卡片显示前九张,末格显示 `+N`,Gallery 仍可浏览全部有效图片;
|
||||
- Gallery 只挂载当前图片和相邻图片,避免多图相册同时解码全部原图;
|
||||
- `creditBalance` 是当前列表/解锁响应快照,不替代 User Store 权益;
|
||||
- Private Zoom 不使用 Chat 的 `conversationKey`、消息缓存或媒体缓存;
|
||||
- Private Zoom 不持有 Payment Actor,Top-up 通过路由级导航进入独立 Payment Provider。
|
||||
- Private Zone 不使用 Chat 的 `conversationKey`、消息缓存或媒体缓存;
|
||||
- Private Zone 不持有 Payment Actor,Top-up 通过路由级导航进入独立 Payment Provider。
|
||||
|
||||
## 8. 变更验收
|
||||
|
||||
Private Zoom 协议相关变更至少验证:
|
||||
Private Zone 协议相关变更至少验证:
|
||||
|
||||
1. `src/data/schemas/private-zoom/__tests__`;
|
||||
2. `src/data/services/api/__tests__/multi_character_api.test.ts` 中的 Private Zoom 请求;
|
||||
3. `src/stores/private-zoom/__tests__`;
|
||||
4. `src/app/private-zoom/__tests__` 与组件测试;
|
||||
1. `src/data/schemas/private-zone/__tests__`;
|
||||
2. `src/data/services/api/__tests__/multi_character_api.test.ts` 中的 Private Zone 请求;
|
||||
3. `src/stores/private-zone/__tests__`;
|
||||
4. `src/app/private-zone/__tests__` 与组件测试;
|
||||
5. Elio、Maya、Nayeli 列表互不串联;
|
||||
6. 登录身份变化会刷新当前角色列表;
|
||||
7. 成功、余额不足、价格变化、重复解锁、退款失败和 not found 分支;
|
||||
@@ -19,7 +19,7 @@ https://<APP_HOST>/external-entry?<参数>
|
||||
|
||||
| 参数 | 可选值或格式 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `target` | `chat`、`tip`、`private-zoom` | 指定进入的页面;不传或值无效时进入聊天页。 |
|
||||
| `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)。
|
||||
@@ -78,13 +80,13 @@ https://<APP_HOST>/external-entry?target=tip
|
||||
私密空间:
|
||||
|
||||
```text
|
||||
https://<APP_HOST>/external-entry?target=private-zoom
|
||||
https://<APP_HOST>/external-entry?target=private-zone
|
||||
```
|
||||
|
||||
进入 Nayeli 私密空间:
|
||||
|
||||
```text
|
||||
https://<APP_HOST>/external-entry?target=private-zoom&character=nayeli
|
||||
https://<APP_HOST>/external-entry?target=private-zone&character=nayeli
|
||||
```
|
||||
|
||||
`psid` 可以与任意 `target` 或聊天促销参数组合使用。参数值需要进行 URL 编码,不要在入口中传递登录 Token、Page Access Token 或 App Secret。
|
||||
|
||||
@@ -40,8 +40,8 @@
|
||||
|
||||
| 角色 | 链接 |
|
||||
| --- | --- |
|
||||
| Elio | [打开 Elio 私密空间](http://localhost:3000/external-entry?target=private-zoom&character=elio) |
|
||||
| Maya | [打开 Maya 私密空间](http://localhost:3000/external-entry?target=private-zoom&character=maya) |
|
||||
| Nayeli | [打开 Nayeli 私密空间](http://localhost:3000/external-entry?target=private-zoom&character=nayeli) |
|
||||
| Elio | [打开 Elio 私密空间](http://localhost:3000/external-entry?target=private-zone&character=elio) |
|
||||
| Maya | [打开 Maya 私密空间](http://localhost:3000/external-entry?target=private-zone&character=maya) |
|
||||
| Nayeli | [打开 Nayeli 私密空间](http://localhost:3000/external-entry?target=private-zone&character=nayeli) |
|
||||
|
||||
如需为其他入口携带 PSID,在链接末尾追加 `&psid=27511427698460020`。对于不带查询参数的默认入口,请改为追加 `?psid=27511427698460020`。
|
||||
|
||||
@@ -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-zoom) |
|
||||
| Maya 私密空间 | [打开 Maya 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zoom&character=maya) |
|
||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zoom&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-zoom) |
|
||||
| Maya 私密空间 | [打开 Maya 私密空间](https://cozsweet.com/external-entry?target=private-zoom&character=maya) |
|
||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://cozsweet.com/external-entry?target=private-zoom&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`。
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Private Zoom 全链路改名联调说明
|
||||
# Private Zone 全链路改名联调说明
|
||||
|
||||
- 日期:2026-07-22
|
||||
- 目标环境:本地、`pre`、生产
|
||||
- 当前状态:已实现待联调
|
||||
- 当前状态:已验证
|
||||
|
||||
## 1. 目标
|
||||
|
||||
原功能名称存在拼写错误。本次将前端、unified 后端、Manager、数据库、埋点和文档中的正式命名统一为 `Private Zoom`,并同步切换页面路由、API 路径和公开枚举值。
|
||||
原功能名称存在拼写错误。本次将前端、unified 后端、Manager、数据库、埋点和文档中的正式命名统一为 `Private Zone`,并同步切换页面路由、API 路径和公开枚举值。
|
||||
|
||||
## 2. 环境地址
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
|
||||
前端已完成以下修改:
|
||||
|
||||
- 页面路由统一为 `/private-zoom` 和 `/characters/{characterSlug}/private-zoom`。
|
||||
- 外部入口参数统一为 `target=private-zoom`。
|
||||
- 支付回跳参数统一为 `returnTo=private-zoom`。
|
||||
- 类型、Repository、API client、XState actor、Provider 和资源目录统一使用 `privateZoom`、`PrivateZoom`、`private-zoom` 或 `private_zoom`。
|
||||
- 埋点键统一为 `navigation.private_zoom`、`chat.open_private_zoom_from_avatar` 等新名称。
|
||||
- 角色能力字段统一为 `capabilities.privateZoom`。
|
||||
- 页面路由统一为 `/private-zone` 和 `/characters/{characterSlug}/private-zone`。
|
||||
- 外部入口参数统一为 `target=private-zone`。
|
||||
- 支付回跳参数统一为 `returnTo=private-zone`。
|
||||
- 类型、Repository、API client、XState actor、Provider 和资源目录统一使用 `privateZone`、`PrivateZone`、`private-zone` 或 `private_zone`。
|
||||
- 埋点键统一为 `navigation.private_zone`、`chat.open_private_zone_from_avatar` 等新名称。
|
||||
- 角色能力字段统一为 `capabilities.privateZone`。
|
||||
|
||||
旧页面和旧查询参数不再作为正式入口保留。发布时必须让前后端属于同一个发布批次。
|
||||
|
||||
@@ -34,19 +34,19 @@
|
||||
|
||||
| 方法 | 新路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/api/private-zoom/albums` | 查询付费图片包 |
|
||||
| `POST` | `/api/private-zoom/albums/{albumId}/unlock` | 解锁图片包 |
|
||||
| `GET` | `/api/private-zoom/moments` | 查询朋友圈式内容 |
|
||||
| `POST` | `/api/private-zoom/moments/{momentId}/unlock` | 解锁单条内容 |
|
||||
| `GET` | `/api/private-zoom/config` | 查询当前角色和用户解锁配置 |
|
||||
| `GET` | `/api/private-zoom/diaries` | 查询关系日记 |
|
||||
| `POST` | `/api/private-zoom/diaries/{diaryId}/seen` | 标记关系日记已读 |
|
||||
| `POST` | `/api/private-zoom/diaries/{diaryId}/unlock` | 解锁关系日记 |
|
||||
| `GET` | `/api/private-zone/albums` | 查询付费图片包 |
|
||||
| `POST` | `/api/private-zone/albums/{albumId}/unlock` | 解锁图片包 |
|
||||
| `GET` | `/api/private-zone/moments` | 查询朋友圈式内容 |
|
||||
| `POST` | `/api/private-zone/moments/{momentId}/unlock` | 解锁单条内容 |
|
||||
| `GET` | `/api/private-zone/config` | 查询当前角色和用户解锁配置 |
|
||||
| `GET` | `/api/private-zone/diaries` | 查询关系日记 |
|
||||
| `POST` | `/api/private-zone/diaries/{diaryId}/seen` | 标记关系日记已读 |
|
||||
| `POST` | `/api/private-zone/diaries/{diaryId}/unlock` | 解锁关系日记 |
|
||||
|
||||
### 4.1 图片包列表
|
||||
|
||||
```http
|
||||
GET /api/private-zoom/albums?characterId=elio&limit=20
|
||||
GET /api/private-zone/albums?characterId=elio&limit=20
|
||||
Authorization: Bearer <TOKEN>
|
||||
```
|
||||
|
||||
@@ -59,14 +59,14 @@ Authorization: Bearer <TOKEN>
|
||||
调用示例:
|
||||
|
||||
```bash
|
||||
curl 'https://proapi.banlv-ai.com/api/private-zoom/albums?characterId=elio&limit=20' \
|
||||
curl 'https://proapi.banlv-ai.com/api/private-zone/albums?characterId=elio&limit=20' \
|
||||
-H 'Authorization: Bearer <TOKEN>'
|
||||
```
|
||||
|
||||
### 4.2 解锁图片包
|
||||
|
||||
```http
|
||||
POST /api/private-zoom/albums/{albumId}/unlock
|
||||
POST /api/private-zone/albums/{albumId}/unlock
|
||||
Authorization: Bearer <TOKEN>
|
||||
Content-Type: application/json
|
||||
```
|
||||
@@ -77,7 +77,7 @@ Content-Type: application/json
|
||||
| `expectedCost` | body | integer | 否 | 是 | 前端确认价格;与后端价格不一致时拒绝解锁 |
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://proapi.banlv-ai.com/api/private-zoom/albums/<ALBUM_ID>/unlock' \
|
||||
curl -X POST 'https://proapi.banlv-ai.com/api/private-zone/albums/<ALBUM_ID>/unlock' \
|
||||
-H 'Authorization: Bearer <TOKEN>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"expectedCost":320}'
|
||||
@@ -86,8 +86,8 @@ curl -X POST 'https://proapi.banlv-ai.com/api/private-zoom/albums/<ALBUM_ID>/unl
|
||||
### 4.3 Moments 内容与解锁
|
||||
|
||||
```http
|
||||
GET /api/private-zoom/moments?characterId=elio&limit=20
|
||||
POST /api/private-zoom/moments/{momentId}/unlock
|
||||
GET /api/private-zone/moments?characterId=elio&limit=20
|
||||
POST /api/private-zone/moments/{momentId}/unlock
|
||||
```
|
||||
|
||||
解锁请求体与图片包一致,`expectedCost` 为可选整数。响应中的正式分类值同步改为:
|
||||
@@ -95,8 +95,8 @@ POST /api/private-zoom/moments/{momentId}/unlock
|
||||
```json
|
||||
{
|
||||
"lockDetail": {
|
||||
"type": "private_zoom_moment",
|
||||
"reason": "private_zoom_moment"
|
||||
"type": "private_zone_moment",
|
||||
"reason": "private_zone_moment"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -105,24 +105,24 @@ POST /api/private-zoom/moments/{momentId}/unlock
|
||||
|
||||
| 使用位置 | 新值 | 类型 |
|
||||
| --- | --- | --- |
|
||||
| `/api/chat/unlock-private` 的 `lockType` 别名 | `private_zoom` | string enum |
|
||||
| 日程导入 `contentType` 别名 | `private_zoom` | string enum,归一化为 `paid_content` |
|
||||
| 外部入口 `target` | `private-zoom` | string enum |
|
||||
| 支付回跳 `returnTo` | `private-zoom` | string enum |
|
||||
| 锁定详情分类 | `private_zoom_moment` | string enum |
|
||||
| `/api/chat/unlock-private` 的 `lockType` 别名 | `private_zone` | string enum |
|
||||
| 日程导入 `contentType` 别名 | `private_zone` | string enum,归一化为 `paid_content` |
|
||||
| 外部入口 `target` | `private-zone` | string enum |
|
||||
| 支付回跳 `returnTo` | `private-zone` | string enum |
|
||||
| 锁定详情分类 | `private_zone_moment` | string enum |
|
||||
|
||||
## 6. 数据库迁移
|
||||
|
||||
因为 `pre` 与生产当前共用 `https://dbapi.banlv-ai.com`,预发部署前先执行 unified 仓库中的临时桥接脚本:
|
||||
|
||||
```text
|
||||
database/private-zoom-bridge.sql
|
||||
database/private-zone-bridge.sql
|
||||
```
|
||||
|
||||
桥接脚本会创建新表并在切换窗口内保持新旧解锁写入双向同步。生产前后端全部切换完成后,再执行最终迁移:
|
||||
|
||||
```text
|
||||
database/private-zoom-migration.sql
|
||||
database/private-zone-migration.sql
|
||||
```
|
||||
|
||||
迁移会在同一事务中完成:
|
||||
@@ -130,7 +130,7 @@ database/private-zoom-migration.sql
|
||||
- 将历史解锁表无损重命名;新旧表同时存在时先合并再删除旧表。
|
||||
- 重命名关联约束、索引、策略和触发器。
|
||||
- 合并 `users.preferences` 中历史解锁键,防止已解锁内容重新锁定。
|
||||
- 把 `credit_ledger` 历史分类迁移到 `private_zoom` 和 `private_zoom_moment`。
|
||||
- 把 `credit_ledger` 历史分类迁移到 `private_zone` 和 `private_zone_moment`。
|
||||
- 定向迁移历史埋点键、页面 URL 和系统媒体路径,不改写用户聊天正文。
|
||||
- 删除切换窗口使用的双写触发器和函数。
|
||||
- 支持重复执行。
|
||||
@@ -140,13 +140,13 @@ database/private-zoom-migration.sql
|
||||
这是破坏性命名修正,不保留旧 API、旧页面路由或旧公开枚举作为正式兼容层。必须按以下顺序发布:
|
||||
|
||||
1. 备份数据库并记录当前 unified、前端和 Manager 版本。
|
||||
2. 执行 `database/private-zoom-bridge.sql`,确认新旧表双向写入一致。
|
||||
3. 部署 unified `pre`,验证所有 `/api/private-zoom/*` 接口。
|
||||
2. 执行 `database/private-zone-bridge.sql`,确认新旧表双向写入一致。
|
||||
3. 部署 unified `pre`,验证所有 `/api/private-zone/*` 接口。
|
||||
4. 部署前端 `pre`,验证页面、外部入口、解锁和支付回跳。
|
||||
5. Manager 更新后验证积分用途显示为新分类。
|
||||
6. `pre` 验证通过后,先启动新生产后端并临时配置旧 API 到新 API 的 Nginx 转发。
|
||||
7. 切换生产后端,再部署同批次生产前端;确认新前端只调用 `/api/private-zoom/*`。
|
||||
8. 删除临时 Nginx 转发,执行 `database/private-zoom-migration.sql` 清理旧数据库对象。
|
||||
7. 切换生产后端,再部署同批次生产前端;确认新前端只调用 `/api/private-zone/*`。
|
||||
8. 删除临时 Nginx 转发,执行 `database/private-zone-migration.sql` 清理旧数据库对象。
|
||||
|
||||
## 8. 错误与界面状态
|
||||
|
||||
@@ -154,32 +154,35 @@ database/private-zoom-migration.sql
|
||||
- `403`:游客访问仅注册用户可用的关系日记操作,展示现有注册引导。
|
||||
- `404`:角色、图片包、内容或日记不存在,展示现有空状态或失效提示。
|
||||
- `409`:`expectedCost` 与后端价格不同,刷新列表后重新确认。
|
||||
- `402` 或业务余额不足错误:进入现有充值流程,并使用 `returnTo=private-zoom` 返回原角色页面。
|
||||
- `402` 或业务余额不足错误:进入现有充值流程,并使用 `returnTo=private-zone` 返回原角色页面。
|
||||
- 网络失败:不修改本地解锁状态,保留重试入口。
|
||||
|
||||
## 9. 验收用例
|
||||
|
||||
1. `/characters/elio/private-zoom`、Maya 和 Nayeli 对应页面均可打开。
|
||||
2. `GET /api/private-zoom/albums` 返回当前角色内容,角色之间不混用。
|
||||
1. `/characters/elio/private-zone`、Maya 和 Nayeli 对应页面均可打开。
|
||||
2. `GET /api/private-zone/albums` 返回当前角色内容,角色之间不混用。
|
||||
3. 已解锁历史记录在迁移后保持解锁状态,不重复扣积分。
|
||||
4. 新解锁成功后刷新页面仍为已解锁状态。
|
||||
5. 积分不足进入充值页后,回跳到原角色 `/private-zoom` 页面。
|
||||
6. `target=private-zoom&character=nayeli` 进入 Nayeli 对应页面。
|
||||
5. 积分不足进入充值页后,回跳到原角色 `/private-zone` 页面。
|
||||
6. `target=private-zone&character=nayeli` 进入 Nayeli 对应页面。
|
||||
7. Manager 的积分用途不再出现旧分类。
|
||||
8. 三个仓库执行旧命名残留扫描,结果为 `0`。
|
||||
|
||||
## 10. 当前测试证据
|
||||
|
||||
- unified:`316 passed`。
|
||||
- 前端:TypeScript 类型检查通过;Vitest `639 passed`;ESLint 通过;契约测试 `4 passed`;生产构建通过并生成三个角色的 `/private-zoom` 页面。
|
||||
- 前端:TypeScript 类型检查通过;Vitest `639 passed`;ESLint 通过;契约测试 `4 passed`;生产构建通过并生成三个角色的 `/private-zone` 页面。
|
||||
- Manager:`75 passed`。
|
||||
- PostgreSQL 16 临时库:升级、重复升级、回滚和再次升级全部通过;历史解锁、偏好键、积分账本、埋点、媒体路径和数据库对象名均通过断言,临时容器已删除。
|
||||
- `pre`:unified `71da49b` 和前端 `35939e7` 已验证;新 API 已注册 `8` 条 `/api/private-zone/*` 路径,旧 API 路径数量为 `0`;新页面返回 `200`,旧页面返回 `404`。
|
||||
- 生产:unified 镜像 `ai-boyfriend-unified:prod-20260722-71da49b`(镜像 ID `sha256:755ef5741856d83d7d808e7df8ee259b6fa5fb94fe333b523ee280ed1d5f674b`)和前端镜像 `prod-35939e7` 已健康运行;Manager 当前版本为 `6eea005`。
|
||||
- 生产接口:测试账号调用 `GET https://api.banlv-ai.com/api/private-zone/config?characterId=elio` 返回 `200`,`success=true`;旧版 API 路径在所有公开 API 入口均返回 `404`。
|
||||
- 生产数据库:最终迁移已执行,旧表、桥接函数、桥接触发器、旧偏好键、旧积分分类和旧埋点值的残留数量均为 `0`。
|
||||
|
||||
## 11. 回滚影响
|
||||
|
||||
最终迁移执行前可直接恢复旧应用,桥接表会保留双向一致的数据。最终迁移执行后,回滚必须同时执行 unified 仓库中的 `database/private-zoom-rollback.sql`。回滚前应停止写入,先保存切换后的新增解锁记录,再执行逆向迁移并恢复旧应用版本。不得只恢复前端或只恢复 unified。
|
||||
最终迁移执行前可直接恢复旧应用,桥接表会保留双向一致的数据。最终迁移执行后,回滚必须同时执行 unified 仓库中的 `database/private-zone-rollback.sql`。回滚前应停止写入,先保存切换后的新增解锁记录,再执行逆向迁移并恢复旧应用版本。不得只恢复前端或只恢复 unified。
|
||||
|
||||
## 12. 待确认事项
|
||||
|
||||
- `pre` 浏览器真实联调和生产发布尚未执行。
|
||||
- 生产镜像 ID 将在发布前固化到发布记录。
|
||||
- 无。
|
||||
@@ -20,6 +20,23 @@ export interface ChatMockState {
|
||||
export async function registerChatMocks(page: Page, options: ChatMockOptions, state: ChatMockState) {
|
||||
let sendCount = 0;
|
||||
|
||||
await page.route("**/api/chat/opening-message", async (route) => {
|
||||
const body = route.request().postDataJSON() as {
|
||||
openingMessage?: unknown;
|
||||
} | undefined;
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({
|
||||
messageId: "mock-opening-message",
|
||||
created: true,
|
||||
openingMessage:
|
||||
typeof body?.openingMessage === "string"
|
||||
? body.openingMessage
|
||||
: "Hello",
|
||||
createdAt: "2026-07-23T00:00:00Z",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route("**/api/chat/history**", async (route) => {
|
||||
const response = options.paidVoiceInsufficientCreditsFlow
|
||||
? paidVoiceHistoryResponse
|
||||
@@ -44,7 +61,35 @@ export async function registerChatMocks(page: Page, options: ChatMockOptions, st
|
||||
await route.fulfill({ status: 401, json: { message: "expired" } });
|
||||
return;
|
||||
}
|
||||
const response = options.paidImageFlow && message.includes("给我发图片")
|
||||
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.",
|
||||
messageId: "commercial-action-message",
|
||||
commercialAction: {
|
||||
actionId: "commercial-action-1",
|
||||
type: "privateAlbumOffer",
|
||||
copy: "There are more private photos waiting for you.",
|
||||
ctaLabel: "Open private zone",
|
||||
target: "privateZone",
|
||||
ruleId: "private_album_after_appearance_praise",
|
||||
},
|
||||
}
|
||||
: options.paidImageFlow && message.includes("给我发图片")
|
||||
? paidImageChatSendResponse
|
||||
: options.chatLimitTriggerAt != null && sendCount >= options.chatLimitTriggerAt
|
||||
? createWeeklyLimitChatSendResponse(sendCount, options.chatLimitTriggerAt)
|
||||
|
||||
@@ -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) }));
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -31,5 +31,5 @@ test("user can email login from other sign-in options and return to chat", async
|
||||
expect(["desktop", "android"]).toContain(loginRequest?.postDataJSON().platform);
|
||||
|
||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Profile" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -27,9 +27,12 @@ test("user can log out from the profile after email login", async ({
|
||||
await expect(page).toHaveURL(/\/auth(?:\?.*)?$/);
|
||||
await switchToEmailSignIn(page);
|
||||
await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });
|
||||
await expect(page.getByRole("button", { name: "Profile" })).toBeVisible();
|
||||
await page.getByRole("link", { name: "Back to home" }).click();
|
||||
await expect(page).toHaveURL(
|
||||
new RegExp(defaultCharacterSplashPath.replace("?", "\\?") + "$"),
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Profile" }).click();
|
||||
await page.getByRole("button", { name: "Menu" }).click();
|
||||
await expect(page).toHaveURL(
|
||||
new RegExp(defaultCharacterProfilePath.replace("?", "\\?") + "$"),
|
||||
);
|
||||
|
||||
@@ -42,7 +42,7 @@ test("guest user avatar returns to Profile after sign-in", async ({
|
||||
});
|
||||
|
||||
for (const character of characters) {
|
||||
test(`${character.displayName} avatar opens the matching Private Zoom`, async ({
|
||||
test(`${character.displayName} avatar opens the matching Private Zone`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await enterCharacterChat(page, character.slug);
|
||||
@@ -50,13 +50,13 @@ for (const character of characters) {
|
||||
|
||||
await page
|
||||
.getByRole("button", {
|
||||
name: `Open ${character.displayName}'s private zoom`,
|
||||
name: `Open ${character.displayName}'s private zone`,
|
||||
})
|
||||
.last()
|
||||
.click();
|
||||
|
||||
await expect(page).toHaveURL(
|
||||
new RegExp(`/characters/${character.slug}/private-zoom(?:\\?.*)?$`),
|
||||
new RegExp(`/characters/${character.slug}/private-zone(?:\\?.*)?$`),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||
import {
|
||||
clearBrowserState,
|
||||
enterChatFromSplash,
|
||||
expectAuthRedirectToVipChatSubscription,
|
||||
} from "@e2e/fixtures/test-helpers";
|
||||
|
||||
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||
await clearBrowserState(context, page, baseURL);
|
||||
await mockCoreApis(page);
|
||||
});
|
||||
|
||||
test("renders a backend commercial action and opens the private zone", async ({
|
||||
page,
|
||||
}) => {
|
||||
await enterChatFromSplash(page);
|
||||
|
||||
const input = page.getByRole("textbox", { name: "Message" });
|
||||
await expect(input).toBeEnabled();
|
||||
await input.fill("private album offer test");
|
||||
await input.press("Enter");
|
||||
|
||||
const offer = page.getByLabel("Open private zone");
|
||||
await expect(offer).toContainText(
|
||||
"There are more private photos waiting for you.",
|
||||
);
|
||||
await offer.getByRole("button", { name: "Open private zone" }).click();
|
||||
|
||||
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 });
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||
import { apiEnvelope } from "@e2e/fixtures/data/common";
|
||||
import { e2eEmailUser } from "@e2e/fixtures/data/auth";
|
||||
import { chatCharactersResponse } from "@e2e/fixtures/data/character";
|
||||
import {
|
||||
emptyChatHistoryResponse,
|
||||
emptyChatPreviewsResponse,
|
||||
} from "@e2e/fixtures/data/chat";
|
||||
import { paymentPlansResponse } from "@e2e/fixtures/data/payment";
|
||||
import { userEntitlementsResponse } from "@e2e/fixtures/data/user";
|
||||
import {
|
||||
defaultCharacterChatPath,
|
||||
defaultCharacterSplashPath,
|
||||
seedEmailSession,
|
||||
} from "@e2e/fixtures/helpers/auth";
|
||||
|
||||
const previewDirectory = path.join(
|
||||
process.cwd(),
|
||||
".codex",
|
||||
"artifacts",
|
||||
"frontend-preview",
|
||||
"2026-07-22",
|
||||
"favorite-menu",
|
||||
);
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await registerFavoriteMenuMocks(page);
|
||||
});
|
||||
|
||||
test("favorite entry and three-tab Menu navigation render on the real pages", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const mobile = testInfo.project.name.includes("mobile");
|
||||
await page.setViewportSize(
|
||||
mobile ? { width: 390, height: 844 } : { width: 1440, height: 900 },
|
||||
);
|
||||
const browserErrors = collectBrowserErrors(page);
|
||||
|
||||
await seedEmailSession(page);
|
||||
await page.goto(defaultCharacterChatPath);
|
||||
|
||||
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: /First recharge offer, 50% off/i }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Profile" })).toHaveCount(0);
|
||||
await savePreview(page, `${mobile ? "mobile" : "desktop"}-chat.png`);
|
||||
|
||||
await page.goto(defaultCharacterSplashPath);
|
||||
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
||||
const navigation = page.getByRole("navigation", {
|
||||
name: "Primary navigation",
|
||||
});
|
||||
await expect(navigation).toContainText("Chat");
|
||||
await expect(navigation).toContainText("Private Zone");
|
||||
await expect(navigation).toContainText("Menu");
|
||||
await savePreview(page, `${mobile ? "mobile" : "desktop"}-splash.png`);
|
||||
|
||||
await page.goto("/characters/elio/private-zone");
|
||||
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
||||
await savePreview(
|
||||
page,
|
||||
`${mobile ? "mobile" : "desktop"}-private-zone.png`,
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Menu" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Menu" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Menu" })).toHaveAttribute(
|
||||
"aria-current",
|
||||
"page",
|
||||
);
|
||||
await savePreview(page, `${mobile ? "mobile" : "desktop"}-menu.png`);
|
||||
|
||||
if (mobile) {
|
||||
await page.evaluate(() => {
|
||||
localStorage.setItem("cozsweet:favorite_entry", "1");
|
||||
});
|
||||
await page.goto(defaultCharacterChatPath);
|
||||
await expect(page.getByRole("button", { name: "Download" })).toBeVisible();
|
||||
await savePreview(page, "mobile-android-external-chat-download.png");
|
||||
|
||||
await page.addInitScript(() => {
|
||||
Object.defineProperty(navigator, "userAgent", {
|
||||
configurable: true,
|
||||
value:
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
|
||||
});
|
||||
});
|
||||
await page.goto(defaultCharacterChatPath);
|
||||
const iosDownload = page.getByRole("button", { name: "Download" });
|
||||
await expect(iosDownload).toBeVisible();
|
||||
await iosDownload.click();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Add CozSweet to Home Screen" }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("dialog")).toContainText(
|
||||
"In Safari, tap the Share button, then choose “Add to Home Screen”.",
|
||||
);
|
||||
await savePreview(page, "mobile-ios-external-chat-download.png");
|
||||
}
|
||||
|
||||
expect(browserErrors.filter(isFeatureRuntimeError)).toEqual([]);
|
||||
});
|
||||
|
||||
async function registerFavoriteMenuMocks(page: Page): Promise<void> {
|
||||
await mockCoreApis(page);
|
||||
await page.route("**/api/payment/plans**", async (route) => {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({
|
||||
...paymentPlansResponse,
|
||||
isFirstRecharge: true,
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route("**/api/private-zone/albums**", async (route) => {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({ items: [], creditBalance: 80 }),
|
||||
});
|
||||
});
|
||||
await page.context().route("**/api/**", async (route) => {
|
||||
const pathname = new URL(route.request().url()).pathname;
|
||||
if (pathname === "/api/auth/session") {
|
||||
await route.fulfill({
|
||||
json: {
|
||||
expires: "2099-12-31T23:59:59.000Z",
|
||||
user: { email: null, image: null, name: null },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/characters") {
|
||||
await route.fulfill({ json: apiEnvelope(chatCharactersResponse) });
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/user/profile") {
|
||||
await route.fulfill({ json: apiEnvelope(e2eEmailUser) });
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/user/entitlements") {
|
||||
await route.fulfill({ json: apiEnvelope(userEntitlementsResponse) });
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/chat/history") {
|
||||
await route.fulfill({ json: apiEnvelope(emptyChatHistoryResponse) });
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/chat/previews") {
|
||||
await route.fulfill({ json: apiEnvelope(emptyChatPreviewsResponse) });
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/payment/plans") {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({
|
||||
...paymentPlansResponse,
|
||||
isFirstRecharge: true,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/payment/vip-status") {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({ isVip: false, expiresAt: null }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (pathname === "/api/private-zone/albums") {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({ items: [], creditBalance: 80 }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fallback();
|
||||
});
|
||||
}
|
||||
|
||||
function collectBrowserErrors(page: Page): string[] {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (error) => errors.push(error.stack ?? error.message));
|
||||
page.on("console", (message) => {
|
||||
if (message.type() === "error") errors.push(message.text());
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
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("Cannot read properties of undefined (reading 'waiting')");
|
||||
return !isKnownLocalPreviewDependencyError;
|
||||
}
|
||||
|
||||
async function savePreview(page: Page, fileName: string): Promise<void> {
|
||||
if (process.env.FRONTEND_PREVIEW_SCREENSHOTS !== "1") return;
|
||||
await page.screenshot({
|
||||
path: path.join(previewDirectory, fileName),
|
||||
animations: "disabled",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||
import { apiEnvelope } from "@e2e/fixtures/data/common";
|
||||
import { clearBrowserState } from "@e2e/fixtures/test-helpers";
|
||||
|
||||
const characters = [
|
||||
{
|
||||
id: "elio",
|
||||
slug: "elio",
|
||||
displayName: "Elio Silvestri",
|
||||
shortName: "Elio",
|
||||
cover: "elio.png",
|
||||
splashCover: "elio.png",
|
||||
},
|
||||
{
|
||||
id: "maya-tan",
|
||||
slug: "maya",
|
||||
displayName: "Maya Tan",
|
||||
shortName: "Maya",
|
||||
cover: "maya.webp",
|
||||
splashCover: "maya-home.webp",
|
||||
},
|
||||
{
|
||||
id: "nayeli-cervantes",
|
||||
slug: "nayeli",
|
||||
displayName: "Nayeli Cervantes",
|
||||
shortName: "Nayeli",
|
||||
cover: "nayeli.webp",
|
||||
splashCover: "nayeli.webp",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const previewDirectory = path.join(
|
||||
process.cwd(),
|
||||
".codex",
|
||||
"artifacts",
|
||||
"frontend-preview",
|
||||
"2026-07-22",
|
||||
"multi-role-commercial",
|
||||
);
|
||||
|
||||
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||
await clearBrowserState(context, page, baseURL);
|
||||
await mockCoreApis(page);
|
||||
await registerMultiRoleCommercialMocks(page);
|
||||
});
|
||||
|
||||
for (const character of characters) {
|
||||
test(`${character.displayName} homepage renders its assigned cover`, async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const mobile = testInfo.project.name.includes("mobile");
|
||||
await page.setViewportSize(
|
||||
mobile ? { width: 390, height: 844 } : { width: 1440, height: 900 },
|
||||
);
|
||||
|
||||
await page.goto(`/characters/${character.slug}/splash`);
|
||||
|
||||
const cover = page.locator(`img[src*="${character.splashCover}"]`);
|
||||
await expect(cover).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("navigation", { name: "Primary navigation" }),
|
||||
).toContainText("Private Zone");
|
||||
await expect
|
||||
.poll(() =>
|
||||
cover.evaluate((image: HTMLImageElement) =>
|
||||
image.complete ? image.naturalWidth : 0,
|
||||
),
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
if (
|
||||
process.env.FRONTEND_PREVIEW_SCREENSHOTS === "1" &&
|
||||
character.id !== "elio"
|
||||
) {
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
previewDirectory,
|
||||
`${character.slug}-${mobile ? "mobile-390x844" : "desktop-1440x900"}.png`,
|
||||
),
|
||||
animations: "disabled",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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 (
|
||||
url.pathname === "/api/private-zone/albums" &&
|
||||
url.searchParams.get("characterId") === character.id
|
||||
);
|
||||
});
|
||||
|
||||
await page.goto(`/characters/${character.slug}/private-zone`);
|
||||
|
||||
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();
|
||||
await expect(page.getByText(character.displayName).last()).toBeVisible();
|
||||
const albumButton = page.getByRole("button", {
|
||||
name: `View locked collection with 8 images from ${character.displayName}`,
|
||||
});
|
||||
if (character.id === "maya-tan") {
|
||||
await expect(albumButton).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: "Refresh" })).toHaveCount(0);
|
||||
await expect(page.getByText("No private albums yet.")).toHaveCount(0);
|
||||
} else {
|
||||
await expect(albumButton).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${character.displayName} receives a character-scoped Tip catalog`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const catalogRequest = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url());
|
||||
return (
|
||||
url.pathname === "/api/payment/gift-products" &&
|
||||
url.searchParams.get("characterId") === character.id
|
||||
);
|
||||
});
|
||||
|
||||
await page.goto(`/characters/${character.slug}/tip`);
|
||||
|
||||
await catalogRequest;
|
||||
await expect(
|
||||
page.getByRole("heading", { name: `Buy ${character.shortName} a coffee` }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("radio", { name: /Small Coffee/ })).toBeChecked();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Order and Buy" }),
|
||||
).toBeEnabled();
|
||||
await expect(
|
||||
page.getByText("This character does not have any gifts available yet."),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
test("a real Private Zone request failure still offers Retry", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.route("**/api/private-zone/albums**", async (route) => {
|
||||
await route.fulfill({ status: 503, json: { message: "Albums unavailable" } });
|
||||
});
|
||||
|
||||
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";
|
||||
const character =
|
||||
characters.find((candidate) => candidate.id === characterId) ?? characters[0];
|
||||
|
||||
const hasCompleteAlbum = character.id !== "maya-tan";
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({
|
||||
creditBalance: 1000,
|
||||
pendingImageCount: hasCompleteAlbum ? 0 : 7,
|
||||
hasIncompleteContent: !hasCompleteAlbum,
|
||||
items: hasCompleteAlbum ? [
|
||||
{
|
||||
albumId: `album-${character.id}`,
|
||||
title: `${character.shortName} private photos`,
|
||||
content: null,
|
||||
previewText: "Unlock this private album",
|
||||
imageCount: 8,
|
||||
images: [
|
||||
{
|
||||
url: `/images/private-zone/banner/${character.slug}.png`,
|
||||
locked: true,
|
||||
index: 0,
|
||||
},
|
||||
],
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
unlockCost: 320,
|
||||
publishedAt: "2026-07-22T10:00:00+08:00",
|
||||
lockDetail: { locked: true },
|
||||
},
|
||||
] : [],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route("**/api/payment/gift-products**", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const characterId = url.searchParams.get("characterId") ?? "elio";
|
||||
const planPrefix =
|
||||
characterId === "elio"
|
||||
? "tip"
|
||||
: `tip_${characterId.replaceAll("-", "_")}`;
|
||||
|
||||
await route.fulfill({
|
||||
json: apiEnvelope({
|
||||
characterId,
|
||||
categories: [
|
||||
{
|
||||
category: "coffee",
|
||||
name: "Coffee",
|
||||
productCount: 1,
|
||||
imageUrl: null,
|
||||
},
|
||||
],
|
||||
plans: [
|
||||
{
|
||||
planId: `${planPrefix}_coffee_usd_4_99`,
|
||||
planName: "Small Coffee",
|
||||
orderType: "tip",
|
||||
tipType: "coffee_small",
|
||||
category: "coffee",
|
||||
characterId,
|
||||
description: "A character-scoped coffee gift",
|
||||
imageUrl: null,
|
||||
amountCents: 499,
|
||||
currency: "USD",
|
||||
autoRenew: false,
|
||||
isFirstRechargeOffer: false,
|
||||
firstRechargeDiscountPercent: 0,
|
||||
promotionType: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||
import { apiEnvelope } from "@e2e/fixtures/data/common";
|
||||
import { createPaidImageHistoryResponse } from "@e2e/fixtures/data/chat";
|
||||
import {
|
||||
paidImageDisplayMessageId,
|
||||
paidImageMessageId,
|
||||
@@ -17,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, {
|
||||
@@ -46,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);
|
||||
@@ -73,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;
|
||||
@@ -97,3 +87,38 @@ test("guest can unlock a paid image after email login and subscription payment",
|
||||
expect(new URL(page.url()).pathname).toBe(defaultCharacterChatPath);
|
||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("fullscreen image closes from its back button, the image, and browser history Back", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.route("**/api/chat/history**", async (route) => {
|
||||
await route.fulfill({
|
||||
json: apiEnvelope(createPaidImageHistoryResponse(true)),
|
||||
});
|
||||
});
|
||||
await enterChatFromSplash(page);
|
||||
await dismissChatInterruptions(page);
|
||||
|
||||
const imageButton = page.getByRole("button", {
|
||||
name: "Open image in fullscreen",
|
||||
});
|
||||
const imageDialog = page.getByRole("dialog", { name: "Fullscreen image" });
|
||||
|
||||
await imageButton.click();
|
||||
await expect(imageDialog).toBeVisible();
|
||||
await imageDialog.getByRole("button", { name: "Back" }).click();
|
||||
await expect(imageDialog).toHaveCount(0);
|
||||
await expect(page).toHaveURL(defaultCharacterChatPath);
|
||||
|
||||
await imageButton.click();
|
||||
await expect(imageDialog).toBeVisible();
|
||||
await imageDialog.locator("img").click();
|
||||
await expect(imageDialog).toHaveCount(0);
|
||||
await expect(page).toHaveURL(defaultCharacterChatPath);
|
||||
|
||||
await imageButton.click();
|
||||
await expect(imageDialog).toBeVisible();
|
||||
await page.goBack();
|
||||
await expect(imageDialog).toHaveCount(0);
|
||||
await expect(page).toHaveURL(defaultCharacterChatPath);
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 482 KiB |
|
Before Width: | Height: | Size: 10 MiB |
|
After Width: | Height: | Size: 581 KiB |
|
Before Width: | Height: | Size: 351 KiB |
|
After Width: | Height: | Size: 129 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 814 KiB After Width: | Height: | Size: 814 KiB |
|
Before Width: | Height: | Size: 652 KiB After Width: | Height: | Size: 652 KiB |
|
Before Width: | Height: | Size: 907 KiB After Width: | Height: | Size: 907 KiB |
@@ -11,13 +11,13 @@
|
||||
"lang": "en",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/images/icons/Icon-192.png",
|
||||
"src": "/images/icons/Icon-192.png?v=20260724",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/images/icons/Icon-512.png",
|
||||
"src": "/images/icons/Icon-512.png?v=20260724",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
|
||||
@@ -13,13 +13,13 @@ describe("OpenAPI contract comparison", () => {
|
||||
chatHistory: { method: "get", path: "/api/chat/history" },
|
||||
unlockAlbum: {
|
||||
method: "post",
|
||||
path: "/api/private-zoom/albums/{albumId}/unlock",
|
||||
path: "/api/private-zone/albums/{albumId}/unlock",
|
||||
},
|
||||
},
|
||||
{
|
||||
paths: {
|
||||
"/api/chat/history": { get: {} },
|
||||
"/api/private-zoom/albums/{album_id}/unlock/": { post: {} },
|
||||
"/api/private-zone/albums/{album_id}/unlock/": { post: {} },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -85,8 +85,8 @@ describe("shared Tailwind components", () => {
|
||||
<CharacterAvatar
|
||||
src="/images/avatar/elio.png"
|
||||
alt="Elio Silvestri"
|
||||
actionLabel="Open Elio's private zoom"
|
||||
analyticsKey="chat.open_private_zoom_from_avatar"
|
||||
actionLabel="Open Elio's private zone"
|
||||
analyticsKey="chat.open_private_zone_from_avatar"
|
||||
onClick={() => undefined}
|
||||
/>,
|
||||
);
|
||||
@@ -100,10 +100,10 @@ describe("shared Tailwind components", () => {
|
||||
|
||||
expect(characterHtml).toContain('<button type="button"');
|
||||
expect(characterHtml).toContain(
|
||||
'aria-label="Open Elio's private zoom"',
|
||||
'aria-label="Open Elio's private zone"',
|
||||
);
|
||||
expect(characterHtml).toContain(
|
||||
'data-analytics-key="chat.open_private_zoom_from_avatar"',
|
||||
'data-analytics-key="chat.open_private_zone_from_avatar"',
|
||||
);
|
||||
expect(userHtml).toContain('<button type="button"');
|
||||
expect(userHtml).toContain('aria-label="Open profile"');
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/* @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 { BrowserDetector } from "@/utils/browser-detect";
|
||||
import { PlatformDetector } from "@/utils/platform-detect";
|
||||
import { pwaUtil } from "@/utils/pwa";
|
||||
|
||||
import { FavoriteEntryButton } from "../favorite-entry-button";
|
||||
|
||||
describe("FavoriteEntryButton install flow", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
window.localStorage.setItem("cozsweet:favorite_entry", "1");
|
||||
vi.spyOn(BrowserDetector, "isInAppBrowser").mockReturnValue(false);
|
||||
vi.spyOn(pwaUtil, "isInstalled").mockReturnValue(false);
|
||||
vi.spyOn(pwaUtil, "prepareInstallPrompt").mockImplementation(() => undefined);
|
||||
vi.spyOn(pwaUtil, "subscribe").mockReturnValue(() => undefined);
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("shows Download on iOS and opens Safari add-to-home instructions", () => {
|
||||
vi.spyOn(PlatformDetector, "isIOS").mockReturnValue(true);
|
||||
vi.spyOn(PlatformDetector, "isAndroid").mockReturnValue(false);
|
||||
|
||||
renderButton();
|
||||
const downloadButton = getButton("Download");
|
||||
act(() => downloadButton.click());
|
||||
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(container.textContent).toContain("Add CozSweet to Home Screen");
|
||||
expect(container.textContent).toContain(
|
||||
"In Safari, tap the Share button, then choose “Add to Home Screen”.",
|
||||
);
|
||||
});
|
||||
|
||||
it("opens the native Android install prompt and marks an accepted install as Saved", async () => {
|
||||
vi.spyOn(PlatformDetector, "isIOS").mockReturnValue(false);
|
||||
vi.spyOn(PlatformDetector, "isAndroid").mockReturnValue(true);
|
||||
const install = vi.spyOn(pwaUtil, "install").mockResolvedValue("accepted");
|
||||
|
||||
renderButton();
|
||||
await act(async () => {
|
||||
getButton("Download").click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(install).toHaveBeenCalledTimes(1);
|
||||
expect(getButton("Saved")).not.toBeNull();
|
||||
});
|
||||
|
||||
function renderButton(): void {
|
||||
act(() => {
|
||||
root.render(<FavoriteEntryButton characterSlug="elio" />);
|
||||
});
|
||||
}
|
||||
|
||||
function getButton(label: string): HTMLButtonElement {
|
||||
const button = container.querySelector<HTMLButtonElement>(
|
||||
`button[aria-label="${label}"]`,
|
||||
);
|
||||
if (!button) throw new Error(`Missing button: ${label}`);
|
||||
return button;
|
||||
}
|
||||
});
|
||||
@@ -79,18 +79,20 @@ describe("core Tailwind components", () => {
|
||||
<AppBottomNav
|
||||
activeItem="chat"
|
||||
variant="dark"
|
||||
privateZoomLabel="Maya Private Zoom"
|
||||
privateZoneLabel="Maya Private Zone"
|
||||
onChatClick={() => undefined}
|
||||
onPrivateZoomClick={() => undefined}
|
||||
onPrivateZoneClick={() => undefined}
|
||||
onMenuClick={() => undefined}
|
||||
/>,
|
||||
);
|
||||
const privateZoomHtml = renderToStaticMarkup(
|
||||
const privateZoneHtml = renderToStaticMarkup(
|
||||
<AppBottomNav
|
||||
activeItem="privateZoom"
|
||||
activeItem="privateZone"
|
||||
variant="warm"
|
||||
privateZoomLabel="Maya Private Zoom"
|
||||
privateZoneLabel="Maya Private Zone"
|
||||
onChatClick={() => undefined}
|
||||
onPrivateZoomClick={() => undefined}
|
||||
onPrivateZoneClick={() => undefined}
|
||||
onMenuClick={() => undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -99,13 +101,15 @@ describe("core Tailwind components", () => {
|
||||
expect(chatHtml).toMatch(
|
||||
/<button[^>]*aria-current="page"[^>]*>.*?<span>Chat<\/span>/,
|
||||
);
|
||||
expect(privateZoomHtml).toMatch(/class="[^"]*warm[^"]*"/);
|
||||
expect(privateZoomHtml).toMatch(
|
||||
/<button[^>]*aria-current="page"[^>]*>.*?<span>Maya Private Zoom<\/span>/,
|
||||
expect(privateZoneHtml).toMatch(/class="[^"]*warm[^"]*"/);
|
||||
expect(privateZoneHtml).toMatch(
|
||||
/<button[^>]*aria-current="page"[^>]*>.*?<span>Maya Private Zone<\/span>/,
|
||||
);
|
||||
expect(chatHtml).toContain('data-analytics-key="navigation.chat"');
|
||||
expect(privateZoomHtml).toContain(
|
||||
'data-analytics-key="navigation.private_zoom"',
|
||||
expect(privateZoneHtml).toContain(
|
||||
'data-analytics-key="navigation.private_zone"',
|
||||
);
|
||||
expect(chatHtml).toContain('data-analytics-key="navigation.menu"');
|
||||
expect(chatHtml).toContain("<span>Menu</span>");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
left: 50%;
|
||||
z-index: 30;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
box-sizing: border-box;
|
||||
width: min(100vw, var(--app-max-width, 540px));
|
||||
min-height: calc(
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { Camera, MessageCircle } from "lucide-react";
|
||||
import { Camera, Menu as MenuIcon, MessageCircle } from "lucide-react";
|
||||
|
||||
import styles from "./app-bottom-nav.module.css";
|
||||
|
||||
export type AppBottomNavItem = "chat" | "privateZoom";
|
||||
export type AppBottomNavItem = "chat" | "privateZone" | "menu";
|
||||
export type AppBottomNavVariant = "warm" | "dark";
|
||||
|
||||
export interface AppBottomNavProps {
|
||||
activeItem?: AppBottomNavItem | null;
|
||||
variant?: AppBottomNavVariant;
|
||||
privateZoomLabel: string;
|
||||
privateZoneLabel: string;
|
||||
onChatClick: () => void;
|
||||
onPrivateZoomClick: () => void;
|
||||
onPrivateZoneClick: () => void;
|
||||
onMenuClick: () => void;
|
||||
}
|
||||
|
||||
export function AppBottomNav({
|
||||
activeItem = null,
|
||||
variant = "warm",
|
||||
privateZoomLabel,
|
||||
privateZoneLabel,
|
||||
onChatClick,
|
||||
onPrivateZoomClick,
|
||||
onPrivateZoneClick,
|
||||
onMenuClick,
|
||||
}: AppBottomNavProps) {
|
||||
return (
|
||||
<nav className={getRootClass(variant)} aria-label="Primary navigation">
|
||||
@@ -37,14 +39,25 @@ export function AppBottomNav({
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-analytics-key="navigation.private_zoom"
|
||||
data-analytics-label="Private Zoom navigation"
|
||||
className={getButtonClass(activeItem === "privateZoom")}
|
||||
aria-current={activeItem === "privateZoom" ? "page" : undefined}
|
||||
onClick={onPrivateZoomClick}
|
||||
data-analytics-key="navigation.private_zone"
|
||||
data-analytics-label="Private Zone navigation"
|
||||
className={getButtonClass(activeItem === "privateZone")}
|
||||
aria-current={activeItem === "privateZone" ? "page" : undefined}
|
||||
onClick={onPrivateZoneClick}
|
||||
>
|
||||
<Camera size={20} aria-hidden="true" />
|
||||
<span>{privateZoomLabel}</span>
|
||||
<span>{privateZoneLabel}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-analytics-key="navigation.menu"
|
||||
data-analytics-label="Menu navigation"
|
||||
className={getButtonClass(activeItem === "menu")}
|
||||
aria-current={activeItem === "menu" ? "page" : undefined}
|
||||
onClick={onMenuClick}
|
||||
>
|
||||
<MenuIcon size={20} aria-hidden="true" />
|
||||
<span>Menu</span>
|
||||
</button>
|
||||
</nav>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
.wrap {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.button {
|
||||
display: inline-flex;
|
||||
min-width: var(--responsive-icon-button-size, 42px);
|
||||
height: var(--responsive-icon-button-size, 42px);
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
box-sizing: border-box;
|
||||
padding: 0 11px;
|
||||
border: 1px solid var(--favorite-border);
|
||||
border-radius: 999px;
|
||||
background: var(--favorite-background);
|
||||
color: var(--favorite-color);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 850;
|
||||
line-height: 1;
|
||||
box-shadow: var(--favorite-shadow);
|
||||
backdrop-filter: blur(16px);
|
||||
transition: background 160ms ease, transform 160ms ease,
|
||||
box-shadow 160ms ease;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--favorite-background: rgba(18, 15, 24, 0.72);
|
||||
--favorite-border: rgba(255, 255, 255, 0.22);
|
||||
--favorite-color: #ffffff;
|
||||
--favorite-shadow: 0 10px 26px rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.light {
|
||||
--favorite-background: rgba(255, 255, 255, 0.88);
|
||||
--favorite-border: rgba(43, 27, 34, 0.1);
|
||||
--favorite-color: #34272c;
|
||||
--favorite-shadow: 0 10px 24px rgba(74, 48, 58, 0.1);
|
||||
}
|
||||
|
||||
.favorite {
|
||||
width: var(--responsive-icon-button-size, 42px);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.download {
|
||||
color: #ffffff;
|
||||
background: linear-gradient(135deg, #ff76ab, #f84d96);
|
||||
border-color: rgba(255, 255, 255, 0.42);
|
||||
box-shadow: 0 10px 25px rgba(248, 77, 150, 0.3);
|
||||
}
|
||||
|
||||
.saved {
|
||||
color: #f84d96;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 13px 30px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.button:active {
|
||||
transform: translateY(1px) scale(0.98);
|
||||
}
|
||||
|
||||
.button:focus-visible {
|
||||
outline: 2px solid #ffffff;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
.light:focus-visible {
|
||||
outline-color: #f84d96;
|
||||
}
|
||||
|
||||
.guideBackdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 240;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding:
|
||||
calc(18px + var(--app-safe-top, 0px))
|
||||
calc(18px + var(--app-safe-right, 0px))
|
||||
calc(18px + var(--app-safe-bottom, 0px))
|
||||
calc(18px + var(--app-safe-left, 0px));
|
||||
background: rgba(15, 11, 18, 0.58);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.guideDialog {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: min(100%, 340px);
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 28px 22px 20px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.72);
|
||||
border-radius: 28px;
|
||||
background: rgba(255, 250, 252, 0.98);
|
||||
box-shadow: 0 24px 70px rgba(33, 17, 26, 0.3);
|
||||
color: #2d2026;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.guideClose {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
display: inline-flex;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: rgba(45, 32, 38, 0.07);
|
||||
color: #5b4a52;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.guideIcon {
|
||||
display: inline-flex;
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 14px;
|
||||
border-radius: 19px;
|
||||
background: linear-gradient(135deg, #ff82b2, #f84d96);
|
||||
box-shadow: 0 12px 26px rgba(248, 77, 150, 0.26);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.guideDialog h2 {
|
||||
margin: 0;
|
||||
color: #281a21;
|
||||
font-size: 21px;
|
||||
font-weight: 850;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.guideDialog p {
|
||||
margin: 12px 0 20px;
|
||||
color: #685761;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.guideConfirm {
|
||||
width: 100%;
|
||||
min-height: 46px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, #ff76ab, #f84d96);
|
||||
box-shadow: 0 10px 24px rgba(248, 77, 150, 0.24);
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
font-weight: 850;
|
||||
}
|
||||
|
||||
.guideClose:focus-visible,
|
||||
.guideConfirm:focus-visible {
|
||||
outline: 2px solid #f84d96;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { Download, Share2, Star, X } from "lucide-react";
|
||||
|
||||
import { openChatInExternalBrowser } from "@/lib/chat/chat_external_browser";
|
||||
import {
|
||||
hasPersistedFavoriteEntryIntent,
|
||||
resolveFavoriteEntryMode,
|
||||
type FavoriteEntryMode,
|
||||
} from "@/lib/navigation/favorite_entry";
|
||||
import { BrowserDetector } from "@/utils/browser-detect";
|
||||
import { PlatformDetector } from "@/utils/platform-detect";
|
||||
import { pwaUtil } from "@/utils/pwa";
|
||||
|
||||
import styles from "./favorite-entry-button.module.css";
|
||||
|
||||
export interface FavoriteEntryButtonProps {
|
||||
characterSlug: string;
|
||||
tone?: "dark" | "light";
|
||||
}
|
||||
|
||||
export function FavoriteEntryButton({
|
||||
characterSlug,
|
||||
tone = "dark",
|
||||
}: FavoriteEntryButtonProps) {
|
||||
const [mode, setMode] = useState<FavoriteEntryMode>("favorite");
|
||||
const [installGuide, setInstallGuide] = useState<
|
||||
"ios" | "browser" | null
|
||||
>(null);
|
||||
const installGuideTitleId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
const updateMode = () => {
|
||||
setMode(
|
||||
resolveFavoriteEntryMode({
|
||||
hasFavoriteIntent: hasPersistedFavoriteEntryIntent(),
|
||||
isAndroid: PlatformDetector.isAndroid(),
|
||||
isIOS: PlatformDetector.isIOS(),
|
||||
isInAppBrowser: BrowserDetector.isInAppBrowser(),
|
||||
isInstalled: pwaUtil.isInstalled(),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
pwaUtil.prepareInstallPrompt();
|
||||
updateMode();
|
||||
const unsubscribe = pwaUtil.subscribe(updateMode);
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!installGuide) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setInstallGuide(null);
|
||||
};
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => document.removeEventListener("keydown", handleKeyDown);
|
||||
}, [installGuide]);
|
||||
|
||||
const handleClick = async (): Promise<void> => {
|
||||
if (mode === "favorite") {
|
||||
await openChatInExternalBrowser({ characterSlug });
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === "download") {
|
||||
if (PlatformDetector.isIOS()) {
|
||||
setInstallGuide("ios");
|
||||
return;
|
||||
}
|
||||
pwaUtil.prepareInstallPrompt();
|
||||
const result = await pwaUtil.install();
|
||||
if (result === "accepted" || pwaUtil.isInstalled()) {
|
||||
setMode("saved");
|
||||
setInstallGuide(null);
|
||||
return;
|
||||
}
|
||||
if (result === "unavailable") setInstallGuide("browser");
|
||||
}
|
||||
};
|
||||
|
||||
const label = getFavoriteEntryLabel(mode);
|
||||
|
||||
return (
|
||||
<div className={styles.wrap}>
|
||||
<button
|
||||
type="button"
|
||||
data-analytics-key={`favorite.${mode}`}
|
||||
data-analytics-label={label}
|
||||
className={[styles.button, styles[tone], styles[mode]]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
aria-label={label}
|
||||
aria-pressed={mode === "saved"}
|
||||
onClick={() => void handleClick()}
|
||||
>
|
||||
{mode === "download" ? (
|
||||
<Download size={16} strokeWidth={2.4} aria-hidden="true" />
|
||||
) : (
|
||||
<Star
|
||||
size={21}
|
||||
strokeWidth={2.3}
|
||||
fill={mode === "saved" ? "currentColor" : "none"}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
{mode === "favorite" ? null : <span>{label}</span>}
|
||||
</button>
|
||||
{installGuide ? (
|
||||
<div
|
||||
className={styles.guideBackdrop}
|
||||
onClick={() => setInstallGuide(null)}
|
||||
role="presentation"
|
||||
>
|
||||
<section
|
||||
className={styles.guideDialog}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={installGuideTitleId}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.guideClose}
|
||||
onClick={() => setInstallGuide(null)}
|
||||
aria-label="Close install instructions"
|
||||
>
|
||||
<X size={18} aria-hidden="true" />
|
||||
</button>
|
||||
<span className={styles.guideIcon} aria-hidden="true">
|
||||
{installGuide === "ios" ? (
|
||||
<Share2 size={28} strokeWidth={2.2} />
|
||||
) : (
|
||||
<Download size={28} strokeWidth={2.2} />
|
||||
)}
|
||||
</span>
|
||||
<h2 id={installGuideTitleId}>Add CozSweet to Home Screen</h2>
|
||||
<p>
|
||||
{installGuide === "ios"
|
||||
? "In Safari, tap the Share button, then choose “Add to Home Screen”."
|
||||
: "Open your browser menu, then choose “Add to Home screen”."}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.guideConfirm}
|
||||
onClick={() => setInstallGuide(null)}
|
||||
>
|
||||
Got it
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getFavoriteEntryLabel(mode: FavoriteEntryMode): string {
|
||||
if (mode === "download") return "Download";
|
||||
if (mode === "saved") return "Saved";
|
||||
return "Save CozSweet";
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
export * from "./app-bottom-nav";
|
||||
export * from "./bottom-sheet";
|
||||
export * from "./checkbox";
|
||||
export * from "./favorite-entry-button";
|
||||
export * from "./loading-indicator";
|
||||
export * from "./mobile-shell";
|
||||
export * from "./page-loading-fallback";
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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?.();
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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 />;
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import type { ReactNode } from "react";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { getCharacterBySlug } from "@/data/constants/character";
|
||||
import { PrivateZoomRouteProvider } from "@/providers/private-zoom-route-provider";
|
||||
import { PrivateZoneRouteProvider } from "@/providers/private-zone-route-provider";
|
||||
|
||||
export default async function CharacterPrivateZoomLayout({
|
||||
export default async function CharacterPrivateZoneLayout({
|
||||
children,
|
||||
params,
|
||||
}: {
|
||||
@@ -13,11 +13,11 @@ export default async function CharacterPrivateZoomLayout({
|
||||
}) {
|
||||
const { characterSlug } = await params;
|
||||
const character = getCharacterBySlug(characterSlug);
|
||||
if (!character?.capabilities.privateZoom) notFound();
|
||||
if (!character?.capabilities.privateZone) notFound();
|
||||
|
||||
return (
|
||||
<PrivateZoomRouteProvider characterId={character.id}>
|
||||
<PrivateZoneRouteProvider characterId={character.id}>
|
||||
{children}
|
||||
</PrivateZoomRouteProvider>
|
||||
</PrivateZoneRouteProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PrivateZoneScreen } from "@/app/private-zone/private-zone-screen";
|
||||
|
||||
export default function CharacterPrivateZonePage() {
|
||||
return <PrivateZoneScreen />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { PrivateZoomScreen } from "@/app/private-zoom/private-zoom-screen";
|
||||
|
||||
export default function CharacterPrivateZoomPage() {
|
||||
return <PrivateZoomScreen />;
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, type CSSProperties } from "react";
|
||||
import { useEffect, useMemo, useRef, type CSSProperties } from "react";
|
||||
import Image from "next/image";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
@@ -17,7 +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 { 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";
|
||||
|
||||
@@ -38,7 +45,6 @@ import {
|
||||
} from "./chat-image-overlay-url";
|
||||
import {
|
||||
deriveIsGuest,
|
||||
shouldStartExternalBrowserPrompt,
|
||||
} from "./chat-screen.helpers";
|
||||
import { useFirstRechargeOfferBanner } from "./hooks/use-first-recharge-offer-banner";
|
||||
import { useChatUnlockCoordinator } from "./hooks/use-chat-unlock-coordinator";
|
||||
@@ -46,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)",
|
||||
@@ -63,11 +70,21 @@ 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();
|
||||
const authState = useAuthState();
|
||||
const authDispatch = useAuthDispatch();
|
||||
const imageOpenedFromChatRef = useRef(false);
|
||||
const imageViewerClosingRef = useRef(false);
|
||||
useSplashLatestMessageSync({
|
||||
characterId: state.characterId,
|
||||
historyLoaded: state.historyLoaded,
|
||||
@@ -118,12 +135,6 @@ export function ChatScreen() {
|
||||
});
|
||||
const shouldShowPwaInstall =
|
||||
state.historyLoaded && state.historyMessages.length >= 10;
|
||||
const shouldShowBrowserHint = shouldStartExternalBrowserPrompt({
|
||||
hasInitialized: authState.hasInitialized,
|
||||
isLoading: authState.isLoading,
|
||||
loginStatus: authState.loginStatus,
|
||||
});
|
||||
|
||||
useChatGuestLogin({
|
||||
dispatch: authDispatch,
|
||||
hasInitialized: authState.hasInitialized,
|
||||
@@ -131,6 +142,13 @@ export function ChatScreen() {
|
||||
loginStatus: authState.loginStatus,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!imageMessageId) {
|
||||
imageOpenedFromChatRef.current = false;
|
||||
imageViewerClosingRef.current = false;
|
||||
}
|
||||
}, [imageMessageId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!imageMessageId ||
|
||||
@@ -222,6 +240,7 @@ export function ChatScreen() {
|
||||
}
|
||||
|
||||
function handleOpenImage(displayMessageId: string): void {
|
||||
imageOpenedFromChatRef.current = true;
|
||||
router.push(
|
||||
buildChatImageOverlayUrl(displayMessageId, characterRoutes.chat),
|
||||
{ scroll: false },
|
||||
@@ -229,6 +248,13 @@ export function ChatScreen() {
|
||||
}
|
||||
|
||||
function handleCloseImageViewer(): void {
|
||||
if (imageViewerClosingRef.current) return;
|
||||
imageViewerClosingRef.current = true;
|
||||
if (imageOpenedFromChatRef.current) {
|
||||
imageOpenedFromChatRef.current = false;
|
||||
router.back();
|
||||
return;
|
||||
}
|
||||
router.replace(
|
||||
buildChatWithoutImageOverlayUrl(searchParams, characterRoutes.chat),
|
||||
{ scroll: false },
|
||||
@@ -253,8 +279,126 @@ export function ChatScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
function handleOpenCharacterPrivateZoom(): void {
|
||||
router.push(characterRoutes.privateZoom);
|
||||
function handleOpenCharacterPrivateZone(): void {
|
||||
router.push(characterRoutes.privateZone);
|
||||
}
|
||||
|
||||
async function handleCommercialAction(action: CommercialAction): Promise<void> {
|
||||
behaviorAnalytics.elementClick(
|
||||
"chat.commercial_action.open",
|
||||
action.ctaLabel,
|
||||
{
|
||||
actionId: action.actionId,
|
||||
actionType: action.type,
|
||||
characterId: state.characterId,
|
||||
ruleId: action.ruleId,
|
||||
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
|
||||
: characterRoutes.privateZone,
|
||||
);
|
||||
}
|
||||
|
||||
function handleCommercialActionDismiss(action: CommercialAction): void {
|
||||
behaviorAnalytics.elementClick(
|
||||
"chat.commercial_action.dismiss",
|
||||
"Dismiss commercial action",
|
||||
{
|
||||
actionId: action.actionId,
|
||||
actionType: action.type,
|
||||
characterId: state.characterId,
|
||||
ruleId: action.ruleId,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
@@ -276,13 +420,13 @@ export function ChatScreen() {
|
||||
<div className="relative z-1 flex min-h-0 flex-[1_1_auto] flex-col">
|
||||
<ChatHeader
|
||||
isGuest={isGuest}
|
||||
showBrowserHint={shouldShowBrowserHint}
|
||||
offerBanner={
|
||||
<FirstRechargeOfferBanner
|
||||
visible={firstRechargeOfferBanner.visible}
|
||||
discountPercent={firstRechargeOfferBanner.discountPercent}
|
||||
onClick={firstRechargeOfferBanner.claim}
|
||||
onClose={firstRechargeOfferBanner.close}
|
||||
variant="compact"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -304,7 +448,12 @@ export function ChatScreen() {
|
||||
onUnlockImageMessage={handleUnlockImageMessage}
|
||||
onOpenImage={handleOpenImage}
|
||||
onUserAvatarClick={handleOpenUserProfile}
|
||||
onCharacterAvatarClick={handleOpenCharacterPrivateZoom}
|
||||
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("");
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,36 @@ describe("ChatInputBar", () => {
|
||||
expect(getButton("Open chat actions")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("suppresses the Facebook WebView click that follows a pointer send for 300ms", () => {
|
||||
const now = vi.spyOn(Date, "now").mockReturnValue(1_000);
|
||||
renderBar();
|
||||
setTextareaValue(getTextarea(), "Hello Maya");
|
||||
const sendButton = getButton("Send message");
|
||||
const pointerDown = new Event("pointerdown", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
Object.defineProperty(pointerDown, "pointerType", { value: "touch" });
|
||||
|
||||
act(() => sendButton.dispatchEvent(pointerDown));
|
||||
|
||||
expect(mocks.dispatch).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.dispatch).toHaveBeenCalledWith({
|
||||
type: "ChatSendMessage",
|
||||
content: "Hello Maya",
|
||||
});
|
||||
expect(getTextarea().value).toBe("");
|
||||
expect(getButton("Open chat actions")).toBe(sendButton);
|
||||
|
||||
now.mockReturnValue(1_299);
|
||||
act(() => sendButton.click());
|
||||
expect(container.querySelector('[aria-label="Chat actions"]')).toBeNull();
|
||||
|
||||
now.mockReturnValue(1_300);
|
||||
act(() => sendButton.click());
|
||||
expect(container.querySelector('[aria-label="Chat actions"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("closes the menu on outside interaction and when disabled", () => {
|
||||
renderBar();
|
||||
act(() => getButton("Open chat actions").click());
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CommercialActionCard } from "../commercial-action-card";
|
||||
|
||||
describe("CommercialActionCard", () => {
|
||||
it("renders a private-zone offer with a usable CTA", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<CommercialActionCard
|
||||
action={{
|
||||
actionId: "action-1",
|
||||
type: "privateAlbumOffer",
|
||||
copy: "There are more private photos waiting for you.",
|
||||
ctaLabel: "Open private zone",
|
||||
target: "privateZone",
|
||||
ruleId: "private_album_after_appearance_praise",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-commercial-action="privateAlbumOffer"');
|
||||
expect(html).toContain("There are more private photos waiting for you.");
|
||||
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,80 @@
|
||||
/* @vitest-environment jsdom */
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
type Mock,
|
||||
vi,
|
||||
} from "vitest";
|
||||
|
||||
import { FullscreenImageViewer } from "../fullscreen-image-viewer";
|
||||
|
||||
describe("FullscreenImageViewer", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let onClose: Mock<() => void>;
|
||||
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
onClose = vi.fn<() => void>();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FullscreenImageViewer
|
||||
characterId="elio-silvestri"
|
||||
remoteMessageId="message-1"
|
||||
imageUrl="/chat-image.png"
|
||||
onClose={onClose}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("closes exactly once when the fullscreen image is tapped", () => {
|
||||
const image = container.querySelector("img");
|
||||
expect(image).not.toBeNull();
|
||||
|
||||
act(() => image?.click());
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("closes exactly once from the visible back button", () => {
|
||||
const backButton = container.querySelector<HTMLButtonElement>(
|
||||
'button[aria-label="Back"]',
|
||||
);
|
||||
expect(backButton).not.toBeNull();
|
||||
|
||||
act(() => backButton?.click());
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("closes from the backdrop and Escape key", () => {
|
||||
const viewer = container.querySelector<HTMLDivElement>(
|
||||
'[aria-label="Fullscreen image"]',
|
||||
);
|
||||
expect(viewer).not.toBeNull();
|
||||
|
||||
act(() => viewer?.click());
|
||||
act(() =>
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })),
|
||||
);
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -62,10 +62,10 @@ describe("chat Tailwind components", () => {
|
||||
|
||||
expect(aiHtml).toContain('<button type="button"');
|
||||
expect(aiHtml).toContain(
|
||||
'data-analytics-key="chat.open_private_zoom_from_avatar"',
|
||||
'data-analytics-key="chat.open_private_zone_from_avatar"',
|
||||
);
|
||||
expect(aiHtml).toContain(
|
||||
'aria-label="Open Elio Silvestri's private zoom"',
|
||||
'aria-label="Open Elio Silvestri's private zone"',
|
||||
);
|
||||
expect(userHtml).toContain('<button type="button"');
|
||||
expect(userHtml).toContain(
|
||||
@@ -242,12 +242,6 @@ describe("chat Tailwind components", () => {
|
||||
const memberHtml = renderWithCharacter(
|
||||
<ChatHeader isGuest={false} offerBanner={<div>Offer</div>} />,
|
||||
);
|
||||
const memberWithHintHtml = renderWithCharacter(
|
||||
<ChatHeader isGuest={false} showBrowserHint />,
|
||||
);
|
||||
const guestWithHintHtml = renderWithCharacter(
|
||||
<ChatHeader isGuest={true} showBrowserHint />,
|
||||
);
|
||||
|
||||
expect(guestHtml).toContain('aria-label="Sign up to unlock more features"');
|
||||
expect(guestHtml).toContain("bg-accent");
|
||||
@@ -257,50 +251,33 @@ describe("chat Tailwind components", () => {
|
||||
expect(guestHtml).toContain('data-analytics-key="chat.back_to_home"');
|
||||
expect(guestHtml).toContain("px-(--chat-inline-padding,16px)");
|
||||
expect(guestHtml).not.toContain('aria-label="Profile"');
|
||||
expect(guestHtml).toContain('aria-label="Save CozSweet"');
|
||||
expect(memberHtml).toContain("Offer");
|
||||
expect(memberHtml).toContain('href="/characters/elio/splash"');
|
||||
expect(memberHtml).toContain('aria-label="Back to home"');
|
||||
expect(memberHtml).toContain('aria-label="Profile"');
|
||||
expect(memberHtml).toContain('data-analytics-key="chat.open_profile"');
|
||||
expect(memberHtml).toContain('aria-label="Save CozSweet"');
|
||||
expect(memberHtml).toContain('data-analytics-key="favorite.favorite"');
|
||||
expect(memberHtml).toContain('data-analytics-key="chat.back_to_home"');
|
||||
expect(memberHtml).toContain("px-(--chat-inline-padding,16px)");
|
||||
expect(memberHtml).not.toContain("px-(--spacing-md,12px)");
|
||||
expect(memberHtml).toContain("bg-[rgba(13,11,20,0.7)]");
|
||||
expect(memberHtml).toContain("size-(--responsive-icon-button-size,42px)");
|
||||
expect(memberHtml).toContain("lucide-user-round");
|
||||
expect(memberWithHintHtml).toContain(
|
||||
'data-analytics-key="chat.external_browser_hint"',
|
||||
);
|
||||
expect(memberWithHintHtml).toContain(
|
||||
expect(memberHtml).toContain(
|
||||
"grid-cols-[auto_minmax(0,1fr)_auto]",
|
||||
);
|
||||
expect(memberWithHintHtml.indexOf('aria-label="Back to home"')).toBeLessThan(
|
||||
memberWithHintHtml.indexOf(
|
||||
'data-analytics-key="chat.external_browser_hint"',
|
||||
),
|
||||
);
|
||||
expect(
|
||||
memberWithHintHtml.indexOf(
|
||||
'data-analytics-key="chat.external_browser_hint"',
|
||||
),
|
||||
).toBeLessThan(memberWithHintHtml.indexOf('aria-label="Profile"'));
|
||||
expect(guestWithHintHtml).not.toContain(
|
||||
expect(memberHtml).not.toContain(
|
||||
'data-analytics-key="chat.external_browser_hint"',
|
||||
);
|
||||
});
|
||||
|
||||
it("renders the user avatar in the ChatHeader Profile action", () => {
|
||||
it("replaces the ChatHeader Profile avatar with the favorite action", () => {
|
||||
userMocks.avatarUrl = "/images/avatar/profile-user.png";
|
||||
|
||||
const html = renderWithCharacter(<ChatHeader isGuest={false} />);
|
||||
|
||||
expect(html).toContain("%2Fimages%2Favatar%2Fprofile-user.png");
|
||||
expect(html).toContain('aria-label="Profile"');
|
||||
expect(html).toContain('data-analytics-key="chat.open_profile"');
|
||||
expect(html).toContain(
|
||||
"var(--responsive-icon-button-size, 42px)",
|
||||
);
|
||||
expect(html).not.toContain("lucide-user-round");
|
||||
expect(html).not.toContain("%2Fimages%2Favatar%2Fprofile-user.png");
|
||||
expect(html).not.toContain('aria-label="Profile"');
|
||||
expect(html).not.toContain('data-analytics-key="chat.open_profile"');
|
||||
expect(html).toContain('aria-label="Save CozSweet"');
|
||||
expect(html).toContain("lucide-star");
|
||||
});
|
||||
|
||||
it("links guest chat back to the active character splash", () => {
|
||||
@@ -315,6 +292,7 @@ describe("chat Tailwind components", () => {
|
||||
|
||||
expect(html).toContain('href="/characters/maya/splash"');
|
||||
expect(html).not.toContain('aria-label="Profile"');
|
||||
expect(html).toContain('aria-label="Save CozSweet"');
|
||||
expect(html).not.toContain(
|
||||
'data-analytics-key="chat.external_browser_hint"',
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -131,6 +131,84 @@
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.commercialAction {
|
||||
width: min(100%, 286px);
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
border-radius: 8px;
|
||||
background: rgba(25, 21, 31, 0.92);
|
||||
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.commercialActionHeader {
|
||||
display: flex;
|
||||
min-height: 24px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
color: #f4b860;
|
||||
}
|
||||
|
||||
.commercialActionDismiss {
|
||||
display: inline-flex;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.66);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.commercialActionCopy {
|
||||
margin: 7px 0 11px;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: var(--responsive-caption, var(--font-size-sm, 13px));
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.commercialActionButton {
|
||||
display: inline-flex;
|
||||
min-height: 38px;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 7px;
|
||||
padding: 8px 12px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: #f4b860;
|
||||
color: #201710;
|
||||
cursor: pointer;
|
||||
font-size: var(--responsive-caption, var(--font-size-sm, 13px));
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.commercialActionButton span {
|
||||
min-width: 0;
|
||||
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));
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import { LoaderCircle } from "lucide-react";
|
||||
|
||||
import type { UiMessage } from "@/stores/chat/ui-message";
|
||||
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
|
||||
import { usePullToRefresh } from "@/hooks/use-pull-to-refresh";
|
||||
|
||||
import {
|
||||
@@ -61,6 +62,11 @@ export interface ChatAreaProps {
|
||||
onLoadMoreHistory?: () => void;
|
||||
onUserAvatarClick?: () => void;
|
||||
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 = (
|
||||
@@ -85,6 +91,11 @@ export function ChatArea({
|
||||
onLoadMoreHistory,
|
||||
onUserAvatarClick,
|
||||
onCharacterAvatarClick,
|
||||
onCommercialAction,
|
||||
onCommercialActionDismiss,
|
||||
onChatActionViewed,
|
||||
onChatAction,
|
||||
onChatActionDismiss,
|
||||
}: ChatAreaProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
@@ -257,6 +268,11 @@ export function ChatArea({
|
||||
onOpenImage,
|
||||
onUserAvatarClick,
|
||||
onCharacterAvatarClick,
|
||||
onCommercialAction,
|
||||
onCommercialActionDismiss,
|
||||
onChatActionViewed,
|
||||
onChatAction,
|
||||
onChatActionDismiss,
|
||||
)}
|
||||
|
||||
{isReplyingAI ? (
|
||||
@@ -295,6 +311,11 @@ function renderMessagesWithDateHeaders(
|
||||
onOpenImage?: (displayMessageId: string) => void,
|
||||
onUserAvatarClick?: () => void,
|
||||
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" ? (
|
||||
@@ -314,6 +335,8 @@ function renderMessagesWithDateHeaders(
|
||||
lockReason={item.message.lockReason}
|
||||
lockedPrivate={item.message.lockedPrivate}
|
||||
privateMessageHint={item.message.privateMessageHint}
|
||||
commercialAction={item.message.commercialAction}
|
||||
chatAction={item.message.chatAction}
|
||||
isUnlockingMessage={
|
||||
isUnlockingMessage === true &&
|
||||
item.message.displayId === unlockingMessageId
|
||||
@@ -324,6 +347,11 @@ function renderMessagesWithDateHeaders(
|
||||
onOpenImage={onOpenImage}
|
||||
onUserAvatarClick={onUserAvatarClick}
|
||||
onCharacterAvatarClick={onCharacterAvatarClick}
|
||||
onCommercialAction={onCommercialAction}
|
||||
onCommercialActionDismiss={onCommercialActionDismiss}
|
||||
onChatActionViewed={onChatActionViewed}
|
||||
onChatAction={onChatAction}
|
||||
onChatActionDismiss={onChatActionDismiss}
|
||||
/>
|
||||
),
|
||||
);
|
||||
|
||||
@@ -2,37 +2,32 @@
|
||||
/**
|
||||
* ChatHeader 顶部栏
|
||||
*
|
||||
* Profile 优先展示用户头像;头像缺失时回退到 lucide-react <UserRound />。
|
||||
* 顶部保持返回、首充优惠、收藏入口三段结构。
|
||||
*/
|
||||
import type { ReactNode } from "react";
|
||||
import { Lock, UserRound } from "lucide-react";
|
||||
import { Lock, Phone } from "lucide-react";
|
||||
|
||||
import { BackButton, UserMessageAvatar } from "@/app/_components";
|
||||
import { useActiveCharacterRoutes } from "@/providers/character-provider";
|
||||
import { buildGlobalPageUrl } from "@/router/global-route-context";
|
||||
import { ROUTES } from "@/router/routes";
|
||||
import { BackButton } from "@/app/_components";
|
||||
import { FavoriteEntryButton } from "@/app/_components/core";
|
||||
import {
|
||||
useActiveCharacter,
|
||||
useActiveCharacterRoutes,
|
||||
} from "@/providers/character-provider";
|
||||
import { useAppNavigator } from "@/router/use-app-navigator";
|
||||
import { useUserSelector } from "@/stores/user/user-context";
|
||||
|
||||
import { BrowserHintOverlay } from "./browser-hint-overlay";
|
||||
|
||||
export interface ChatHeaderProps {
|
||||
isGuest: boolean;
|
||||
offerBanner?: ReactNode;
|
||||
showBrowserHint?: boolean;
|
||||
}
|
||||
|
||||
export function ChatHeader({
|
||||
isGuest,
|
||||
offerBanner,
|
||||
showBrowserHint = false,
|
||||
}: ChatHeaderProps) {
|
||||
const navigator = useAppNavigator();
|
||||
const character = useActiveCharacter();
|
||||
const characterRoutes = useActiveCharacterRoutes();
|
||||
const avatarUrl = useUserSelector((state) => state.context.avatarUrl);
|
||||
const handleOpenProfile = () => {
|
||||
navigator.push(buildGlobalPageUrl(ROUTES.profile, characterRoutes.chat));
|
||||
};
|
||||
const voiceCallEnabled = process.env.NEXT_PUBLIC_ENABLE_VOICE_CALL === "true";
|
||||
|
||||
return (
|
||||
<header className="flex shrink-0 flex-col items-stretch bg-transparent p-0">
|
||||
@@ -52,17 +47,9 @@ export function ChatHeader({
|
||||
/>
|
||||
<span>Sign up to unlock more features</span>
|
||||
</button>
|
||||
) : (
|
||||
offerBanner
|
||||
)}
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={
|
||||
isGuest
|
||||
? "flex items-center px-(--chat-inline-padding,16px) py-(--spacing-sm,8px)"
|
||||
: "grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-(--spacing-sm,8px) px-(--chat-inline-padding,16px) py-(--spacing-sm,8px)"
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-(--spacing-sm,8px) px-(--chat-inline-padding,16px) py-(--spacing-sm,8px)">
|
||||
<BackButton
|
||||
href={characterRoutes.splash}
|
||||
variant="dark"
|
||||
@@ -70,34 +57,26 @@ export function ChatHeader({
|
||||
analyticsKey="chat.back_to_home"
|
||||
/>
|
||||
|
||||
{!isGuest ? (
|
||||
<>
|
||||
<div className="flex min-w-0 justify-center">
|
||||
{showBrowserHint ? <BrowserHintOverlay /> : null}
|
||||
</div>
|
||||
<div className="flex min-w-0 justify-center">{offerBanner}</div>
|
||||
|
||||
{avatarUrl ? (
|
||||
<UserMessageAvatar
|
||||
avatarUrl={avatarUrl}
|
||||
size="var(--responsive-icon-button-size, 42px)"
|
||||
actionLabel="Profile"
|
||||
analyticsKey="chat.open_profile"
|
||||
onClick={handleOpenProfile}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
data-analytics-key="chat.open_profile"
|
||||
data-analytics-label="Open profile"
|
||||
className="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-(--color-text-primary,#fff) shadow-[0_10px_24px_rgba(0,0,0,0.2)] backdrop-blur-md transition-[background,transform] duration-150 hover:bg-[rgba(28,24,39,0.82)] active:scale-96 focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-[#f657a0]"
|
||||
onClick={handleOpenProfile}
|
||||
aria-label="Profile"
|
||||
>
|
||||
<UserRound size={24} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
<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>
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ import { ChatSendButton } from "./chat-send-button";
|
||||
import styles from "./chat-input-bar.module.css";
|
||||
|
||||
const log = new Logger("AppChatComponentsChatInputBar");
|
||||
const POINTER_SEND_CLICK_DEDUPE_MS = 500;
|
||||
const POINTER_SEND_DEBOUNCE_MS = 300;
|
||||
const CHAT_ACTION_MENU_ID = "chat-composer-action-menu";
|
||||
|
||||
export interface ChatInputBarProps {
|
||||
@@ -82,7 +82,7 @@ export function ChatInputBar({ disabled = false }: ChatInputBarProps) {
|
||||
const handleSend = (source: "click" | "keyboard" | "pointerdown") => {
|
||||
if (source === "click") {
|
||||
const elapsed = Date.now() - lastPointerSendAtRef.current;
|
||||
if (elapsed >= 0 && elapsed < POINTER_SEND_CLICK_DEDUPE_MS) {
|
||||
if (elapsed >= 0 && elapsed < POINTER_SEND_DEBOUNCE_MS) {
|
||||
log.debug("[chat-input-bar] suppress duplicate click", {
|
||||
elapsed,
|
||||
contentLength: input.length,
|
||||
@@ -115,6 +115,15 @@ export function ChatInputBar({ disabled = false }: ChatInputBarProps) {
|
||||
|
||||
const handleMenuToggle = () => {
|
||||
if (disabled || hasContent) return;
|
||||
const elapsed = Date.now() - lastPointerSendAtRef.current;
|
||||
if (elapsed >= 0 && elapsed < POINTER_SEND_DEBOUNCE_MS) {
|
||||
log.debug("[chat-input-bar] suppress post-send menu toggle", {
|
||||
elapsed,
|
||||
disabled,
|
||||
isFocused,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!isActionMenuOpen) textareaRef.current?.blur();
|
||||
setIsActionMenuOpen((open) => !open);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { ArrowRight, BadgePercent, Gift, Images, LoaderCircle, X } from "lucide-react";
|
||||
|
||||
import type { CommercialAction } from "@/data/schemas/chat";
|
||||
|
||||
import styles from "./chat-area.module.css";
|
||||
|
||||
export interface CommercialActionCardProps {
|
||||
action: CommercialAction;
|
||||
onActivate?: (action: CommercialAction) => void | Promise<void>;
|
||||
onDismiss?: (action: CommercialAction) => void;
|
||||
}
|
||||
|
||||
export function CommercialActionCard({
|
||||
action,
|
||||
onActivate,
|
||||
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
|
||||
: action.type === "discountOffer"
|
||||
? BadgePercent
|
||||
: Images;
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={styles.commercialAction}
|
||||
aria-label={action.ctaLabel}
|
||||
data-commercial-action={action.type}
|
||||
>
|
||||
<div className={styles.commercialActionHeader}>
|
||||
<Icon size={18} aria-hidden="true" />
|
||||
<button
|
||||
type="button"
|
||||
className={styles.commercialActionDismiss}
|
||||
title="Dismiss offer"
|
||||
aria-label="Dismiss offer"
|
||||
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 private offer 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>
|
||||
);
|
||||
}
|
||||
@@ -121,8 +121,74 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.compactButton {
|
||||
display: grid;
|
||||
width: min(100%, 240px);
|
||||
min-width: 0;
|
||||
max-width: 240px;
|
||||
min-height: 50px;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 10px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(255, 255, 255, 0.42);
|
||||
border-radius: 16px;
|
||||
background:
|
||||
radial-gradient(circle at 15% 0%, rgba(255, 255, 255, 0.68), transparent 38%),
|
||||
linear-gradient(135deg, #fff0b8 0%, #ffd0df 50%, #ff6cab 100%);
|
||||
color: #2c111d;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
box-shadow: 0 9px 24px rgba(114, 21, 63, 0.2);
|
||||
animation: firstRechargeBannerIn 260ms ease-out both;
|
||||
}
|
||||
|
||||
.compactIcon {
|
||||
display: inline-flex;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.55);
|
||||
color: #f90073;
|
||||
}
|
||||
|
||||
.compactCopy {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
line-height: 1.05;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.compactCopy span,
|
||||
.compactCopy strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.compactCopy span {
|
||||
color: rgba(44, 17, 29, 0.68);
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.compactCopy strong {
|
||||
color: #ec006d;
|
||||
font-size: 17px;
|
||||
font-weight: 950;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.contentButton:focus-visible,
|
||||
.closeButton:focus-visible {
|
||||
.closeButton:focus-visible,
|
||||
.compactButton:focus-visible {
|
||||
outline: 2px solid rgba(255, 255, 255, 0.94);
|
||||
outline-offset: -3px;
|
||||
}
|
||||
@@ -144,4 +210,14 @@
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.compactButton {
|
||||
gap: 5px;
|
||||
padding-inline: 6px;
|
||||
}
|
||||
|
||||
.compactIcon {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface FirstRechargeOfferBannerProps {
|
||||
discountPercent: number;
|
||||
onClick: () => void;
|
||||
onClose: () => void;
|
||||
variant?: "banner" | "compact";
|
||||
}
|
||||
|
||||
export function FirstRechargeOfferBanner({
|
||||
@@ -16,9 +17,32 @@ export function FirstRechargeOfferBanner({
|
||||
discountPercent,
|
||||
onClick,
|
||||
onClose,
|
||||
variant = "banner",
|
||||
}: FirstRechargeOfferBannerProps) {
|
||||
if (!visible) return null;
|
||||
|
||||
if (variant === "compact") {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-analytics-key="chat.first_recharge_offer"
|
||||
data-analytics-label="Open first recharge offer"
|
||||
className={styles.compactButton}
|
||||
aria-label={`First recharge offer, ${discountPercent}% off`}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span className={styles.compactIcon} aria-hidden="true">
|
||||
<Sparkles size={14} strokeWidth={2.4} />
|
||||
</span>
|
||||
<span className={styles.compactCopy}>
|
||||
<span>First recharge</span>
|
||||
<strong>{discountPercent}% OFF</strong>
|
||||
</span>
|
||||
<ChevronRight size={14} strokeWidth={2.4} aria-hidden="true" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={styles.banner} aria-label="First recharge offer">
|
||||
<button
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* - 双指缩放(CSS `touch-action: pinch-zoom`)
|
||||
*/
|
||||
import { ChevronLeft } from "lucide-react";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, type MouseEvent } from "react";
|
||||
|
||||
import { BackButton } from "@/app/_components";
|
||||
|
||||
@@ -44,6 +44,10 @@ export function FullscreenImageViewer({
|
||||
return () => document.removeEventListener("keydown", handleKey);
|
||||
}, [onClose]);
|
||||
|
||||
const handleBackdropClick = (event: MouseEvent<HTMLDivElement>) => {
|
||||
if (event.target === event.currentTarget) onClose();
|
||||
};
|
||||
|
||||
if (imagePaywalled) {
|
||||
return (
|
||||
<div
|
||||
@@ -90,7 +94,7 @@ export function FullscreenImageViewer({
|
||||
return (
|
||||
<div
|
||||
className={styles.viewer}
|
||||
onClick={onClose}
|
||||
onClick={handleBackdropClick}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Fullscreen image"
|
||||
@@ -110,7 +114,7 @@ export function FullscreenImageViewer({
|
||||
errorClassName="error"
|
||||
width={800}
|
||||
height={800}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onClick={onClose}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
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";
|
||||
|
||||
@@ -29,8 +29,8 @@ export function MessageAvatar({
|
||||
imageSize={43}
|
||||
priority
|
||||
className={AVATAR_CLASS_NAME}
|
||||
actionLabel={`Open ${character.displayName}'s private zoom`}
|
||||
analyticsKey="chat.open_private_zoom_from_avatar"
|
||||
actionLabel={`Open ${character.displayName}'s private zone`}
|
||||
analyticsKey="chat.open_private_zone_from_avatar"
|
||||
onClick={onClick}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* - 用户:[占位 spacer] [Content] [Avatar]
|
||||
*/
|
||||
import { useUserSelector } from "@/stores/user/user-context";
|
||||
import type { ChatAction, CommercialAction } from "@/data/schemas/chat";
|
||||
|
||||
import { MessageAvatar } from "./message-avatar";
|
||||
import { MessageContent } from "./message-content";
|
||||
@@ -27,6 +28,8 @@ export interface MessageBubbleProps {
|
||||
lockReason?: string | null;
|
||||
lockedPrivate?: boolean | null;
|
||||
privateMessageHint?: string | null;
|
||||
commercialAction?: CommercialAction | null;
|
||||
chatAction?: ChatAction | null;
|
||||
isUnlockingMessage?: boolean;
|
||||
onUnlockPrivateMessage?: ChatMessageAction;
|
||||
onUnlockVoiceMessage?: ChatMessageAction;
|
||||
@@ -34,6 +37,11 @@ export interface MessageBubbleProps {
|
||||
onOpenImage?: (displayMessageId: string) => void;
|
||||
onUserAvatarClick?: () => void;
|
||||
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 = (
|
||||
@@ -54,6 +62,8 @@ export function MessageBubble({
|
||||
lockReason,
|
||||
lockedPrivate,
|
||||
privateMessageHint,
|
||||
commercialAction,
|
||||
chatAction,
|
||||
isUnlockingMessage,
|
||||
onUnlockPrivateMessage,
|
||||
onUnlockVoiceMessage,
|
||||
@@ -61,6 +71,11 @@ export function MessageBubble({
|
||||
onOpenImage,
|
||||
onUserAvatarClick,
|
||||
onCharacterAvatarClick,
|
||||
onCommercialAction,
|
||||
onCommercialActionDismiss,
|
||||
onChatActionViewed,
|
||||
onChatAction,
|
||||
onChatActionDismiss,
|
||||
}: MessageBubbleProps) {
|
||||
const avatarUrl = useUserSelector((state) => state.context.avatarUrl);
|
||||
|
||||
@@ -89,11 +104,18 @@ export function MessageBubble({
|
||||
lockReason={lockReason}
|
||||
lockedPrivate={lockedPrivate}
|
||||
privateMessageHint={privateMessageHint}
|
||||
commercialAction={commercialAction}
|
||||
chatAction={chatAction}
|
||||
isUnlockingMessage={isUnlockingMessage}
|
||||
onUnlockPrivateMessage={onUnlockPrivateMessage}
|
||||
onUnlockVoiceMessage={onUnlockVoiceMessage}
|
||||
onUnlockImageMessage={onUnlockImageMessage}
|
||||
onOpenImage={onOpenImage}
|
||||
onCommercialAction={onCommercialAction}
|
||||
onCommercialActionDismiss={onCommercialActionDismiss}
|
||||
onChatActionViewed={onChatActionViewed}
|
||||
onChatAction={onChatAction}
|
||||
onChatActionDismiss={onChatActionDismiss}
|
||||
/>
|
||||
<div className={styles.bubbleAvatarSpacer} aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
"use client";
|
||||
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";
|
||||
import { PrivateMessageCard } from "./private-message-card";
|
||||
@@ -19,11 +23,18 @@ export interface MessageContentProps {
|
||||
lockReason?: string | null;
|
||||
lockedPrivate?: boolean | null;
|
||||
privateMessageHint?: string | null;
|
||||
commercialAction?: CommercialAction | null;
|
||||
chatAction?: ChatAction | null;
|
||||
isUnlockingMessage?: boolean;
|
||||
onUnlockPrivateMessage?: ChatMessageAction;
|
||||
onUnlockVoiceMessage?: ChatMessageAction;
|
||||
onUnlockImageMessage?: ChatMessageAction;
|
||||
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 = (
|
||||
@@ -46,11 +57,18 @@ export function MessageContent({
|
||||
lockReason,
|
||||
lockedPrivate,
|
||||
privateMessageHint,
|
||||
commercialAction,
|
||||
chatAction,
|
||||
isUnlockingMessage,
|
||||
onUnlockPrivateMessage,
|
||||
onUnlockVoiceMessage,
|
||||
onUnlockImageMessage,
|
||||
onOpenImage,
|
||||
onCommercialAction,
|
||||
onCommercialActionDismiss,
|
||||
onChatActionViewed,
|
||||
onChatAction,
|
||||
onChatActionDismiss,
|
||||
}: MessageContentProps) {
|
||||
const hasImage = imageUrl != null && imageUrl.length > 0;
|
||||
const hasAudio = audioUrl != null && audioUrl.length > 0;
|
||||
@@ -125,6 +143,20 @@ export function MessageContent({
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
{isFromAI && chatAction ? (
|
||||
<ChatActionCard
|
||||
action={chatAction}
|
||||
onViewed={onChatActionViewed}
|
||||
onActivate={onChatAction}
|
||||
onDismiss={onChatActionDismiss}
|
||||
/>
|
||||
) : isFromAI && commercialAction ? (
|
||||
<CommercialActionCard
|
||||
action={commercialAction}
|
||||
onActivate={onCommercialAction}
|
||||
onDismiss={onCommercialActionDismiss}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
@@ -21,6 +21,10 @@ import {
|
||||
} from "@/data/constants/character";
|
||||
import { Logger } from "@/utils/logger";
|
||||
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
|
||||
import {
|
||||
isFavoriteEntryRequest,
|
||||
persistFavoriteEntryIntent,
|
||||
} from "@/lib/navigation/favorite_entry";
|
||||
|
||||
const log = new Logger("ExternalEntryPersist");
|
||||
|
||||
@@ -33,6 +37,7 @@ interface ExternalEntryPersistProps {
|
||||
character: string | null;
|
||||
mode: string | null;
|
||||
promotionType: string | null;
|
||||
favorite: string | null;
|
||||
}
|
||||
|
||||
export default function ExternalEntryPersist({
|
||||
@@ -44,6 +49,7 @@ export default function ExternalEntryPersist({
|
||||
character,
|
||||
mode,
|
||||
promotionType,
|
||||
favorite,
|
||||
}: ExternalEntryPersistProps) {
|
||||
const router = useRouter();
|
||||
const authState = useAuthState();
|
||||
@@ -75,6 +81,9 @@ export default function ExternalEntryPersist({
|
||||
? savePendingChatPromotion(resolvedPromotionType, characterId)
|
||||
: clearPendingChatPromotion(),
|
||||
]);
|
||||
if (isFavoriteEntryRequest(favorite)) {
|
||||
persistFavoriteEntryIntent();
|
||||
}
|
||||
for (const result of results) {
|
||||
if (result.status === "rejected") {
|
||||
log.warn(
|
||||
@@ -96,6 +105,7 @@ export default function ExternalEntryPersist({
|
||||
characterId,
|
||||
destination,
|
||||
deviceId,
|
||||
favorite,
|
||||
mode,
|
||||
promotionType,
|
||||
psid,
|
||||
|
||||
@@ -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 并跳转到最终页面。
|
||||
@@ -34,6 +35,7 @@ export default async function ExternalEntryPage({
|
||||
character={pickParam(params.character)}
|
||||
mode={pickParam(params.mode)}
|
||||
promotionType={pickParam(params.promotion_type)}
|
||||
favorite={pickParam(params.favorite)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ export const metadata: Metadata = {
|
||||
},
|
||||
// iOS 触屏图标
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
apple: "/favicon.ico",
|
||||
icon: "/favicon.ico?v=20260724",
|
||||
apple: "/images/icons/Icon-192.png?v=20260724",
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildPrivateAlbumGalleryUrl,
|
||||
buildPrivateZoomWithoutGalleryUrl,
|
||||
buildPrivateZoneWithoutGalleryUrl,
|
||||
getPrivateAlbumGalleryState,
|
||||
} from "../private-album-gallery-url";
|
||||
|
||||
@@ -11,7 +11,7 @@ describe("private album gallery URL", () => {
|
||||
const url = buildPrivateAlbumGalleryUrl("album:91", 3);
|
||||
const params = new URL(url, "https://cozsweet.test").searchParams;
|
||||
|
||||
expect(url).toBe("/private-zoom?album=album%3A91&image=3");
|
||||
expect(url).toBe("/private-zone?album=album%3A91&image=3");
|
||||
expect(getPrivateAlbumGalleryState(params)).toEqual({
|
||||
albumId: "album:91",
|
||||
imageIndex: 3,
|
||||
@@ -29,9 +29,9 @@ describe("private album gallery URL", () => {
|
||||
|
||||
it("removes gallery params without dropping other query values", () => {
|
||||
expect(
|
||||
buildPrivateZoomWithoutGalleryUrl(
|
||||
buildPrivateZoneWithoutGalleryUrl(
|
||||
new URLSearchParams("album=album-1&image=2&source=external"),
|
||||
),
|
||||
).toBe("/private-zoom?source=external");
|
||||
).toBe("/private-zone?source=external");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zoom";
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zone";
|
||||
|
||||
import {
|
||||
findPrivateAlbumDisplayImage,
|
||||
@@ -6,10 +6,10 @@ import { getCharacterBySlug } from "@/data/constants/character";
|
||||
import type { LoginStatus } from "@/data/schemas/auth";
|
||||
import { CharacterProvider } from "@/providers/character-provider";
|
||||
import { getCharacterRoutes } from "@/router/routes";
|
||||
import type { PrivateZoomEvent } from "@/stores/private-zoom";
|
||||
import type { PrivateZoomUnlockPaywallRequest } from "@/stores/private-zoom/private-zoom-state";
|
||||
import type { PrivateZoneEvent } from "@/stores/private-zone";
|
||||
import type { PrivateZoneUnlockPaywallRequest } from "@/stores/private-zone/private-zone-state";
|
||||
|
||||
import { usePrivateZoomUnlockPaywallNavigation } from "../use-private-zoom-flow";
|
||||
import { usePrivateZoneUnlockPaywallNavigation } from "../use-private-zone-flow";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
openAuth: vi.fn(),
|
||||
@@ -30,7 +30,7 @@ vi.mock("@/lib/analytics", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const unlockPaywallRequest: PrivateZoomUnlockPaywallRequest = {
|
||||
const unlockPaywallRequest: PrivateZoneUnlockPaywallRequest = {
|
||||
albumId: "album-1",
|
||||
reason: "insufficient_credits",
|
||||
requiredCredits: 10,
|
||||
@@ -38,7 +38,7 @@ const unlockPaywallRequest: PrivateZoomUnlockPaywallRequest = {
|
||||
shortfallCredits: 7,
|
||||
};
|
||||
|
||||
describe("Private Zoom paywall navigation", () => {
|
||||
describe("Private Zone paywall navigation", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
@@ -58,31 +58,31 @@ describe("Private Zoom paywall navigation", () => {
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("opens top up with a private zoom return target", () => {
|
||||
const roomDispatch = vi.fn<Dispatch<PrivateZoomEvent>>();
|
||||
it("opens top up with a private zone return target", () => {
|
||||
const roomDispatch = vi.fn<Dispatch<PrivateZoneEvent>>();
|
||||
|
||||
renderHarness(root, "email", roomDispatch);
|
||||
|
||||
expect(mocks.openSubscription).toHaveBeenCalledWith({
|
||||
type: "topup",
|
||||
returnTo: "private-zoom",
|
||||
returnTo: "private-zone",
|
||||
analytics: {
|
||||
entryPoint: "private_album_unlock",
|
||||
triggerReason: "insufficient_credits",
|
||||
},
|
||||
});
|
||||
expect(roomDispatch).toHaveBeenCalledWith({
|
||||
type: "PrivateZoomUnlockPaywallConsumed",
|
||||
type: "PrivateZoneUnlockPaywallConsumed",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps guest users on the private zoom auth return path", () => {
|
||||
const roomDispatch = vi.fn<Dispatch<PrivateZoomEvent>>();
|
||||
it("keeps guest users on the private zone auth return path", () => {
|
||||
const roomDispatch = vi.fn<Dispatch<PrivateZoneEvent>>();
|
||||
|
||||
renderHarness(root, "guest", roomDispatch);
|
||||
|
||||
expect(mocks.openAuth).toHaveBeenCalledWith(
|
||||
getCharacterRoutes("maya").privateZoom,
|
||||
getCharacterRoutes("maya").privateZone,
|
||||
);
|
||||
expect(mocks.openSubscription).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -91,7 +91,7 @@ describe("Private Zoom paywall navigation", () => {
|
||||
function renderHarness(
|
||||
root: Root,
|
||||
loginStatus: LoginStatus,
|
||||
roomDispatch: Dispatch<PrivateZoomEvent>,
|
||||
roomDispatch: Dispatch<PrivateZoneEvent>,
|
||||
): void {
|
||||
const character = getCharacterBySlug("maya");
|
||||
if (!character) throw new Error("Missing Maya character fixture");
|
||||
@@ -109,9 +109,9 @@ function Harness({
|
||||
roomDispatch,
|
||||
}: {
|
||||
loginStatus: LoginStatus;
|
||||
roomDispatch: Dispatch<PrivateZoomEvent>;
|
||||
roomDispatch: Dispatch<PrivateZoneEvent>;
|
||||
}) {
|
||||
usePrivateZoomUnlockPaywallNavigation({
|
||||
usePrivateZoneUnlockPaywallNavigation({
|
||||
loginStatus,
|
||||
roomDispatch,
|
||||
unlockPaywallRequest,
|
||||
@@ -1,19 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isPrivateZoomAuthRequired } from "../use-private-zoom-flow";
|
||||
import { isPrivateZoneAuthRequired } from "../use-private-zone-flow";
|
||||
|
||||
describe("isPrivateZoomAuthRequired", () => {
|
||||
describe("isPrivateZoneAuthRequired", () => {
|
||||
it.each(["guest", "notLoggedIn"] as const)(
|
||||
"requires auth for %s users",
|
||||
(loginStatus) => {
|
||||
expect(isPrivateZoomAuthRequired(loginStatus)).toBe(true);
|
||||
expect(isPrivateZoneAuthRequired(loginStatus)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["email", "facebook", "google"] as const)(
|
||||
"allows %s users to top up directly",
|
||||
(loginStatus) => {
|
||||
expect(isPrivateZoomAuthRequired(loginStatus)).toBe(false);
|
||||
expect(isPrivateZoneAuthRequired(loginStatus)).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zoom";
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zone";
|
||||
|
||||
import { PrivateAlbumCard } from "../private-album-card";
|
||||
|
||||
@@ -33,9 +33,9 @@ describe("PrivateAlbumCard interactions", () => {
|
||||
imageCount: 4,
|
||||
images: [
|
||||
{ url: "", locked: false, index: 0 },
|
||||
{ url: "/images/private-zoom/locked.png", locked: true, index: 1 },
|
||||
{ url: "/images/private-zoom/photo-2.png", locked: false, index: 2 },
|
||||
{ url: "/images/private-zoom/photo-3.png", locked: false, index: 3 },
|
||||
{ url: "/images/private-zone/locked.png", locked: true, index: 1 },
|
||||
{ url: "/images/private-zone/photo-2.png", locked: false, index: 2 },
|
||||
{ url: "/images/private-zone/photo-3.png", locked: false, index: 3 },
|
||||
],
|
||||
locked: false,
|
||||
unlocked: true,
|
||||
@@ -72,7 +72,7 @@ describe("PrivateAlbumCard interactions", () => {
|
||||
title: "Locked afternoon",
|
||||
imageCount: 3,
|
||||
images: [
|
||||
{ url: "/images/private-zoom/locked.png", locked: true, index: 0 },
|
||||
{ url: "/images/private-zone/locked.png", locked: true, index: 0 },
|
||||
],
|
||||
locked: true,
|
||||
unlocked: false,
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
PrivateAlbumSchema,
|
||||
type PrivateAlbum,
|
||||
type PrivateAlbumInput,
|
||||
} from "@/data/schemas/private-zoom";
|
||||
} from "@/data/schemas/private-zone";
|
||||
|
||||
import { PrivateAlbumCard } from "../private-album-card";
|
||||
|
||||
const COVER_URL = "/images/private-zoom/banner/elio.png";
|
||||
const COVER_URL = "/images/private-zone/banner/elio.png";
|
||||
|
||||
function makeAlbum(overrides: Partial<PrivateAlbumInput> = {}): PrivateAlbum {
|
||||
return PrivateAlbumSchema.parse({
|
||||
@@ -157,7 +157,7 @@ describe("PrivateAlbumCard", () => {
|
||||
|
||||
function makeImages(count: number) {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
url: `/images/private-zoom/photo-${index}.png`,
|
||||
url: `/images/private-zone/photo-${index}.png`,
|
||||
locked: false,
|
||||
index,
|
||||
}));
|
||||
@@ -4,7 +4,7 @@ import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zoom";
|
||||
import { PrivateAlbumSchema } from "@/data/schemas/private-zone";
|
||||
|
||||
import { PrivateAlbumGallery } from "../private-album-gallery";
|
||||
|
||||
@@ -13,11 +13,11 @@ const album = PrivateAlbumSchema.parse({
|
||||
title: "Private afternoon",
|
||||
imageCount: 5,
|
||||
images: [
|
||||
{ url: "/images/private-zoom/photo-0.png", locked: false, index: 0 },
|
||||
{ url: "/images/private-zone/photo-0.png", locked: false, index: 0 },
|
||||
{ url: "", locked: false, index: 1 },
|
||||
{ url: "/images/private-zoom/locked.png", locked: true, index: 2 },
|
||||
{ url: "/images/private-zoom/photo-3.png", locked: false, index: 3 },
|
||||
{ url: "/images/private-zoom/photo-4.png", locked: false, index: 4 },
|
||||
{ url: "/images/private-zone/locked.png", locked: true, index: 2 },
|
||||
{ url: "/images/private-zone/photo-3.png", locked: false, index: 3 },
|
||||
{ url: "/images/private-zone/photo-4.png", locked: false, index: 4 },
|
||||
],
|
||||
locked: false,
|
||||
unlocked: true,
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -3,8 +3,8 @@ import Image from "next/image";
|
||||
import { Copy, ImageIcon, LockKeyhole } from "lucide-react";
|
||||
|
||||
import { CharacterAvatar } from "@/app/_components";
|
||||
import type { PrivateAlbum } from "@/data/schemas/private-zoom";
|
||||
import { isPrivateAlbumLocked } from "@/lib/private-zoom/private_album";
|
||||
import type { PrivateAlbum } from "@/data/schemas/private-zone";
|
||||
import { isPrivateAlbumLocked } from "@/lib/private-zone/private_album";
|
||||
|
||||
import {
|
||||
getPrivateAlbumDisplayImages,
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
PRIVATE_ALBUM_GRID_LIMIT,
|
||||
} from "../private-album-images";
|
||||
|
||||
import styles from "../private-zoom-screen.module.css";
|
||||
import styles from "../private-zone-screen.module.css";
|
||||
|
||||
export interface PrivateAlbumCardProps {
|
||||
album: PrivateAlbum;
|
||||