Compare commits
62 Commits
5afa1c609d
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| ec3e256a8c | |||
| 3547f49bd9 | |||
| ee6ab77f4d | |||
| ce3f0af82d | |||
| 638fc054b1 | |||
| 897bce11db | |||
| 1466cb01d2 | |||
| f6c75dcb86 | |||
| 187de82eaf | |||
| d372541925 | |||
| ef9b79bc83 | |||
| aee35353a3 | |||
| fcb2492118 | |||
| cab2ba868f | |||
| dab9e2e45a | |||
| 54ce485f41 | |||
| e36f94add3 | |||
| ca9cac21f1 | |||
| 662e5e67ea | |||
| f403c47052 | |||
| ac36837add | |||
| fe9d31146b | |||
| 01c55f5630 | |||
| b21ef2f6ec | |||
| a44fc4860e | |||
| ff2759cf0f | |||
| d746d04503 | |||
| 2a90b4d9ec | |||
| 9094bcbab0 | |||
| 29abd746da | |||
| 556bfd2919 | |||
| e3ef289b53 | |||
| 46588bd98c | |||
| 05f625dd0b | |||
| 3790fb813f | |||
| a55a59bff4 | |||
| d2a46ff6b9 | |||
| a4c4ca6666 | |||
| 163ba78f06 | |||
| 4e71dbd5f8 | |||
| 40184c7631 | |||
| 4fceab537d | |||
| e1454cd002 | |||
| 1e25279e8f | |||
| a0b2d44ec6 | |||
| ed3b34ce1c | |||
| e813333607 | |||
| 8bd67b83c5 | |||
| 91e4a074c8 | |||
| 06af88dc44 | |||
| 56ee6f7b96 | |||
| eec4aa2c9f | |||
| ca58e53beb | |||
| a9cdf31d28 | |||
| 9a51acd636 | |||
| 3e3d0ced85 | |||
| 7f271ef2e0 | |||
| 9fff5b16fd | |||
| 9deb320cf6 | |||
| 6cd3a0c2d2 | |||
| fe954f7098 | |||
| 3d3f7e725b |
@@ -8,39 +8,8 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
quality:
|
|
||||||
name: Quality and Bundle Budgets
|
|
||||||
runs-on: gitea-label
|
|
||||||
container:
|
|
||||||
image: cozsweet-act-runner-node24-docker:latest
|
|
||||||
env:
|
|
||||||
NEXT_TELEMETRY_DISABLED: "1"
|
|
||||||
SENTRY_UPLOAD_SOURCEMAPS: "0"
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Skip quality gate for test branch
|
|
||||||
if: ${{ github.ref == 'refs/heads/test' }}
|
|
||||||
run: echo "Quality gate is disabled for the test branch."
|
|
||||||
|
|
||||||
- name: Checkout
|
|
||||||
if: ${{ github.ref != 'refs/heads/test' }}
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
if: ${{ github.ref != 'refs/heads/test' }}
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Run quality checks
|
|
||||||
if: ${{ github.ref != 'refs/heads/test' }}
|
|
||||||
run: pnpm quality
|
|
||||||
|
|
||||||
- name: Enforce bundle budgets
|
|
||||||
if: ${{ github.ref != 'refs/heads/test' }}
|
|
||||||
run: pnpm perf:bundle:check
|
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
name: Build and Push Docker Image
|
name: Build and Push Docker Image
|
||||||
needs: quality
|
|
||||||
runs-on: gitea-label
|
runs-on: gitea-label
|
||||||
container:
|
container:
|
||||||
image: cozsweet-act-runner-node24-docker:latest
|
image: cozsweet-act-runner-node24-docker:latest
|
||||||
@@ -183,12 +152,9 @@ jobs:
|
|||||||
- name: Deploy image over SSH
|
- name: Deploy image over SSH
|
||||||
env:
|
env:
|
||||||
SSH_HOST: ${{ secrets.SSH_HOST }}
|
SSH_HOST: ${{ secrets.SSH_HOST }}
|
||||||
SSH_USER: ${{ secrets.SSH_USER }}
|
|
||||||
SSH_PORT: ${{ secrets.SSH_PORT }}
|
SSH_PORT: ${{ secrets.SSH_PORT }}
|
||||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||||
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
|
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_HOST: ${{ secrets.REGISTRY_HOST }}
|
||||||
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
@@ -197,16 +163,18 @@ jobs:
|
|||||||
|
|
||||||
case "$DEPLOY_ENV" in
|
case "$DEPLOY_ENV" in
|
||||||
test)
|
test)
|
||||||
DEPLOY_DIR="${TEST_DEPLOY_DIR:-/opt/cozsweet-web-test}"
|
DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-test"
|
||||||
HOST_PORT="9135"
|
HOST_PORT="9135"
|
||||||
CONTAINER_NAME="cozsweet-web-test"
|
CONTAINER_NAME="cozsweet-web-test"
|
||||||
PROJECT_NAME="cozsweet-web-test"
|
PROJECT_NAME="cozsweet-web-test"
|
||||||
|
SERVER_RETAIN_COUNT="1"
|
||||||
;;
|
;;
|
||||||
prod)
|
prod)
|
||||||
DEPLOY_DIR="${PROD_DEPLOY_DIR:-/opt/cozsweet-web-prod}"
|
DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-prod"
|
||||||
HOST_PORT="9185"
|
HOST_PORT="9185"
|
||||||
CONTAINER_NAME="cozsweet-web-prod"
|
CONTAINER_NAME="cozsweet-web-prod"
|
||||||
PROJECT_NAME="cozsweet-web-prod"
|
PROJECT_NAME="cozsweet-web-prod"
|
||||||
|
SERVER_RETAIN_COUNT="2"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "Unsupported deploy env: $DEPLOY_ENV" >&2
|
echo "Unsupported deploy env: $DEPLOY_ENV" >&2
|
||||||
@@ -214,8 +182,11 @@ jobs:
|
|||||||
;;
|
;;
|
||||||
esac
|
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_HOST="$SSH_HOST"
|
||||||
DEPLOY_USER="$SSH_USER"
|
DEPLOY_USER="lzf"
|
||||||
DEPLOY_PORT="${SSH_PORT:-22}"
|
DEPLOY_PORT="${SSH_PORT:-22}"
|
||||||
DEPLOY_KEY="$SSH_PRIVATE_KEY"
|
DEPLOY_KEY="$SSH_PRIVATE_KEY"
|
||||||
DEPLOY_KNOWN_HOSTS="$SSH_KNOWN_HOSTS"
|
DEPLOY_KNOWN_HOSTS="$SSH_KNOWN_HOSTS"
|
||||||
@@ -241,19 +212,19 @@ jobs:
|
|||||||
SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o IdentitiesOnly=yes"
|
SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o IdentitiesOnly=yes"
|
||||||
SCP_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 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 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" \
|
printf '%s' "$REGISTRY_PASSWORD" \
|
||||||
| ssh $SSH_OPTS "$SSH_TARGET" \
|
| ssh $SSH_OPTS "$SSH_TARGET" \
|
||||||
"docker login '$REGISTRY_HOST' -u '$REGISTRY_USERNAME' --password-stdin"
|
"docker login '$REGISTRY_HOST' -u '$REGISTRY_USERNAME' --password-stdin"
|
||||||
|
|
||||||
SERVER_RETAIN_COUNT="1"
|
|
||||||
|
|
||||||
ssh $SSH_OPTS "$SSH_TARGET" \
|
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
|
- name: Purge Cloudflare cache
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
name: Deploy frontend to domestic test
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
name: Build and deploy isolated domestic test
|
||||||
|
runs-on: gitea-label
|
||||||
|
container:
|
||||||
|
image: cozsweet-act-runner-node24-docker:latest
|
||||||
|
env:
|
||||||
|
NEXT_TELEMETRY_DISABLED: "1"
|
||||||
|
SENTRY_UPLOAD_SOURCEMAPS: "0"
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Validate domestic SSH configuration
|
||||||
|
env:
|
||||||
|
SSH_HOST: ${{ secrets.DOMESTIC_TEST_SSH_HOST }}
|
||||||
|
SSH_PORT: ${{ secrets.DOMESTIC_TEST_SSH_PORT }}
|
||||||
|
SSH_PRIVATE_KEY_B64: ${{ secrets.DOMESTIC_TEST_SSH_PRIVATE_KEY_B64 }}
|
||||||
|
SSH_KNOWN_HOSTS: ${{ secrets.DOMESTIC_TEST_SSH_KNOWN_HOSTS }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
if [ -z "$SSH_HOST" ] || [ -z "$SSH_PRIVATE_KEY_B64" ] || [ -z "$SSH_KNOWN_HOSTS" ]; then
|
||||||
|
echo "Missing domestic test SSH secrets" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
mkdir -p "$HOME/.ssh"
|
||||||
|
chmod 700 "$HOME/.ssh"
|
||||||
|
printf '%s' "$SSH_PRIVATE_KEY_B64" | base64 -d > "$HOME/.ssh/domestic_test_deploy_key"
|
||||||
|
printf '%s\n' "$SSH_KNOWN_HOSTS" > "$HOME/.ssh/known_hosts"
|
||||||
|
chmod 600 "$HOME/.ssh/domestic_test_deploy_key" "$HOME/.ssh/known_hosts"
|
||||||
|
|
||||||
|
- name: Prepare domestic test environment
|
||||||
|
env:
|
||||||
|
TEST_ENV_FILE_CONTENT: ${{ secrets.TEST_ENV_FILE }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
if [ -z "$TEST_ENV_FILE_CONTENT" ]; then
|
||||||
|
echo "Missing existing secret: TEST_ENV_FILE" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
umask 077
|
||||||
|
printf '%s\n' "$TEST_ENV_FILE_CONTENT" > .env.domestic-test
|
||||||
|
|
||||||
|
replace_env() {
|
||||||
|
key="$1"
|
||||||
|
value="$2"
|
||||||
|
awk -v key="$key" -v value="$value" '
|
||||||
|
BEGIN { replaced = 0 }
|
||||||
|
$0 ~ "^" key "=" { print key "=" value; replaced = 1; next }
|
||||||
|
{ print }
|
||||||
|
END { if (!replaced) print key "=" value }
|
||||||
|
' .env.domestic-test > .env.domestic-test.next
|
||||||
|
mv .env.domestic-test.next .env.domestic-test
|
||||||
|
}
|
||||||
|
|
||||||
|
replace_env NEXT_PUBLIC_APP_ENV test
|
||||||
|
replace_env NEXT_PUBLIC_API_BASE_URL https://testapi.banlv-ai.com
|
||||||
|
replace_env NEXT_PUBLIC_WS_BASE_URL wss://testapi.banlv-ai.com/ws
|
||||||
|
replace_env NEXTAUTH_URL http://127.0.0.1:9135
|
||||||
|
replace_env NEXTAUTH_URL_INTERNAL http://127.0.0.1:3000
|
||||||
|
|
||||||
|
grep -Eq '^AUTH_SECRET=.+$' .env.domestic-test
|
||||||
|
grep -Eq '^NEXT_PUBLIC_API_BASE_URL=https://testapi\.banlv-ai\.com/?$' .env.domestic-test
|
||||||
|
grep -Eq '^NEXT_PUBLIC_WS_BASE_URL=wss://testapi\.banlv-ai\.com/ws/?$' .env.domestic-test
|
||||||
|
|
||||||
|
- name: Prepare image metadata
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
SHORT_SHA="$(git rev-parse --short HEAD)"
|
||||||
|
IMAGE="cozsweet-frontend-domestic-test:test-$SHORT_SHA"
|
||||||
|
ARCHIVE="cozsweet-frontend-domestic-test-$SHORT_SHA.tar.gz"
|
||||||
|
{
|
||||||
|
echo "SHORT_SHA=$SHORT_SHA"
|
||||||
|
echo "IMAGE=$IMAGE"
|
||||||
|
echo "ARCHIVE=$ARCHIVE"
|
||||||
|
} >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Run frontend quality checks
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
pnpm install --frozen-lockfile
|
||||||
|
pnpm lint
|
||||||
|
pnpm typecheck
|
||||||
|
pnpm test:contracts
|
||||||
|
|
||||||
|
- name: Build and archive runtime image
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
DOCKER_BUILDKIT=1 docker build \
|
||||||
|
--secret id=next_env,src=.env.domestic-test \
|
||||||
|
--build-arg NEXT_ENV_FILE=.env.domestic-test \
|
||||||
|
-t "$IMAGE" \
|
||||||
|
.
|
||||||
|
docker save "$IMAGE" | gzip -1 > "$ARCHIVE"
|
||||||
|
test -s "$ARCHIVE"
|
||||||
|
|
||||||
|
- name: Deploy isolated domestic test container
|
||||||
|
env:
|
||||||
|
SSH_HOST: ${{ secrets.DOMESTIC_TEST_SSH_HOST }}
|
||||||
|
SSH_PORT: ${{ secrets.DOMESTIC_TEST_SSH_PORT }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
DEPLOY_PORT="${SSH_PORT:-22}"
|
||||||
|
KEY_FILE="$HOME/.ssh/domestic_test_deploy_key"
|
||||||
|
SSH_TARGET="lzf@$SSH_HOST"
|
||||||
|
RUN_TOKEN="${GITHUB_RUN_ID:-manual}-${GITHUB_RUN_ATTEMPT:-1}"
|
||||||
|
DEPLOY_ROOT="/home/lzf/apps/cozsweet-web-test"
|
||||||
|
REMOTE_TMP="$DEPLOY_ROOT/tmp/actions-$RUN_TOKEN"
|
||||||
|
REMOTE_ARCHIVE="$REMOTE_TMP/$ARCHIVE"
|
||||||
|
REMOTE_ENV_FILE="$DEPLOY_ROOT/shared/test.env"
|
||||||
|
SSH_OPTS="-i $KEY_FILE -p $DEPLOY_PORT -o BatchMode=yes -o IdentitiesOnly=yes"
|
||||||
|
SCP_OPTS="-i $KEY_FILE -P $DEPLOY_PORT -o BatchMode=yes -o IdentitiesOnly=yes"
|
||||||
|
|
||||||
|
cleanup_remote() {
|
||||||
|
ssh $SSH_OPTS "$SSH_TARGET" \
|
||||||
|
"rm -f '$REMOTE_ARCHIVE' && rmdir '$REMOTE_TMP' 2>/dev/null || true"
|
||||||
|
}
|
||||||
|
trap cleanup_remote EXIT
|
||||||
|
|
||||||
|
ssh $SSH_OPTS "$SSH_TARGET" \
|
||||||
|
"mkdir -p '$DEPLOY_ROOT/current' '$DEPLOY_ROOT/releases/docker' '$DEPLOY_ROOT/shared' '$REMOTE_TMP' && chmod 700 '$DEPLOY_ROOT/shared'"
|
||||||
|
scp $SCP_OPTS scripts/server/deploy-domestic-test-archive.sh \
|
||||||
|
"$SSH_TARGET:$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh"
|
||||||
|
scp $SCP_OPTS .env.domestic-test "$SSH_TARGET:$REMOTE_ENV_FILE"
|
||||||
|
scp $SCP_OPTS "$ARCHIVE" "$SSH_TARGET:$REMOTE_ARCHIVE"
|
||||||
|
ssh $SSH_OPTS "$SSH_TARGET" \
|
||||||
|
"chmod 600 '$REMOTE_ENV_FILE' && chmod 700 '$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh' && '$DEPLOY_ROOT/current/deploy-domestic-test-archive.sh' '$REMOTE_ARCHIVE' '$IMAGE' '$REMOTE_ENV_FILE' 9135"
|
||||||
|
|
||||||
|
- name: Cleanup runner artifacts
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
rm -f .env.domestic-test .env.domestic-test.next "${ARCHIVE:-}" "$HOME/.ssh/domestic_test_deploy_key"
|
||||||
@@ -6,10 +6,12 @@ ENV PNPM_HOME=/pnpm
|
|||||||
ENV PNPM_STORE_PATH=/pnpm/store
|
ENV PNPM_STORE_PATH=/pnpm/store
|
||||||
ENV PATH=$PNPM_HOME:$PATH
|
ENV PATH=$PNPM_HOME:$PATH
|
||||||
|
|
||||||
|
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||||
|
|
||||||
RUN apk add --no-cache libc6-compat \
|
RUN apk add --no-cache libc6-compat \
|
||||||
&& corepack enable \
|
&& npm install --global "pnpm@10.30.3" --registry="$NPM_REGISTRY" \
|
||||||
&& corepack prepare pnpm@10.30.3 --activate \
|
&& pnpm config set store-dir "$PNPM_STORE_PATH" \
|
||||||
&& pnpm config set store-dir "$PNPM_STORE_PATH"
|
&& pnpm config set registry "$NPM_REGISTRY"
|
||||||
|
|
||||||
FROM base AS deps
|
FROM base AS deps
|
||||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
|
|||||||
@@ -25,9 +25,9 @@
|
|||||||
"./src/data/schemas/payment",
|
"./src/data/schemas/payment",
|
||||||
"./src/data/schemas/payment/request",
|
"./src/data/schemas/payment/request",
|
||||||
"./src/data/schemas/payment/response",
|
"./src/data/schemas/payment/response",
|
||||||
"./src/data/schemas/private-room",
|
"./src/data/schemas/private-zone",
|
||||||
"./src/data/schemas/private-room/request",
|
"./src/data/schemas/private-zone/request",
|
||||||
"./src/data/schemas/private-room/response",
|
"./src/data/schemas/private-zone/response",
|
||||||
"./src/data/schemas/user",
|
"./src/data/schemas/user",
|
||||||
"./src/data/storage/app",
|
"./src/data/storage/app",
|
||||||
"./src/data/storage/auth",
|
"./src/data/storage/auth",
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ Authorization: Bearer <TOKEN>
|
|||||||
2. `isActive=true`;
|
2. `isActive=true`;
|
||||||
3. `capabilities.chat=true`。
|
3. `capabilities.chat=true`。
|
||||||
|
|
||||||
服务端目录决定角色是否可聊天及排序;本地目录继续提供 slug、图片、文案和 Tip 能力。`privateRoom` 只有在本地能力和服务端 `privateContent` 同时开启时可用。
|
服务端目录决定角色是否可聊天及排序;本地目录继续提供 slug、图片、文案和 Tip 能力。`privateZone` 只有在本地能力和服务端 `privateContent` 同时开启时可用。
|
||||||
|
|
||||||
远端目录返回前,生产环境只使用 Elio 作为临时目录;非生产环境可使用完整本地目录。远端目录加载成功后,以合并结果为准。
|
远端目录返回前,生产环境只使用 Elio 作为临时目录;非生产环境可使用完整本地目录。远端目录加载成功后,以合并结果为准。
|
||||||
|
|
||||||
@@ -72,7 +72,7 @@ Authorization: Bearer <TOKEN>
|
|||||||
```text
|
```text
|
||||||
/characters/{slug}/splash
|
/characters/{slug}/splash
|
||||||
/characters/{slug}/chat
|
/characters/{slug}/chat
|
||||||
/characters/{slug}/private-room
|
/characters/{slug}/private-zone
|
||||||
/characters/{slug}/tip
|
/characters/{slug}/tip
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -81,11 +81,11 @@ Authorization: Bearer <TOKEN>
|
|||||||
```text
|
```text
|
||||||
/splash -> /characters/elio/splash
|
/splash -> /characters/elio/splash
|
||||||
/chat -> /characters/elio/chat
|
/chat -> /characters/elio/chat
|
||||||
/private-room -> /characters/elio/private-room
|
/private-zone -> /characters/elio/private-zone
|
||||||
/tip -> /characters/elio/tip
|
/tip -> /characters/elio/tip
|
||||||
```
|
```
|
||||||
|
|
||||||
Chat Provider 以 `characterId` 为边界,路由角色变化时创建新的 Actor。Private Room 的角色边界由 [Private Room 权威协议](./FRONTEND_PRIVATE_ROOM_API.md) 定义。
|
Chat Provider 以 `characterId` 为边界,路由角色变化时创建新的 Actor。Private Zone 的角色边界由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||||
|
|
||||||
## 3. Chat HTTP 协议
|
## 3. Chat HTTP 协议
|
||||||
|
|
||||||
@@ -308,7 +308,7 @@ conversationKey = {ownerKey}::character:{encodeURIComponent(characterId)}
|
|||||||
|
|
||||||
## 7. 关联业务边界
|
## 7. 关联业务边界
|
||||||
|
|
||||||
- Private Room 的相册、解锁、Gallery 和支付回跳由 [Private Room 权威协议](./FRONTEND_PRIVATE_ROOM_API.md) 定义。
|
- Private Zone 的相册、解锁、Gallery 和支付回跳由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||||
- Tip 的角色归属、订单轮询和支付回跳由 [Payment 权威协议](./FRONTEND_PAYMENT_API.md) 定义;Chat 只保存解锁所需的原角色回跳地址。
|
- Tip 的角色归属、订单轮询和支付回跳由 [Payment 权威协议](./FRONTEND_PAYMENT_API.md) 定义;Chat 只保存解锁所需的原角色回跳地址。
|
||||||
- 登录、支付和解锁回跳保存原角色动态 URL,不能降级为通用 `/chat`。
|
- 登录、支付和解锁回跳保存原角色动态 URL,不能降级为通用 `/chat`。
|
||||||
- Analytics 可以使用 `characterId`,聊天正文不属于路由或身份协议的一部分。
|
- Analytics 可以使用 `characterId`,聊天正文不属于路由或身份协议的一部分。
|
||||||
|
|||||||
@@ -224,7 +224,7 @@ payChannel = ezpay
|
|||||||
subscriptionType = vip | topup | tip
|
subscriptionType = vip | topup | tip
|
||||||
giftCategory(仅 Tip,可空)
|
giftCategory(仅 Tip,可空)
|
||||||
giftPlanId(仅 Tip,可空)
|
giftPlanId(仅 Tip,可空)
|
||||||
returnTo = chat | private-room | sidebar(可选)
|
returnTo = chat | private-zone | profile(可选)
|
||||||
characterSlug(可选)
|
characterSlug(可选)
|
||||||
createdAt
|
createdAt
|
||||||
```
|
```
|
||||||
@@ -238,7 +238,7 @@ Tip -> /characters/{slug}/tip?category=...&planId=...&payChannel=ezpay&
|
|||||||
|
|
||||||
恢复页面只接受与当前 `paymentType` 相同的待处理订单。带有 `paymentReturn=1` 时派发 `PaymentReturned` 并继续轮询;普通进入支付页时会清理同类型的旧待处理订单。订单进入 paid、failed 或 expired 后清理持久化记录。缺少 Gift 字段的旧记录由最新目录默认选择第一件商品,不再读取 `coffee_type`。
|
恢复页面只接受与当前 `paymentType` 相同的待处理订单。带有 `paymentReturn=1` 时派发 `PaymentReturned` 并继续轮询;普通进入支付页时会清理同类型的旧待处理订单。订单进入 paid、failed 或 expired 后清理持久化记录。缺少 Gift 字段的旧记录由最新目录默认选择第一件商品,不再读取 `coffee_type`。
|
||||||
|
|
||||||
无效或未知 `characterSlug` 回退到默认角色 slug。有效角色回跳必须保留原角色,不能统一返回 Elio。`returnTo=private-room` 的最终页面行为由 [Private Room 权威协议](./FRONTEND_PRIVATE_ROOM_API.md) 定义。
|
无效或未知 `characterSlug` 回退到默认角色 slug。有效角色回跳必须保留原角色,不能统一返回 Elio。`returnTo=private-zone` 的最终页面行为由 [Private Zone 权威协议](./FRONTEND_PRIVATE_ZONE_API.md) 定义。
|
||||||
|
|
||||||
## 8. 成功后的跨域同步
|
## 8. 成功后的跨域同步
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# CozSweet Private Room 权威协议
|
# CozSweet Private Zone 权威协议
|
||||||
|
|
||||||
## 1. 状态与范围
|
## 1. 状态与范围
|
||||||
|
|
||||||
@@ -9,11 +9,11 @@
|
|||||||
| 边界 | 实现位置 |
|
| 边界 | 实现位置 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| API 路径与方法 | `src/data/services/api/api_contract.json` |
|
| API 路径与方法 | `src/data/services/api/api_contract.json` |
|
||||||
| 请求与响应字段 | `src/data/schemas/private-room` |
|
| 请求与响应字段 | `src/data/schemas/private-zone` |
|
||||||
| API 与 Repository | `src/data/services/api/private_room_api.ts`、`src/data/repositories/private_room_repository.ts` |
|
| API 与 Repository | `src/data/services/api/private_zone_api.ts`、`src/data/repositories/private_zone_repository.ts` |
|
||||||
| Private Room 状态机 | `src/stores/private-room` |
|
| Private Zone 状态机 | `src/stores/private-zone` |
|
||||||
| 页面、Gallery 与导航 | `src/app/private-room` |
|
| 页面、Gallery 与导航 | `src/app/private-zone` |
|
||||||
| 角色 Provider | `src/providers/private-room-route-provider.tsx` |
|
| 角色 Provider | `src/providers/private-zone-route-provider.tsx` |
|
||||||
|
|
||||||
修改上述实现时必须在同一变更中更新本文,不能再新增按相册列表、解锁或 Gallery 拆分的并行协议。
|
修改上述实现时必须在同一变更中更新本文,不能再新增按相册列表、解锁或 Gallery 拆分的并行协议。
|
||||||
|
|
||||||
@@ -22,13 +22,13 @@
|
|||||||
标准路由:
|
标准路由:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/characters/{characterSlug}/private-room
|
/characters/{characterSlug}/private-zone
|
||||||
```
|
```
|
||||||
|
|
||||||
旧地址保留为默认角色重定向,并保留查询参数:
|
旧地址保留为默认角色重定向,并保留查询参数:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/private-room -> /characters/elio/private-room
|
/private-zone -> /characters/elio/private-zone
|
||||||
```
|
```
|
||||||
|
|
||||||
URL 使用角色 `slug`,API 和 Actor 使用角色业务 `id`:
|
URL 使用角色 `slug`,API 和 Actor 使用角色业务 `id`:
|
||||||
@@ -39,14 +39,14 @@ URL 使用角色 `slug`,API 和 Actor 使用角色业务 `id`:
|
|||||||
| `maya-tan` | `maya` |
|
| `maya-tan` | `maya` |
|
||||||
| `nayeli-cervantes` | `nayeli` |
|
| `nayeli-cervantes` | `nayeli` |
|
||||||
|
|
||||||
角色必须同时存在于本地目录且 `capabilities.privateRoom=true`。该能力由本地配置和角色目录响应的 `privateContent` 共同决定;能力关闭或 slug 未知时路由返回 Not Found。
|
角色必须同时存在于本地目录且 `capabilities.privateZone=true`。该能力由本地配置和角色目录响应的 `privateContent` 共同决定;能力关闭或 slug 未知时路由返回 Not Found。
|
||||||
|
|
||||||
`PrivateRoomProvider` 以 `characterId` 为输入和 React key。切换角色会销毁旧 Actor 并创建空状态,不能复用上一角色的相册、余额或解锁请求。
|
`PrivateZoneProvider` 以 `characterId` 为输入和 React key。切换角色会销毁旧 Actor 并创建空状态,不能复用上一角色的相册、余额或解锁请求。
|
||||||
|
|
||||||
## 3. 相册列表
|
## 3. 相册列表
|
||||||
|
|
||||||
```http
|
```http
|
||||||
GET <API_BASE_URL>/api/private-room/albums?characterId=maya-tan&limit=20
|
GET <API_BASE_URL>/api/private-zone/albums?characterId=maya-tan&limit=20
|
||||||
Authorization: Bearer <TOKEN>
|
Authorization: Bearer <TOKEN>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ Authorization: Bearer <TOKEN>
|
|||||||
| `characterId` | 是 | 当前角色业务 ID |
|
| `characterId` | 是 | 当前角色业务 ID |
|
||||||
| `limit` | 否 | 当前固定为 20 |
|
| `limit` | 否 | 当前固定为 20 |
|
||||||
|
|
||||||
前端当前只加载第一页,不实现 Private Room 分页,也不把相册列表写入本地缓存。初始化、手动刷新或登录身份变化时重新请求网络。
|
前端当前只加载第一页,不实现 Private Zone 分页,也不把相册列表写入本地缓存。初始化、手动刷新或登录身份变化时重新请求网络。
|
||||||
|
|
||||||
标准响应数据:
|
标准响应数据:
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ album.locked || !album.unlocked || album.lockDetail.locked
|
|||||||
用户点击锁定相册后,前端先展示确认 Dialog。只有待确认 `albumId` 仍存在于当前 Actor 的 `items` 中,才会发起请求。
|
用户点击锁定相册后,前端先展示确认 Dialog。只有待确认 `albumId` 仍存在于当前 Actor 的 `items` 中,才会发起请求。
|
||||||
|
|
||||||
```http
|
```http
|
||||||
POST <API_BASE_URL>/api/private-room/albums/{albumId}/unlock
|
POST <API_BASE_URL>/api/private-zone/albums/{albumId}/unlock
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
Authorization: Bearer <TOKEN>
|
Authorization: Bearer <TOKEN>
|
||||||
```
|
```
|
||||||
@@ -177,25 +177,25 @@ Schema 同时允许未知字符串,未知失败原因使用通用错误文案
|
|||||||
|
|
||||||
## 5. 身份与支付导航
|
## 5. 身份与支付导航
|
||||||
|
|
||||||
Private Room 初始化会复用 Guest 登录引导。Auth 尚未初始化或正在加载时不请求列表;`notLoggedIn` 完成 Guest bootstrap 后再进入列表加载。Guest 和正式用户都可以读取后端允许的相册列表。
|
Private Zone 初始化会复用 Guest 登录引导。Auth 尚未初始化或正在加载时不请求列表;`notLoggedIn` 完成 Guest bootstrap 后再进入列表加载。Guest 和正式用户都可以读取后端允许的相册列表。
|
||||||
|
|
||||||
积分不足生成 Paywall 请求后:
|
积分不足生成 Paywall 请求后:
|
||||||
|
|
||||||
| 当前身份 | 导航 |
|
| 当前身份 | 导航 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Guest 或 Not Logged In | 打开 Auth,redirect 为当前角色 Private Room |
|
| Guest 或 Not Logged In | 打开 Auth,redirect 为当前角色 Private Zone |
|
||||||
| 已认证用户 | 打开 Top-up,`returnTo=private-room`,保留当前角色来源 |
|
| 已认证用户 | 打开 Top-up,`returnTo=private-zone`,保留当前角色来源 |
|
||||||
|
|
||||||
Paywall 导航发起后立即消费当前请求,避免 React 重渲染重复导航。支付回跳和订单恢复遵循 [Payment 权威协议](./FRONTEND_PAYMENT_API.md)。
|
Paywall 导航发起后立即消费当前请求,避免 React 重渲染重复导航。支付回跳和订单恢复遵循 [Payment 权威协议](./FRONTEND_PAYMENT_API.md)。
|
||||||
|
|
||||||
解锁成功后 `unlockSuccessNonce` 递增,页面桥接到 `UserFetch`,刷新当前积分和权益。Private Room 不自行修改 User Store 余额。
|
解锁成功后 `unlockSuccessNonce` 递增,页面桥接到 `UserFetch`,刷新当前积分和权益。Private Zone 不自行修改 User Store 余额。
|
||||||
|
|
||||||
## 6. Gallery URL 协议
|
## 6. Gallery URL 协议
|
||||||
|
|
||||||
解锁相册使用查询参数打开页内 Gallery:
|
解锁相册使用查询参数打开页内 Gallery:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/characters/{slug}/private-room?album={albumId}&image={zeroBasedIndex}
|
/characters/{slug}/private-zone?album={albumId}&image={zeroBasedIndex}
|
||||||
```
|
```
|
||||||
|
|
||||||
解析规则:
|
解析规则:
|
||||||
@@ -208,25 +208,31 @@ Paywall 导航发起后立即消费当前请求,避免 React 重渲染重复
|
|||||||
|
|
||||||
任一条件不满足时,页面通过 replace 删除 `album` 和 `image`,并保留其他查询参数。
|
任一条件不满足时,页面通过 replace 删除 `album` 和 `image`,并保留其他查询参数。
|
||||||
|
|
||||||
页面内点击打开 Gallery 时,关闭操作优先使用浏览器 back;直接刷新或外部分享 Gallery URL 时,关闭操作使用 replace 返回当前角色 Private Room。键盘 Escape 关闭,左右方向键和横向滑动切换图片。
|
页面内点击九宫格缩略图时,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` 下取消吸附过渡。
|
||||||
|
|
||||||
## 7. UI 与数据边界
|
## 7. UI 与数据边界
|
||||||
|
|
||||||
- React key 使用稳定 `albumId`;
|
- React key 使用稳定 `albumId`;
|
||||||
- 卡片图片数量优先使用 `imageCount`,为 0 时回退到 `images.length`;
|
- 卡片图片数量优先使用 `imageCount`,为 0 时回退到 `images.length`;
|
||||||
- Gallery 只渲染当前索引存在 URL 的图片;
|
- 锁定相册显示模糊封面、角色头像、锁标识、图片数量和 `View collection` 入口;卡片不展示视频数量或积分价格,解锁价格只在确认 Dialog 中展示;
|
||||||
|
- 解锁相册过滤锁定或空 URL 图片,并保留剩余图片的原始数组索引;
|
||||||
|
- 1 张图片显示 4:5 大图,2/4 张使用两列,其余使用三列正方形九宫格;
|
||||||
|
- 超过 9 张时卡片显示前九张,末格显示 `+N`,Gallery 仍可浏览全部有效图片;
|
||||||
|
- Gallery 只挂载当前图片和相邻图片,避免多图相册同时解码全部原图;
|
||||||
- `creditBalance` 是当前列表/解锁响应快照,不替代 User Store 权益;
|
- `creditBalance` 是当前列表/解锁响应快照,不替代 User Store 权益;
|
||||||
- Private Room 不使用 Chat 的 `conversationKey`、消息缓存或媒体缓存;
|
- Private Zone 不使用 Chat 的 `conversationKey`、消息缓存或媒体缓存;
|
||||||
- Private Room 不持有 Payment Actor,Top-up 通过路由级导航进入独立 Payment Provider。
|
- Private Zone 不持有 Payment Actor,Top-up 通过路由级导航进入独立 Payment Provider。
|
||||||
|
|
||||||
## 8. 变更验收
|
## 8. 变更验收
|
||||||
|
|
||||||
Private Room 协议相关变更至少验证:
|
Private Zone 协议相关变更至少验证:
|
||||||
|
|
||||||
1. `src/data/schemas/private-room/__tests__`;
|
1. `src/data/schemas/private-zone/__tests__`;
|
||||||
2. `src/data/services/api/__tests__/multi_character_api.test.ts` 中的 Private Room 请求;
|
2. `src/data/services/api/__tests__/multi_character_api.test.ts` 中的 Private Zone 请求;
|
||||||
3. `src/stores/private-room/__tests__`;
|
3. `src/stores/private-zone/__tests__`;
|
||||||
4. `src/app/private-room/__tests__` 与组件测试;
|
4. `src/app/private-zone/__tests__` 与组件测试;
|
||||||
5. Elio、Maya、Nayeli 列表互不串联;
|
5. Elio、Maya、Nayeli 列表互不串联;
|
||||||
6. 登录身份变化会刷新当前角色列表;
|
6. 登录身份变化会刷新当前角色列表;
|
||||||
7. 成功、余额不足、价格变化、重复解锁、退款失败和 not found 分支;
|
7. 成功、余额不足、价格变化、重复解锁、退款失败和 not found 分支;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
# 外部入口接入说明
|
# 外部入口接入说明
|
||||||
|
|
||||||
外部应用通过 `/external-entry` 进入本应用。
|
Facebook 等外部应用统一通过 `/external-entry` 进入本应用。入口先保存外部身份和短期业务意图,再跳转到对应角色页面并清理地址栏中的入口查询参数。
|
||||||
|
|
||||||
| 环境 | APP HOST |
|
| 环境 | APP HOST |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 测试环境 | `frontend-test.banlv-ai.com` |
|
| 预发环境 `pre` | `frontend-test.banlv-ai.com` |
|
||||||
| 正式环境 | `cozsweet.com` |
|
| 正式环境 `production` | `cozsweet.com` |
|
||||||
|
|
||||||
入口格式:
|
入口格式:
|
||||||
|
|
||||||
@@ -13,80 +13,78 @@
|
|||||||
https://<APP_HOST>/external-entry?<参数>
|
https://<APP_HOST>/external-entry?<参数>
|
||||||
```
|
```
|
||||||
|
|
||||||
## 可选参数
|
## 当前 Facebook 业务入口
|
||||||
|
|
||||||
所有参数均为可选参数。
|
当前正式投放固定为 4 类入口乘以 3 个角色,共 12 条链接。Facebook 业务名称与应用页面的对应关系如下:
|
||||||
|
|
||||||
|
| Facebook 入口 | 参数组合 | 落地行为 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 私密空间 | `target=chat` | 进入普通聊天页,不插入任何锁定内容。 |
|
||||||
|
| 语音 | `target=chat&mode=promotion&promotion_type=voice` | 进入聊天页,并插入一条待解锁语音。 |
|
||||||
|
| 图片包 | `target=private-zone` | 进入角色的 `private-zone` 图片空间。 |
|
||||||
|
| 帮忙买咖啡 | `target=tip` | 进入角色的咖啡打赏页。 |
|
||||||
|
|
||||||
|
每条正式链接还必须显式传入:
|
||||||
|
|
||||||
|
- `character=elio`、`character=maya` 或 `character=nayeli`;
|
||||||
|
- `psid=<PSID>`,其中 `<PSID>` 必须由 Facebook 发送端替换为当前用户经过 URL 编码的 Page-scoped User ID。
|
||||||
|
|
||||||
|
完整的 12 条正式发送模板见 [Facebook 12 条外部入口链接清单](./links.md)。
|
||||||
|
|
||||||
|
## 参数说明
|
||||||
|
|
||||||
| 参数 | 可选值或格式 | 用途 |
|
| 参数 | 可选值或格式 | 用途 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `target` | `chat`、`tip`、`private-room` | 指定进入的页面;不传或值无效时进入聊天页。 |
|
| `target` | `chat`、`tip`、`private-zone` | 指定进入的页面;不传或值无效时进入聊天页。 |
|
||||||
| `character` | `elio`、`maya`、`nayeli` | 指定角色;不传或值无效时使用 Elio。 |
|
| `character` | `elio`、`maya`、`nayeli` | 指定角色;不传或值无效时使用 Elio。正式投放链接必须显式传入。 |
|
||||||
| `psid` | string | 传入 Facebook Page-scoped User ID。 |
|
| `psid` | string | Facebook Page-scoped User ID。Facebook 正式投放链接必须动态传入。 |
|
||||||
| `mode` | `promotion` | 开启聊天促销模式。 |
|
| `mode` | `promotion` | 开启聊天促销模式。 |
|
||||||
| `promotion_type` | `voice`、`image`、`private` | 指定促销消息类型,仅与 `mode=promotion` 一起使用。 |
|
| `promotion_type` | `voice`、`image`、`private` | 指定促销消息类型,仅与 `mode=promotion` 一起使用。 |
|
||||||
|
|
||||||
`mode=promotion` 只有在 `target=chat` 且同时提供有效的 `promotion_type` 时生效。
|
`mode=promotion` 只有在 `target=chat` 且同时提供有效的 `promotion_type` 时生效。当前 12 条正式投放链接只使用 `promotion_type=voice`;`image` 和 `private` 保留为兼容能力,不属于本次业务清单。
|
||||||
|
|
||||||
|
## 四类发送模板
|
||||||
|
|
||||||
|
发送前必须把 `<CHARACTER>` 替换为角色值,把 `<PSID>` 替换为当前 Facebook 用户的真实 PSID;不得把占位符原样发送给用户。
|
||||||
|
|
||||||
|
私密空间(普通聊天):
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://<APP_HOST>/external-entry?target=chat&character=<CHARACTER>&psid=<PSID>
|
||||||
|
```
|
||||||
|
|
||||||
|
语音:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://<APP_HOST>/external-entry?target=chat&character=<CHARACTER>&mode=promotion&promotion_type=voice&psid=<PSID>
|
||||||
|
```
|
||||||
|
|
||||||
|
图片包:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://<APP_HOST>/external-entry?target=private-zone&character=<CHARACTER>&psid=<PSID>
|
||||||
|
```
|
||||||
|
|
||||||
|
帮忙买咖啡:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://<APP_HOST>/external-entry?target=tip&character=<CHARACTER>&psid=<PSID>
|
||||||
|
```
|
||||||
|
|
||||||
## PSID 与登录状态流程
|
## PSID 与登录状态流程
|
||||||
|
|
||||||
PSID 保存、登录状态判断和 Facebook Identity 绑定逻辑见 [PSID 与登录状态流程图](./psid-login-flow.md)。
|
`psid` 可以和任意有效入口参数组合使用。应用会先保存 PSID,再执行登录状态判断和 Facebook Identity 绑定。详细流程见 [PSID 与登录状态流程图](./psid-login-flow.md)。
|
||||||
|
|
||||||
## 使用示例
|
所有参数值都必须进行 URL 编码。入口中禁止传递登录 Token、Page Access Token、App Secret 或其他秘密。
|
||||||
|
|
||||||
普通聊天:
|
## 兼容说明
|
||||||
|
|
||||||
```text
|
- 历史参数 `target=private-room` 继续兼容进入 `private-zone`,但不得用于新投放链接。
|
||||||
https://<APP_HOST>/external-entry?target=chat
|
- `private_zone` 等其他拼写仍按无效目标处理并回退聊天页。
|
||||||
```
|
- `promotion_type=image` 和 `promotion_type=private` 继续由现有代码支持,但不计入当前 12 条 Facebook 业务链接。
|
||||||
|
- 无效或缺失的 `character` 继续回退 Elio;正式投放模板始终显式传入角色,不能依赖回退。
|
||||||
|
|
||||||
进入 Maya 聊天:
|
## 调试与正式清单
|
||||||
|
|
||||||
```text
|
- [本地调试链接清单](./debug-links.md)
|
||||||
https://<APP_HOST>/external-entry?target=chat&character=maya
|
- [Facebook 12 条外部入口链接清单](./links.md)
|
||||||
```
|
|
||||||
|
|
||||||
携带 PSID 进入聊天,示例 PSID 为 `27511427698460020`:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=chat&psid=27511427698460020
|
|
||||||
```
|
|
||||||
|
|
||||||
语音促销聊天:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=chat&mode=promotion&promotion_type=voice
|
|
||||||
```
|
|
||||||
|
|
||||||
图片促销聊天:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=chat&mode=promotion&promotion_type=image
|
|
||||||
```
|
|
||||||
|
|
||||||
私密文本促销聊天:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=chat&mode=promotion&promotion_type=private
|
|
||||||
```
|
|
||||||
|
|
||||||
咖啡打赏:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=tip
|
|
||||||
```
|
|
||||||
|
|
||||||
私密空间:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=private-room
|
|
||||||
```
|
|
||||||
|
|
||||||
进入 Nayeli 私密空间:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=private-room&character=nayeli
|
|
||||||
```
|
|
||||||
|
|
||||||
`psid` 可以与任意 `target` 或聊天促销参数组合使用。参数值需要进行 URL 编码,不要在入口中传递登录 Token、Page Access Token 或 App Secret。
|
|
||||||
|
|
||||||
测试环境和正式环境的完整可点击示例见 [外部入口链接清单](./links.md)。
|
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# 外部入口本地调试链接清单
|
||||||
|
|
||||||
|
[返回外部入口接入说明](./README.md)
|
||||||
|
|
||||||
|
启动本地应用后,可以直接点击以下链接进行调试。根网址为 `http://localhost:3000`,PSID 示例统一使用 `27511427698460020`。
|
||||||
|
|
||||||
|
## 默认入口
|
||||||
|
|
||||||
|
| 入口 | 链接 |
|
||||||
|
| --- | --- |
|
||||||
|
| 默认入口(Elio 聊天) | [打开默认入口](http://localhost:3000/external-entry) |
|
||||||
|
| 普通聊天 | [打开普通聊天](http://localhost:3000/external-entry?target=chat) |
|
||||||
|
| 携带 PSID 的聊天 | [打开 PSID 聊天示例](http://localhost:3000/external-entry?target=chat&psid=27511427698460020) |
|
||||||
|
|
||||||
|
## 角色聊天
|
||||||
|
|
||||||
|
| 角色 | 链接 |
|
||||||
|
| --- | --- |
|
||||||
|
| Elio | [打开 Elio 聊天](http://localhost:3000/external-entry?target=chat&character=elio) |
|
||||||
|
| Maya | [打开 Maya 聊天](http://localhost:3000/external-entry?target=chat&character=maya) |
|
||||||
|
| Nayeli | [打开 Nayeli 聊天](http://localhost:3000/external-entry?target=chat&character=nayeli) |
|
||||||
|
|
||||||
|
## 聊天促销
|
||||||
|
|
||||||
|
| 促销类型 | 链接 |
|
||||||
|
| --- | --- |
|
||||||
|
| 语音促销 | [打开语音促销](http://localhost:3000/external-entry?target=chat&mode=promotion&promotion_type=voice) |
|
||||||
|
| 图片促销 | [打开图片促销](http://localhost:3000/external-entry?target=chat&mode=promotion&promotion_type=image) |
|
||||||
|
| 私密文本促销 | [打开私密文本促销](http://localhost:3000/external-entry?target=chat&mode=promotion&promotion_type=private) |
|
||||||
|
|
||||||
|
## 咖啡打赏
|
||||||
|
|
||||||
|
| 角色 | 链接 |
|
||||||
|
| --- | --- |
|
||||||
|
| Elio | [打开 Elio 咖啡打赏](http://localhost:3000/external-entry?target=tip&character=elio) |
|
||||||
|
| Maya | [打开 Maya 咖啡打赏](http://localhost:3000/external-entry?target=tip&character=maya) |
|
||||||
|
| Nayeli | [打开 Nayeli 咖啡打赏](http://localhost:3000/external-entry?target=tip&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,52 @@
|
|||||||
# 外部入口链接清单
|
# Facebook 12 条外部入口链接清单
|
||||||
|
|
||||||
[返回外部入口接入说明](./README.md)
|
本清单是 Facebook 正式投放的唯一业务链接清单,共 4 类入口乘以 3 个角色,合计 12 条模板。
|
||||||
|
|
||||||
以下链接可以直接点击打开。PSID 示例统一使用 `27511427698460020`。
|
## 发送规则
|
||||||
|
|
||||||
## 测试环境
|
- 发送前必须把每条模板中的 `<PSID>` 替换为当前用户经过 URL 编码的 Facebook Page-scoped User ID;不得把占位符原样发送。
|
||||||
|
- 每条链接都显式传入 `character`,不得依赖缺省角色回退。
|
||||||
|
- Facebook 业务名称“私密空间”进入普通聊天页;业务名称“图片包”才进入应用的 `private-zone`。
|
||||||
|
- 不要在入口中传递登录 Token、Page Access Token、App Secret 或其他秘密。
|
||||||
|
- 以下模板包含占位符,替换真实 PSID 后才能直接发送或点击。
|
||||||
|
|
||||||
| 入口 | 链接 |
|
## 正式投放模板
|
||||||
| --- | --- |
|
|
||||||
| 普通聊天 | [打开普通聊天](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-room) |
|
|
||||||
| Maya 私密空间 | [打开 Maya 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=maya) |
|
|
||||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=nayeli) |
|
|
||||||
|
|
||||||
## 正式环境
|
| 编号 | Facebook 入口 | 角色 | 发送模板 | 预期落地与页面状态 |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| 1 | 私密空间 | Elio | `https://cozsweet.com/external-entry?target=chat&character=elio&psid=<PSID>` | `/characters/elio/chat`,不显示促销锁卡 |
|
||||||
|
| 2 | 私密空间 | Maya | `https://cozsweet.com/external-entry?target=chat&character=maya&psid=<PSID>` | `/characters/maya/chat`,不显示促销锁卡 |
|
||||||
|
| 3 | 私密空间 | Nayeli | `https://cozsweet.com/external-entry?target=chat&character=nayeli&psid=<PSID>` | `/characters/nayeli/chat`,不显示促销锁卡 |
|
||||||
|
| 4 | 语音 | Elio | `https://cozsweet.com/external-entry?target=chat&character=elio&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/elio/chat`,显示一条锁定语音 |
|
||||||
|
| 5 | 语音 | Maya | `https://cozsweet.com/external-entry?target=chat&character=maya&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/maya/chat`,显示一条锁定语音 |
|
||||||
|
| 6 | 语音 | Nayeli | `https://cozsweet.com/external-entry?target=chat&character=nayeli&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/nayeli/chat`,显示一条锁定语音 |
|
||||||
|
| 7 | 图片包 | Elio | `https://cozsweet.com/external-entry?target=private-zone&character=elio&psid=<PSID>` | `/characters/elio/private-zone` |
|
||||||
|
| 8 | 图片包 | Maya | `https://cozsweet.com/external-entry?target=private-zone&character=maya&psid=<PSID>` | `/characters/maya/private-zone` |
|
||||||
|
| 9 | 图片包 | Nayeli | `https://cozsweet.com/external-entry?target=private-zone&character=nayeli&psid=<PSID>` | `/characters/nayeli/private-zone` |
|
||||||
|
| 10 | 帮忙买咖啡 | Elio | `https://cozsweet.com/external-entry?target=tip&character=elio&psid=<PSID>` | `/characters/elio/tip` |
|
||||||
|
| 11 | 帮忙买咖啡 | Maya | `https://cozsweet.com/external-entry?target=tip&character=maya&psid=<PSID>` | `/characters/maya/tip` |
|
||||||
|
| 12 | 帮忙买咖啡 | Nayeli | `https://cozsweet.com/external-entry?target=tip&character=nayeli&psid=<PSID>` | `/characters/nayeli/tip` |
|
||||||
|
|
||||||
| 入口 | 链接 |
|
## 预发验证
|
||||||
| --- | --- |
|
|
||||||
| 普通聊天 | [打开普通聊天](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-room) |
|
|
||||||
| Maya 私密空间 | [打开 Maya 私密空间](https://cozsweet.com/external-entry?target=private-room&character=maya) |
|
|
||||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://cozsweet.com/external-entry?target=private-room&character=nayeli) |
|
|
||||||
|
|
||||||
如需在其他入口携带 PSID,在链接末尾追加 `&psid=27511427698460020`。
|
预发验证不维护第二套业务清单。将上述 12 条模板的主机统一替换为 `frontend-test.banlv-ai.com`,其余路径和参数保持不变:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://frontend-test.banlv-ai.com/external-entry?<与正式模板相同的查询参数>
|
||||||
|
```
|
||||||
|
|
||||||
|
预发环境是 `pre`,不是正式环境。预发验证通过不代表已经更新 `cozsweet.com` 或获得生产发布批准。
|
||||||
|
|
||||||
|
## 验收判断
|
||||||
|
|
||||||
|
- 最终浏览器地址必须是表格中的预期页面,且不再保留 `/external-entry` 的查询参数。
|
||||||
|
- `<PSID>` 替换后的真实值必须由应用保存。
|
||||||
|
- “私密空间”只进入普通聊天,不得出现锁定语音、锁定图片或私密文本促销卡。
|
||||||
|
- “语音”进入聊天后必须只注入一条锁定语音。
|
||||||
|
- “图片包”和“帮忙买咖啡”必须分别进入对应角色的 `private-zone` 与 `tip`,不能串到其他角色。
|
||||||
|
|
||||||
|
## 不属于当前 12 条清单的兼容能力
|
||||||
|
|
||||||
|
- 历史 `target=private-room` 继续兼容,但不得创建新的投放链接。
|
||||||
|
- `promotion_type=image`、`promotion_type=private` 和独立 PSID 示例不属于当前正式业务清单。
|
||||||
|
- 兼容能力的保留不改变本页“只有 12 条正式投放模板”的口径。
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
# Private Zone 全链路改名联调说明
|
||||||
|
|
||||||
|
- 日期:2026-07-22
|
||||||
|
- 目标环境:本地、`pre`、生产
|
||||||
|
- 当前状态:已验证
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
原功能名称存在拼写错误。本次将前端、unified 后端、Manager、数据库、埋点和文档中的正式命名统一为 `Private Zone`,并同步切换页面路由、API 路径和公开枚举值。
|
||||||
|
|
||||||
|
## 2. 环境地址
|
||||||
|
|
||||||
|
| 环境 | 前端 | API Base URL |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `pre` | `https://frontend-test.banlv-ai.com` | `https://proapi.banlv-ai.com` |
|
||||||
|
| 生产 | `https://cozsweet.com` | `https://api.banlv-ai.com` |
|
||||||
|
|
||||||
|
## 3. 前端影响
|
||||||
|
|
||||||
|
前端已完成以下修改:
|
||||||
|
|
||||||
|
- 页面路由统一为 `/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`。
|
||||||
|
|
||||||
|
旧页面和旧查询参数不再作为正式入口保留。发布时必须让前后端属于同一个发布批次。
|
||||||
|
|
||||||
|
## 4. API 变更清单
|
||||||
|
|
||||||
|
所有接口都使用 `Authorization: Bearer <TOKEN>`,响应继续使用现有统一 envelope。请求与响应中未列出的业务字段保持原类型和含义。
|
||||||
|
|
||||||
|
| 方法 | 新路径 | 用途 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `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-zone/albums?characterId=elio&limit=20
|
||||||
|
Authorization: Bearer <TOKEN>
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 位置 | 类型 | 必填 | 可为 `null` | 说明 |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| `characterId` | query | string | 是 | 否 | 角色 ID |
|
||||||
|
| `limit` | query | integer | 否 | 否 | `1-50`,默认 `20` |
|
||||||
|
| `cursor` | query | string | 否 | 是 | 分页游标 |
|
||||||
|
|
||||||
|
调用示例:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl 'https://proapi.banlv-ai.com/api/private-zone/albums?characterId=elio&limit=20' \
|
||||||
|
-H 'Authorization: Bearer <TOKEN>'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 解锁图片包
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/private-zone/albums/{albumId}/unlock
|
||||||
|
Authorization: Bearer <TOKEN>
|
||||||
|
Content-Type: application/json
|
||||||
|
```
|
||||||
|
|
||||||
|
| 字段 | 位置 | 类型 | 必填 | 可为 `null` | 说明 |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| `albumId` | path | string | 是 | 否 | 图片包 ID |
|
||||||
|
| `expectedCost` | body | integer | 否 | 是 | 前端确认价格;与后端价格不一致时拒绝解锁 |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
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}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Moments 内容与解锁
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/private-zone/moments?characterId=elio&limit=20
|
||||||
|
POST /api/private-zone/moments/{momentId}/unlock
|
||||||
|
```
|
||||||
|
|
||||||
|
解锁请求体与图片包一致,`expectedCost` 为可选整数。响应中的正式分类值同步改为:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"lockDetail": {
|
||||||
|
"type": "private_zone_moment",
|
||||||
|
"reason": "private_zone_moment"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 其他公开值
|
||||||
|
|
||||||
|
| 使用位置 | 新值 | 类型 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `/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-zone-bridge.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
桥接脚本会创建新表并在切换窗口内保持新旧解锁写入双向同步。生产前后端全部切换完成后,再执行最终迁移:
|
||||||
|
|
||||||
|
```text
|
||||||
|
database/private-zone-migration.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
迁移会在同一事务中完成:
|
||||||
|
|
||||||
|
- 将历史解锁表无损重命名;新旧表同时存在时先合并再删除旧表。
|
||||||
|
- 重命名关联约束、索引、策略和触发器。
|
||||||
|
- 合并 `users.preferences` 中历史解锁键,防止已解锁内容重新锁定。
|
||||||
|
- 把 `credit_ledger` 历史分类迁移到 `private_zone` 和 `private_zone_moment`。
|
||||||
|
- 定向迁移历史埋点键、页面 URL 和系统媒体路径,不改写用户聊天正文。
|
||||||
|
- 删除切换窗口使用的双写触发器和函数。
|
||||||
|
- 支持重复执行。
|
||||||
|
|
||||||
|
## 7. 兼容性与发布顺序
|
||||||
|
|
||||||
|
这是破坏性命名修正,不保留旧 API、旧页面路由或旧公开枚举作为正式兼容层。必须按以下顺序发布:
|
||||||
|
|
||||||
|
1. 备份数据库并记录当前 unified、前端和 Manager 版本。
|
||||||
|
2. 执行 `database/private-zone-bridge.sql`,确认新旧表双向写入一致。
|
||||||
|
3. 部署 unified `pre`,验证所有 `/api/private-zone/*` 接口。
|
||||||
|
4. 部署前端 `pre`,验证页面、外部入口、解锁和支付回跳。
|
||||||
|
5. Manager 更新后验证积分用途显示为新分类。
|
||||||
|
6. `pre` 验证通过后,先启动新生产后端并临时配置旧 API 到新 API 的 Nginx 转发。
|
||||||
|
7. 切换生产后端,再部署同批次生产前端;确认新前端只调用 `/api/private-zone/*`。
|
||||||
|
8. 删除临时 Nginx 转发,执行 `database/private-zone-migration.sql` 清理旧数据库对象。
|
||||||
|
|
||||||
|
## 8. 错误与界面状态
|
||||||
|
|
||||||
|
- `401`:Token 缺失或无效,前端进入现有登录恢复流程。
|
||||||
|
- `403`:游客访问仅注册用户可用的关系日记操作,展示现有注册引导。
|
||||||
|
- `404`:角色、图片包、内容或日记不存在,展示现有空状态或失效提示。
|
||||||
|
- `409`:`expectedCost` 与后端价格不同,刷新列表后重新确认。
|
||||||
|
- `402` 或业务余额不足错误:进入现有充值流程,并使用 `returnTo=private-zone` 返回原角色页面。
|
||||||
|
- 网络失败:不修改本地解锁状态,保留重试入口。
|
||||||
|
|
||||||
|
## 9. 验收用例
|
||||||
|
|
||||||
|
1. `/characters/elio/private-zone`、Maya 和 Nayeli 对应页面均可打开。
|
||||||
|
2. `GET /api/private-zone/albums` 返回当前角色内容,角色之间不混用。
|
||||||
|
3. 已解锁历史记录在迁移后保持解锁状态,不重复扣积分。
|
||||||
|
4. 新解锁成功后刷新页面仍为已解锁状态。
|
||||||
|
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-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-zone-rollback.sql`。回滚前应停止写入,先保存切换后的新增解锁记录,再执行逆向迁移并恢复旧应用版本。不得只恢复前端或只恢复 unified。
|
||||||
|
|
||||||
|
## 12. 待确认事项
|
||||||
|
|
||||||
|
- 无。
|
||||||
@@ -40,6 +40,6 @@ pnpm test:e2e:real
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
PLAYWRIGHT_BASE_URL=https://cozsweet.com \
|
PLAYWRIGHT_BASE_URL=https://cozsweet.com \
|
||||||
E2E_API_BASE_URL=https://proapi.banlv-ai.com \
|
E2E_API_BASE_URL=https://api.banlv-ai.com \
|
||||||
pnpm test:e2e:prod
|
pnpm test:e2e:prod
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export interface MockCoreApisOptions {
|
|||||||
paidImageFlow?: boolean;
|
paidImageFlow?: boolean;
|
||||||
paidImageInsufficientCreditsFlow?: boolean;
|
paidImageInsufficientCreditsFlow?: boolean;
|
||||||
paidVoiceInsufficientCreditsFlow?: boolean;
|
paidVoiceInsufficientCreditsFlow?: boolean;
|
||||||
psidLoginFlow?: boolean;
|
topUpHandoffFlow?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function mockCoreApis(page: Page, options: MockCoreApisOptions = {}) {
|
export async function mockCoreApis(page: Page, options: MockCoreApisOptions = {}) {
|
||||||
@@ -22,14 +22,14 @@ export async function mockCoreApis(page: Page, options: MockCoreApisOptions = {}
|
|||||||
paidImageFlow: options.paidImageFlow ?? false,
|
paidImageFlow: options.paidImageFlow ?? false,
|
||||||
paidImageInsufficientCreditsFlow: options.paidImageInsufficientCreditsFlow ?? false,
|
paidImageInsufficientCreditsFlow: options.paidImageInsufficientCreditsFlow ?? false,
|
||||||
paidVoiceInsufficientCreditsFlow: options.paidVoiceInsufficientCreditsFlow ?? false,
|
paidVoiceInsufficientCreditsFlow: options.paidVoiceInsufficientCreditsFlow ?? false,
|
||||||
psidLoginFlow: options.psidLoginFlow ?? false,
|
topUpHandoffFlow: options.topUpHandoffFlow ?? false,
|
||||||
};
|
};
|
||||||
const chatState = { hasExpiredChatSend: false, paidImageRequested: false, paidImageUnlocked: false };
|
const chatState = { hasExpiredChatSend: false, paidImageRequested: false, paidImageUnlocked: false };
|
||||||
|
|
||||||
await registerAuthMocks(page, {
|
await registerAuthMocks(page, {
|
||||||
chatSendTokenRefreshFlow: chatOptions.chatSendTokenRefreshFlow,
|
chatSendTokenRefreshFlow: chatOptions.chatSendTokenRefreshFlow,
|
||||||
isChatSendTokenExpired: () => chatState.hasExpiredChatSend,
|
isChatSendTokenExpired: () => chatState.hasExpiredChatSend,
|
||||||
psidLoginFlow: chatOptions.psidLoginFlow,
|
topUpHandoffFlow: chatOptions.topUpHandoffFlow,
|
||||||
});
|
});
|
||||||
await registerCharacterMocks(page);
|
await registerCharacterMocks(page);
|
||||||
await registerUserMocks(page);
|
await registerUserMocks(page);
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
import type { Page } from "@playwright/test";
|
import type { Page } from "@playwright/test";
|
||||||
|
|
||||||
import { apiEnvelope } from "../data/common";
|
import { apiEnvelope } from "../data/common";
|
||||||
import { emailLoginResponse, guestLoginResponse, psidLoginResponse, refreshedEmailLoginResponse, refreshedGuestLoginResponse } from "../data/auth";
|
import { emailLoginResponse, guestLoginResponse, refreshedEmailLoginResponse, refreshedGuestLoginResponse, topUpHandoffResponse } from "../data/auth";
|
||||||
|
|
||||||
export interface AuthMockState {
|
export interface AuthMockState {
|
||||||
chatSendTokenRefreshFlow: boolean;
|
chatSendTokenRefreshFlow: boolean;
|
||||||
isChatSendTokenExpired: () => boolean;
|
isChatSendTokenExpired: () => boolean;
|
||||||
psidLoginFlow: boolean;
|
topUpHandoffFlow: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function registerAuthMocks(page: Page, state: AuthMockState) {
|
export async function registerAuthMocks(page: Page, state: AuthMockState) {
|
||||||
await page.route("**/api/auth/login/facebook/psid", async (route) => {
|
await page.route("**/api/auth/handoff/topup/consume", async (route) => {
|
||||||
if (!state.psidLoginFlow) {
|
if (!state.topUpHandoffFlow) {
|
||||||
await route.continue();
|
await route.continue();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
await route.fulfill({ json: apiEnvelope(topUpHandoffResponse) });
|
||||||
await route.fulfill({ json: apiEnvelope(psidLoginResponse) });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await page.route("**/api/auth/guest", async (route) => {
|
await page.route("**/api/auth/guest", async (route) => {
|
||||||
|
|||||||
@@ -20,6 +20,23 @@ export interface ChatMockState {
|
|||||||
export async function registerChatMocks(page: Page, options: ChatMockOptions, state: ChatMockState) {
|
export async function registerChatMocks(page: Page, options: ChatMockOptions, state: ChatMockState) {
|
||||||
let sendCount = 0;
|
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) => {
|
await page.route("**/api/chat/history**", async (route) => {
|
||||||
const response = options.paidVoiceInsufficientCreditsFlow
|
const response = options.paidVoiceInsufficientCreditsFlow
|
||||||
? paidVoiceHistoryResponse
|
? paidVoiceHistoryResponse
|
||||||
@@ -44,7 +61,35 @@ export async function registerChatMocks(page: Page, options: ChatMockOptions, st
|
|||||||
await route.fulfill({ status: 401, json: { message: "expired" } });
|
await route.fulfill({ status: 401, json: { message: "expired" } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const response = 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
|
? paidImageChatSendResponse
|
||||||
: options.chatLimitTriggerAt != null && sendCount >= options.chatLimitTriggerAt
|
: options.chatLimitTriggerAt != null && sendCount >= options.chatLimitTriggerAt
|
||||||
? createWeeklyLimitChatSendResponse(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";
|
import { createPaymentOrderResponse, paidPaymentOrderStatusResponse, paymentPlansResponse, tipPaymentPlansResponse, vipStatusResponse } from "../data/payment";
|
||||||
|
|
||||||
export async function registerPaymentMocks(page: Page) {
|
export async function registerPaymentMocks(page: Page) {
|
||||||
|
await page.route("**/api/payment/commercial-offers/*/accept", async (route) => route.fulfill({ json: apiEnvelope({
|
||||||
|
commercialOfferId: "13ec8a10-58d7-4d24-b66b-8db5699a1aa8",
|
||||||
|
planId: "vip_annual",
|
||||||
|
subscriptionType: "vip",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-24T08:00:00+00:00",
|
||||||
|
message: "I got it for you.",
|
||||||
|
promotionType: "commercial_seven_discount",
|
||||||
|
}) }));
|
||||||
await page.route("**/api/payment/plans**", async (route) => route.fulfill({ json: apiEnvelope(paymentPlansResponse) }));
|
await page.route("**/api/payment/plans**", async (route) => route.fulfill({ json: apiEnvelope(paymentPlansResponse) }));
|
||||||
await page.route("**/api/payment/tip-plans**", async (route) => route.fulfill({ json: apiEnvelope(tipPaymentPlansResponse) }));
|
await page.route("**/api/payment/tip-plans**", async (route) => route.fulfill({ json: apiEnvelope(tipPaymentPlansResponse) }));
|
||||||
await page.route("**/api/payment/create-order", async (route) => route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) }));
|
await page.route("**/api/payment/create-order", async (route) => route.fulfill({ json: apiEnvelope(createPaymentOrderResponse) }));
|
||||||
|
|||||||
@@ -50,14 +50,16 @@ export const refreshedEmailLoginResponse = {
|
|||||||
refreshToken: "e2e-refreshed-email-refresh-token",
|
refreshToken: "e2e-refreshed-email-refresh-token",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const psidLoginResponse = {
|
export const topUpHandoffResponse = {
|
||||||
token: "e2e-psid-guest-token",
|
token: "e2e-messenger-token",
|
||||||
refreshToken: "",
|
refreshToken: "e2e-messenger-refresh-token",
|
||||||
matchedBy: "psid",
|
loginStatus: "facebookMessenger",
|
||||||
fbAsid: "",
|
merged: false,
|
||||||
fbPsid: "e2e-facebook-psid",
|
user: {
|
||||||
hasCompleteFacebookIdentity: false,
|
...e2eEmailUser,
|
||||||
isGuest: true,
|
id: "user_e2e_messenger",
|
||||||
user: e2eUser,
|
username: "E2E Messenger User",
|
||||||
userId: e2eUser.id,
|
email: "messenger_hash@messenger.cozsweet.invalid",
|
||||||
|
loginProvider: "facebook_messenger",
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ export function createWeeklyLimitChatSendResponse(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const paidImageMessageId = "msg_photo_paywall_001";
|
export const paidImageMessageId = "msg_photo_paywall_001";
|
||||||
|
export const paidImageDisplayMessageId = `server:${paidImageMessageId}:assistant`;
|
||||||
export const paidImageUrl =
|
export const paidImageUrl =
|
||||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
|
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
|
||||||
export const paidImageChatSendResponse = {
|
export const paidImageChatSendResponse = {
|
||||||
@@ -74,13 +75,13 @@ export const paidImageChatSendResponse = {
|
|||||||
messageId: paidImageMessageId,
|
messageId: paidImageMessageId,
|
||||||
isGuest: true,
|
isGuest: true,
|
||||||
timestamp: 1_782_180_725_000,
|
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 },
|
lockDetail: { locked: true, showContent: true, showUpgrade: true, reason: "image", hint: "Activate VIP to unlock the full photo.", detail: null },
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createPaidImageHistoryResponse(unlocked: boolean) {
|
export function createPaidImageHistoryResponse(unlocked: boolean) {
|
||||||
return {
|
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,
|
total: 1, limit: 50, offset: 0, isVip: unlocked, privateFreeLimit: 0, privateUsedToday: 0, privateCanViewFree: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export const splashStartChatButtonName = "Start Chatting";
|
|||||||
export const defaultCharacterSlug = "elio";
|
export const defaultCharacterSlug = "elio";
|
||||||
export const defaultCharacterSplashPath = `/characters/${defaultCharacterSlug}/splash`;
|
export const defaultCharacterSplashPath = `/characters/${defaultCharacterSlug}/splash`;
|
||||||
export const defaultCharacterChatPath = `/characters/${defaultCharacterSlug}/chat`;
|
export const defaultCharacterChatPath = `/characters/${defaultCharacterSlug}/chat`;
|
||||||
export const defaultCharacterSidebarPath = `/sidebar?returnTo=%2Fcharacters%2F${defaultCharacterSlug}%2Fchat`;
|
export const defaultCharacterProfilePath = `/profile?returnTo=%2Fcharacters%2F${defaultCharacterSlug}%2Fchat`;
|
||||||
export const defaultCharacterChatUrl = new RegExp(
|
export const defaultCharacterChatUrl = new RegExp(
|
||||||
`/characters/${defaultCharacterSlug}/chat(?:\\?.*)?$`,
|
`/characters/${defaultCharacterSlug}/chat(?:\\?.*)?$`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export async function enterChatFromSplash(page: Page, options: { expectedUrl?: R
|
|||||||
await expect(startChatButton).toBeVisible({ timeout });
|
await expect(startChatButton).toBeVisible({ timeout });
|
||||||
await expect(startChatButton).toBeEnabled();
|
await expect(startChatButton).toBeEnabled();
|
||||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
await startChatButton.click();
|
await startChatButton.click({ timeout: 3_000 }).catch(() => {});
|
||||||
try { await expect(page).toHaveURL(expectedUrl, { timeout: 3_000 }); return; } catch { await page.waitForTimeout(500); }
|
try { await expect(page).toHaveURL(expectedUrl, { timeout: 3_000 }); return; } catch { await page.waitForTimeout(500); }
|
||||||
}
|
}
|
||||||
await expect(page).toHaveURL(expectedUrl, { timeout });
|
await expect(page).toHaveURL(expectedUrl, { timeout });
|
||||||
@@ -42,9 +42,7 @@ export async function dismissChatInterruptions(page: Page) {
|
|||||||
|
|
||||||
export async function signInWithEmailAndOpenChat(page: Page) {
|
export async function signInWithEmailAndOpenChat(page: Page) {
|
||||||
await seedEmailSession(page);
|
await seedEmailSession(page);
|
||||||
const historyResponsePromise = page.waitForResponse("**/api/chat/history**");
|
|
||||||
await page.goto(defaultCharacterChatPath);
|
await page.goto(defaultCharacterChatPath);
|
||||||
await historyResponsePromise;
|
|
||||||
await dismissChatInterruptions(page);
|
await dismissChatInterruptions(page);
|
||||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled({ timeout: 20_000 });
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled({ timeout: 20_000 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,19 @@
|
|||||||
import { expect, type Page } from "@playwright/test";
|
import { expect, type Page } from "@playwright/test";
|
||||||
|
|
||||||
export async function completeVipPayment(page: Page) {
|
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 createOrderRequestPromise = page.waitForRequest("**/api/payment/create-order");
|
||||||
const orderStatusRequestPromise = page.waitForRequest("**/api/payment/order-status**");
|
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;
|
const createOrderRequest = await createOrderRequestPromise;
|
||||||
expect(createOrderRequest.postDataJSON()).toMatchObject({ planId: "vip_monthly", payChannel: "stripe" });
|
expect(createOrderRequest.postDataJSON()).toMatchObject({ planId: "vip_monthly", payChannel: "stripe" });
|
||||||
await orderStatusRequestPromise;
|
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);
|
expect(["desktop", "android"]).toContain(loginRequest?.postDataJSON().platform);
|
||||||
|
|
||||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||||
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
await expect(page.getByRole("button", { name: "Save CozSweet" })).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { expect, test } from "@playwright/test";
|
|||||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
import {
|
import {
|
||||||
clearBrowserState,
|
clearBrowserState,
|
||||||
defaultCharacterSidebarPath,
|
defaultCharacterProfilePath,
|
||||||
defaultCharacterSplashPath,
|
defaultCharacterSplashPath,
|
||||||
defaultCharacterChatUrl,
|
defaultCharacterChatUrl,
|
||||||
enterChatFromSplash,
|
enterChatFromSplash,
|
||||||
@@ -17,7 +17,7 @@ test.beforeEach(async ({ baseURL, context, page }) => {
|
|||||||
await mockCoreApis(page);
|
await mockCoreApis(page);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("user can log out from the sidebar after email login", async ({
|
test("user can log out from the profile after email login", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
await enterChatFromSplash(page);
|
await enterChatFromSplash(page);
|
||||||
@@ -27,11 +27,14 @@ test("user can log out from the sidebar after email login", async ({
|
|||||||
await expect(page).toHaveURL(/\/auth(?:\?.*)?$/);
|
await expect(page).toHaveURL(/\/auth(?:\?.*)?$/);
|
||||||
await switchToEmailSignIn(page);
|
await switchToEmailSignIn(page);
|
||||||
await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });
|
await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });
|
||||||
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
await page.getByRole("link", { name: "Back to home" }).click();
|
||||||
|
await expect(page).toHaveURL(
|
||||||
|
new RegExp(defaultCharacterSplashPath.replace("?", "\\?") + "$"),
|
||||||
|
);
|
||||||
|
|
||||||
await page.getByRole("button", { name: "Menu" }).click();
|
await page.getByRole("button", { name: "Menu" }).click();
|
||||||
await expect(page).toHaveURL(
|
await expect(page).toHaveURL(
|
||||||
new RegExp(defaultCharacterSidebarPath.replace("?", "\\?") + "$"),
|
new RegExp(defaultCharacterProfilePath.replace("?", "\\?") + "$"),
|
||||||
);
|
);
|
||||||
|
|
||||||
const logoutRequestPromise = page.waitForRequest("**/api/auth/logout");
|
const logoutRequestPromise = page.waitForRequest("**/api/auth/logout");
|
||||||
@@ -1,49 +1,74 @@
|
|||||||
import { expect, test } from "@playwright/test";
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
import {
|
import { clearBrowserState } from "@e2e/fixtures/test-helpers";
|
||||||
clearBrowserState,
|
|
||||||
defaultCharacterChatUrl,
|
|
||||||
} from "@e2e/fixtures/test-helpers";
|
|
||||||
|
|
||||||
const psid = "e2e-facebook-psid";
|
const handoffToken = "e2e-handoff-token-that-is-at-least-32-characters";
|
||||||
|
|
||||||
test.beforeEach(async ({ baseURL, context, page }) => {
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
await clearBrowserState(context, page, baseURL);
|
await clearBrowserState(context, page, baseURL);
|
||||||
await mockCoreApis(page, { psidLoginFlow: true });
|
await mockCoreApis(page, { topUpHandoffFlow: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
test("user enters from an external PSID link and becomes a guest", async ({
|
test("user consumes a top-up handoff and opens credit packages as a formal Messenger user", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const psidLoginRequestPromise = page.waitForRequest(
|
const handoffRequestPromise = page.waitForRequest(
|
||||||
"**/api/auth/login/facebook/psid",
|
"**/api/auth/handoff/topup/consume",
|
||||||
);
|
);
|
||||||
|
|
||||||
await page.goto(`/external-entry?target=chat&psid=${psid}`);
|
await page.goto(
|
||||||
|
`/external-entry?target=topup&handoffToken=${encodeURIComponent(handoffToken)}`,
|
||||||
|
);
|
||||||
|
|
||||||
const psidLoginRequest = await psidLoginRequestPromise;
|
const handoffRequest = await handoffRequestPromise;
|
||||||
expect(psidLoginRequest.method()).toBe("POST");
|
expect(handoffRequest.method()).toBe("POST");
|
||||||
expect(psidLoginRequest.postDataJSON()).toMatchObject({
|
expect(handoffRequest.postDataJSON()).toEqual({ handoffToken });
|
||||||
psid,
|
|
||||||
bindToGuest: true,
|
|
||||||
});
|
|
||||||
expect(psidLoginRequest.postDataJSON().deviceId).toEqual(expect.any(String));
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(defaultCharacterChatUrl);
|
await expect(page).toHaveURL("/subscription?type=topup");
|
||||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
await expect(
|
||||||
|
page.getByRole("button", { name: /Pay and Top Up/i }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(() =>
|
.poll(() =>
|
||||||
page.evaluate(() => ({
|
page.evaluate(() => ({
|
||||||
loginProvider: localStorage.getItem("cozsweet:login_provider"),
|
loginProvider: localStorage.getItem("cozsweet:login_provider"),
|
||||||
guestToken: localStorage.getItem("cozsweet:guest_token"),
|
loginToken: localStorage.getItem("cozsweet:login_token"),
|
||||||
psid: localStorage.getItem("cozsweet:psid"),
|
refreshToken: localStorage.getItem("cozsweet:refresh_token"),
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
.toMatchObject({
|
.toMatchObject({
|
||||||
loginProvider: "guest",
|
loginProvider: "facebookMessenger",
|
||||||
guestToken: "e2e-psid-guest-token",
|
loginToken: "e2e-messenger-token",
|
||||||
psid,
|
refreshToken: "e2e-messenger-refresh-token",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("invalid top-up handoff does not log in and is removed from the URL", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.route("**/api/auth/handoff/topup/consume", async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 410,
|
||||||
|
json: {
|
||||||
|
detail: {
|
||||||
|
code: "HANDOFF_EXPIRED",
|
||||||
|
message: "充值链接已过期",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(
|
||||||
|
`/external-entry?target=topup&handoffToken=${encodeURIComponent(handoffToken)}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(page).toHaveURL("/external-entry?target=topup");
|
||||||
|
await expect(
|
||||||
|
page.getByText(/invalid or has expired/i),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect
|
||||||
|
.poll(() => page.evaluate(() => localStorage.getItem("cozsweet:login_provider")))
|
||||||
|
.not.toBe("facebookMessenger");
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { expect, test, type Page } from "@playwright/test";
|
||||||
|
|
||||||
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
|
import {
|
||||||
|
clearBrowserState,
|
||||||
|
defaultCharacterProfilePath,
|
||||||
|
dismissChatInterruptions,
|
||||||
|
enterChatFromSplash,
|
||||||
|
submitEmailLogin,
|
||||||
|
switchToEmailSignIn,
|
||||||
|
} from "@e2e/fixtures/test-helpers";
|
||||||
|
|
||||||
|
const characters = [
|
||||||
|
{ slug: "elio", displayName: "Elio Silvestri" },
|
||||||
|
{ slug: "maya", displayName: "Maya Tan" },
|
||||||
|
{ slug: "nayeli", displayName: "Nayeli Cervantes" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
|
await clearBrowserState(context, page, baseURL);
|
||||||
|
await mockCoreApis(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("guest user avatar returns to Profile after sign-in", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await enterChatFromSplash(page, { timeout: 30_000 });
|
||||||
|
await sendMessage(page, "Open my profile");
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Open profile" }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/auth\?redirect=/);
|
||||||
|
expect(new URL(page.url()).searchParams.get("redirect")).toBe(
|
||||||
|
defaultCharacterProfilePath,
|
||||||
|
);
|
||||||
|
await switchToEmailSignIn(page);
|
||||||
|
await submitEmailLogin(page, {
|
||||||
|
expectedUrl: new RegExp(
|
||||||
|
`${defaultCharacterProfilePath.replace("?", "\\?")}$`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const character of characters) {
|
||||||
|
test(`${character.displayName} avatar opens the matching Private Zone`, async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await enterCharacterChat(page, character.slug);
|
||||||
|
await sendMessage(page, `Hello ${character.displayName}`);
|
||||||
|
|
||||||
|
await page
|
||||||
|
.getByRole("button", {
|
||||||
|
name: `Open ${character.displayName}'s private zone`,
|
||||||
|
})
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(
|
||||||
|
new RegExp(`/characters/${character.slug}/private-zone(?:\\?.*)?$`),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enterCharacterChat(page: Page, characterSlug: string) {
|
||||||
|
const chatPath = `/characters/${characterSlug}/chat`;
|
||||||
|
|
||||||
|
await page.goto(`/characters/${characterSlug}/splash`);
|
||||||
|
await page.getByRole("button", { name: "Start Chatting" }).click();
|
||||||
|
await expect(page).toHaveURL(new RegExp(`${chatPath}(?:\\?.*)?$`));
|
||||||
|
await dismissChatInterruptions(page);
|
||||||
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled({
|
||||||
|
timeout: 20_000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendMessage(page: Page, message: string) {
|
||||||
|
await dismissChatInterruptions(page);
|
||||||
|
const messageInput = page.getByRole("textbox", { name: "Message" });
|
||||||
|
|
||||||
|
await expect(messageInput).toBeEnabled({ timeout: 20_000 });
|
||||||
|
await messageInput.fill(message);
|
||||||
|
await messageInput.press("Enter");
|
||||||
|
await expect(page.getByRole("button", { name: "Open profile" })).toBeVisible({
|
||||||
|
timeout: 10_000,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
|
import {
|
||||||
|
clearBrowserState,
|
||||||
|
enterChatFromSplash,
|
||||||
|
} 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(
|
||||||
|
/\/subscription\?type=vip.*planId=vip_annual.*commercialOfferId=13ec8a10/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
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 testPsid = "e2e-facebook-psid-27511427698460020";
|
||||||
|
|
||||||
|
const characters = [
|
||||||
|
{
|
||||||
|
id: "elio",
|
||||||
|
slug: "elio",
|
||||||
|
displayName: "Elio Silvestri",
|
||||||
|
shortName: "Elio",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "maya-tan",
|
||||||
|
slug: "maya",
|
||||||
|
displayName: "Maya Tan",
|
||||||
|
shortName: "Maya",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "nayeli-cervantes",
|
||||||
|
slug: "nayeli",
|
||||||
|
displayName: "Nayeli Cervantes",
|
||||||
|
shortName: "Nayeli",
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
type Character = (typeof characters)[number];
|
||||||
|
type EntryKind = "private-space" | "voice" | "image-pack" | "coffee";
|
||||||
|
|
||||||
|
interface FacebookEntryCase {
|
||||||
|
character: Character;
|
||||||
|
kind: EntryKind;
|
||||||
|
target: "chat" | "private-zone" | "tip";
|
||||||
|
expectedPath: string;
|
||||||
|
promotionType?: "voice";
|
||||||
|
}
|
||||||
|
|
||||||
|
const entryCases: FacebookEntryCase[] = characters.flatMap((character) => [
|
||||||
|
{
|
||||||
|
character,
|
||||||
|
kind: "private-space",
|
||||||
|
target: "chat",
|
||||||
|
expectedPath: `/characters/${character.slug}/chat`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
character,
|
||||||
|
kind: "voice",
|
||||||
|
target: "chat",
|
||||||
|
expectedPath: `/characters/${character.slug}/chat`,
|
||||||
|
promotionType: "voice",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
character,
|
||||||
|
kind: "image-pack",
|
||||||
|
target: "private-zone",
|
||||||
|
expectedPath: `/characters/${character.slug}/private-zone`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
character,
|
||||||
|
kind: "coffee",
|
||||||
|
target: "tip",
|
||||||
|
expectedPath: `/characters/${character.slug}/tip`,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
|
await clearBrowserState(context, page, baseURL);
|
||||||
|
await mockCoreApis(page);
|
||||||
|
await registerEntryPageMocks(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const entryCase of entryCases) {
|
||||||
|
test(`${entryCase.character.displayName} opens Facebook ${entryCase.kind} entry`, async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto(buildEntryUrl(entryCase));
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(entryCase.expectedPath, { timeout: 20_000 });
|
||||||
|
await expect
|
||||||
|
.poll(() =>
|
||||||
|
page.evaluate(() => localStorage.getItem("cozsweet:psid")),
|
||||||
|
)
|
||||||
|
.toBe(testPsid);
|
||||||
|
|
||||||
|
if (entryCase.kind === "private-space") {
|
||||||
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "Unlock voice message" }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entryCase.kind === "voice") {
|
||||||
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "Unlock voice message" }),
|
||||||
|
).toHaveCount(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entryCase.kind === "image-pack") {
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "Private albums" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByText(entryCase.character.displayName).last(),
|
||||||
|
).toBeVisible();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", {
|
||||||
|
name: `Buy ${entryCase.character.shortName} a coffee`,
|
||||||
|
}),
|
||||||
|
).toBeVisible();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEntryUrl(entryCase: FacebookEntryCase): string {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
target: entryCase.target,
|
||||||
|
character: entryCase.character.slug,
|
||||||
|
psid: testPsid,
|
||||||
|
});
|
||||||
|
if (entryCase.promotionType) {
|
||||||
|
params.set("mode", "promotion");
|
||||||
|
params.set("promotion_type", entryCase.promotionType);
|
||||||
|
}
|
||||||
|
return `/external-entry?${params.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function registerEntryPageMocks(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) => {
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
creditBalance: 1000,
|
||||||
|
pendingImageCount: 0,
|
||||||
|
hasIncompleteContent: false,
|
||||||
|
items: [],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
defaultCharacterChatUrl,
|
defaultCharacterChatUrl,
|
||||||
expectInsufficientCreditsDialog,
|
expectInsufficientCreditsDialog,
|
||||||
expectVipChatSubscriptionUrl,
|
expectVipChatSubscriptionUrl,
|
||||||
setEmailSessionStorage,
|
|
||||||
submitEmailLogin,
|
submitEmailLogin,
|
||||||
switchToEmailSignIn,
|
switchToEmailSignIn,
|
||||||
} from "@e2e/fixtures/test-helpers";
|
} from "@e2e/fixtures/test-helpers";
|
||||||
@@ -36,13 +35,10 @@ test("guest unlocks a promoted image through email login and top-up", async ({
|
|||||||
await expect(page).toHaveURL(/\/auth\?redirect=/);
|
await expect(page).toHaveURL(/\/auth\?redirect=/);
|
||||||
|
|
||||||
await switchToEmailSignIn(page);
|
await switchToEmailSignIn(page);
|
||||||
await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });
|
|
||||||
|
|
||||||
await setEmailSessionStorage(page);
|
|
||||||
const unlockRequestPromise = page.waitForRequest(
|
const unlockRequestPromise = page.waitForRequest(
|
||||||
"**/api/chat/unlock-private",
|
"**/api/chat/unlock-private",
|
||||||
);
|
);
|
||||||
await page.reload();
|
await submitEmailLogin(page, { expectedUrl: defaultCharacterChatUrl });
|
||||||
|
|
||||||
const unlockRequest = await unlockRequestPromise;
|
const unlockRequest = await unlockRequestPromise;
|
||||||
expect(unlockRequest.method()).toBe("POST");
|
expect(unlockRequest.method()).toBe("POST");
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
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.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");
|
||||||
|
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 albums" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByRole("tab")).toHaveText(["Albums", "Moments"]);
|
||||||
|
await expect(page.getByRole("tab", { name: "Albums" })).toHaveAttribute(
|
||||||
|
"aria-selected",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
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 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,7 +1,12 @@
|
|||||||
import { expect, test } from "@playwright/test";
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
import { paidImageMessageId } from "@e2e/fixtures/test-data";
|
import { apiEnvelope } from "@e2e/fixtures/data/common";
|
||||||
|
import { createPaidImageHistoryResponse } from "@e2e/fixtures/data/chat";
|
||||||
|
import {
|
||||||
|
paidImageDisplayMessageId,
|
||||||
|
paidImageMessageId,
|
||||||
|
} from "@e2e/fixtures/test-data";
|
||||||
import {
|
import {
|
||||||
clearBrowserState,
|
clearBrowserState,
|
||||||
completeVipPayment,
|
completeVipPayment,
|
||||||
@@ -10,15 +15,10 @@ import {
|
|||||||
enterChatFromSplash,
|
enterChatFromSplash,
|
||||||
expectInsufficientCreditsDialog,
|
expectInsufficientCreditsDialog,
|
||||||
expectVipChatSubscriptionUrl,
|
expectVipChatSubscriptionUrl,
|
||||||
setEmailSessionStorage,
|
|
||||||
submitEmailLogin,
|
submitEmailLogin,
|
||||||
switchToEmailSignIn,
|
switchToEmailSignIn,
|
||||||
} from "@e2e/fixtures/test-helpers";
|
} from "@e2e/fixtures/test-helpers";
|
||||||
|
|
||||||
const paidImageOverlayUrl = new RegExp(
|
|
||||||
`${defaultCharacterChatPath}\\?image=${paidImageMessageId}$`,
|
|
||||||
);
|
|
||||||
|
|
||||||
test.beforeEach(async ({ baseURL, context, page }) => {
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
await clearBrowserState(context, page, baseURL);
|
await clearBrowserState(context, page, baseURL);
|
||||||
await mockCoreApis(page, {
|
await mockCoreApis(page, {
|
||||||
@@ -44,38 +44,27 @@ test("guest can unlock a paid image after email login and subscription payment",
|
|||||||
message: "给我发图片",
|
message: "给我发图片",
|
||||||
});
|
});
|
||||||
|
|
||||||
const paidImageButton = page.getByRole("button", {
|
const lockedImageCard = page.getByRole("group", {
|
||||||
name: "Open image in fullscreen",
|
name: "Locked private image",
|
||||||
}).last();
|
}).last();
|
||||||
await expect(paidImageButton).toBeVisible();
|
await expect(lockedImageCard).toBeVisible();
|
||||||
|
await expect(lockedImageCard.locator("img")).toHaveCount(0);
|
||||||
await paidImageButton.click();
|
await lockedImageCard
|
||||||
await expect(page).toHaveURL(paidImageOverlayUrl);
|
.getByRole("button", { name: "Unlock private image" })
|
||||||
|
|
||||||
const lockedImageDialog = page.getByRole("dialog", {
|
|
||||||
name: "Locked fullscreen image",
|
|
||||||
});
|
|
||||||
await expect(lockedImageDialog).toBeVisible();
|
|
||||||
|
|
||||||
await lockedImageDialog
|
|
||||||
.getByRole("button", { name: "Unlock high-definition large image" })
|
|
||||||
.click();
|
.click();
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/auth\?redirect=/);
|
await expect(page).toHaveURL(/\/auth\?redirect=/);
|
||||||
expect(new URL(page.url()).searchParams.get("redirect")).toBe(
|
expect(new URL(page.url()).searchParams.get("redirect")).toBe(
|
||||||
`${defaultCharacterChatPath}?image=${paidImageMessageId}`,
|
defaultCharacterChatPath,
|
||||||
);
|
);
|
||||||
|
|
||||||
await switchToEmailSignIn(page);
|
await switchToEmailSignIn(page);
|
||||||
await submitEmailLogin(page, {
|
|
||||||
expectedUrl: paidImageOverlayUrl,
|
|
||||||
});
|
|
||||||
|
|
||||||
await setEmailSessionStorage(page);
|
|
||||||
const unlockRequestPromise = page.waitForRequest(
|
const unlockRequestPromise = page.waitForRequest(
|
||||||
"**/api/chat/unlock-private",
|
"**/api/chat/unlock-private",
|
||||||
);
|
);
|
||||||
await page.goto(`${defaultCharacterChatPath}?image=${paidImageMessageId}`);
|
await submitEmailLogin(page, {
|
||||||
|
expectedUrl: new RegExp(`${defaultCharacterChatPath}$`),
|
||||||
|
});
|
||||||
|
|
||||||
const unlockRequest = await unlockRequestPromise;
|
const unlockRequest = await unlockRequestPromise;
|
||||||
expect(unlockRequest.postDataJSON()).toMatchObject({
|
expect(unlockRequest.postDataJSON()).toMatchObject({
|
||||||
@@ -92,9 +81,44 @@ test("guest can unlock a paid image after email login and subscription payment",
|
|||||||
|
|
||||||
await expect(page).toHaveURL(
|
await expect(page).toHaveURL(
|
||||||
new RegExp(
|
new RegExp(
|
||||||
`${defaultCharacterChatPath}(?:\\?image=msg_photo_paywall_001)?$`,
|
`${defaultCharacterChatPath}(?:\\?image=${encodeURIComponent(paidImageDisplayMessageId)})?$`,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(new URL(page.url()).pathname).toBe(defaultCharacterChatPath);
|
expect(new URL(page.url()).pathname).toBe(defaultCharacterChatPath);
|
||||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
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,119 @@
|
|||||||
|
import { expect, test, type Page } from "@playwright/test";
|
||||||
|
|
||||||
|
import { stripePaymentDialogStyles } from "@/app/_components/payment/stripe-payment-dialog.styles";
|
||||||
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
|
|
||||||
|
const viewports = [
|
||||||
|
{ width: 390, height: 844 },
|
||||||
|
{ width: 405, height: 797 },
|
||||||
|
{ width: 540, height: 900 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await mockCoreApis(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const viewport of viewports) {
|
||||||
|
test(`payment portal stays viewport-bound at ${viewport.width}x${viewport.height}`, async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize(viewport);
|
||||||
|
await page.goto("/subscription?type=topup", {
|
||||||
|
waitUntil: "domcontentloaded",
|
||||||
|
});
|
||||||
|
|
||||||
|
await mountPaymentPanel(page, 180);
|
||||||
|
await expectViewportScrim(page, viewport);
|
||||||
|
await expectCenteredShortPanel(page, viewport);
|
||||||
|
|
||||||
|
await mountPaymentPanel(page, 1_200);
|
||||||
|
await expectViewportScrim(page, viewport);
|
||||||
|
await expectScrollableTallPanel(page, viewport);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountPaymentPanel(page: Page, contentHeight: number) {
|
||||||
|
await page.evaluate(
|
||||||
|
({ dialogClassName, overlayClassName, requestedContentHeight }) => {
|
||||||
|
document.querySelector('[data-testid="payment-layout-overlay"]')?.remove();
|
||||||
|
document.querySelector('[data-testid="transformed-checkout-host"]')?.remove();
|
||||||
|
|
||||||
|
const transformedCheckoutHost = document.createElement("div");
|
||||||
|
transformedCheckoutHost.dataset.testid = "transformed-checkout-host";
|
||||||
|
transformedCheckoutHost.style.transform = "translateX(50%)";
|
||||||
|
document.body.appendChild(transformedCheckoutHost);
|
||||||
|
|
||||||
|
const overlay = document.createElement("div");
|
||||||
|
overlay.dataset.testid = "payment-layout-overlay";
|
||||||
|
overlay.className = overlayClassName;
|
||||||
|
|
||||||
|
const panel = document.createElement("div");
|
||||||
|
panel.dataset.testid = "payment-layout-panel";
|
||||||
|
panel.className = dialogClassName;
|
||||||
|
|
||||||
|
const content = document.createElement("div");
|
||||||
|
content.style.height = `${requestedContentHeight}px`;
|
||||||
|
content.textContent = "Complete payment";
|
||||||
|
panel.appendChild(content);
|
||||||
|
overlay.appendChild(panel);
|
||||||
|
|
||||||
|
// Mirrors ModalPortal: the overlay must be a body child, never a child of
|
||||||
|
// the transformed checkout host that triggered it.
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
},
|
||||||
|
{
|
||||||
|
dialogClassName: stripePaymentDialogStyles.dialog,
|
||||||
|
overlayClassName: stripePaymentDialogStyles.overlay,
|
||||||
|
requestedContentHeight: contentHeight,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectViewportScrim(
|
||||||
|
page: Page,
|
||||||
|
viewport: { width: number; height: number },
|
||||||
|
) {
|
||||||
|
const overlay = page.getByTestId("payment-layout-overlay");
|
||||||
|
await expect(overlay).toBeVisible();
|
||||||
|
const box = await overlay.boundingBox();
|
||||||
|
|
||||||
|
expect(box).not.toBeNull();
|
||||||
|
expect(box?.x).toBeCloseTo(0, 0);
|
||||||
|
expect(box?.y).toBeCloseTo(0, 0);
|
||||||
|
expect(box?.width).toBeCloseTo(viewport.width, 0);
|
||||||
|
expect(box?.height).toBeCloseTo(viewport.height, 0);
|
||||||
|
await expect(overlay.evaluate((node) => node.parentElement === document.body))
|
||||||
|
.resolves.toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectCenteredShortPanel(
|
||||||
|
page: Page,
|
||||||
|
viewport: { width: number; height: number },
|
||||||
|
) {
|
||||||
|
const panel = page.getByTestId("payment-layout-panel");
|
||||||
|
const box = await panel.boundingBox();
|
||||||
|
|
||||||
|
expect(box).not.toBeNull();
|
||||||
|
expect(box?.y ?? 0).toBeGreaterThan(100);
|
||||||
|
expect(Math.abs((box?.y ?? 0) * 2 + (box?.height ?? 0) - viewport.height))
|
||||||
|
.toBeLessThanOrEqual(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectScrollableTallPanel(
|
||||||
|
page: Page,
|
||||||
|
viewport: { width: number; height: number },
|
||||||
|
) {
|
||||||
|
const panel = page.getByTestId("payment-layout-panel");
|
||||||
|
const box = await panel.boundingBox();
|
||||||
|
const scrollMetrics = await panel.evaluate((node) => ({
|
||||||
|
clientHeight: node.clientHeight,
|
||||||
|
scrollHeight: node.scrollHeight,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(box).not.toBeNull();
|
||||||
|
expect(box?.y ?? 0).toBeGreaterThanOrEqual(15);
|
||||||
|
expect(box?.y ?? 100).toBeLessThanOrEqual(25);
|
||||||
|
expect((box?.y ?? 0) + (box?.height ?? 0))
|
||||||
|
.toBeLessThanOrEqual(viewport.height - 15);
|
||||||
|
expect(scrollMetrics.scrollHeight).toBeGreaterThan(scrollMetrics.clientHeight);
|
||||||
|
}
|
||||||
@@ -0,0 +1,422 @@
|
|||||||
|
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/user";
|
||||||
|
import {
|
||||||
|
clearBrowserState,
|
||||||
|
seedEmailSession,
|
||||||
|
} from "@e2e/fixtures/test-helpers";
|
||||||
|
|
||||||
|
const idrPlans = {
|
||||||
|
plans: [
|
||||||
|
{
|
||||||
|
planId: "vip_monthly",
|
||||||
|
planName: "Monthly",
|
||||||
|
orderType: "vip_monthly",
|
||||||
|
amountCents: 19_590_000,
|
||||||
|
originalAmountCents: 19_590_000,
|
||||||
|
dailyPriceCents: 653_000,
|
||||||
|
currency: "IDR",
|
||||||
|
vipDays: 30,
|
||||||
|
dolAmount: null,
|
||||||
|
creditBalance: 3_000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
planId: "dol_1000",
|
||||||
|
planName: "1,000 Credits",
|
||||||
|
orderType: "dol",
|
||||||
|
amountCents: 8_890_000,
|
||||||
|
originalAmountCents: null,
|
||||||
|
dailyPriceCents: null,
|
||||||
|
currency: "IDR",
|
||||||
|
vipDays: null,
|
||||||
|
dolAmount: 1_000,
|
||||||
|
creditBalance: 1_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const idrGiftCatalog = {
|
||||||
|
characterId: "elio",
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
category: "coffee",
|
||||||
|
name: "Coffee",
|
||||||
|
productCount: 1,
|
||||||
|
imageUrl: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
plans: [
|
||||||
|
{
|
||||||
|
planId: "tip_coffee_usd_4_99",
|
||||||
|
planName: "Velvet Espresso",
|
||||||
|
orderType: "tip",
|
||||||
|
tipType: "coffee_small",
|
||||||
|
category: "coffee",
|
||||||
|
characterId: "elio",
|
||||||
|
description: "Buy Elio a Velvet Espresso",
|
||||||
|
imageUrl: null,
|
||||||
|
amountCents: 8_929_900,
|
||||||
|
currency: "IDR",
|
||||||
|
autoRenew: false,
|
||||||
|
isFirstRechargeOffer: false,
|
||||||
|
firstRechargeDiscountPercent: 0,
|
||||||
|
promotionType: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
async function registerIndonesiaPaymentMocks(page: Page) {
|
||||||
|
const orderStatuses = new Map<string, "pending" | "paid">();
|
||||||
|
const orderPlans = new Map<string, { planId: string; orderType: string }>();
|
||||||
|
let createOrderCount = 0;
|
||||||
|
|
||||||
|
await page.route("**/api/user/profile", async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({ ...e2eEmailUser, countryCode: "ID" }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/plans**", async (route) => {
|
||||||
|
await route.fulfill({ json: apiEnvelope(idrPlans) });
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/gift-products**", async (route) => {
|
||||||
|
await route.fulfill({ json: apiEnvelope(idrGiftCatalog) });
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/create-order", async (route) => {
|
||||||
|
createOrderCount += 1;
|
||||||
|
const body = route.request().postDataJSON() as {
|
||||||
|
planId: string;
|
||||||
|
payChannel: "ezpay" | "stripe";
|
||||||
|
};
|
||||||
|
const plan =
|
||||||
|
idrPlans.plans.find((item) => item.planId === body.planId) ??
|
||||||
|
idrGiftCatalog.plans.find((item) => item.planId === body.planId);
|
||||||
|
const orderId = `order_${body.payChannel}_${body.planId}`;
|
||||||
|
orderStatuses.set(orderId, "pending");
|
||||||
|
orderPlans.set(orderId, {
|
||||||
|
planId: body.planId,
|
||||||
|
orderType: plan?.orderType ?? "dol",
|
||||||
|
});
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
orderId,
|
||||||
|
payParams:
|
||||||
|
body.payChannel === "stripe"
|
||||||
|
? {
|
||||||
|
provider: "stripe",
|
||||||
|
clientSecret: "pi_e2e_secret_mock",
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
provider: "ezpay",
|
||||||
|
countryCode: "ID",
|
||||||
|
channelCode: "ID_QRIS_DYNAMIC_QR",
|
||||||
|
channelType: "QR",
|
||||||
|
payData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
|
firstChargeAmountCents: plan?.amountCents ?? 0,
|
||||||
|
currency: "IDR",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/order-status**", async (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
const orderId = url.searchParams.get("order_id") ?? "";
|
||||||
|
const plan = orderPlans.get(orderId);
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
orderId,
|
||||||
|
status: orderStatuses.get(orderId) ?? "pending",
|
||||||
|
orderType: plan?.orderType ?? "dol",
|
||||||
|
planId: plan?.planId ?? null,
|
||||||
|
creditsAdded: 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/tip-message", async (route) => {
|
||||||
|
const body = route.request().postDataJSON() as { orderId: string };
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
orderId: body.orderId,
|
||||||
|
characterId: "elio",
|
||||||
|
planId: "tip_coffee_usd_4_99",
|
||||||
|
productName: "Velvet Espresso",
|
||||||
|
tipCount: 1,
|
||||||
|
poolIndex: 0,
|
||||||
|
message: "Thank you. Your gift made me smile.",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
getCreateOrderCount() {
|
||||||
|
return createOrderCount;
|
||||||
|
},
|
||||||
|
markPaid(orderId: string) {
|
||||||
|
orderStatuses.set(orderId, "paid");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepareIndonesiaUser(page: Page) {
|
||||||
|
await seedEmailSession(page);
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const rawUser = localStorage.getItem("cozsweet:user");
|
||||||
|
const user = rawUser ? JSON.parse(rawUser) : {};
|
||||||
|
localStorage.setItem(
|
||||||
|
"cozsweet:user",
|
||||||
|
JSON.stringify({ ...user, countryCode: "ID" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectQrisOrder(
|
||||||
|
page: Page,
|
||||||
|
buttonName: RegExp,
|
||||||
|
planId: string,
|
||||||
|
formattedAmount: RegExp,
|
||||||
|
) {
|
||||||
|
const requestPromise = page.waitForRequest("**/api/payment/create-order");
|
||||||
|
await page.getByRole("button", { name: buttonName }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
expect(request.postDataJSON()).toMatchObject({
|
||||||
|
planId,
|
||||||
|
payChannel: "ezpay",
|
||||||
|
recipientCharacterId: "elio",
|
||||||
|
});
|
||||||
|
|
||||||
|
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
await expect(dialog).toContainText(formattedAmount);
|
||||||
|
await expect(dialog).toContainText("Waiting for payment");
|
||||||
|
await expect(
|
||||||
|
dialog.getByRole("img", { name: "QRIS payment QR code" }),
|
||||||
|
).toBeVisible();
|
||||||
|
return `order_ezpay_${planId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expectCheckoutButtonLayout(page: Page) {
|
||||||
|
const viewport = page.viewportSize();
|
||||||
|
const checkoutBox = await page
|
||||||
|
.getByRole("button", { name: "Pay and Top Up" })
|
||||||
|
.boundingBox();
|
||||||
|
const stripeBox = await page.getByRole("button", { name: "Stripe" }).boundingBox();
|
||||||
|
expect(viewport).not.toBeNull();
|
||||||
|
expect(checkoutBox).not.toBeNull();
|
||||||
|
expect(stripeBox).not.toBeNull();
|
||||||
|
if (!viewport || !checkoutBox || !stripeBox) return;
|
||||||
|
expect(checkoutBox.y + checkoutBox.height).toBeLessThanOrEqual(viewport.height);
|
||||||
|
expect(stripeBox.y + stripeBox.height).toBeLessThanOrEqual(checkoutBox.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
|
await clearBrowserState(context, page, baseURL);
|
||||||
|
await mockCoreApis(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Indonesia VIP defaults to QRIS and completes after status polling", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
await page.goto("/subscription?type=vip&character=elio");
|
||||||
|
|
||||||
|
await expect(page.getByText("Choose who you want to support")).toHaveCount(0);
|
||||||
|
await expect(page.getByText("Supporting Elio")).toHaveCount(0);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "Elio", exact: true }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
await expect(page.getByRole("button", { name: "QRIS" })).toHaveAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
const checkoutButton = page.getByRole("button", { name: "Pay and Top Up" });
|
||||||
|
await expect(checkoutButton).toBeDisabled();
|
||||||
|
await expectCheckoutButtonLayout(page);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: /Monthly, 195900 IDR/i }).click();
|
||||||
|
const renewalDialog = page.getByRole("dialog", {
|
||||||
|
name: "Automatic Renewal Confirmation",
|
||||||
|
});
|
||||||
|
await expect(renewalDialog).toBeVisible();
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(0);
|
||||||
|
|
||||||
|
await renewalDialog.getByRole("button", { name: "Confirm" }).click();
|
||||||
|
await expect(renewalDialog).toBeHidden();
|
||||||
|
await expect(checkoutButton).toBeEnabled();
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(0);
|
||||||
|
|
||||||
|
const orderId = await expectQrisOrder(
|
||||||
|
page,
|
||||||
|
/Pay and Top Up/i,
|
||||||
|
"vip_monthly",
|
||||||
|
/Rp\s*195[.,]900/,
|
||||||
|
);
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
payment.markPaid(orderId);
|
||||||
|
|
||||||
|
const success = page.getByRole("alertdialog", { name: "Payment successful" });
|
||||||
|
await expect(success).toBeVisible({ timeout: 10_000 });
|
||||||
|
await expect(
|
||||||
|
page.getByRole("dialog", { name: "Scan to pay with QRIS" }),
|
||||||
|
).toBeHidden();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Indonesia credit top-up uses QRIS display cents", async ({ page }) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
await expect(page.getByText("Supporting Elio")).toHaveCount(0);
|
||||||
|
await expectCheckoutButtonLayout(page);
|
||||||
|
|
||||||
|
const orderId = await expectQrisOrder(
|
||||||
|
page,
|
||||||
|
/Pay and Top Up/i,
|
||||||
|
"dol_1000",
|
||||||
|
/Rp\s*88[.,]900/,
|
||||||
|
);
|
||||||
|
payment.markPaid(orderId);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByRole("alertdialog", { name: "Payment successful" }),
|
||||||
|
).toBeVisible({ timeout: 10_000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("closing QRIS restores payment selection and allows switching to Stripe", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
|
||||||
|
await expectQrisOrder(
|
||||||
|
page,
|
||||||
|
/Pay and Top Up/i,
|
||||||
|
"dol_1000",
|
||||||
|
/Rp\s*88[.,]900/,
|
||||||
|
);
|
||||||
|
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
||||||
|
await dialog.getByRole("button", { name: "Close" }).click();
|
||||||
|
|
||||||
|
await expect(dialog).toBeHidden();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toBeEnabled();
|
||||||
|
await page.getByRole("button", { name: "Stripe" }).click();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toHaveAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
await expect(page.getByRole("button", { name: "Pay and Top Up" })).toBeEnabled();
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("closing QRIS allows switching to Stripe and creating a Stripe order", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
|
||||||
|
await expectQrisOrder(
|
||||||
|
page,
|
||||||
|
/Pay and Top Up/i,
|
||||||
|
"dol_1000",
|
||||||
|
/Rp\s*88[.,]900/,
|
||||||
|
);
|
||||||
|
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
||||||
|
await dialog.getByRole("button", { name: "Close" }).click();
|
||||||
|
await expect(dialog).toBeHidden();
|
||||||
|
|
||||||
|
const stripeButton = page.getByRole("button", {
|
||||||
|
name: "Stripe",
|
||||||
|
exact: true,
|
||||||
|
});
|
||||||
|
await expect(stripeButton).toBeEnabled();
|
||||||
|
await stripeButton.click();
|
||||||
|
await expect(stripeButton).toHaveAttribute("aria-pressed", "true");
|
||||||
|
await expect(
|
||||||
|
page.getByRole("button", { name: "Resume QRIS payment" }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
const stripeRequestPromise = page.waitForRequest(
|
||||||
|
"**/api/payment/create-order",
|
||||||
|
);
|
||||||
|
await page.getByRole("button", { name: "Pay and Top Up" }).click();
|
||||||
|
const stripeRequest = await stripeRequestPromise;
|
||||||
|
expect(stripeRequest.postDataJSON()).toMatchObject({
|
||||||
|
planId: "dol_1000",
|
||||||
|
payChannel: "stripe",
|
||||||
|
recipientCharacterId: "elio",
|
||||||
|
});
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("payment issue submits Other to the feedback API without creating an order", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
let feedbackBody = "";
|
||||||
|
let idempotencyKey = "";
|
||||||
|
await page.route("**/api/feedback", async (route) => {
|
||||||
|
feedbackBody = route.request().postData() ?? "";
|
||||||
|
idempotencyKey = route.request().headers()["idempotency-key"] ?? "";
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({ feedbackId: "feedback-payment-1", duplicate: false }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
await page.getByRole("button", { name: "Payment issue?" }).click();
|
||||||
|
const dialog = page.getByRole("dialog", {
|
||||||
|
name: "What problem did you encounter?",
|
||||||
|
});
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
await dialog.getByRole("radio", { name: "Other" }).check();
|
||||||
|
await dialog
|
||||||
|
.getByLabel("Please describe the issue")
|
||||||
|
.fill("QRIS did not open correctly.");
|
||||||
|
await dialog.getByRole("button", { name: "Submit" }).click();
|
||||||
|
|
||||||
|
await expect(page.getByRole("status")).toHaveText(
|
||||||
|
"Thanks. Your payment issue has been submitted.",
|
||||||
|
);
|
||||||
|
await expect(dialog).toBeHidden();
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(0);
|
||||||
|
expect(idempotencyKey).toMatch(/^payment_feedback_[A-Za-z0-9_-]+$/);
|
||||||
|
expect(feedbackBody).toContain('name="category"');
|
||||||
|
expect(feedbackBody).toContain("payment");
|
||||||
|
expect(feedbackBody).toContain(
|
||||||
|
"Payment issue: Other\r\nDetails: QRIS did not open correctly.",
|
||||||
|
);
|
||||||
|
expect(feedbackBody).toContain('name="context"');
|
||||||
|
expect(feedbackBody).toContain('"paymentIssueReason":"other"');
|
||||||
|
expect(feedbackBody).toContain('"characterId":"elio"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Indonesia gift checkout keeps IDR price through QRIS and thank-you flow", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
|
await prepareIndonesiaUser(page);
|
||||||
|
await page.goto("/characters/elio/tip");
|
||||||
|
|
||||||
|
await expect(page.getByText(/IDR\s*89[.,]299/)).toBeVisible();
|
||||||
|
await expectQrisOrder(
|
||||||
|
page,
|
||||||
|
/Order and Buy/i,
|
||||||
|
"tip_coffee_usd_4_99",
|
||||||
|
/Rp\s*89[.,]299/,
|
||||||
|
);
|
||||||
|
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
||||||
|
await dialog.getByRole("button", { name: "Close" }).click();
|
||||||
|
await expect(dialog).toBeHidden();
|
||||||
|
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toBeEnabled();
|
||||||
|
await page.getByRole("button", { name: "Stripe" }).click();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toHaveAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
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/user";
|
||||||
|
import {
|
||||||
|
clearBrowserState,
|
||||||
|
seedEmailSession,
|
||||||
|
} from "@e2e/fixtures/test-helpers";
|
||||||
|
|
||||||
|
const phpPlans = {
|
||||||
|
plans: [
|
||||||
|
{
|
||||||
|
planId: "dol_1000",
|
||||||
|
planName: "1,000 Credits",
|
||||||
|
orderType: "dol",
|
||||||
|
amountCents: 49_990,
|
||||||
|
originalAmountCents: 74_990,
|
||||||
|
dailyPriceCents: null,
|
||||||
|
currency: "PHP",
|
||||||
|
vipDays: null,
|
||||||
|
dolAmount: 1_000,
|
||||||
|
creditBalance: 1_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
async function registerPhilippinesPaymentMocks(
|
||||||
|
page: Page,
|
||||||
|
response: "hosted" | "qr",
|
||||||
|
) {
|
||||||
|
let createOrderCount = 0;
|
||||||
|
|
||||||
|
await page.route("**/api/user/profile", async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({ ...e2eEmailUser, countryCode: "PH" }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/plans**", async (route) => {
|
||||||
|
await route.fulfill({ json: apiEnvelope(phpPlans) });
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/create-order", async (route) => {
|
||||||
|
createOrderCount += 1;
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
orderId: `order_gcash_${response}`,
|
||||||
|
payParams: {
|
||||||
|
provider: "ezpay",
|
||||||
|
countryCode: "PH",
|
||||||
|
channelCode: "PH_QRPH_DYNAMIC",
|
||||||
|
channelType: "QR",
|
||||||
|
payData: "000201010212ph-qr-payload",
|
||||||
|
...(response === "hosted"
|
||||||
|
? { cashierUrl: "https://pay.example/gcash-hosted" }
|
||||||
|
: {}),
|
||||||
|
firstChargeAmountCents: 49_990,
|
||||||
|
currency: "PHP",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.route("**/api/payment/order-status**", async (route) => {
|
||||||
|
await route.fulfill({
|
||||||
|
json: apiEnvelope({
|
||||||
|
orderId: `order_gcash_${response}`,
|
||||||
|
status: "pending",
|
||||||
|
orderType: "dol",
|
||||||
|
planId: "dol_1000",
|
||||||
|
creditsAdded: 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
getCreateOrderCount: () => createOrderCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function preparePhilippinesUser(page: Page) {
|
||||||
|
await seedEmailSession(page);
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const rawUser = localStorage.getItem("cozsweet:user");
|
||||||
|
const user = rawUser ? JSON.parse(rawUser) : {};
|
||||||
|
localStorage.setItem(
|
||||||
|
"cozsweet:user",
|
||||||
|
JSON.stringify({ ...user, countryCode: "PH" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
|
await clearBrowserState(context, page, baseURL);
|
||||||
|
await mockCoreApis(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Philippines checkout prefers the hosted GCash URL even for a QR response", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const payment = await registerPhilippinesPaymentMocks(page, "hosted");
|
||||||
|
await preparePhilippinesUser(page);
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
|
||||||
|
await expect(page.getByRole("button", { name: "GCash" })).toHaveAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
await page.getByRole("button", { name: "Pay and Top Up" }).click();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByRole("alertdialog", { name: "Continue to payment?" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole("dialog", { name: "Pay with GCash / QR Ph" }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("dialog", { name: "Scan to pay with QRIS" }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Cancel" }).click();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toBeEnabled();
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Philippines QR-only fallback is labeled GCash / QR Ph and can switch to Stripe", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
const payment = await registerPhilippinesPaymentMocks(page, "qr");
|
||||||
|
await preparePhilippinesUser(page);
|
||||||
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Pay and Top Up" }).click();
|
||||||
|
const dialog = page.getByRole("dialog", {
|
||||||
|
name: "Pay with GCash / QR Ph",
|
||||||
|
});
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
await expect(dialog).toContainText(/₱\s*499\.90/);
|
||||||
|
await expect(dialog).not.toContainText("QRIS");
|
||||||
|
await expect(
|
||||||
|
dialog.getByRole("img", { name: "GCash / QR Ph payment QR code" }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
|
await dialog.getByRole("button", { name: "Close" }).click();
|
||||||
|
await expect(dialog).toBeHidden();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toBeEnabled();
|
||||||
|
await page.getByRole("button", { name: "Stripe" }).click();
|
||||||
|
await expect(page.getByRole("button", { name: "Stripe" })).toHaveAttribute(
|
||||||
|
"aria-pressed",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
expect(payment.getCreateOrderCount()).toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
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 Albums and reveals video after switching to Moments", 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 albums" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByText("Maya archive")).toBeVisible();
|
||||||
|
await page.getByRole("tab", { name: "Moments" }).click();
|
||||||
|
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 render first and Moments remain available behind the second tab", async ({ page }) => {
|
||||||
|
await seedEmailSession(page);
|
||||||
|
await page.goto("/characters/maya/private-zone");
|
||||||
|
|
||||||
|
const tabs = page.getByRole("tab");
|
||||||
|
await expect(tabs).toHaveText(["Albums", "Moments"]);
|
||||||
|
await expect(page.getByRole("tab", { name: "Albums" })).toHaveAttribute(
|
||||||
|
"aria-selected",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "Private albums" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByText("Maya archive")).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole("tab", { name: "Moments" }).click();
|
||||||
|
await expect(page.getByRole("tab", { name: "Moments" })).toHaveAttribute(
|
||||||
|
"aria-selected",
|
||||||
|
"true",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "Private moments" }),
|
||||||
|
).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",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,20 +1,17 @@
|
|||||||
import { expect, test } from "@playwright/test";
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
import { mockCoreApis } from "@e2e/fixtures/api-mocks";
|
||||||
import { paidImageMessageId } from "@e2e/fixtures/test-data";
|
import {
|
||||||
|
paidImageMessageId,
|
||||||
|
} from "@e2e/fixtures/test-data";
|
||||||
import {
|
import {
|
||||||
clearBrowserState,
|
clearBrowserState,
|
||||||
defaultCharacterChatPath,
|
|
||||||
dismissChatInterruptions,
|
dismissChatInterruptions,
|
||||||
expectInsufficientCreditsDialog,
|
expectInsufficientCreditsDialog,
|
||||||
expectVipChatSubscriptionUrl,
|
expectVipChatSubscriptionUrl,
|
||||||
signInWithEmailAndOpenChat,
|
signInWithEmailAndOpenChat,
|
||||||
} from "@e2e/fixtures/test-helpers";
|
} from "@e2e/fixtures/test-helpers";
|
||||||
|
|
||||||
const paidImageOverlayUrl = new RegExp(
|
|
||||||
`${defaultCharacterChatPath}\\?image=${paidImageMessageId}$`,
|
|
||||||
);
|
|
||||||
|
|
||||||
test.beforeEach(async ({ baseURL, context, page }) => {
|
test.beforeEach(async ({ baseURL, context, page }) => {
|
||||||
await clearBrowserState(context, page, baseURL);
|
await clearBrowserState(context, page, baseURL);
|
||||||
await mockCoreApis(page, {
|
await mockCoreApis(page, {
|
||||||
@@ -22,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,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
await signInWithEmailAndOpenChat(page);
|
await signInWithEmailAndOpenChat(page);
|
||||||
await dismissChatInterruptions(page);
|
await dismissChatInterruptions(page);
|
||||||
|
|
||||||
const paidImageButton = page.getByRole("button", {
|
const lockedImageCard = page.getByRole("group", {
|
||||||
name: "Open image in fullscreen",
|
name: "Locked private image",
|
||||||
}).last();
|
}).last();
|
||||||
await expect(paidImageButton).toBeVisible({ timeout: 10_000 });
|
await expect(lockedImageCard).toBeVisible({ timeout: 10_000 });
|
||||||
|
await expect(lockedImageCard.locator("img")).toHaveCount(0);
|
||||||
await paidImageButton.click();
|
|
||||||
await expect(page).toHaveURL(paidImageOverlayUrl);
|
|
||||||
|
|
||||||
const lockedImageDialog = page.getByRole("dialog", {
|
|
||||||
name: "Locked fullscreen image",
|
|
||||||
});
|
|
||||||
await expect(lockedImageDialog).toBeVisible();
|
|
||||||
|
|
||||||
const unlockRequestPromise = page.waitForRequest(
|
const unlockRequestPromise = page.waitForRequest(
|
||||||
"**/api/chat/unlock-private",
|
"**/api/chat/unlock-private",
|
||||||
);
|
);
|
||||||
await lockedImageDialog
|
await lockedImageCard
|
||||||
.getByRole("button", { name: "Unlock high-definition large image" })
|
.getByRole("button", { name: "Unlock private image" })
|
||||||
.click();
|
.click();
|
||||||
|
|
||||||
const unlockRequest = await unlockRequestPromise;
|
const unlockRequest = await unlockRequestPromise;
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ test.describe("pre-release email login smoke", () => {
|
|||||||
urlTimeout: 20_000,
|
urlTimeout: 20_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(page.getByRole("button", { name: "Menu" })).toBeVisible();
|
await expect(page.getByRole("button", { name: "Profile" })).toBeVisible();
|
||||||
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
await expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ NEXTAUTH_URL=https://frontend-test.banlv-ai.com
|
|||||||
NEXTAUTH_URL_INTERNAL=http://localhost:3000
|
NEXTAUTH_URL_INTERNAL=http://localhost:3000
|
||||||
NEXT_PUBLIC_API_BASE_URL=https://proapi.banlv-ai.com
|
NEXT_PUBLIC_API_BASE_URL=https://proapi.banlv-ai.com
|
||||||
NEXT_PUBLIC_WS_BASE_URL=wss://proapi.banlv-ai.com/ws
|
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_STRIPE_PUBLISHABLE_KEY=pk_test_51Te8ybEJDtUGxQHo0UMySJ2hW0vVryynzllmIUI3UQdQCFgxNLci0Jmm2lQkRsTaIP7C7IQlFzfFyBJ5rOhr1ML800G8P8DF5R
|
||||||
|
|
||||||
NEXT_PUBLIC_API_CONNECT_TIMEOUT=30000
|
NEXT_PUBLIC_API_CONNECT_TIMEOUT=30000
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ NEXT_PUBLIC_API_BASE_URL=https://api.banlv-ai.com
|
|||||||
|
|
||||||
# WebSocket URL(生产环境)
|
# WebSocket URL(生产环境)
|
||||||
NEXT_PUBLIC_WS_BASE_URL=wss://api.banlv-ai.com/ws
|
NEXT_PUBLIC_WS_BASE_URL=wss://api.banlv-ai.com/ws
|
||||||
|
NEXT_PUBLIC_ENABLE_VOICE_CALL=false
|
||||||
|
|
||||||
# Stripe 支付(publishable key 可暴露在浏览器端)
|
# Stripe 支付(publishable key 可暴露在浏览器端)
|
||||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_51Te8ybEJDtUGxQHouKlEMfMuCZWifzlhBIReeKvANOtyCXS4zL0SMTWJXiFHPKz7azpF6OnIKXUPFSLs82fevVjr00w1bw5mvl
|
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 |
@@ -25,9 +25,9 @@
|
|||||||
"test:e2e:chrome": "PLAYWRIGHT_USE_SYSTEM_CHROME=1 playwright test --project=mock-chromium",
|
"test:e2e:chrome": "PLAYWRIGHT_USE_SYSTEM_CHROME=1 playwright test --project=mock-chromium",
|
||||||
"test:e2e:headed": "playwright test --project=mock-chromium --headed",
|
"test:e2e:headed": "playwright test --project=mock-chromium --headed",
|
||||||
"test:e2e:ui": "playwright test --ui",
|
"test:e2e:ui": "playwright test --ui",
|
||||||
"test:e2e:mobile-smoke": "playwright test --project=mock-mobile-chrome e2e/specs/mock/auth/email-login-from-other-options.spec.ts e2e/specs/mock/auth/logout-from-sidebar.spec.ts e2e/specs/mock/chat/chat-send-token-refresh-retry.spec.ts e2e/specs/mock/unlock-message/image-unlock-insufficient-credits.spec.ts",
|
"test:e2e:mobile-smoke": "playwright test --project=mock-mobile-chrome e2e/specs/mock/auth/email-login-from-other-options.spec.ts e2e/specs/mock/auth/logout-from-profile.spec.ts e2e/specs/mock/chat/chat-send-token-refresh-retry.spec.ts e2e/specs/mock/unlock-message/image-unlock-insufficient-credits.spec.ts",
|
||||||
"test:e2e:real": "E2E_REAL_BACKEND=1 PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-https://frontend-test.banlv-ai.com} E2E_API_BASE_URL=${E2E_API_BASE_URL:-https://proapi.banlv-ai.com} playwright test --project=real-backend",
|
"test:e2e:real": "E2E_REAL_BACKEND=1 PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-https://frontend-test.banlv-ai.com} E2E_API_BASE_URL=${E2E_API_BASE_URL:-https://proapi.banlv-ai.com} playwright test --project=real-backend",
|
||||||
"test:e2e:prod": "E2E_REAL_BACKEND=1 PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-https://cozsweet.com} E2E_API_BASE_URL=${E2E_API_BASE_URL:-https://proapi.banlv-ai.com} playwright test --project=prod-smoke",
|
"test:e2e:prod": "E2E_REAL_BACKEND=1 PLAYWRIGHT_BASE_URL=${PLAYWRIGHT_BASE_URL:-https://cozsweet.com} E2E_API_BASE_URL=${E2E_API_BASE_URL:-https://api.banlv-ai.com} playwright test --project=prod-smoke",
|
||||||
"contract:check": "node scripts/contracts/check-openapi.mjs",
|
"contract:check": "node scripts/contracts/check-openapi.mjs",
|
||||||
"test:contracts": "node --test scripts/contracts/__tests__/*.test.mjs",
|
"test:contracts": "node --test scripts/contracts/__tests__/*.test.mjs",
|
||||||
"perf:bundle": "next experimental-analyze --output && node scripts/performance/report-bundle.mjs",
|
"perf:bundle": "next experimental-analyze --output && node scripts/performance/report-bundle.mjs",
|
||||||
@@ -50,6 +50,7 @@
|
|||||||
"next-auth": "^4.24.14",
|
"next-auth": "^4.24.14",
|
||||||
"ofetch": "^1.5.1",
|
"ofetch": "^1.5.1",
|
||||||
"pino": "^10.3.1",
|
"pino": "^10.3.1",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"react-icons": "^5.6.0",
|
"react-icons": "^5.6.0",
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ export default defineConfig({
|
|||||||
fullyParallel: true,
|
fullyParallel: true,
|
||||||
forbidOnly: Boolean(process.env.CI),
|
forbidOnly: Boolean(process.env.CI),
|
||||||
retries: process.env.CI ? 2 : 0,
|
retries: process.env.CI ? 2 : 0,
|
||||||
workers: process.env.CI ? 1 : undefined,
|
// Next.js dev + Turbopack can return incomplete module payloads when the
|
||||||
|
// local mock suite compiles many routes concurrently. Keep this tier
|
||||||
|
// deterministic locally as well as in CI.
|
||||||
|
workers: 1,
|
||||||
reporter: process.env.CI
|
reporter: process.env.CI
|
||||||
? [["list"], ["html", { open: "never" }]]
|
? [["list"], ["html", { open: "never" }]]
|
||||||
: [["list"], ["html", { open: "never" }]],
|
: [["list"], ["html", { open: "never" }]],
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ importers:
|
|||||||
pino:
|
pino:
|
||||||
specifier: ^10.3.1
|
specifier: ^10.3.1
|
||||||
version: 10.3.1
|
version: 10.3.1
|
||||||
|
qrcode.react:
|
||||||
|
specifier: ^4.2.0
|
||||||
|
version: 4.2.0(react@19.2.4)
|
||||||
react:
|
react:
|
||||||
specifier: 19.2.4
|
specifier: 19.2.4
|
||||||
version: 19.2.4
|
version: 19.2.4
|
||||||
@@ -3290,6 +3293,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
|
|
||||||
|
qrcode.react@4.2.0:
|
||||||
|
resolution: {integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==}
|
||||||
|
peerDependencies:
|
||||||
|
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||||
|
|
||||||
queue-microtask@1.2.3:
|
queue-microtask@1.2.3:
|
||||||
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
||||||
|
|
||||||
@@ -7085,6 +7093,10 @@ snapshots:
|
|||||||
|
|
||||||
punycode@2.3.1: {}
|
punycode@2.3.1: {}
|
||||||
|
|
||||||
|
qrcode.react@4.2.0(react@19.2.4):
|
||||||
|
dependencies:
|
||||||
|
react: 19.2.4
|
||||||
|
|
||||||
queue-microtask@1.2.3: {}
|
queue-microtask@1.2.3: {}
|
||||||
|
|
||||||
quick-format-unescaped@4.0.4: {}
|
quick-format-unescaped@4.0.4: {}
|
||||||
|
|||||||
|
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 |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 663 KiB After Width: | Height: | Size: 577 KiB |
|
Before Width: | Height: | Size: 468 KiB After Width: | Height: | Size: 342 KiB |
|
Before Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 490 KiB |
@@ -11,13 +11,13 @@
|
|||||||
"lang": "en",
|
"lang": "en",
|
||||||
"icons": [
|
"icons": [
|
||||||
{
|
{
|
||||||
"src": "/images/icons/Icon-192.png",
|
"src": "/images/icons/Icon-192.png?v=20260724",
|
||||||
"sizes": "192x192",
|
"sizes": "192x192",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"purpose": "any"
|
"purpose": "any"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/images/icons/Icon-512.png",
|
"src": "/images/icons/Icon-512.png?v=20260724",
|
||||||
"sizes": "512x512",
|
"sizes": "512x512",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"purpose": "any"
|
"purpose": "any"
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const workflowUrl = new URL(
|
||||||
|
"../../../.gitea/workflows/domestic-test.yml",
|
||||||
|
import.meta.url,
|
||||||
|
);
|
||||||
|
const deployScriptUrl = new URL(
|
||||||
|
"../../server/deploy-domestic-test-archive.sh",
|
||||||
|
import.meta.url,
|
||||||
|
);
|
||||||
|
|
||||||
|
test("domestic frontend workflow is manual and registry-free", async () => {
|
||||||
|
const workflow = await readFile(workflowUrl, "utf8");
|
||||||
|
|
||||||
|
assert.match(workflow, /workflow_dispatch:/);
|
||||||
|
assert.doesNotMatch(workflow, /\bpush:/);
|
||||||
|
assert.doesNotMatch(workflow, /REGISTRY_IMAGE/);
|
||||||
|
assert.match(workflow, /docker save/);
|
||||||
|
assert.match(workflow, /DOMESTIC_TEST_SSH_PRIVATE_KEY_B64/);
|
||||||
|
assert.match(workflow, /base64 -d/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("domestic frontend workflow pins the China test API and isolated port", async () => {
|
||||||
|
const workflow = await readFile(workflowUrl, "utf8");
|
||||||
|
const deployScript = await readFile(deployScriptUrl, "utf8");
|
||||||
|
|
||||||
|
assert.match(workflow, /https:\/\/testapi\.banlv-ai\.com/);
|
||||||
|
assert.match(workflow, /wss:\/\/testapi\.banlv-ai\.com\/ws/);
|
||||||
|
assert.match(workflow, /9135/);
|
||||||
|
assert.match(deployScript, /127\.0\.0\.1:\$HOST_PORT/);
|
||||||
|
assert.match(deployScript, /cozsweet-frontend-domestic-test/);
|
||||||
|
});
|
||||||
@@ -13,13 +13,13 @@ describe("OpenAPI contract comparison", () => {
|
|||||||
chatHistory: { method: "get", path: "/api/chat/history" },
|
chatHistory: { method: "get", path: "/api/chat/history" },
|
||||||
unlockAlbum: {
|
unlockAlbum: {
|
||||||
method: "post",
|
method: "post",
|
||||||
path: "/api/private-room/albums/{albumId}/unlock",
|
path: "/api/private-zone/albums/{albumId}/unlock",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
paths: {
|
paths: {
|
||||||
"/api/chat/history": { get: {} },
|
"/api/chat/history": { get: {} },
|
||||||
"/api/private-room/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[@]}" up -d --remove-orphans --no-build web
|
||||||
"${COMPOSE[@]}" ps
|
"${COMPOSE[@]}" ps
|
||||||
|
|
||||||
docker image prune -f
|
|
||||||
|
|
||||||
prune_project_images() {
|
prune_project_images() {
|
||||||
local retain_count="$1"
|
local retain_count="$1"
|
||||||
if ! [[ "$retain_count" =~ ^[0-9]+$ ]] || [ "$retain_count" -le 0 ]; then
|
if ! [[ "$retain_count" =~ ^[0-9]+$ ]] || [ "$retain_count" -le 0 ]; then
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ARCHIVE="${1:-}"
|
||||||
|
IMAGE="${2:-}"
|
||||||
|
ENV_FILE="${3:-}"
|
||||||
|
HOST_PORT="${4:-9135}"
|
||||||
|
CONTAINER_NAME="cozsweet-frontend-domestic-test"
|
||||||
|
INTERNAL_PORT="3000"
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
SERVICE_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||||
|
SHARED_ROOT="$SERVICE_ROOT/shared"
|
||||||
|
RELEASE_ROOT="$SERVICE_ROOT/releases/docker"
|
||||||
|
|
||||||
|
if [ -z "$ARCHIVE" ] || [ -z "$IMAGE" ] || [ -z "$ENV_FILE" ]; then
|
||||||
|
echo "Usage: $0 <image-archive> <image> <env-file> [host-port]" >&2
|
||||||
|
exit 64
|
||||||
|
fi
|
||||||
|
if [ "$HOST_PORT" != "9135" ]; then
|
||||||
|
echo "Domestic frontend test must use isolated host port 9135" >&2
|
||||||
|
exit 64
|
||||||
|
fi
|
||||||
|
case "$ENV_FILE" in
|
||||||
|
"$SHARED_ROOT"/*) ;;
|
||||||
|
*)
|
||||||
|
echo "Environment file must be stored under $SHARED_ROOT" >&2
|
||||||
|
exit 64
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
if [ ! -s "$ARCHIVE" ] || [ ! -s "$ENV_FILE" ]; then
|
||||||
|
echo "Image archive or environment file is missing" >&2
|
||||||
|
exit 66
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$RELEASE_ROOT"
|
||||||
|
chmod 700 "$SHARED_ROOT"
|
||||||
|
gzip -dc "$ARCHIVE" | docker load >/dev/null
|
||||||
|
docker image inspect "$IMAGE" >/dev/null
|
||||||
|
|
||||||
|
old_image_id=""
|
||||||
|
old_image_ref=""
|
||||||
|
if docker container inspect "$CONTAINER_NAME" >/dev/null 2>&1; then
|
||||||
|
old_image_id="$(docker inspect -f '{{.Image}}' "$CONTAINER_NAME")"
|
||||||
|
old_image_ref="$(docker inspect -f '{{.Config.Image}}' "$CONTAINER_NAME")"
|
||||||
|
elif ss -ltnH "sport = :$HOST_PORT" 2>/dev/null | grep -q .; then
|
||||||
|
echo "Host port $HOST_PORT is already used by another service" >&2
|
||||||
|
exit 69
|
||||||
|
fi
|
||||||
|
|
||||||
|
run_container() {
|
||||||
|
local image_ref="$1"
|
||||||
|
docker run -d \
|
||||||
|
--name "$CONTAINER_NAME" \
|
||||||
|
--restart unless-stopped \
|
||||||
|
-p "127.0.0.1:$HOST_PORT:$INTERNAL_PORT" \
|
||||||
|
--env-file "$ENV_FILE" \
|
||||||
|
-e "PORT=$INTERNAL_PORT" \
|
||||||
|
"$image_ref" >/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_healthy() {
|
||||||
|
local deadline=$((SECONDS + 180))
|
||||||
|
while [ "$SECONDS" -le "$deadline" ]; do
|
||||||
|
state="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$CONTAINER_NAME" 2>/dev/null || true)"
|
||||||
|
status="$(curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:$HOST_PORT/" 2>/dev/null || true)"
|
||||||
|
if [[ "$status" =~ ^(200|204|301|302|303|307|308)$ ]] && { [ "$state" = "healthy" ] || [ "$state" = "running" ]; }; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
|
||||||
|
deployment_ok="1"
|
||||||
|
if ! run_container "$IMAGE"; then
|
||||||
|
deployment_ok="0"
|
||||||
|
elif ! wait_healthy; then
|
||||||
|
deployment_ok="0"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$deployment_ok" != "1" ]; then
|
||||||
|
docker logs --tail 120 "$CONTAINER_NAME" >&2 || true
|
||||||
|
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
|
||||||
|
if [ -n "$old_image_id" ] && docker image inspect "$old_image_id" >/dev/null 2>&1; then
|
||||||
|
echo "New container failed health checks; restoring previous image" >&2
|
||||||
|
run_container "$old_image_id"
|
||||||
|
wait_healthy || true
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
created_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
image_id="$(docker image inspect "$IMAGE" -f '{{.Id}}')"
|
||||||
|
record="{\"createdAt\":\"$created_at\",\"environment\":\"domestic-test\",\"image\":\"$IMAGE\",\"imageId\":\"$image_id\",\"container\":\"$CONTAINER_NAME\",\"hostPort\":$HOST_PORT}"
|
||||||
|
if [ -f "$RELEASE_ROOT/current.json" ]; then
|
||||||
|
cp "$RELEASE_ROOT/current.json" "$RELEASE_ROOT/previous.json"
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$record" > "$RELEASE_ROOT/current.json"
|
||||||
|
printf '%s\n' "$record" >> "$RELEASE_ROOT/releases.jsonl"
|
||||||
|
|
||||||
|
echo "Domestic frontend test is healthy"
|
||||||
|
echo "container=$CONTAINER_NAME"
|
||||||
|
echo "host_port=$HOST_PORT"
|
||||||
|
echo "image=$IMAGE"
|
||||||
|
if [ -n "$old_image_ref" ]; then
|
||||||
|
echo "previous_image=$old_image_ref"
|
||||||
|
fi
|
||||||
@@ -79,4 +79,34 @@ describe("shared Tailwind components", () => {
|
|||||||
expect(guestHtml).toContain('aria-label="Guest avatar"');
|
expect(guestHtml).toContain('aria-label="Guest avatar"');
|
||||||
expect(guestHtml).toContain("%2Fimages%2Favatar%2Fplaceholder.png");
|
expect(guestHtml).toContain("%2Fimages%2Favatar%2Fplaceholder.png");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("renders interactive avatars as accessible buttons", () => {
|
||||||
|
const characterHtml = renderToStaticMarkup(
|
||||||
|
<CharacterAvatar
|
||||||
|
src="/images/avatar/elio.png"
|
||||||
|
alt="Elio Silvestri"
|
||||||
|
actionLabel="Open Elio's private zone"
|
||||||
|
analyticsKey="chat.open_private_zone_from_avatar"
|
||||||
|
onClick={() => undefined}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
const userHtml = renderToStaticMarkup(
|
||||||
|
<UserMessageAvatar
|
||||||
|
actionLabel="Open profile"
|
||||||
|
analyticsKey="chat.open_profile_from_avatar"
|
||||||
|
onClick={() => undefined}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(characterHtml).toContain('<button type="button"');
|
||||||
|
expect(characterHtml).toContain(
|
||||||
|
'aria-label="Open Elio's private zone"',
|
||||||
|
);
|
||||||
|
expect(characterHtml).toContain(
|
||||||
|
'data-analytics-key="chat.open_private_zone_from_avatar"',
|
||||||
|
);
|
||||||
|
expect(userHtml).toContain('<button type="button"');
|
||||||
|
expect(userHtml).toContain('aria-label="Open profile"');
|
||||||
|
expect(userHtml).toContain("focus-visible:outline-3");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export type AvatarInteractionProps =
|
||||||
|
| {
|
||||||
|
onClick?: undefined;
|
||||||
|
actionLabel?: never;
|
||||||
|
analyticsKey?: never;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
onClick: () => void;
|
||||||
|
actionLabel: string;
|
||||||
|
analyticsKey?: string;
|
||||||
|
};
|
||||||
@@ -3,7 +3,9 @@
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import type { CSSProperties } from "react";
|
import type { CSSProperties } from "react";
|
||||||
|
|
||||||
export interface CharacterAvatarProps {
|
import type { AvatarInteractionProps } from "./avatar-interaction";
|
||||||
|
|
||||||
|
interface CharacterAvatarVisualProps {
|
||||||
src: string;
|
src: string;
|
||||||
alt: string;
|
alt: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
@@ -12,6 +14,9 @@ export interface CharacterAvatarProps {
|
|||||||
priority?: boolean;
|
priority?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CharacterAvatarProps = CharacterAvatarVisualProps &
|
||||||
|
AvatarInteractionProps;
|
||||||
|
|
||||||
export function CharacterAvatar({
|
export function CharacterAvatar({
|
||||||
src,
|
src,
|
||||||
alt,
|
alt,
|
||||||
@@ -19,6 +24,9 @@ export function CharacterAvatar({
|
|||||||
size = 43,
|
size = 43,
|
||||||
imageSize,
|
imageSize,
|
||||||
priority = false,
|
priority = false,
|
||||||
|
onClick,
|
||||||
|
actionLabel,
|
||||||
|
analyticsKey,
|
||||||
}: CharacterAvatarProps) {
|
}: CharacterAvatarProps) {
|
||||||
const resolvedImageSize =
|
const resolvedImageSize =
|
||||||
imageSize ?? (typeof size === "number" ? size : 96);
|
imageSize ?? (typeof size === "number" ? size : 96);
|
||||||
@@ -27,24 +35,45 @@ export function CharacterAvatar({
|
|||||||
height: size,
|
height: size,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const avatarClassName = [
|
||||||
|
"inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full border-0 bg-(--color-avatar-border,#fbf3f5)",
|
||||||
|
onClick
|
||||||
|
? "cursor-pointer p-0 transition-transform duration-150 focus-visible:outline-3 focus-visible:outline-offset-3 focus-visible:outline-accent active:scale-96"
|
||||||
|
: undefined,
|
||||||
|
className,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
const image = (
|
||||||
|
<Image
|
||||||
|
src={src}
|
||||||
|
alt={alt}
|
||||||
|
width={resolvedImageSize}
|
||||||
|
height={resolvedImageSize}
|
||||||
|
priority={priority}
|
||||||
|
className="size-full object-cover"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (onClick) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={avatarClassName}
|
||||||
|
style={style}
|
||||||
|
aria-label={actionLabel}
|
||||||
|
data-analytics-key={analyticsKey}
|
||||||
|
data-analytics-label={actionLabel}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
{image}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span
|
<span className={avatarClassName} style={style}>
|
||||||
className={[
|
{image}
|
||||||
"inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full bg-(--color-avatar-border,#fbf3f5)",
|
|
||||||
className,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" ")}
|
|
||||||
style={style}
|
|
||||||
>
|
|
||||||
<Image
|
|
||||||
src={src}
|
|
||||||
alt={alt}
|
|
||||||
width={resolvedImageSize}
|
|
||||||
height={resolvedImageSize}
|
|
||||||
priority={priority}
|
|
||||||
className="size-full object-cover"
|
|
||||||
/>
|
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { act } from "react";
|
||||||
|
import { createRoot, type Root } from "react-dom/client";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { ModalPortal } from "../modal-portal";
|
||||||
|
|
||||||
|
describe("ModalPortal", () => {
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||||
|
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
container = document.createElement("div");
|
||||||
|
container.style.transform = "translateX(50%)";
|
||||||
|
document.body.appendChild(container);
|
||||||
|
document.body.style.overflow = "auto";
|
||||||
|
root = createRoot(container);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => root.unmount());
|
||||||
|
container.remove();
|
||||||
|
document.body.style.overflow = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
it("portals outside transformed ancestors and exposes dialog semantics", () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<ModalPortal
|
||||||
|
open
|
||||||
|
onClose={onClose}
|
||||||
|
scrimClassName="fixed inset-0"
|
||||||
|
panelClassName="payment-panel"
|
||||||
|
scrimOpacity={0.5}
|
||||||
|
role="alertdialog"
|
||||||
|
ariaLabelledBy="payment-title"
|
||||||
|
ariaDescribedBy="payment-description"
|
||||||
|
>
|
||||||
|
<h2 id="payment-title">Complete payment</h2>
|
||||||
|
<p id="payment-description">Choose a payment method.</p>
|
||||||
|
</ModalPortal>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="alertdialog"]');
|
||||||
|
expect(dialog).not.toBeNull();
|
||||||
|
expect(container.contains(dialog)).toBe(false);
|
||||||
|
expect(dialog?.parentElement?.parentElement).toBe(document.body);
|
||||||
|
expect(dialog?.getAttribute("aria-labelledby")).toBe("payment-title");
|
||||||
|
expect(dialog?.getAttribute("aria-describedby")).toBe(
|
||||||
|
"payment-description",
|
||||||
|
);
|
||||||
|
expect(document.body.style.overflow).toBe("hidden");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores the previous body overflow after the final modal closes", () => {
|
||||||
|
const renderModals = (showFirst: boolean, showSecond: boolean) => (
|
||||||
|
<>
|
||||||
|
<ModalPortal
|
||||||
|
open={showFirst}
|
||||||
|
onClose={() => undefined}
|
||||||
|
scrimClassName="first-scrim"
|
||||||
|
panelClassName="first-panel"
|
||||||
|
scrimOpacity={0.4}
|
||||||
|
>
|
||||||
|
First
|
||||||
|
</ModalPortal>
|
||||||
|
<ModalPortal
|
||||||
|
open={showSecond}
|
||||||
|
onClose={() => undefined}
|
||||||
|
scrimClassName="second-scrim"
|
||||||
|
panelClassName="second-panel"
|
||||||
|
scrimOpacity={0.4}
|
||||||
|
>
|
||||||
|
Second
|
||||||
|
</ModalPortal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => root.render(renderModals(true, true)));
|
||||||
|
expect(document.body.style.overflow).toBe("hidden");
|
||||||
|
|
||||||
|
act(() => root.render(renderModals(false, true)));
|
||||||
|
expect(document.body.style.overflow).toBe("hidden");
|
||||||
|
|
||||||
|
act(() => root.render(renderModals(false, false)));
|
||||||
|
expect(document.body.style.overflow).toBe("auto");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps persistent payment modals open on scrim click and Escape", () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<ModalPortal
|
||||||
|
open
|
||||||
|
persistent
|
||||||
|
onClose={onClose}
|
||||||
|
scrimClassName="fixed inset-0"
|
||||||
|
panelClassName="payment-panel"
|
||||||
|
scrimOpacity={0.5}
|
||||||
|
>
|
||||||
|
Payment
|
||||||
|
</ModalPortal>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const scrim = document.body.querySelector(".fixed.inset-0");
|
||||||
|
act(() => scrim?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
|
||||||
|
act(() =>
|
||||||
|
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(onClose).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -79,18 +79,20 @@ describe("core Tailwind components", () => {
|
|||||||
<AppBottomNav
|
<AppBottomNav
|
||||||
activeItem="chat"
|
activeItem="chat"
|
||||||
variant="dark"
|
variant="dark"
|
||||||
privateRoomLabel="Maya Private room"
|
privateZoneLabel="Maya Private Zone"
|
||||||
onChatClick={() => undefined}
|
onChatClick={() => undefined}
|
||||||
onPrivateRoomClick={() => undefined}
|
onPrivateZoneClick={() => undefined}
|
||||||
|
onMenuClick={() => undefined}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
const privateRoomHtml = renderToStaticMarkup(
|
const privateZoneHtml = renderToStaticMarkup(
|
||||||
<AppBottomNav
|
<AppBottomNav
|
||||||
activeItem="privateRoom"
|
activeItem="privateZone"
|
||||||
variant="warm"
|
variant="warm"
|
||||||
privateRoomLabel="Maya Private room"
|
privateZoneLabel="Maya Private Zone"
|
||||||
onChatClick={() => undefined}
|
onChatClick={() => undefined}
|
||||||
onPrivateRoomClick={() => undefined}
|
onPrivateZoneClick={() => undefined}
|
||||||
|
onMenuClick={() => undefined}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -99,13 +101,15 @@ describe("core Tailwind components", () => {
|
|||||||
expect(chatHtml).toMatch(
|
expect(chatHtml).toMatch(
|
||||||
/<button[^>]*aria-current="page"[^>]*>.*?<span>Chat<\/span>/,
|
/<button[^>]*aria-current="page"[^>]*>.*?<span>Chat<\/span>/,
|
||||||
);
|
);
|
||||||
expect(privateRoomHtml).toMatch(/class="[^"]*warm[^"]*"/);
|
expect(privateZoneHtml).toMatch(/class="[^"]*warm[^"]*"/);
|
||||||
expect(privateRoomHtml).toMatch(
|
expect(privateZoneHtml).toMatch(
|
||||||
/<button[^>]*aria-current="page"[^>]*>.*?<span>Maya Private room<\/span>/,
|
/<button[^>]*aria-current="page"[^>]*>.*?<span>Maya Private Zone<\/span>/,
|
||||||
);
|
);
|
||||||
expect(chatHtml).toContain('data-analytics-key="navigation.chat"');
|
expect(chatHtml).toContain('data-analytics-key="navigation.chat"');
|
||||||
expect(privateRoomHtml).toContain(
|
expect(privateZoneHtml).toContain(
|
||||||
'data-analytics-key="navigation.private_room"',
|
'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%;
|
left: 50%;
|
||||||
z-index: 30;
|
z-index: 30;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
width: min(100vw, var(--app-max-width, 540px));
|
width: min(100vw, var(--app-max-width, 540px));
|
||||||
min-height: calc(
|
min-height: calc(
|
||||||
|
|||||||
@@ -1,26 +1,28 @@
|
|||||||
"use client";
|
"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";
|
import styles from "./app-bottom-nav.module.css";
|
||||||
|
|
||||||
export type AppBottomNavItem = "chat" | "privateRoom";
|
export type AppBottomNavItem = "chat" | "privateZone" | "menu";
|
||||||
export type AppBottomNavVariant = "warm" | "dark";
|
export type AppBottomNavVariant = "warm" | "dark";
|
||||||
|
|
||||||
export interface AppBottomNavProps {
|
export interface AppBottomNavProps {
|
||||||
activeItem?: AppBottomNavItem | null;
|
activeItem?: AppBottomNavItem | null;
|
||||||
variant?: AppBottomNavVariant;
|
variant?: AppBottomNavVariant;
|
||||||
privateRoomLabel: string;
|
privateZoneLabel: string;
|
||||||
onChatClick: () => void;
|
onChatClick: () => void;
|
||||||
onPrivateRoomClick: () => void;
|
onPrivateZoneClick: () => void;
|
||||||
|
onMenuClick: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AppBottomNav({
|
export function AppBottomNav({
|
||||||
activeItem = null,
|
activeItem = null,
|
||||||
variant = "warm",
|
variant = "warm",
|
||||||
privateRoomLabel,
|
privateZoneLabel,
|
||||||
onChatClick,
|
onChatClick,
|
||||||
onPrivateRoomClick,
|
onPrivateZoneClick,
|
||||||
|
onMenuClick,
|
||||||
}: AppBottomNavProps) {
|
}: AppBottomNavProps) {
|
||||||
return (
|
return (
|
||||||
<nav className={getRootClass(variant)} aria-label="Primary navigation">
|
<nav className={getRootClass(variant)} aria-label="Primary navigation">
|
||||||
@@ -37,14 +39,25 @@ export function AppBottomNav({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-analytics-key="navigation.private_room"
|
data-analytics-key="navigation.private_zone"
|
||||||
data-analytics-label="Private room navigation"
|
data-analytics-label="Private Zone navigation"
|
||||||
className={getButtonClass(activeItem === "privateRoom")}
|
className={getButtonClass(activeItem === "privateZone")}
|
||||||
aria-current={activeItem === "privateRoom" ? "page" : undefined}
|
aria-current={activeItem === "privateZone" ? "page" : undefined}
|
||||||
onClick={onPrivateRoomClick}
|
onClick={onPrivateZoneClick}
|
||||||
>
|
>
|
||||||
<Camera size={20} aria-hidden="true" />
|
<Camera size={20} aria-hidden="true" />
|
||||||
<span>{privateRoomLabel}</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>
|
</button>
|
||||||
</nav>
|
</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 "./app-bottom-nav";
|
||||||
export * from "./bottom-sheet";
|
export * from "./bottom-sheet";
|
||||||
export * from "./checkbox";
|
export * from "./checkbox";
|
||||||
|
export * from "./favorite-entry-button";
|
||||||
export * from "./loading-indicator";
|
export * from "./loading-indicator";
|
||||||
export * from "./mobile-shell";
|
export * from "./mobile-shell";
|
||||||
export * from "./page-loading-fallback";
|
export * from "./page-loading-fallback";
|
||||||
|
|||||||
@@ -20,7 +20,10 @@ export interface ModalPortalProps {
|
|||||||
scrimOpacity: number;
|
scrimOpacity: number;
|
||||||
panelStyle?: CSSProperties;
|
panelStyle?: CSSProperties;
|
||||||
persistent?: boolean;
|
persistent?: boolean;
|
||||||
|
role?: "dialog" | "alertdialog";
|
||||||
ariaLabel?: string;
|
ariaLabel?: string;
|
||||||
|
ariaLabelledBy?: string;
|
||||||
|
ariaDescribedBy?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ModalPortal({
|
export function ModalPortal({
|
||||||
@@ -32,7 +35,10 @@ export function ModalPortal({
|
|||||||
scrimOpacity,
|
scrimOpacity,
|
||||||
panelStyle,
|
panelStyle,
|
||||||
persistent = false,
|
persistent = false,
|
||||||
|
role = "dialog",
|
||||||
ariaLabel,
|
ariaLabel,
|
||||||
|
ariaLabelledBy,
|
||||||
|
ariaDescribedBy,
|
||||||
}: ModalPortalProps) {
|
}: ModalPortalProps) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || typeof document === "undefined") return;
|
if (!open || typeof document === "undefined") return;
|
||||||
@@ -63,9 +69,11 @@ export function ModalPortal({
|
|||||||
onClick={handleScrimClick}
|
onClick={handleScrimClick}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
role="dialog"
|
role={role}
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-label={ariaLabel}
|
aria-label={ariaLabel}
|
||||||
|
aria-labelledby={ariaLabelledBy}
|
||||||
|
aria-describedby={ariaDescribedBy}
|
||||||
className={panelClassName}
|
className={panelClassName}
|
||||||
style={panelStyle}
|
style={panelStyle}
|
||||||
onClick={(event) => event.stopPropagation()}
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
|||||||
@@ -3,5 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export * from "./back-button";
|
export * from "./back-button";
|
||||||
|
export * from "./avatar-interaction";
|
||||||
export * from "./character-avatar";
|
export * from "./character-avatar";
|
||||||
export * from "./user-message-avatar";
|
export * from "./user-message-avatar";
|
||||||
|
|||||||
@@ -1,23 +1,47 @@
|
|||||||
import { renderToStaticMarkup } from "react-dom/server";
|
import { act } from "react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { createRoot, type Root } from "react-dom/client";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { PaymentLaunchDialogs } from "../payment-launch-dialogs";
|
import { PaymentLaunchDialogs } from "../payment-launch-dialogs";
|
||||||
|
|
||||||
const hiddenLaunch = {
|
const hiddenLaunch = {
|
||||||
handleEzpayCancel: vi.fn(),
|
handleEzpayCancel: vi.fn(),
|
||||||
handleEzpayConfirm: vi.fn(),
|
handleEzpayConfirm: vi.fn(),
|
||||||
|
handleRegionalQrClose: vi.fn(),
|
||||||
handleStripeClose: vi.fn(),
|
handleStripeClose: vi.fn(),
|
||||||
handleStripeConfirmed: vi.fn(),
|
handleStripeConfirmed: vi.fn(),
|
||||||
isConfirmingEzpay: false,
|
isConfirmingEzpay: false,
|
||||||
|
regionalQrErrorMessage: null,
|
||||||
|
regionalQrPayment: null,
|
||||||
|
regionalQrStatus: null,
|
||||||
shouldShowEzpayConfirmDialog: false,
|
shouldShowEzpayConfirmDialog: false,
|
||||||
|
shouldShowRegionalQrDialog: false,
|
||||||
shouldShowStripeDialog: false,
|
shouldShowStripeDialog: false,
|
||||||
stripeClientSecret: null,
|
stripeClientSecret: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("PaymentLaunchDialogs", () => {
|
describe("PaymentLaunchDialogs", () => {
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||||
|
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
container = document.createElement("div");
|
||||||
|
container.style.transform = "translateX(50%)";
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => root.unmount());
|
||||||
|
container.remove();
|
||||||
|
document.body.style.overflow = "";
|
||||||
|
});
|
||||||
|
|
||||||
it("renders nothing when neither payment dialog is active", () => {
|
it("renders nothing when neither payment dialog is active", () => {
|
||||||
expect(
|
act(() =>
|
||||||
renderToStaticMarkup(
|
root.render(
|
||||||
<PaymentLaunchDialogs
|
<PaymentLaunchDialogs
|
||||||
currentOrderId={null}
|
currentOrderId={null}
|
||||||
externalCheckoutAnalyticsKey="payment.external_checkout"
|
externalCheckoutAnalyticsKey="payment.external_checkout"
|
||||||
@@ -25,28 +49,145 @@ describe("PaymentLaunchDialogs", () => {
|
|||||||
launch={hiddenLaunch}
|
launch={hiddenLaunch}
|
||||||
/>,
|
/>,
|
||||||
),
|
),
|
||||||
).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("renders the shared Ezpay confirmation content", () => {
|
|
||||||
const html = renderToStaticMarkup(
|
|
||||||
<PaymentLaunchDialogs
|
|
||||||
currentOrderId="order-123"
|
|
||||||
externalCheckoutAnalyticsKey="tip.external_checkout"
|
|
||||||
ezpayDescription="Your coffee order is ready."
|
|
||||||
launch={{
|
|
||||||
...hiddenLaunch,
|
|
||||||
isConfirmingEzpay: true,
|
|
||||||
shouldShowEzpayConfirmDialog: true,
|
|
||||||
}}
|
|
||||||
/>,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(html).toContain('role="alertdialog"');
|
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
|
||||||
expect(html).toContain("Continue to GCash?");
|
expect(document.body.querySelector('[role="alertdialog"]')).toBeNull();
|
||||||
expect(html).toContain("Your coffee order is ready.");
|
});
|
||||||
expect(html).toContain("Order No. order-123");
|
|
||||||
expect(html).toContain('data-analytics-key="tip.external_checkout"');
|
it("portals the shared Ezpay confirmation outside transformed checkout UI", () => {
|
||||||
expect(html).toContain("Opening...");
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<PaymentLaunchDialogs
|
||||||
|
currentOrderId="order-123"
|
||||||
|
externalCheckoutAnalyticsKey="tip.external_checkout"
|
||||||
|
ezpayDescription="Your coffee order is ready."
|
||||||
|
launch={{
|
||||||
|
...hiddenLaunch,
|
||||||
|
isConfirmingEzpay: true,
|
||||||
|
shouldShowEzpayConfirmDialog: true,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="alertdialog"]');
|
||||||
|
expect(dialog).not.toBeNull();
|
||||||
|
expect(container.contains(dialog)).toBe(false);
|
||||||
|
expect(dialog?.parentElement?.parentElement).toBe(document.body);
|
||||||
|
expect(dialog?.textContent).toContain("Continue to payment?");
|
||||||
|
expect(dialog?.textContent).toContain("Your coffee order is ready.");
|
||||||
|
expect(dialog?.textContent).toContain("Order No. order-123");
|
||||||
|
expect(
|
||||||
|
dialog?.querySelector("button[data-analytics-key]")?.getAttribute(
|
||||||
|
"data-analytics-key",
|
||||||
|
),
|
||||||
|
).toBe("tip.external_checkout");
|
||||||
|
expect(dialog?.textContent).toContain("Opening...");
|
||||||
|
expect(document.body.style.overflow).toBe("hidden");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("portals an accessible QRIS dialog with display cents and order status", () => {
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<PaymentLaunchDialogs
|
||||||
|
currentOrderId="order-id-qris"
|
||||||
|
externalCheckoutAnalyticsKey="tip.external_checkout"
|
||||||
|
ezpayDescription="Scan QRIS to finish the payment."
|
||||||
|
launch={{
|
||||||
|
...hiddenLaunch,
|
||||||
|
regionalQrPayment: {
|
||||||
|
qrData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
|
orderId: "order-id-qris",
|
||||||
|
amountCents: 5_000_000,
|
||||||
|
currency: "IDR",
|
||||||
|
experience: "qris",
|
||||||
|
},
|
||||||
|
regionalQrStatus: "pending",
|
||||||
|
shouldShowRegionalQrDialog: true,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="dialog"]');
|
||||||
|
expect(dialog).not.toBeNull();
|
||||||
|
expect(container.contains(dialog)).toBe(false);
|
||||||
|
expect(dialog?.textContent).toContain("Scan to pay with QRIS");
|
||||||
|
expect(dialog?.querySelector("svg title")?.textContent).toBe(
|
||||||
|
"QRIS payment QR code",
|
||||||
|
);
|
||||||
|
expect(dialog?.textContent).toContain("Order No. order-id-qris");
|
||||||
|
expect(dialog?.textContent).toContain("Rp");
|
||||||
|
expect(dialog?.textContent).toContain("50.000");
|
||||||
|
expect(dialog?.textContent).toContain("Waiting for payment");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("labels a Philippine QR fallback as GCash / QR Ph", () => {
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<PaymentLaunchDialogs
|
||||||
|
currentOrderId="order-ph-qr"
|
||||||
|
externalCheckoutAnalyticsKey="payment.external_checkout"
|
||||||
|
ezpayDescription="Pay with GCash."
|
||||||
|
launch={{
|
||||||
|
...hiddenLaunch,
|
||||||
|
regionalQrPayment: {
|
||||||
|
qrData: "000201010212ph-qr-payload",
|
||||||
|
orderId: "order-ph-qr",
|
||||||
|
amountCents: 49_990,
|
||||||
|
currency: "PHP",
|
||||||
|
experience: "gcashQrPh",
|
||||||
|
},
|
||||||
|
regionalQrStatus: "pending",
|
||||||
|
shouldShowRegionalQrDialog: true,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="dialog"]');
|
||||||
|
expect(dialog?.textContent).toContain("Pay with GCash / QR Ph");
|
||||||
|
expect(dialog?.textContent).not.toContain("QRIS");
|
||||||
|
expect(dialog?.querySelector("svg title")?.textContent).toBe(
|
||||||
|
"GCash / QR Ph payment QR code",
|
||||||
|
);
|
||||||
|
expect(dialog?.textContent).toContain("₱");
|
||||||
|
|
||||||
|
const closeButton = Array.from(
|
||||||
|
dialog?.querySelectorAll("button") ?? [],
|
||||||
|
).find((button) => button.textContent?.trim() === "Close");
|
||||||
|
act(() => closeButton?.click());
|
||||||
|
expect(hiddenLaunch.handleRegionalQrClose).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows QRIS failure state and handles empty QR data safely", () => {
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<PaymentLaunchDialogs
|
||||||
|
currentOrderId="order-id-qris"
|
||||||
|
externalCheckoutAnalyticsKey="payment.external_checkout"
|
||||||
|
ezpayDescription="Scan QRIS to finish the payment."
|
||||||
|
launch={{
|
||||||
|
...hiddenLaunch,
|
||||||
|
regionalQrErrorMessage: "Payment failed or was cancelled.",
|
||||||
|
regionalQrPayment: {
|
||||||
|
qrData: "",
|
||||||
|
orderId: "order-id-qris",
|
||||||
|
amountCents: 5_000_000,
|
||||||
|
currency: "IDR",
|
||||||
|
experience: "qris",
|
||||||
|
},
|
||||||
|
regionalQrStatus: "failed",
|
||||||
|
shouldShowRegionalQrDialog: true,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="dialog"]');
|
||||||
|
expect(dialog?.textContent).toContain("QRIS data is unavailable");
|
||||||
|
expect(dialog?.textContent).toContain("Payment failed or was cancelled.");
|
||||||
|
expect(dialog?.textContent).toContain("Close");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -62,6 +62,27 @@ describe("PaymentMethodSelector", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("labels Indonesia Ezpay as QRIS without the GCash logo", () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<PaymentMethodSelector
|
||||||
|
config={{
|
||||||
|
canChoosePaymentMethod: true,
|
||||||
|
initialPayChannel: "ezpay",
|
||||||
|
showPaymentMethodSelector: true,
|
||||||
|
ezpayDisplayName: "QRIS",
|
||||||
|
}}
|
||||||
|
value="ezpay"
|
||||||
|
caption="QRIS by default in Indonesia"
|
||||||
|
analyticsKey="subscription.payment_method"
|
||||||
|
onChange={() => undefined}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(html).toContain('aria-label="QRIS"');
|
||||||
|
expect(html).toContain("QRIS by default in Indonesia");
|
||||||
|
expect(html).not.toContain("gcash-logo.svg");
|
||||||
|
});
|
||||||
|
|
||||||
it("renders compact controls without the caption", () => {
|
it("renders compact controls without the caption", () => {
|
||||||
const html = renderToStaticMarkup(
|
const html = renderToStaticMarkup(
|
||||||
<PaymentMethodSelector
|
<PaymentMethodSelector
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { act } from "react";
|
||||||
|
import { createRoot, type Root } from "react-dom/client";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { StripePaymentDialogLoading } from "../lazy-stripe-payment-dialog";
|
||||||
|
import { StripePaymentDialog } from "../stripe-payment-dialog";
|
||||||
|
|
||||||
|
describe("Stripe payment portal states", () => {
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||||
|
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
container = document.createElement("div");
|
||||||
|
container.style.transform = "translateX(50%)";
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = createRoot(container);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => root.unmount());
|
||||||
|
container.remove();
|
||||||
|
document.body.style.overflow = "";
|
||||||
|
});
|
||||||
|
|
||||||
|
it("portals the unavailable state and keeps its explicit close action", () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<StripePaymentDialog
|
||||||
|
clientSecret="client-secret"
|
||||||
|
onClose={onClose}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="alertdialog"]');
|
||||||
|
expect(dialog).not.toBeNull();
|
||||||
|
expect(container.contains(dialog)).toBe(false);
|
||||||
|
expect(dialog?.textContent).toContain("Payment unavailable");
|
||||||
|
expect(dialog?.getAttribute("aria-labelledby")).toBeTruthy();
|
||||||
|
expect(dialog?.getAttribute("aria-describedby")).toBeTruthy();
|
||||||
|
|
||||||
|
const okButton = Array.from(dialog?.querySelectorAll("button") ?? []).find(
|
||||||
|
(button) => button.textContent === "OK",
|
||||||
|
);
|
||||||
|
act(() => okButton?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
|
||||||
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("portals the lazy loading state", () => {
|
||||||
|
act(() => root.render(<StripePaymentDialogLoading />));
|
||||||
|
|
||||||
|
const dialog = document.body.querySelector('[role="dialog"]');
|
||||||
|
expect(dialog).not.toBeNull();
|
||||||
|
expect(container.contains(dialog)).toBe(false);
|
||||||
|
expect(dialog?.textContent).toContain("Preparing secure payment");
|
||||||
|
expect(dialog?.textContent).toContain("Loading payment methods...");
|
||||||
|
expect(dialog?.querySelector('[aria-busy="true"]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
|
|
||||||
|
import { ModalPortal } from "@/app/_components/core/modal-portal";
|
||||||
|
|
||||||
import type { StripePaymentDialogProps } from "./stripe-payment-dialog";
|
import type { StripePaymentDialogProps } from "./stripe-payment-dialog";
|
||||||
import { stripePaymentDialogStyles as styles } from "./stripe-payment-dialog.styles";
|
import { stripePaymentDialogStyles as styles } from "./stripe-payment-dialog.styles";
|
||||||
|
|
||||||
@@ -20,22 +22,28 @@ export function LazyStripePaymentDialog(props: StripePaymentDialogProps) {
|
|||||||
return <StripePaymentDialog {...props} />;
|
return <StripePaymentDialog {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function StripePaymentDialogLoading() {
|
export function StripePaymentDialogLoading() {
|
||||||
return (
|
return (
|
||||||
<div
|
<ModalPortal
|
||||||
className={styles.overlay}
|
open
|
||||||
role="dialog"
|
persistent
|
||||||
aria-modal="true"
|
onClose={() => undefined}
|
||||||
aria-labelledby="stripe-payment-loading-title"
|
scrimClassName={styles.overlay}
|
||||||
|
panelClassName={styles.dialog}
|
||||||
|
scrimOpacity={0.5}
|
||||||
|
ariaLabelledBy="stripe-payment-loading-title"
|
||||||
|
ariaDescribedBy="stripe-payment-loading-description"
|
||||||
>
|
>
|
||||||
<div className={styles.dialog} aria-busy="true">
|
<div aria-busy="true">
|
||||||
<div className={styles.header}>
|
<div className={styles.header}>
|
||||||
<h2 id="stripe-payment-loading-title" className={styles.title}>
|
<h2 id="stripe-payment-loading-title" className={styles.title}>
|
||||||
Preparing secure payment
|
Preparing secure payment
|
||||||
</h2>
|
</h2>
|
||||||
<p className={styles.content}>Loading payment methods...</p>
|
<p id="stripe-payment-loading-description" className={styles.content}>
|
||||||
|
Loading payment methods...
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</ModalPortal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useId, type ReactNode } from "react";
|
import { useId, type ReactNode } from "react";
|
||||||
|
import { QRCodeSVG } from "qrcode.react";
|
||||||
|
|
||||||
|
import { ModalPortal } from "@/app/_components/core/modal-portal";
|
||||||
import type { PaymentLaunchFlow } from "@/app/_hooks/use-payment-launch-flow";
|
import type { PaymentLaunchFlow } from "@/app/_hooks/use-payment-launch-flow";
|
||||||
|
|
||||||
import { LazyStripePaymentDialog } from "./lazy-stripe-payment-dialog";
|
import { LazyStripePaymentDialog } from "./lazy-stripe-payment-dialog";
|
||||||
@@ -11,10 +13,15 @@ type PaymentLaunchDialogFlow = Pick<
|
|||||||
PaymentLaunchFlow,
|
PaymentLaunchFlow,
|
||||||
| "handleEzpayCancel"
|
| "handleEzpayCancel"
|
||||||
| "handleEzpayConfirm"
|
| "handleEzpayConfirm"
|
||||||
|
| "handleRegionalQrClose"
|
||||||
| "handleStripeClose"
|
| "handleStripeClose"
|
||||||
| "handleStripeConfirmed"
|
| "handleStripeConfirmed"
|
||||||
| "isConfirmingEzpay"
|
| "isConfirmingEzpay"
|
||||||
|
| "regionalQrErrorMessage"
|
||||||
|
| "regionalQrPayment"
|
||||||
|
| "regionalQrStatus"
|
||||||
| "shouldShowEzpayConfirmDialog"
|
| "shouldShowEzpayConfirmDialog"
|
||||||
|
| "shouldShowRegionalQrDialog"
|
||||||
| "shouldShowStripeDialog"
|
| "shouldShowStripeDialog"
|
||||||
| "stripeClientSecret"
|
| "stripeClientSecret"
|
||||||
>;
|
>;
|
||||||
@@ -46,6 +53,14 @@ export function PaymentLaunchDialogs({
|
|||||||
onConfirm={launch.handleEzpayConfirm}
|
onConfirm={launch.handleEzpayConfirm}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
{launch.shouldShowRegionalQrDialog && launch.regionalQrPayment ? (
|
||||||
|
<RegionalQrPaymentDialog
|
||||||
|
payment={launch.regionalQrPayment}
|
||||||
|
status={launch.regionalQrStatus}
|
||||||
|
errorMessage={launch.regionalQrErrorMessage}
|
||||||
|
onClose={launch.handleRegionalQrClose}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
{launch.shouldShowStripeDialog && launch.stripeClientSecret ? (
|
{launch.shouldShowStripeDialog && launch.stripeClientSecret ? (
|
||||||
<LazyStripePaymentDialog
|
<LazyStripePaymentDialog
|
||||||
clientSecret={launch.stripeClientSecret}
|
clientSecret={launch.stripeClientSecret}
|
||||||
@@ -58,6 +73,151 @@ export function PaymentLaunchDialogs({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface RegionalQrPaymentDialogProps {
|
||||||
|
errorMessage: string | null;
|
||||||
|
onClose: () => void;
|
||||||
|
payment: NonNullable<PaymentLaunchFlow["regionalQrPayment"]>;
|
||||||
|
status: PaymentLaunchFlow["regionalQrStatus"];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRegionalQrAmount(amountCents: number, currency: string): string {
|
||||||
|
const normalizedCurrency = currency.trim().toUpperCase() || "IDR";
|
||||||
|
try {
|
||||||
|
return new Intl.NumberFormat(
|
||||||
|
normalizedCurrency === "PHP" ? "en-PH" : "id-ID",
|
||||||
|
{
|
||||||
|
style: "currency",
|
||||||
|
currency: normalizedCurrency,
|
||||||
|
maximumFractionDigits: normalizedCurrency === "IDR" ? 0 : 2,
|
||||||
|
},
|
||||||
|
).format(amountCents / 100);
|
||||||
|
} catch {
|
||||||
|
return `${normalizedCurrency} ${(amountCents / 100).toFixed(2)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function regionalQrStatusMessage(
|
||||||
|
status: PaymentLaunchFlow["regionalQrStatus"],
|
||||||
|
errorMessage: string | null,
|
||||||
|
paymentName: string,
|
||||||
|
): string {
|
||||||
|
if (status === "failed") {
|
||||||
|
return errorMessage || "Payment failed. Please try again.";
|
||||||
|
}
|
||||||
|
if (status === "expired") {
|
||||||
|
return errorMessage || `This ${paymentName} order has expired.`;
|
||||||
|
}
|
||||||
|
return "Waiting for payment";
|
||||||
|
}
|
||||||
|
|
||||||
|
function RegionalQrPaymentDialog({
|
||||||
|
errorMessage,
|
||||||
|
onClose,
|
||||||
|
payment,
|
||||||
|
status,
|
||||||
|
}: RegionalQrPaymentDialogProps) {
|
||||||
|
const titleId = useId();
|
||||||
|
const copy = regionalQrCopy(payment.experience);
|
||||||
|
const statusMessage = regionalQrStatusMessage(
|
||||||
|
status,
|
||||||
|
errorMessage,
|
||||||
|
copy.paymentName,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ModalPortal
|
||||||
|
open
|
||||||
|
persistent
|
||||||
|
onClose={onClose}
|
||||||
|
scrimClassName={styles.overlay}
|
||||||
|
panelClassName={styles.dialog}
|
||||||
|
scrimOpacity={0.5}
|
||||||
|
ariaLabelledBy={titleId}
|
||||||
|
>
|
||||||
|
<div className={`${styles.header} text-center`}>
|
||||||
|
<h2 id={titleId} className={styles.title}>
|
||||||
|
{copy.title}
|
||||||
|
</h2>
|
||||||
|
<p className={styles.content}>
|
||||||
|
{copy.description}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="mb-4 flex min-h-64 items-center justify-center rounded-2xl bg-white p-4">
|
||||||
|
{payment.qrData ? (
|
||||||
|
<QRCodeSVG
|
||||||
|
value={payment.qrData}
|
||||||
|
title={copy.qrTitle}
|
||||||
|
size={256}
|
||||||
|
level="M"
|
||||||
|
marginSize={2}
|
||||||
|
className="h-auto w-full max-w-64"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p className={styles.error} role="alert">
|
||||||
|
{copy.unavailableMessage}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mb-4 flex flex-col gap-2 text-center">
|
||||||
|
<p className={styles.content}>Order No. {payment.orderId}</p>
|
||||||
|
<p className="m-0 text-xl font-bold text-text-foreground">
|
||||||
|
{formatRegionalQrAmount(payment.amountCents, payment.currency)}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
className={status === "failed" || status === "expired" ? styles.error : styles.content}
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
{statusMessage}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className={styles.actions}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`${styles.button} ${styles.secondary}`}
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</ModalPortal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function regionalQrCopy(
|
||||||
|
experience: NonNullable<PaymentLaunchFlow["regionalQrPayment"]>["experience"],
|
||||||
|
) {
|
||||||
|
if (experience === "gcashQrPh") {
|
||||||
|
return {
|
||||||
|
paymentName: "GCash / QR Ph",
|
||||||
|
title: "Pay with GCash / QR Ph",
|
||||||
|
description:
|
||||||
|
"Open GCash or another QR Ph-compatible app and scan this code.",
|
||||||
|
qrTitle: "GCash / QR Ph payment QR code",
|
||||||
|
unavailableMessage:
|
||||||
|
"GCash / QR Ph data is unavailable. Please close this dialog and try again.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (experience === "qris") {
|
||||||
|
return {
|
||||||
|
paymentName: "QRIS",
|
||||||
|
title: "Scan to pay with QRIS",
|
||||||
|
description:
|
||||||
|
"Open a QRIS-compatible banking or wallet app and scan this code.",
|
||||||
|
qrTitle: "QRIS payment QR code",
|
||||||
|
unavailableMessage:
|
||||||
|
"QRIS data is unavailable. Please close this dialog and try again.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
paymentName: "payment QR",
|
||||||
|
title: "Scan to pay",
|
||||||
|
description: "Open a compatible banking or wallet app and scan this code.",
|
||||||
|
qrTitle: "Payment QR code",
|
||||||
|
unavailableMessage:
|
||||||
|
"Payment QR data is unavailable. Please close this dialog and try again.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface EzpayRedirectConfirmDialogProps {
|
interface EzpayRedirectConfirmDialogProps {
|
||||||
description: ReactNode;
|
description: ReactNode;
|
||||||
externalCheckoutAnalyticsKey: string;
|
externalCheckoutAnalyticsKey: string;
|
||||||
@@ -78,41 +238,43 @@ function EzpayRedirectConfirmDialog({
|
|||||||
const titleId = useId();
|
const titleId = useId();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<ModalPortal
|
||||||
className={styles.overlay}
|
open
|
||||||
|
persistent
|
||||||
|
onClose={onCancel}
|
||||||
|
scrimClassName={styles.overlay}
|
||||||
|
panelClassName={styles.dialog}
|
||||||
|
scrimOpacity={0.5}
|
||||||
role="alertdialog"
|
role="alertdialog"
|
||||||
aria-modal="true"
|
ariaLabelledBy={titleId}
|
||||||
aria-labelledby={titleId}
|
|
||||||
>
|
>
|
||||||
<div className={styles.dialog}>
|
<div className={styles.header}>
|
||||||
<div className={styles.header}>
|
<h2 id={titleId} className={styles.title}>
|
||||||
<h2 id={titleId} className={styles.title}>
|
Continue to payment?
|
||||||
Continue to GCash?
|
</h2>
|
||||||
</h2>
|
<p className={styles.content}>{description}</p>
|
||||||
<p className={styles.content}>{description}</p>
|
<p className={styles.content}>Order No. {orderId}</p>
|
||||||
<p className={styles.content}>Order No. {orderId}</p>
|
|
||||||
</div>
|
|
||||||
<div className={styles.actions}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`${styles.button} ${styles.secondary}`}
|
|
||||||
disabled={isConfirming}
|
|
||||||
onClick={onCancel}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
data-analytics-key={externalCheckoutAnalyticsKey}
|
|
||||||
data-analytics-label="Continue to external checkout"
|
|
||||||
className={`${styles.button} ${styles.primary}`}
|
|
||||||
disabled={isConfirming}
|
|
||||||
onClick={onConfirm}
|
|
||||||
>
|
|
||||||
{isConfirming ? "Opening..." : "Continue"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className={styles.actions}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`${styles.button} ${styles.secondary}`}
|
||||||
|
disabled={isConfirming}
|
||||||
|
onClick={onCancel}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-analytics-key={externalCheckoutAnalyticsKey}
|
||||||
|
data-analytics-label="Continue to external checkout"
|
||||||
|
className={`${styles.button} ${styles.primary}`}
|
||||||
|
disabled={isConfirming}
|
||||||
|
onClick={onConfirm}
|
||||||
|
>
|
||||||
|
{isConfirming ? "Opening..." : "Continue"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</ModalPortal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,13 +44,24 @@ export function PaymentMethodSelector({
|
|||||||
}: PaymentMethodSelectorProps) {
|
}: PaymentMethodSelectorProps) {
|
||||||
if (!config.showPaymentMethodSelector) return null;
|
if (!config.showPaymentMethodSelector) return null;
|
||||||
const isCompact = density === "compact";
|
const isCompact = density === "compact";
|
||||||
|
const ezpayDisplayName = config.ezpayDisplayName ?? "GCash";
|
||||||
|
const configuredPaymentMethods = PAYMENT_METHODS.map((method) =>
|
||||||
|
method.channel === "ezpay"
|
||||||
|
? {
|
||||||
|
...method,
|
||||||
|
title: ezpayDisplayName,
|
||||||
|
logoSrc:
|
||||||
|
ezpayDisplayName === "GCash" ? method.logoSrc : undefined,
|
||||||
|
}
|
||||||
|
: method,
|
||||||
|
);
|
||||||
|
|
||||||
const paymentMethods =
|
const paymentMethods =
|
||||||
config.initialPayChannel === "ezpay"
|
config.initialPayChannel === "ezpay"
|
||||||
? [...PAYMENT_METHODS].sort((a, b) =>
|
? [...configuredPaymentMethods].sort((a, b) =>
|
||||||
a.channel === "ezpay" ? -1 : b.channel === "ezpay" ? 1 : 0,
|
a.channel === "ezpay" ? -1 : b.channel === "ezpay" ? 1 : 0,
|
||||||
)
|
)
|
||||||
: PAYMENT_METHODS;
|
: configuredPaymentMethods;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ export const stripePaymentDialogStyles = {
|
|||||||
overlay:
|
overlay:
|
||||||
"fixed inset-0 z-70 flex items-center justify-center bg-[rgba(0,0,0,0.5)] pb-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-bottom,0))] pl-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-left,0))] pr-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-right,0))] pt-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-top,0))]",
|
"fixed inset-0 z-70 flex items-center justify-center bg-[rgba(0,0,0,0.5)] pb-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-bottom,0))] pl-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-left,0))] pr-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-right,0))] pt-[calc(var(--dialog-safe-margin,20px)+var(--app-safe-top,0))]",
|
||||||
dialog:
|
dialog:
|
||||||
"max-h-[calc(var(--app-visible-height,100dvh)-calc(var(--dialog-safe-margin,20px)*2))] w-full max-w-(--dialog-wide-max-width,420px) overflow-y-auto rounded-(--responsive-card-radius,32px) bg-(--color-page-background,#ffffff) px-(--responsive-card-padding,18px) pb-(--responsive-card-padding,18px) pt-(--responsive-card-padding-lg,24px) shadow-[0_18px_40px_rgba(0,0,0,0.16)]",
|
"max-h-[calc(var(--app-visible-height,100dvh)-calc(var(--dialog-safe-margin,20px)*2))] w-full max-w-(--dialog-wide-max-width,420px) overflow-y-auto overscroll-contain rounded-(--responsive-card-radius,32px) bg-(--color-page-background,#ffffff) px-(--responsive-card-padding,18px) pb-(--responsive-card-padding,18px) pt-(--responsive-card-padding-lg,24px) shadow-[0_18px_40px_rgba(0,0,0,0.16)]",
|
||||||
header: "mb-(--page-section-gap,18px) text-left",
|
header: "mb-(--page-section-gap,18px) text-left",
|
||||||
title:
|
title:
|
||||||
"m-0 mb-[clamp(7px,1.481vw,8px)] text-(length:--responsive-page-title,22px) font-bold leading-[1.2] text-text-foreground",
|
"m-0 mb-[clamp(7px,1.481vw,8px)] text-(length:--responsive-page-title,22px) font-bold leading-[1.2] text-text-foreground",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
*
|
*
|
||||||
* 后端当前返回 PaymentIntent clientSecret,因此这里直接用它完成前端确认。
|
* 后端当前返回 PaymentIntent clientSecret,因此这里直接用它完成前端确认。
|
||||||
*/
|
*/
|
||||||
import { useState, type FormEvent } from "react";
|
import { useId, useState, type FormEvent } from "react";
|
||||||
import {
|
import {
|
||||||
Elements,
|
Elements,
|
||||||
PaymentElement,
|
PaymentElement,
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from "@stripe/react-stripe-js";
|
} from "@stripe/react-stripe-js";
|
||||||
import { loadStripe } from "@stripe/stripe-js";
|
import { loadStripe } from "@stripe/stripe-js";
|
||||||
|
|
||||||
|
import { ModalPortal } from "@/app/_components/core/modal-portal";
|
||||||
import { ExceptionHandler } from "@/core/errors";
|
import { ExceptionHandler } from "@/core/errors";
|
||||||
import { ROUTES } from "@/router/routes";
|
import { ROUTES } from "@/router/routes";
|
||||||
import { Logger } from "@/utils/logger";
|
import { Logger } from "@/utils/logger";
|
||||||
@@ -38,69 +39,84 @@ export function StripePaymentDialog({
|
|||||||
onClose,
|
onClose,
|
||||||
onConfirmed,
|
onConfirmed,
|
||||||
}: StripePaymentDialogProps) {
|
}: StripePaymentDialogProps) {
|
||||||
|
const titleId = useId();
|
||||||
|
const descriptionId = useId();
|
||||||
|
|
||||||
if (!stripePromise) {
|
if (!stripePromise) {
|
||||||
return (
|
return (
|
||||||
<div className={styles.overlay} role="alertdialog" aria-modal="true">
|
<ModalPortal
|
||||||
<div className={styles.dialog}>
|
open
|
||||||
<div className={styles.header}>
|
persistent
|
||||||
<h2 className={styles.title}>Payment unavailable</h2>
|
onClose={onClose}
|
||||||
<p className={styles.content}>
|
scrimClassName={styles.overlay}
|
||||||
Stripe publishable key is not configured for this build.
|
panelClassName={styles.dialog}
|
||||||
</p>
|
scrimOpacity={0.5}
|
||||||
</div>
|
role="alertdialog"
|
||||||
<div className={styles.actions}>
|
ariaLabelledBy={titleId}
|
||||||
<button
|
ariaDescribedBy={descriptionId}
|
||||||
type="button"
|
>
|
||||||
className={`${styles.button} ${styles.primary}`}
|
<div className={styles.header}>
|
||||||
onClick={onClose}
|
<h2 id={titleId} className={styles.title}>
|
||||||
>
|
Payment unavailable
|
||||||
OK
|
</h2>
|
||||||
</button>
|
<p id={descriptionId} className={styles.content}>
|
||||||
</div>
|
Stripe publishable key is not configured for this build.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className={styles.actions}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`${styles.button} ${styles.primary}`}
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
OK
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</ModalPortal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<ModalPortal
|
||||||
className={styles.overlay}
|
open
|
||||||
role="dialog"
|
persistent
|
||||||
aria-modal="true"
|
onClose={onClose}
|
||||||
aria-labelledby="stripe-payment-title"
|
scrimClassName={styles.overlay}
|
||||||
|
panelClassName={styles.dialog}
|
||||||
|
scrimOpacity={0.5}
|
||||||
|
ariaLabelledBy={titleId}
|
||||||
|
ariaDescribedBy={descriptionId}
|
||||||
>
|
>
|
||||||
<div className={styles.dialog}>
|
<div className={styles.header}>
|
||||||
<div className={styles.header}>
|
<h2 id={titleId} className={styles.title}>
|
||||||
<h2 id="stripe-payment-title" className={styles.title}>
|
Complete payment
|
||||||
Complete payment
|
</h2>
|
||||||
</h2>
|
<p id={descriptionId} className={styles.content}>
|
||||||
<p className={styles.content}>
|
Enter your payment details securely through Stripe.
|
||||||
Enter your payment details securely through Stripe.
|
</p>
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Elements
|
|
||||||
key={clientSecret}
|
|
||||||
stripe={stripePromise}
|
|
||||||
options={{
|
|
||||||
clientSecret,
|
|
||||||
appearance: {
|
|
||||||
theme: "stripe",
|
|
||||||
variables: {
|
|
||||||
borderRadius: "14px",
|
|
||||||
colorPrimary: "#ff52a2",
|
|
||||||
colorText: "#171717",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<StripePaymentForm
|
|
||||||
returnPath={returnPath}
|
|
||||||
onClose={onClose}
|
|
||||||
onConfirmed={onConfirmed}
|
|
||||||
/>
|
|
||||||
</Elements>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<Elements
|
||||||
|
key={clientSecret}
|
||||||
|
stripe={stripePromise}
|
||||||
|
options={{
|
||||||
|
clientSecret,
|
||||||
|
appearance: {
|
||||||
|
theme: "stripe",
|
||||||
|
variables: {
|
||||||
|
borderRadius: "14px",
|
||||||
|
colorPrimary: "#ff52a2",
|
||||||
|
colorText: "#171717",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<StripePaymentForm
|
||||||
|
returnPath={returnPath}
|
||||||
|
onClose={onClose}
|
||||||
|
onConfirmed={onConfirmed}
|
||||||
|
/>
|
||||||
|
</Elements>
|
||||||
|
</ModalPortal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,19 +2,30 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
|
||||||
export interface UserMessageAvatarProps {
|
import type { AvatarInteractionProps } from "./avatar-interaction";
|
||||||
|
|
||||||
|
interface UserMessageAvatarVisualProps {
|
||||||
avatarUrl?: string | null;
|
avatarUrl?: string | null;
|
||||||
className?: string;
|
className?: string;
|
||||||
size?: number | string;
|
size?: number | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type UserMessageAvatarProps = UserMessageAvatarVisualProps &
|
||||||
|
AvatarInteractionProps;
|
||||||
|
|
||||||
export function UserMessageAvatar({
|
export function UserMessageAvatar({
|
||||||
avatarUrl,
|
avatarUrl,
|
||||||
className,
|
className,
|
||||||
size = 43,
|
size = 43,
|
||||||
|
onClick,
|
||||||
|
actionLabel,
|
||||||
|
analyticsKey,
|
||||||
}: UserMessageAvatarProps) {
|
}: UserMessageAvatarProps) {
|
||||||
const avatarClassName = [
|
const avatarClassName = [
|
||||||
"flex shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-(--color-avatar-border,#fbf3f5) bg-(--color-avatar-border,#fbf3f5) shadow-(--shadow-input-box,0_1px_2px_rgba(0,0,0,0.1))",
|
"flex shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-(--color-avatar-border,#fbf3f5) bg-(--color-avatar-border,#fbf3f5) shadow-(--shadow-input-box,0_1px_2px_rgba(0,0,0,0.1))",
|
||||||
|
onClick
|
||||||
|
? "cursor-pointer p-0 transition-transform duration-150 focus-visible:outline-3 focus-visible:outline-offset-3 focus-visible:outline-accent active:scale-96"
|
||||||
|
: undefined,
|
||||||
className,
|
className,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
@@ -22,21 +33,30 @@ export function UserMessageAvatar({
|
|||||||
const avatarStyle = { width: size, height: size };
|
const avatarStyle = { width: size, height: size };
|
||||||
const imageSize = typeof size === "number" ? size : 64;
|
const imageSize = typeof size === "number" ? size : 64;
|
||||||
|
|
||||||
if (avatarUrl && avatarUrl.length > 0) {
|
const hasUserAvatar = Boolean(avatarUrl && avatarUrl.length > 0);
|
||||||
|
const image = (
|
||||||
|
<Image
|
||||||
|
src={hasUserAvatar ? avatarUrl! : "/images/avatar/placeholder.png"}
|
||||||
|
alt={hasUserAvatar ? "" : "Guest"}
|
||||||
|
width={imageSize}
|
||||||
|
height={imageSize}
|
||||||
|
className="size-full object-cover"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (onClick) {
|
||||||
return (
|
return (
|
||||||
<div
|
<button
|
||||||
|
type="button"
|
||||||
className={avatarClassName}
|
className={avatarClassName}
|
||||||
style={avatarStyle}
|
style={avatarStyle}
|
||||||
aria-label="User avatar"
|
aria-label={actionLabel}
|
||||||
|
data-analytics-key={analyticsKey}
|
||||||
|
data-analytics-label={actionLabel}
|
||||||
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
<Image
|
{image}
|
||||||
src={avatarUrl}
|
</button>
|
||||||
alt=""
|
|
||||||
width={imageSize}
|
|
||||||
height={imageSize}
|
|
||||||
className="size-full object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,15 +64,9 @@ export function UserMessageAvatar({
|
|||||||
<div
|
<div
|
||||||
className={avatarClassName}
|
className={avatarClassName}
|
||||||
style={avatarStyle}
|
style={avatarStyle}
|
||||||
aria-label="Guest avatar"
|
aria-label={hasUserAvatar ? "User avatar" : "Guest avatar"}
|
||||||
>
|
>
|
||||||
<Image
|
{image}
|
||||||
src="/images/avatar/placeholder.png"
|
|
||||||
alt="Guest"
|
|
||||||
width={imageSize}
|
|
||||||
height={imageSize}
|
|
||||||
className="size-full object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import { type Dispatch, useEffect, useRef, useState } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
getPaymentUrl,
|
getPaymentUrl,
|
||||||
|
getPaymentUrlHostname,
|
||||||
getStripeClientSecret,
|
getStripeClientSecret,
|
||||||
isEzpayPayment,
|
isEzpayPayment,
|
||||||
launchEzpayRedirect,
|
launchEzpayRedirect,
|
||||||
|
resolveEzpayLaunchTarget,
|
||||||
} from "@/lib/payment/payment_launch";
|
} from "@/lib/payment/payment_launch";
|
||||||
import { behaviorAnalytics } from "@/lib/analytics";
|
import { behaviorAnalytics } from "@/lib/analytics";
|
||||||
import type {
|
import type {
|
||||||
@@ -40,21 +42,63 @@ export interface UsePaymentLaunchFlowInput {
|
|||||||
subscriptionType: PendingPaymentSubscriptionType;
|
subscriptionType: PendingPaymentSubscriptionType;
|
||||||
giftCategory?: string | null;
|
giftCategory?: string | null;
|
||||||
giftPlanId?: string | null;
|
giftPlanId?: string | null;
|
||||||
|
countryCode?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PaymentLaunchFlow {
|
export interface PaymentLaunchFlow {
|
||||||
ezpayPaymentUrl: string | null;
|
ezpayPaymentUrl: string | null;
|
||||||
handleEzpayCancel: () => void;
|
handleEzpayCancel: () => void;
|
||||||
handleEzpayConfirm: () => void;
|
handleEzpayConfirm: () => void;
|
||||||
|
handleRegionalQrClose: () => void;
|
||||||
handleStripeClose: () => void;
|
handleStripeClose: () => void;
|
||||||
handleStripeConfirmed: () => void;
|
handleStripeConfirmed: () => void;
|
||||||
isConfirmingEzpay: boolean;
|
isConfirmingEzpay: boolean;
|
||||||
|
regionalQrErrorMessage: string | null;
|
||||||
|
regionalQrPayment: RegionalQrPaymentDetails | null;
|
||||||
|
regionalQrStatus: PaymentContextState["orderStatus"];
|
||||||
resetLaunchState: () => void;
|
resetLaunchState: () => void;
|
||||||
shouldShowEzpayConfirmDialog: boolean;
|
shouldShowEzpayConfirmDialog: boolean;
|
||||||
|
shouldShowRegionalQrDialog: boolean;
|
||||||
shouldShowStripeDialog: boolean;
|
shouldShowStripeDialog: boolean;
|
||||||
stripeClientSecret: string | null;
|
stripeClientSecret: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RegionalQrPaymentDetails {
|
||||||
|
amountCents: number;
|
||||||
|
currency: string;
|
||||||
|
experience: "gcashQrPh" | "qris" | "paymentQr";
|
||||||
|
orderId: string;
|
||||||
|
qrData: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function paymentParamString(
|
||||||
|
payParams: Record<string, unknown>,
|
||||||
|
...keys: string[]
|
||||||
|
): string | null {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = payParams[key];
|
||||||
|
if (typeof value === "string" && value.trim()) return value.trim();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function paymentParamAmountCents(
|
||||||
|
payParams: Record<string, unknown>,
|
||||||
|
): number | null {
|
||||||
|
for (const key of [
|
||||||
|
"firstChargeAmountCents",
|
||||||
|
"first_charge_amount_cents",
|
||||||
|
"amountCents",
|
||||||
|
"amount_cents",
|
||||||
|
]) {
|
||||||
|
const value = payParams[key];
|
||||||
|
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function trackPaymentCheckoutOpened(
|
function trackPaymentCheckoutOpened(
|
||||||
payment: PaymentContextState,
|
payment: PaymentContextState,
|
||||||
checkoutUrl: string,
|
checkoutUrl: string,
|
||||||
@@ -112,6 +156,7 @@ export function usePaymentLaunchFlow({
|
|||||||
subscriptionType,
|
subscriptionType,
|
||||||
giftCategory,
|
giftCategory,
|
||||||
giftPlanId,
|
giftPlanId,
|
||||||
|
countryCode,
|
||||||
}: UsePaymentLaunchFlowInput): PaymentLaunchFlow {
|
}: UsePaymentLaunchFlowInput): PaymentLaunchFlow {
|
||||||
const launchedNonceRef = useRef(0);
|
const launchedNonceRef = useRef(0);
|
||||||
const [hiddenStripeClientSecret, setHiddenStripeClientSecret] = useState<
|
const [hiddenStripeClientSecret, setHiddenStripeClientSecret] = useState<
|
||||||
@@ -121,9 +166,42 @@ export function usePaymentLaunchFlow({
|
|||||||
const stripeClientSecret = payment.payParams
|
const stripeClientSecret = payment.payParams
|
||||||
? getStripeClientSecret(payment.payParams)
|
? getStripeClientSecret(payment.payParams)
|
||||||
: null;
|
: null;
|
||||||
const ezpayPaymentUrl = payment.payParams
|
const selectedPlan = payment.plans.find(
|
||||||
? getPaymentUrl(payment.payParams)
|
(item) => item.planId === payment.selectedPlanId,
|
||||||
: null;
|
);
|
||||||
|
const paymentCurrency = payment.payParams
|
||||||
|
? paymentParamString(payment.payParams, "currency") ??
|
||||||
|
selectedPlan?.currency ??
|
||||||
|
null
|
||||||
|
: selectedPlan?.currency ?? null;
|
||||||
|
const ezpayLaunchTarget =
|
||||||
|
payment.payParams && isEzpayPayment(payment.payParams)
|
||||||
|
? resolveEzpayLaunchTarget(payment.payParams, {
|
||||||
|
countryCode,
|
||||||
|
currency: paymentCurrency,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
const ezpayPaymentUrl =
|
||||||
|
ezpayLaunchTarget?.kind === "url"
|
||||||
|
? ezpayLaunchTarget.paymentUrl
|
||||||
|
: null;
|
||||||
|
const regionalQrPayment: RegionalQrPaymentDetails | null =
|
||||||
|
payment.payParams &&
|
||||||
|
payment.currentOrderId &&
|
||||||
|
ezpayLaunchTarget?.kind === "qr"
|
||||||
|
? {
|
||||||
|
amountCents:
|
||||||
|
paymentParamAmountCents(payment.payParams) ??
|
||||||
|
selectedPlan?.amountCents ??
|
||||||
|
0,
|
||||||
|
currency:
|
||||||
|
paymentCurrency ??
|
||||||
|
(ezpayLaunchTarget.experience === "gcashQrPh" ? "PHP" : "IDR"),
|
||||||
|
experience: ezpayLaunchTarget.experience,
|
||||||
|
orderId: payment.currentOrderId,
|
||||||
|
qrData: ezpayLaunchTarget.qrData,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!payment.payParams || payment.launchNonce <= launchedNonceRef.current) {
|
if (!payment.payParams || payment.launchNonce <= launchedNonceRef.current) {
|
||||||
return;
|
return;
|
||||||
@@ -136,39 +214,95 @@ export function usePaymentLaunchFlow({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const paymentUrl = getPaymentUrl(payment.payParams);
|
const isEzpay = isEzpayPayment(payment.payParams);
|
||||||
if (paymentUrl) {
|
if (isEzpay) {
|
||||||
const isEzpay = isEzpayPayment(payment.payParams);
|
const target = resolveEzpayLaunchTarget(payment.payParams, {
|
||||||
|
countryCode,
|
||||||
|
currency: paymentCurrency,
|
||||||
|
});
|
||||||
|
const channelType = paymentParamString(
|
||||||
|
payment.payParams,
|
||||||
|
"channelType",
|
||||||
|
"channel_type",
|
||||||
|
);
|
||||||
|
const channelCode = paymentParamString(
|
||||||
|
payment.payParams,
|
||||||
|
"channelCode",
|
||||||
|
"channel_code",
|
||||||
|
);
|
||||||
|
const namedPaymentUrl = getPaymentUrl(payment.payParams);
|
||||||
|
log.debug(`[${logScope}] ezpay launch target resolved`, {
|
||||||
|
countryCode: countryCode?.trim().toUpperCase() ?? null,
|
||||||
|
currency: paymentCurrency?.trim().toUpperCase() ?? null,
|
||||||
|
channelType: channelType?.toUpperCase() ?? null,
|
||||||
|
channelCode,
|
||||||
|
hasCashierUrl: getPaymentUrlHostname(namedPaymentUrl) !== null,
|
||||||
|
hasQrData: target.kind === "qr",
|
||||||
|
paymentUrlHost:
|
||||||
|
target.kind === "url"
|
||||||
|
? getPaymentUrlHostname(target.paymentUrl)
|
||||||
|
: null,
|
||||||
|
});
|
||||||
|
if (target.kind === "error") {
|
||||||
|
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
||||||
|
paymentDispatch({
|
||||||
|
type: "PaymentLaunchFailed",
|
||||||
|
errorMessage: target.errorMessage,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!AppEnvUtil.isProduction() && isEzpay) {
|
if (target.kind === "qr") {
|
||||||
|
if (!payment.currentOrderId) {
|
||||||
|
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
||||||
|
paymentDispatch({
|
||||||
|
type: "PaymentLaunchFailed",
|
||||||
|
errorMessage: "Missing order id before showing payment QR code.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
trackPaymentCheckoutOpened(
|
||||||
|
payment,
|
||||||
|
target.experience === "qris"
|
||||||
|
? "qris_embedded"
|
||||||
|
: target.experience === "gcashQrPh"
|
||||||
|
? "gcash_qrph_embedded"
|
||||||
|
: "payment_qr_embedded",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const paymentUrl = target.paymentUrl;
|
||||||
|
if (!AppEnvUtil.isProduction()) {
|
||||||
log.debug(`[${logScope}] ezpay confirmation required`, {
|
log.debug(`[${logScope}] ezpay confirmation required`, {
|
||||||
orderId: payment.currentOrderId,
|
orderId: payment.currentOrderId,
|
||||||
paymentUrl,
|
paymentUrlHost: getPaymentUrlHostname(paymentUrl),
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isEzpay) {
|
void launchEzpayRedirect({
|
||||||
void launchEzpayRedirect({
|
orderId: payment.currentOrderId,
|
||||||
orderId: payment.currentOrderId,
|
paymentUrl,
|
||||||
paymentUrl,
|
subscriptionType,
|
||||||
subscriptionType,
|
giftCategory,
|
||||||
giftCategory,
|
giftPlanId,
|
||||||
giftPlanId,
|
...(returnTo ? { returnTo } : {}),
|
||||||
...(returnTo ? { returnTo } : {}),
|
...(characterSlug ? { characterSlug } : {}),
|
||||||
...(characterSlug ? { characterSlug } : {}),
|
onOpened: () => trackPaymentCheckoutOpened(payment, paymentUrl),
|
||||||
onOpened: () => trackPaymentCheckoutOpened(payment, paymentUrl),
|
onFailed: (errorMessage) => {
|
||||||
onFailed: (errorMessage) => {
|
trackPaymentCheckoutFailed(payment, "payment_redirect_failed");
|
||||||
trackPaymentCheckoutFailed(payment, "payment_redirect_failed");
|
paymentDispatch({ type: "PaymentLaunchFailed", errorMessage });
|
||||||
paymentDispatch({ type: "PaymentLaunchFailed", errorMessage });
|
},
|
||||||
},
|
});
|
||||||
});
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
const paymentUrl = getPaymentUrl(payment.payParams);
|
||||||
|
if (paymentUrl) {
|
||||||
try {
|
try {
|
||||||
window.location.href = paymentUrl;
|
window.location.assign(paymentUrl);
|
||||||
trackPaymentCheckoutOpened(payment, paymentUrl);
|
trackPaymentCheckoutOpened(payment, paymentUrl);
|
||||||
} catch {
|
} catch {
|
||||||
trackPaymentCheckoutFailed(payment, "payment_redirect_failed");
|
trackPaymentCheckoutFailed(payment, "payment_redirect_failed");
|
||||||
@@ -189,6 +323,7 @@ export function usePaymentLaunchFlow({
|
|||||||
log,
|
log,
|
||||||
logScope,
|
logScope,
|
||||||
characterSlug,
|
characterSlug,
|
||||||
|
countryCode,
|
||||||
payment.currentOrderId,
|
payment.currentOrderId,
|
||||||
payment,
|
payment,
|
||||||
payment.launchNonce,
|
payment.launchNonce,
|
||||||
@@ -197,6 +332,7 @@ export function usePaymentLaunchFlow({
|
|||||||
payment.plans,
|
payment.plans,
|
||||||
payment.selectedPlanId,
|
payment.selectedPlanId,
|
||||||
paymentDispatch,
|
paymentDispatch,
|
||||||
|
paymentCurrency,
|
||||||
returnTo,
|
returnTo,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
giftCategory,
|
giftCategory,
|
||||||
@@ -213,6 +349,9 @@ export function usePaymentLaunchFlow({
|
|||||||
payParams: payment.payParams,
|
payParams: payment.payParams,
|
||||||
paymentUrl: ezpayPaymentUrl,
|
paymentUrl: ezpayPaymentUrl,
|
||||||
});
|
});
|
||||||
|
const shouldShowRegionalQrDialog = Boolean(
|
||||||
|
regionalQrPayment && !payment.isPaid,
|
||||||
|
);
|
||||||
|
|
||||||
function resetLaunchState(): void {
|
function resetLaunchState(): void {
|
||||||
setIsConfirmingEzpay(false);
|
setIsConfirmingEzpay(false);
|
||||||
@@ -263,15 +402,29 @@ export function usePaymentLaunchFlow({
|
|||||||
paymentDispatch({ type: "PaymentReset" });
|
paymentDispatch({ type: "PaymentReset" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleRegionalQrClose(): void {
|
||||||
|
log.debug(`[${logScope}] regional payment QR dialog closed`, {
|
||||||
|
orderId: regionalQrPayment?.orderId ?? payment.currentOrderId,
|
||||||
|
experience: regionalQrPayment?.experience ?? null,
|
||||||
|
subscriptionType,
|
||||||
|
});
|
||||||
|
paymentDispatch({ type: "PaymentReset" });
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ezpayPaymentUrl,
|
ezpayPaymentUrl,
|
||||||
handleEzpayCancel,
|
handleEzpayCancel,
|
||||||
handleEzpayConfirm,
|
handleEzpayConfirm,
|
||||||
|
handleRegionalQrClose,
|
||||||
handleStripeClose,
|
handleStripeClose,
|
||||||
handleStripeConfirmed,
|
handleStripeConfirmed,
|
||||||
isConfirmingEzpay,
|
isConfirmingEzpay,
|
||||||
|
regionalQrErrorMessage: payment.errorMessage,
|
||||||
|
regionalQrPayment,
|
||||||
|
regionalQrStatus: payment.orderStatus,
|
||||||
resetLaunchState,
|
resetLaunchState,
|
||||||
shouldShowEzpayConfirmDialog,
|
shouldShowEzpayConfirmDialog,
|
||||||
|
shouldShowRegionalQrDialog,
|
||||||
shouldShowStripeDialog,
|
shouldShowStripeDialog,
|
||||||
stripeClientSecret,
|
stripeClientSecret,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ export interface UsePaymentRouteFlowInput {
|
|||||||
characterId?: string;
|
characterId?: string;
|
||||||
initialCategory?: string | null;
|
initialCategory?: string | null;
|
||||||
initialPlanId?: string | null;
|
initialPlanId?: string | null;
|
||||||
|
commercialOfferId?: string | null;
|
||||||
|
resumeOrderId?: string | null;
|
||||||
|
chatActionId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PaymentRouteFlow {
|
export interface PaymentRouteFlow {
|
||||||
@@ -41,15 +44,21 @@ export function usePaymentRouteFlow({
|
|||||||
characterId,
|
characterId,
|
||||||
initialCategory = null,
|
initialCategory = null,
|
||||||
initialPlanId = null,
|
initialPlanId = null,
|
||||||
|
commercialOfferId = null,
|
||||||
|
resumeOrderId = null,
|
||||||
|
chatActionId = null,
|
||||||
}: UsePaymentRouteFlowInput): PaymentRouteFlow {
|
}: UsePaymentRouteFlowInput): PaymentRouteFlow {
|
||||||
const payment = usePaymentState();
|
const payment = usePaymentState();
|
||||||
const paymentDispatch = usePaymentDispatch();
|
const paymentDispatch = usePaymentDispatch();
|
||||||
const initializedCatalogKeyRef = useRef<string | null>(null);
|
const initializedCatalogKeyRef = useRef<string | null>(null);
|
||||||
|
const resumedOrderIdRef = useRef<string | null>(null);
|
||||||
const catalogKey = [
|
const catalogKey = [
|
||||||
catalog,
|
catalog,
|
||||||
characterId ?? "",
|
characterId ?? "",
|
||||||
initialCategory ?? "",
|
initialCategory ?? "",
|
||||||
initialPlanId ?? "",
|
initialPlanId ?? "",
|
||||||
|
commercialOfferId ?? "",
|
||||||
|
chatActionId ?? "",
|
||||||
].join(":");
|
].join(":");
|
||||||
|
|
||||||
usePendingPaymentOrderLifecycle({
|
usePendingPaymentOrderLifecycle({
|
||||||
@@ -69,16 +78,26 @@ export function usePaymentRouteFlow({
|
|||||||
...(characterId ? { characterId } : {}),
|
...(characterId ? { characterId } : {}),
|
||||||
...(initialCategory ? { category: initialCategory } : {}),
|
...(initialCategory ? { category: initialCategory } : {}),
|
||||||
...(initialPlanId ? { planId: initialPlanId } : {}),
|
...(initialPlanId ? { planId: initialPlanId } : {}),
|
||||||
|
...(commercialOfferId ? { commercialOfferId } : {}),
|
||||||
|
...(chatActionId ? { chatActionId } : {}),
|
||||||
});
|
});
|
||||||
}, [
|
}, [
|
||||||
catalog,
|
catalog,
|
||||||
catalogKey,
|
catalogKey,
|
||||||
characterId,
|
characterId,
|
||||||
|
commercialOfferId,
|
||||||
|
chatActionId,
|
||||||
initialCategory,
|
initialCategory,
|
||||||
initialPlanId,
|
initialPlanId,
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
paymentDispatch,
|
paymentDispatch,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!resumeOrderId || resumedOrderIdRef.current === resumeOrderId) return;
|
||||||
|
resumedOrderIdRef.current = resumeOrderId;
|
||||||
|
paymentDispatch({ type: "PaymentReturned", orderId: resumeOrderId });
|
||||||
|
}, [paymentDispatch, resumeOrderId]);
|
||||||
|
|
||||||
return { payment, paymentDispatch };
|
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 />;
|
||||||
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
import { PrivateRoomScreen } from "@/app/private-room/private-room-screen";
|
|
||||||
|
|
||||||
export default function CharacterPrivateRoomPage() {
|
|
||||||
return <PrivateRoomScreen />;
|
|
||||||
}
|
|
||||||
@@ -2,9 +2,9 @@ import type { ReactNode } from "react";
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
import { getCharacterBySlug } from "@/data/constants/character";
|
import { getCharacterBySlug } from "@/data/constants/character";
|
||||||
import { PrivateRoomRouteProvider } from "@/providers/private-room-route-provider";
|
import { PrivateZoneRouteProvider } from "@/providers/private-zone-route-provider";
|
||||||
|
|
||||||
export default async function CharacterPrivateRoomLayout({
|
export default async function CharacterPrivateZoneLayout({
|
||||||
children,
|
children,
|
||||||
params,
|
params,
|
||||||
}: {
|
}: {
|
||||||
@@ -13,11 +13,11 @@ export default async function CharacterPrivateRoomLayout({
|
|||||||
}) {
|
}) {
|
||||||
const { characterSlug } = await params;
|
const { characterSlug } = await params;
|
||||||
const character = getCharacterBySlug(characterSlug);
|
const character = getCharacterBySlug(characterSlug);
|
||||||
if (!character?.capabilities.privateRoom) notFound();
|
if (!character?.capabilities.privateZone) notFound();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PrivateRoomRouteProvider characterId={character.id}>
|
<PrivateZoneRouteProvider characterId={character.id}>
|
||||||
{children}
|
{children}
|
||||||
</PrivateRoomRouteProvider>
|
</PrivateZoneRouteProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||