Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 599f3e3d26 | |||
| 2e04260ebd | |||
| ba6d3605b7 | |||
| 17fad9ecc0 | |||
| fbcd5abe22 | |||
| dae04f75dc | |||
| 8f8e067d82 | |||
| 3c74d30189 | |||
| 4cbdd0da7c | |||
| e071f83474 | |||
| 3536045794 | |||
| 74b7eae18b | |||
| 59e4eac736 | |||
| 2e402de15b | |||
| a530850039 |
@@ -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"
|
||||||
@@ -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,85 +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-zone` | 指定进入的页面;不传或值无效时进入聊天页。历史值 `private-room` 兼容进入 `private-zone`,新链接不得继续使用。 |
|
| `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` 保留为兼容能力,不属于本次业务清单。
|
||||||
|
|
||||||
标准私密空间参数是 `target=private-zone`。前端仅为已经发布的旧链接保留 `target=private-room` 兼容;`private_zone` 等其他拼写仍按无效目标处理并回退聊天页。
|
## 四类发送模板
|
||||||
|
|
||||||
|
发送前必须把 `<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
|
|
||||||
https://<APP_HOST>/external-entry?target=chat&character=maya
|
|
||||||
```
|
|
||||||
|
|
||||||
携带 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-zone
|
|
||||||
```
|
|
||||||
|
|
||||||
进入 Nayeli 私密空间:
|
|
||||||
|
|
||||||
```text
|
|
||||||
https://<APP_HOST>/external-entry?target=private-zone&character=nayeli
|
|
||||||
```
|
|
||||||
|
|
||||||
`psid` 可以与任意 `target` 或聊天促销参数组合使用。参数值需要进行 URL 编码,不要在入口中传递登录 Token、Page Access Token 或 App Secret。
|
|
||||||
|
|
||||||
完整可点击示例:
|
|
||||||
|
|
||||||
- [本地调试链接清单](./debug-links.md)
|
- [本地调试链接清单](./debug-links.md)
|
||||||
- [测试环境和正式环境链接清单](./links.md)
|
- [Facebook 12 条外部入口链接清单](./links.md)
|
||||||
|
|||||||
@@ -1,66 +1,52 @@
|
|||||||
# 外部入口链接清单
|
# Facebook 12 条外部入口链接清单
|
||||||
|
|
||||||
这份清单可以独立发送和直接点击。所有新链接统一使用标准参数 `target=private-zone`;历史参数 `target=private-room` 仅用于兼容已经发出的旧链接。
|
本清单是 Facebook 正式投放的唯一业务链接清单,共 4 类入口乘以 3 个角色,合计 12 条模板。
|
||||||
|
|
||||||
## 使用规则
|
## 发送规则
|
||||||
|
|
||||||
- `target=chat`:进入聊天页。
|
- 发送前必须把每条模板中的 `<PSID>` 替换为当前用户经过 URL 编码的 Facebook Page-scoped User ID;不得把占位符原样发送。
|
||||||
- `target=tip`:进入对应角色的打赏页。
|
- 每条链接都显式传入 `character`,不得依赖缺省角色回退。
|
||||||
- `target=private-zone`:进入对应角色的私密空间。
|
- Facebook 业务名称“私密空间”进入普通聊天页;业务名称“图片包”才进入应用的 `private-zone`。
|
||||||
- `character` 可使用 `elio`、`maya`、`nayeli`;不传或值无效时使用 Elio。
|
- 不要在入口中传递登录 Token、Page Access Token、App Secret 或其他秘密。
|
||||||
- `mode=promotion` 只在 `target=chat` 且 `promotion_type` 为 `voice`、`image` 或 `private` 时生效。
|
- 以下模板包含占位符,替换真实 PSID 后才能直接发送或点击。
|
||||||
- PSID 示例统一使用 `27511427698460020`;不要在入口中放登录 Token、Page Access Token 或 App Secret。
|
|
||||||
|
|
||||||
## 测试环境
|
## 正式投放模板
|
||||||
|
|
||||||
| 入口 | 可点击链接 | 预期落地页面 |
|
| 编号 | Facebook 入口 | 角色 | 发送模板 | 预期落地与页面状态 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| 普通聊天(Elio) | [打开普通聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat) | `/characters/elio/chat` |
|
| 1 | 私密空间 | Elio | `https://cozsweet.com/external-entry?target=chat&character=elio&psid=<PSID>` | `/characters/elio/chat`,不显示促销锁卡 |
|
||||||
| Maya 聊天 | [打开 Maya 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=maya) | `/characters/maya/chat` |
|
| 2 | 私密空间 | Maya | `https://cozsweet.com/external-entry?target=chat&character=maya&psid=<PSID>` | `/characters/maya/chat`,不显示促销锁卡 |
|
||||||
| Nayeli 聊天 | [打开 Nayeli 聊天](https://frontend-test.banlv-ai.com/external-entry?target=chat&character=nayeli) | `/characters/nayeli/chat` |
|
| 3 | 私密空间 | Nayeli | `https://cozsweet.com/external-entry?target=chat&character=nayeli&psid=<PSID>` | `/characters/nayeli/chat`,不显示促销锁卡 |
|
||||||
| 携带 PSID 的 Elio 聊天 | [打开 PSID 聊天示例](https://frontend-test.banlv-ai.com/external-entry?target=chat&psid=27511427698460020) | `/characters/elio/chat` |
|
| 4 | 语音 | Elio | `https://cozsweet.com/external-entry?target=chat&character=elio&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/elio/chat`,显示一条锁定语音 |
|
||||||
| 语音促销 | [打开语音促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=voice) | `/characters/elio/chat`,保存语音促销意图 |
|
| 5 | 语音 | Maya | `https://cozsweet.com/external-entry?target=chat&character=maya&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/maya/chat`,显示一条锁定语音 |
|
||||||
| 图片促销 | [打开图片促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=image) | `/characters/elio/chat`,保存图片促销意图 |
|
| 6 | 语音 | Nayeli | `https://cozsweet.com/external-entry?target=chat&character=nayeli&mode=promotion&promotion_type=voice&psid=<PSID>` | `/characters/nayeli/chat`,显示一条锁定语音 |
|
||||||
| 私密文本促销 | [打开私密文本促销](https://frontend-test.banlv-ai.com/external-entry?target=chat&mode=promotion&promotion_type=private) | `/characters/elio/chat`,保存私密文本促销意图 |
|
| 7 | 图片包 | Elio | `https://cozsweet.com/external-entry?target=private-zone&character=elio&psid=<PSID>` | `/characters/elio/private-zone` |
|
||||||
| Elio 咖啡打赏 | [打开 Elio 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=elio) | `/characters/elio/tip` |
|
| 8 | 图片包 | Maya | `https://cozsweet.com/external-entry?target=private-zone&character=maya&psid=<PSID>` | `/characters/maya/private-zone` |
|
||||||
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=maya) | `/characters/maya/tip` |
|
| 9 | 图片包 | Nayeli | `https://cozsweet.com/external-entry?target=private-zone&character=nayeli&psid=<PSID>` | `/characters/nayeli/private-zone` |
|
||||||
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://frontend-test.banlv-ai.com/external-entry?target=tip&character=nayeli) | `/characters/nayeli/tip` |
|
| 10 | 帮忙买咖啡 | Elio | `https://cozsweet.com/external-entry?target=tip&character=elio&psid=<PSID>` | `/characters/elio/tip` |
|
||||||
| Elio 私密空间 | [打开 Elio 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=elio) | `/characters/elio/private-zone` |
|
| 11 | 帮忙买咖啡 | Maya | `https://cozsweet.com/external-entry?target=tip&character=maya&psid=<PSID>` | `/characters/maya/tip` |
|
||||||
| Maya 私密空间 | [打开 Maya 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=maya) | `/characters/maya/private-zone` |
|
| 12 | 帮忙买咖啡 | Nayeli | `https://cozsweet.com/external-entry?target=tip&character=nayeli&psid=<PSID>` | `/characters/nayeli/tip` |
|
||||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://frontend-test.banlv-ai.com/external-entry?target=private-zone&character=nayeli) | `/characters/nayeli/private-zone` |
|
|
||||||
|
|
||||||
## 旧链接兼容验证
|
## 预发验证
|
||||||
|
|
||||||
以下链接仅用于验证已经发出的 `private-room` 旧链接仍能正确进入私密空间。新投放链接不要再使用这些地址。
|
预发验证不维护第二套业务清单。将上述 12 条模板的主机统一替换为 `frontend-test.banlv-ai.com`,其余路径和参数保持不变:
|
||||||
|
|
||||||
| 旧入口 | 可点击链接 | 预期落地页面 |
|
```text
|
||||||
| --- | --- | --- |
|
https://frontend-test.banlv-ai.com/external-entry?<与正式模板相同的查询参数>
|
||||||
| Elio 旧私密空间 | [验证 Elio 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=elio) | `/characters/elio/private-zone` |
|
```
|
||||||
| Maya 旧私密空间 | [验证 Maya 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=maya) | `/characters/maya/private-zone` |
|
|
||||||
| Nayeli 旧私密空间 | [验证 Nayeli 旧链接](https://frontend-test.banlv-ai.com/external-entry?target=private-room&character=nayeli) | `/characters/nayeli/private-zone` |
|
|
||||||
|
|
||||||
## 正式环境
|
预发环境是 `pre`,不是正式环境。预发验证通过不代表已经更新 `cozsweet.com` 或获得生产发布批准。
|
||||||
|
|
||||||
正式环境仅列标准链接,不再传播 `private-room` 旧参数。
|
|
||||||
|
|
||||||
| 入口 | 可点击链接 | 预期落地页面 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 普通聊天(Elio) | [打开普通聊天](https://cozsweet.com/external-entry?target=chat) | `/characters/elio/chat` |
|
|
||||||
| Maya 聊天 | [打开 Maya 聊天](https://cozsweet.com/external-entry?target=chat&character=maya) | `/characters/maya/chat` |
|
|
||||||
| Nayeli 聊天 | [打开 Nayeli 聊天](https://cozsweet.com/external-entry?target=chat&character=nayeli) | `/characters/nayeli/chat` |
|
|
||||||
| 携带 PSID 的 Elio 聊天 | [打开 PSID 聊天示例](https://cozsweet.com/external-entry?target=chat&psid=27511427698460020) | `/characters/elio/chat` |
|
|
||||||
| 语音促销 | [打开语音促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=voice) | `/characters/elio/chat`,保存语音促销意图 |
|
|
||||||
| 图片促销 | [打开图片促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=image) | `/characters/elio/chat`,保存图片促销意图 |
|
|
||||||
| 私密文本促销 | [打开私密文本促销](https://cozsweet.com/external-entry?target=chat&mode=promotion&promotion_type=private) | `/characters/elio/chat`,保存私密文本促销意图 |
|
|
||||||
| Elio 咖啡打赏 | [打开 Elio 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=elio) | `/characters/elio/tip` |
|
|
||||||
| Maya 咖啡打赏 | [打开 Maya 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=maya) | `/characters/maya/tip` |
|
|
||||||
| Nayeli 咖啡打赏 | [打开 Nayeli 咖啡打赏](https://cozsweet.com/external-entry?target=tip&character=nayeli) | `/characters/nayeli/tip` |
|
|
||||||
| Elio 私密空间 | [打开 Elio 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=elio) | `/characters/elio/private-zone` |
|
|
||||||
| Maya 私密空间 | [打开 Maya 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=maya) | `/characters/maya/private-zone` |
|
|
||||||
| Nayeli 私密空间 | [打开 Nayeli 私密空间](https://cozsweet.com/external-entry?target=private-zone&character=nayeli) | `/characters/nayeli/private-zone` |
|
|
||||||
|
|
||||||
## 验收判断
|
## 验收判断
|
||||||
|
|
||||||
打开入口后,浏览器地址最终应与“预期落地页面”一致。普通聊天和私密空间必须分别落在 `/chat` 与 `/private-zone`,不能再进入同一个页面。
|
- 最终浏览器地址必须是表格中的预期页面,且不再保留 `/external-entry` 的查询参数。
|
||||||
|
- `<PSID>` 替换后的真实值必须由应用保存。
|
||||||
|
- “私密空间”只进入普通聊天,不得出现锁定语音、锁定图片或私密文本促销卡。
|
||||||
|
- “语音”进入聊天后必须只注入一条锁定语音。
|
||||||
|
- “图片包”和“帮忙买咖啡”必须分别进入对应角色的 `private-zone` 与 `tip`,不能串到其他角色。
|
||||||
|
|
||||||
如需在其他入口携带 PSID,在已有查询参数的链接末尾追加 `&psid=27511427698460020`。
|
## 不属于当前 12 条清单的兼容能力
|
||||||
|
|
||||||
|
- 历史 `target=private-room` 继续兼容,但不得创建新的投放链接。
|
||||||
|
- `promotion_type=image`、`promotion_type=private` 和独立 PSID 示例不属于当前正式业务清单。
|
||||||
|
- 兼容能力的保留不改变本页“只有 12 条正式投放模板”的口径。
|
||||||
|
|||||||
@@ -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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -85,11 +85,14 @@ async function registerIndonesiaPaymentMocks(page: Page) {
|
|||||||
});
|
});
|
||||||
await page.route("**/api/payment/create-order", async (route) => {
|
await page.route("**/api/payment/create-order", async (route) => {
|
||||||
createOrderCount += 1;
|
createOrderCount += 1;
|
||||||
const body = route.request().postDataJSON() as { planId: string };
|
const body = route.request().postDataJSON() as {
|
||||||
|
planId: string;
|
||||||
|
payChannel: "ezpay" | "stripe";
|
||||||
|
};
|
||||||
const plan =
|
const plan =
|
||||||
idrPlans.plans.find((item) => item.planId === body.planId) ??
|
idrPlans.plans.find((item) => item.planId === body.planId) ??
|
||||||
idrGiftCatalog.plans.find((item) => item.planId === body.planId);
|
idrGiftCatalog.plans.find((item) => item.planId === body.planId);
|
||||||
const orderId = `order_qris_${body.planId}`;
|
const orderId = `order_${body.payChannel}_${body.planId}`;
|
||||||
orderStatuses.set(orderId, "pending");
|
orderStatuses.set(orderId, "pending");
|
||||||
orderPlans.set(orderId, {
|
orderPlans.set(orderId, {
|
||||||
planId: body.planId,
|
planId: body.planId,
|
||||||
@@ -98,15 +101,21 @@ async function registerIndonesiaPaymentMocks(page: Page) {
|
|||||||
await route.fulfill({
|
await route.fulfill({
|
||||||
json: apiEnvelope({
|
json: apiEnvelope({
|
||||||
orderId,
|
orderId,
|
||||||
payParams: {
|
payParams:
|
||||||
provider: "ezpay",
|
body.payChannel === "stripe"
|
||||||
countryCode: "ID",
|
? {
|
||||||
channelCode: "ID_QRIS_DYNAMIC_QR",
|
provider: "stripe",
|
||||||
channelType: "QR",
|
clientSecret: "pi_e2e_secret_mock",
|
||||||
payData: "00020101021226670016COM.NOBUBANK.WWW",
|
}
|
||||||
firstChargeAmountCents: plan?.amountCents ?? 0,
|
: {
|
||||||
currency: "IDR",
|
provider: "ezpay",
|
||||||
},
|
countryCode: "ID",
|
||||||
|
channelCode: "ID_QRIS_DYNAMIC_QR",
|
||||||
|
channelType: "QR",
|
||||||
|
payData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
|
firstChargeAmountCents: plan?.amountCents ?? 0,
|
||||||
|
currency: "IDR",
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -173,6 +182,7 @@ async function expectQrisOrder(
|
|||||||
expect(request.postDataJSON()).toMatchObject({
|
expect(request.postDataJSON()).toMatchObject({
|
||||||
planId,
|
planId,
|
||||||
payChannel: "ezpay",
|
payChannel: "ezpay",
|
||||||
|
recipientCharacterId: "elio",
|
||||||
});
|
});
|
||||||
|
|
||||||
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
const dialog = page.getByRole("dialog", { name: "Scan to pay with QRIS" });
|
||||||
@@ -182,7 +192,7 @@ async function expectQrisOrder(
|
|||||||
await expect(
|
await expect(
|
||||||
dialog.getByRole("img", { name: "QRIS payment QR code" }),
|
dialog.getByRole("img", { name: "QRIS payment QR code" }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
return `order_qris_${planId}`;
|
return `order_ezpay_${planId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function expectCheckoutButtonLayout(page: Page) {
|
async function expectCheckoutButtonLayout(page: Page) {
|
||||||
@@ -209,7 +219,13 @@ test("Indonesia VIP defaults to QRIS and completes after status polling", async
|
|||||||
}) => {
|
}) => {
|
||||||
const payment = await registerIndonesiaPaymentMocks(page);
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
await prepareIndonesiaUser(page);
|
await prepareIndonesiaUser(page);
|
||||||
await page.goto("/subscription?type=vip");
|
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(
|
await expect(page.getByRole("button", { name: "QRIS" })).toHaveAttribute(
|
||||||
"aria-pressed",
|
"aria-pressed",
|
||||||
@@ -250,7 +266,8 @@ test("Indonesia VIP defaults to QRIS and completes after status polling", async
|
|||||||
test("Indonesia credit top-up uses QRIS display cents", async ({ page }) => {
|
test("Indonesia credit top-up uses QRIS display cents", async ({ page }) => {
|
||||||
const payment = await registerIndonesiaPaymentMocks(page);
|
const payment = await registerIndonesiaPaymentMocks(page);
|
||||||
await prepareIndonesiaUser(page);
|
await prepareIndonesiaUser(page);
|
||||||
await page.goto("/subscription?type=topup");
|
await page.goto("/subscription?type=topup&character=elio");
|
||||||
|
await expect(page.getByText("Supporting Elio")).toHaveCount(0);
|
||||||
await expectCheckoutButtonLayout(page);
|
await expectCheckoutButtonLayout(page);
|
||||||
|
|
||||||
const orderId = await expectQrisOrder(
|
const orderId = await expectQrisOrder(
|
||||||
@@ -266,6 +283,74 @@ test("Indonesia credit top-up uses QRIS display cents", async ({ page }) => {
|
|||||||
).toBeVisible({ timeout: 10_000 });
|
).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 ({
|
test("payment issue submits Other to the feedback API without creating an order", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
@@ -317,17 +402,21 @@ test("Indonesia gift checkout keeps IDR price through QRIS and thank-you flow",
|
|||||||
await page.goto("/characters/elio/tip");
|
await page.goto("/characters/elio/tip");
|
||||||
|
|
||||||
await expect(page.getByText(/IDR\s*89[.,]299/)).toBeVisible();
|
await expect(page.getByText(/IDR\s*89[.,]299/)).toBeVisible();
|
||||||
const orderId = await expectQrisOrder(
|
await expectQrisOrder(
|
||||||
page,
|
page,
|
||||||
/Order and Buy/i,
|
/Order and Buy/i,
|
||||||
"tip_coffee_usd_4_99",
|
"tip_coffee_usd_4_99",
|
||||||
/Rp\s*89[.,]299/,
|
/Rp\s*89[.,]299/,
|
||||||
);
|
);
|
||||||
payment.markPaid(orderId);
|
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.getByText("Gift received")).toBeVisible({ timeout: 10_000 });
|
await expect(page.getByRole("button", { name: "Stripe" })).toBeEnabled();
|
||||||
await expect(page.getByRole("button", { name: "Send another gift" })).toBeVisible();
|
await page.getByRole("button", { name: "Stripe" }).click();
|
||||||
await expect(
|
await expect(page.getByRole("button", { name: "Stripe" })).toHaveAttribute(
|
||||||
page.getByRole("dialog", { name: "Scan to pay with QRIS" }),
|
"aria-pressed",
|
||||||
).toBeHidden();
|
"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,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/);
|
||||||
|
});
|
||||||
@@ -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
|
||||||
@@ -7,15 +7,15 @@ import { PaymentLaunchDialogs } from "../payment-launch-dialogs";
|
|||||||
const hiddenLaunch = {
|
const hiddenLaunch = {
|
||||||
handleEzpayCancel: vi.fn(),
|
handleEzpayCancel: vi.fn(),
|
||||||
handleEzpayConfirm: vi.fn(),
|
handleEzpayConfirm: vi.fn(),
|
||||||
handleQrisClose: vi.fn(),
|
handleRegionalQrClose: vi.fn(),
|
||||||
handleStripeClose: vi.fn(),
|
handleStripeClose: vi.fn(),
|
||||||
handleStripeConfirmed: vi.fn(),
|
handleStripeConfirmed: vi.fn(),
|
||||||
isConfirmingEzpay: false,
|
isConfirmingEzpay: false,
|
||||||
qrisErrorMessage: null,
|
regionalQrErrorMessage: null,
|
||||||
qrisPayment: null,
|
regionalQrPayment: null,
|
||||||
qrisStatus: null,
|
regionalQrStatus: null,
|
||||||
shouldShowEzpayConfirmDialog: false,
|
shouldShowEzpayConfirmDialog: false,
|
||||||
shouldShowQrisDialog: false,
|
shouldShowRegionalQrDialog: false,
|
||||||
shouldShowStripeDialog: false,
|
shouldShowStripeDialog: false,
|
||||||
stripeClientSecret: null,
|
stripeClientSecret: null,
|
||||||
};
|
};
|
||||||
@@ -96,14 +96,15 @@ describe("PaymentLaunchDialogs", () => {
|
|||||||
ezpayDescription="Scan QRIS to finish the payment."
|
ezpayDescription="Scan QRIS to finish the payment."
|
||||||
launch={{
|
launch={{
|
||||||
...hiddenLaunch,
|
...hiddenLaunch,
|
||||||
qrisPayment: {
|
regionalQrPayment: {
|
||||||
qrData: "00020101021226670016COM.NOBUBANK.WWW",
|
qrData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
orderId: "order-id-qris",
|
orderId: "order-id-qris",
|
||||||
amountCents: 5_000_000,
|
amountCents: 5_000_000,
|
||||||
currency: "IDR",
|
currency: "IDR",
|
||||||
|
experience: "qris",
|
||||||
},
|
},
|
||||||
qrisStatus: "pending",
|
regionalQrStatus: "pending",
|
||||||
shouldShowQrisDialog: true,
|
shouldShowRegionalQrDialog: true,
|
||||||
}}
|
}}
|
||||||
/>,
|
/>,
|
||||||
),
|
),
|
||||||
@@ -122,6 +123,44 @@ describe("PaymentLaunchDialogs", () => {
|
|||||||
expect(dialog?.textContent).toContain("Waiting for payment");
|
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", () => {
|
it("shows QRIS failure state and handles empty QR data safely", () => {
|
||||||
act(() =>
|
act(() =>
|
||||||
root.render(
|
root.render(
|
||||||
@@ -131,15 +170,16 @@ describe("PaymentLaunchDialogs", () => {
|
|||||||
ezpayDescription="Scan QRIS to finish the payment."
|
ezpayDescription="Scan QRIS to finish the payment."
|
||||||
launch={{
|
launch={{
|
||||||
...hiddenLaunch,
|
...hiddenLaunch,
|
||||||
qrisErrorMessage: "Payment failed or was cancelled.",
|
regionalQrErrorMessage: "Payment failed or was cancelled.",
|
||||||
qrisPayment: {
|
regionalQrPayment: {
|
||||||
qrData: "",
|
qrData: "",
|
||||||
orderId: "order-id-qris",
|
orderId: "order-id-qris",
|
||||||
amountCents: 5_000_000,
|
amountCents: 5_000_000,
|
||||||
currency: "IDR",
|
currency: "IDR",
|
||||||
|
experience: "qris",
|
||||||
},
|
},
|
||||||
qrisStatus: "failed",
|
regionalQrStatus: "failed",
|
||||||
shouldShowQrisDialog: true,
|
shouldShowRegionalQrDialog: true,
|
||||||
}}
|
}}
|
||||||
/>,
|
/>,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -13,15 +13,15 @@ type PaymentLaunchDialogFlow = Pick<
|
|||||||
PaymentLaunchFlow,
|
PaymentLaunchFlow,
|
||||||
| "handleEzpayCancel"
|
| "handleEzpayCancel"
|
||||||
| "handleEzpayConfirm"
|
| "handleEzpayConfirm"
|
||||||
| "handleQrisClose"
|
| "handleRegionalQrClose"
|
||||||
| "handleStripeClose"
|
| "handleStripeClose"
|
||||||
| "handleStripeConfirmed"
|
| "handleStripeConfirmed"
|
||||||
| "isConfirmingEzpay"
|
| "isConfirmingEzpay"
|
||||||
| "qrisErrorMessage"
|
| "regionalQrErrorMessage"
|
||||||
| "qrisPayment"
|
| "regionalQrPayment"
|
||||||
| "qrisStatus"
|
| "regionalQrStatus"
|
||||||
| "shouldShowEzpayConfirmDialog"
|
| "shouldShowEzpayConfirmDialog"
|
||||||
| "shouldShowQrisDialog"
|
| "shouldShowRegionalQrDialog"
|
||||||
| "shouldShowStripeDialog"
|
| "shouldShowStripeDialog"
|
||||||
| "stripeClientSecret"
|
| "stripeClientSecret"
|
||||||
>;
|
>;
|
||||||
@@ -53,12 +53,12 @@ export function PaymentLaunchDialogs({
|
|||||||
onConfirm={launch.handleEzpayConfirm}
|
onConfirm={launch.handleEzpayConfirm}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{launch.shouldShowQrisDialog && launch.qrisPayment ? (
|
{launch.shouldShowRegionalQrDialog && launch.regionalQrPayment ? (
|
||||||
<QrisPaymentDialog
|
<RegionalQrPaymentDialog
|
||||||
payment={launch.qrisPayment}
|
payment={launch.regionalQrPayment}
|
||||||
status={launch.qrisStatus}
|
status={launch.regionalQrStatus}
|
||||||
errorMessage={launch.qrisErrorMessage}
|
errorMessage={launch.regionalQrErrorMessage}
|
||||||
onClose={launch.handleQrisClose}
|
onClose={launch.handleRegionalQrClose}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{launch.shouldShowStripeDialog && launch.stripeClientSecret ? (
|
{launch.shouldShowStripeDialog && launch.stripeClientSecret ? (
|
||||||
@@ -73,43 +73,56 @@ export function PaymentLaunchDialogs({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface QrisPaymentDialogProps {
|
interface RegionalQrPaymentDialogProps {
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
payment: NonNullable<PaymentLaunchFlow["qrisPayment"]>;
|
payment: NonNullable<PaymentLaunchFlow["regionalQrPayment"]>;
|
||||||
status: PaymentLaunchFlow["qrisStatus"];
|
status: PaymentLaunchFlow["regionalQrStatus"];
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatQrisAmount(amountCents: number, currency: string): string {
|
function formatRegionalQrAmount(amountCents: number, currency: string): string {
|
||||||
const normalizedCurrency = currency.trim().toUpperCase() || "IDR";
|
const normalizedCurrency = currency.trim().toUpperCase() || "IDR";
|
||||||
try {
|
try {
|
||||||
return new Intl.NumberFormat("id-ID", {
|
return new Intl.NumberFormat(
|
||||||
style: "currency",
|
normalizedCurrency === "PHP" ? "en-PH" : "id-ID",
|
||||||
currency: normalizedCurrency,
|
{
|
||||||
maximumFractionDigits: normalizedCurrency === "IDR" ? 0 : 2,
|
style: "currency",
|
||||||
}).format(amountCents / 100);
|
currency: normalizedCurrency,
|
||||||
|
maximumFractionDigits: normalizedCurrency === "IDR" ? 0 : 2,
|
||||||
|
},
|
||||||
|
).format(amountCents / 100);
|
||||||
} catch {
|
} catch {
|
||||||
return `${normalizedCurrency} ${(amountCents / 100).toFixed(2)}`;
|
return `${normalizedCurrency} ${(amountCents / 100).toFixed(2)}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function qrisStatusMessage(
|
function regionalQrStatusMessage(
|
||||||
status: PaymentLaunchFlow["qrisStatus"],
|
status: PaymentLaunchFlow["regionalQrStatus"],
|
||||||
errorMessage: string | null,
|
errorMessage: string | null,
|
||||||
|
paymentName: string,
|
||||||
): string {
|
): string {
|
||||||
if (status === "failed") return errorMessage || "Payment failed. Please try again.";
|
if (status === "failed") {
|
||||||
if (status === "expired") return errorMessage || "This QRIS order has expired.";
|
return errorMessage || "Payment failed. Please try again.";
|
||||||
|
}
|
||||||
|
if (status === "expired") {
|
||||||
|
return errorMessage || `This ${paymentName} order has expired.`;
|
||||||
|
}
|
||||||
return "Waiting for payment";
|
return "Waiting for payment";
|
||||||
}
|
}
|
||||||
|
|
||||||
function QrisPaymentDialog({
|
function RegionalQrPaymentDialog({
|
||||||
errorMessage,
|
errorMessage,
|
||||||
onClose,
|
onClose,
|
||||||
payment,
|
payment,
|
||||||
status,
|
status,
|
||||||
}: QrisPaymentDialogProps) {
|
}: RegionalQrPaymentDialogProps) {
|
||||||
const titleId = useId();
|
const titleId = useId();
|
||||||
const statusMessage = qrisStatusMessage(status, errorMessage);
|
const copy = regionalQrCopy(payment.experience);
|
||||||
|
const statusMessage = regionalQrStatusMessage(
|
||||||
|
status,
|
||||||
|
errorMessage,
|
||||||
|
copy.paymentName,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ModalPortal
|
<ModalPortal
|
||||||
@@ -123,17 +136,17 @@ function QrisPaymentDialog({
|
|||||||
>
|
>
|
||||||
<div className={`${styles.header} text-center`}>
|
<div className={`${styles.header} text-center`}>
|
||||||
<h2 id={titleId} className={styles.title}>
|
<h2 id={titleId} className={styles.title}>
|
||||||
Scan to pay with QRIS
|
{copy.title}
|
||||||
</h2>
|
</h2>
|
||||||
<p className={styles.content}>
|
<p className={styles.content}>
|
||||||
Open a QRIS-compatible banking or wallet app and scan this code.
|
{copy.description}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-4 flex min-h-64 items-center justify-center rounded-2xl bg-white p-4">
|
<div className="mb-4 flex min-h-64 items-center justify-center rounded-2xl bg-white p-4">
|
||||||
{payment.qrData ? (
|
{payment.qrData ? (
|
||||||
<QRCodeSVG
|
<QRCodeSVG
|
||||||
value={payment.qrData}
|
value={payment.qrData}
|
||||||
title="QRIS payment QR code"
|
title={copy.qrTitle}
|
||||||
size={256}
|
size={256}
|
||||||
level="M"
|
level="M"
|
||||||
marginSize={2}
|
marginSize={2}
|
||||||
@@ -141,14 +154,14 @@ function QrisPaymentDialog({
|
|||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<p className={styles.error} role="alert">
|
<p className={styles.error} role="alert">
|
||||||
QRIS data is unavailable. Please close this dialog and try again.
|
{copy.unavailableMessage}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-4 flex flex-col gap-2 text-center">
|
<div className="mb-4 flex flex-col gap-2 text-center">
|
||||||
<p className={styles.content}>Order No. {payment.orderId}</p>
|
<p className={styles.content}>Order No. {payment.orderId}</p>
|
||||||
<p className="m-0 text-xl font-bold text-text-foreground">
|
<p className="m-0 text-xl font-bold text-text-foreground">
|
||||||
{formatQrisAmount(payment.amountCents, payment.currency)}
|
{formatRegionalQrAmount(payment.amountCents, payment.currency)}
|
||||||
</p>
|
</p>
|
||||||
<p
|
<p
|
||||||
className={status === "failed" || status === "expired" ? styles.error : styles.content}
|
className={status === "failed" || status === "expired" ? styles.error : styles.content}
|
||||||
@@ -170,6 +183,41 @@ function QrisPaymentDialog({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { type Dispatch, useEffect, useRef, useState } from "react";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
getPaymentUrl,
|
getPaymentUrl,
|
||||||
|
getPaymentUrlHostname,
|
||||||
getStripeClientSecret,
|
getStripeClientSecret,
|
||||||
isEzpayPayment,
|
isEzpayPayment,
|
||||||
launchEzpayRedirect,
|
launchEzpayRedirect,
|
||||||
@@ -41,29 +42,31 @@ 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;
|
||||||
handleQrisClose: () => void;
|
handleRegionalQrClose: () => void;
|
||||||
handleStripeClose: () => void;
|
handleStripeClose: () => void;
|
||||||
handleStripeConfirmed: () => void;
|
handleStripeConfirmed: () => void;
|
||||||
isConfirmingEzpay: boolean;
|
isConfirmingEzpay: boolean;
|
||||||
qrisErrorMessage: string | null;
|
regionalQrErrorMessage: string | null;
|
||||||
qrisPayment: QrisPaymentDetails | null;
|
regionalQrPayment: RegionalQrPaymentDetails | null;
|
||||||
qrisStatus: PaymentContextState["orderStatus"];
|
regionalQrStatus: PaymentContextState["orderStatus"];
|
||||||
resetLaunchState: () => void;
|
resetLaunchState: () => void;
|
||||||
shouldShowEzpayConfirmDialog: boolean;
|
shouldShowEzpayConfirmDialog: boolean;
|
||||||
shouldShowQrisDialog: boolean;
|
shouldShowRegionalQrDialog: boolean;
|
||||||
shouldShowStripeDialog: boolean;
|
shouldShowStripeDialog: boolean;
|
||||||
stripeClientSecret: string | null;
|
stripeClientSecret: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QrisPaymentDetails {
|
export interface RegionalQrPaymentDetails {
|
||||||
amountCents: number;
|
amountCents: number;
|
||||||
currency: string;
|
currency: string;
|
||||||
|
experience: "gcashQrPh" | "qris" | "paymentQr";
|
||||||
orderId: string;
|
orderId: string;
|
||||||
qrData: string;
|
qrData: string;
|
||||||
}
|
}
|
||||||
@@ -153,30 +156,36 @@ 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<
|
||||||
string | null
|
string | null
|
||||||
>(null);
|
>(null);
|
||||||
const [isConfirmingEzpay, setIsConfirmingEzpay] = useState(false);
|
const [isConfirmingEzpay, setIsConfirmingEzpay] = useState(false);
|
||||||
const [hiddenQrisOrderId, setHiddenQrisOrderId] = useState<string | null>(
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const stripeClientSecret = payment.payParams
|
const stripeClientSecret = payment.payParams
|
||||||
? getStripeClientSecret(payment.payParams)
|
? getStripeClientSecret(payment.payParams)
|
||||||
: null;
|
: null;
|
||||||
|
const selectedPlan = payment.plans.find(
|
||||||
|
(item) => item.planId === payment.selectedPlanId,
|
||||||
|
);
|
||||||
|
const paymentCurrency = payment.payParams
|
||||||
|
? paymentParamString(payment.payParams, "currency") ??
|
||||||
|
selectedPlan?.currency ??
|
||||||
|
null
|
||||||
|
: selectedPlan?.currency ?? null;
|
||||||
const ezpayLaunchTarget =
|
const ezpayLaunchTarget =
|
||||||
payment.payParams && isEzpayPayment(payment.payParams)
|
payment.payParams && isEzpayPayment(payment.payParams)
|
||||||
? resolveEzpayLaunchTarget(payment.payParams)
|
? resolveEzpayLaunchTarget(payment.payParams, {
|
||||||
|
countryCode,
|
||||||
|
currency: paymentCurrency,
|
||||||
|
})
|
||||||
: null;
|
: null;
|
||||||
const ezpayPaymentUrl =
|
const ezpayPaymentUrl =
|
||||||
ezpayLaunchTarget?.kind === "url"
|
ezpayLaunchTarget?.kind === "url"
|
||||||
? ezpayLaunchTarget.paymentUrl
|
? ezpayLaunchTarget.paymentUrl
|
||||||
: null;
|
: null;
|
||||||
const selectedPlan = payment.plans.find(
|
const regionalQrPayment: RegionalQrPaymentDetails | null =
|
||||||
(item) => item.planId === payment.selectedPlanId,
|
|
||||||
);
|
|
||||||
const qrisPayment: QrisPaymentDetails | null =
|
|
||||||
payment.payParams &&
|
payment.payParams &&
|
||||||
payment.currentOrderId &&
|
payment.currentOrderId &&
|
||||||
ezpayLaunchTarget?.kind === "qr"
|
ezpayLaunchTarget?.kind === "qr"
|
||||||
@@ -186,9 +195,9 @@ export function usePaymentLaunchFlow({
|
|||||||
selectedPlan?.amountCents ??
|
selectedPlan?.amountCents ??
|
||||||
0,
|
0,
|
||||||
currency:
|
currency:
|
||||||
paymentParamString(payment.payParams, "currency") ??
|
paymentCurrency ??
|
||||||
selectedPlan?.currency ??
|
(ezpayLaunchTarget.experience === "gcashQrPh" ? "PHP" : "IDR"),
|
||||||
"IDR",
|
experience: ezpayLaunchTarget.experience,
|
||||||
orderId: payment.currentOrderId,
|
orderId: payment.currentOrderId,
|
||||||
qrData: ezpayLaunchTarget.qrData,
|
qrData: ezpayLaunchTarget.qrData,
|
||||||
}
|
}
|
||||||
@@ -207,7 +216,33 @@ export function usePaymentLaunchFlow({
|
|||||||
|
|
||||||
const isEzpay = isEzpayPayment(payment.payParams);
|
const isEzpay = isEzpayPayment(payment.payParams);
|
||||||
if (isEzpay) {
|
if (isEzpay) {
|
||||||
const target = resolveEzpayLaunchTarget(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") {
|
if (target.kind === "error") {
|
||||||
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
||||||
paymentDispatch({
|
paymentDispatch({
|
||||||
@@ -222,11 +257,18 @@ export function usePaymentLaunchFlow({
|
|||||||
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
trackPaymentCheckoutFailed(payment, "missing_checkout_url");
|
||||||
paymentDispatch({
|
paymentDispatch({
|
||||||
type: "PaymentLaunchFailed",
|
type: "PaymentLaunchFailed",
|
||||||
errorMessage: "Missing order id before showing QRIS.",
|
errorMessage: "Missing order id before showing payment QR code.",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
trackPaymentCheckoutOpened(payment, "qris_embedded");
|
trackPaymentCheckoutOpened(
|
||||||
|
payment,
|
||||||
|
target.experience === "qris"
|
||||||
|
? "qris_embedded"
|
||||||
|
: target.experience === "gcashQrPh"
|
||||||
|
? "gcash_qrph_embedded"
|
||||||
|
: "payment_qr_embedded",
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +276,7 @@ export function usePaymentLaunchFlow({
|
|||||||
if (!AppEnvUtil.isProduction()) {
|
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;
|
||||||
@@ -260,7 +302,7 @@ export function usePaymentLaunchFlow({
|
|||||||
const paymentUrl = getPaymentUrl(payment.payParams);
|
const paymentUrl = getPaymentUrl(payment.payParams);
|
||||||
if (paymentUrl) {
|
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");
|
||||||
@@ -281,6 +323,7 @@ export function usePaymentLaunchFlow({
|
|||||||
log,
|
log,
|
||||||
logScope,
|
logScope,
|
||||||
characterSlug,
|
characterSlug,
|
||||||
|
countryCode,
|
||||||
payment.currentOrderId,
|
payment.currentOrderId,
|
||||||
payment,
|
payment,
|
||||||
payment.launchNonce,
|
payment.launchNonce,
|
||||||
@@ -289,6 +332,7 @@ export function usePaymentLaunchFlow({
|
|||||||
payment.plans,
|
payment.plans,
|
||||||
payment.selectedPlanId,
|
payment.selectedPlanId,
|
||||||
paymentDispatch,
|
paymentDispatch,
|
||||||
|
paymentCurrency,
|
||||||
returnTo,
|
returnTo,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
giftCategory,
|
giftCategory,
|
||||||
@@ -305,16 +349,13 @@ export function usePaymentLaunchFlow({
|
|||||||
payParams: payment.payParams,
|
payParams: payment.payParams,
|
||||||
paymentUrl: ezpayPaymentUrl,
|
paymentUrl: ezpayPaymentUrl,
|
||||||
});
|
});
|
||||||
const shouldShowQrisDialog = Boolean(
|
const shouldShowRegionalQrDialog = Boolean(
|
||||||
qrisPayment &&
|
regionalQrPayment && !payment.isPaid,
|
||||||
qrisPayment.orderId !== hiddenQrisOrderId &&
|
|
||||||
!payment.isPaid,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
function resetLaunchState(): void {
|
function resetLaunchState(): void {
|
||||||
setIsConfirmingEzpay(false);
|
setIsConfirmingEzpay(false);
|
||||||
setHiddenStripeClientSecret(null);
|
setHiddenStripeClientSecret(null);
|
||||||
setHiddenQrisOrderId(null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleStripeClose(): void {
|
function handleStripeClose(): void {
|
||||||
@@ -361,28 +402,29 @@ export function usePaymentLaunchFlow({
|
|||||||
paymentDispatch({ type: "PaymentReset" });
|
paymentDispatch({ type: "PaymentReset" });
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleQrisClose(): void {
|
function handleRegionalQrClose(): void {
|
||||||
log.debug(`[${logScope}] qris dialog closed`, {
|
log.debug(`[${logScope}] regional payment QR dialog closed`, {
|
||||||
orderId: qrisPayment?.orderId ?? payment.currentOrderId,
|
orderId: regionalQrPayment?.orderId ?? payment.currentOrderId,
|
||||||
|
experience: regionalQrPayment?.experience ?? null,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
});
|
});
|
||||||
setHiddenQrisOrderId(qrisPayment?.orderId ?? payment.currentOrderId);
|
paymentDispatch({ type: "PaymentReset" });
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ezpayPaymentUrl,
|
ezpayPaymentUrl,
|
||||||
handleEzpayCancel,
|
handleEzpayCancel,
|
||||||
handleEzpayConfirm,
|
handleEzpayConfirm,
|
||||||
handleQrisClose,
|
handleRegionalQrClose,
|
||||||
handleStripeClose,
|
handleStripeClose,
|
||||||
handleStripeConfirmed,
|
handleStripeConfirmed,
|
||||||
isConfirmingEzpay,
|
isConfirmingEzpay,
|
||||||
qrisErrorMessage: payment.errorMessage,
|
regionalQrErrorMessage: payment.errorMessage,
|
||||||
qrisPayment,
|
regionalQrPayment,
|
||||||
qrisStatus: payment.orderStatus,
|
regionalQrStatus: payment.orderStatus,
|
||||||
resetLaunchState,
|
resetLaunchState,
|
||||||
shouldShowEzpayConfirmDialog,
|
shouldShowEzpayConfirmDialog,
|
||||||
shouldShowQrisDialog,
|
shouldShowRegionalQrDialog,
|
||||||
shouldShowStripeDialog,
|
shouldShowStripeDialog,
|
||||||
stripeClientSecret,
|
stripeClientSecret,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { deriveChatSupportCta } from "../chat-support-cta";
|
||||||
|
|
||||||
|
describe("deriveChatSupportCta", () => {
|
||||||
|
const now = Date.parse("2026-07-28T00:00:00.000Z");
|
||||||
|
|
||||||
|
it("shows first recharge ahead of a weaker role offer without inventing a timer", () => {
|
||||||
|
expect(
|
||||||
|
deriveChatSupportCta({
|
||||||
|
isFirstRecharge: true,
|
||||||
|
commercialOffer: {
|
||||||
|
enabled: true,
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
characterId: "elio",
|
||||||
|
planId: "vip_annual",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-29T00:00:00.000Z",
|
||||||
|
triggerReason: "price_objection",
|
||||||
|
message: "I got this for you.",
|
||||||
|
},
|
||||||
|
nowMs: now,
|
||||||
|
}),
|
||||||
|
).toMatchObject({
|
||||||
|
kind: "firstRecharge",
|
||||||
|
label: "Support me · 50% OFF · First recharge",
|
||||||
|
commercialOfferId: null,
|
||||||
|
expiresAt: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a server-anchored 24-hour role offer countdown", () => {
|
||||||
|
expect(
|
||||||
|
deriveChatSupportCta({
|
||||||
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: {
|
||||||
|
enabled: true,
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
characterId: "maya-tan",
|
||||||
|
planId: "vip_annual",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-29T00:00:00.000Z",
|
||||||
|
triggerReason: "price_objection",
|
||||||
|
message: "I got this for you.",
|
||||||
|
},
|
||||||
|
nowMs: now,
|
||||||
|
}),
|
||||||
|
).toMatchObject({
|
||||||
|
kind: "commercialOffer",
|
||||||
|
label: "Support me · 30% OFF · 23:59:59",
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
expiresAt: "2026-07-29T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns to Support me after an offer expires or is absent", () => {
|
||||||
|
expect(
|
||||||
|
deriveChatSupportCta({
|
||||||
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: null,
|
||||||
|
nowMs: now,
|
||||||
|
}).label,
|
||||||
|
).toBe("Support me");
|
||||||
|
expect(
|
||||||
|
deriveChatSupportCta({
|
||||||
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: {
|
||||||
|
enabled: true,
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
characterId: "elio",
|
||||||
|
planId: "vip_annual",
|
||||||
|
discountPercent: 30,
|
||||||
|
pricePercent: 70,
|
||||||
|
expiresAt: "2026-07-27T00:00:00.000Z",
|
||||||
|
triggerReason: "price_objection",
|
||||||
|
message: "I got this for you.",
|
||||||
|
},
|
||||||
|
nowMs: now,
|
||||||
|
}).label,
|
||||||
|
).toBe("Support me");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,8 +33,8 @@ import {
|
|||||||
ChatHeader,
|
ChatHeader,
|
||||||
ChatInputBar,
|
ChatInputBar,
|
||||||
ChatInsufficientCreditsBanner,
|
ChatInsufficientCreditsBanner,
|
||||||
|
ChatSupportButton,
|
||||||
ChatUnlockDialogs,
|
ChatUnlockDialogs,
|
||||||
FirstRechargeOfferBanner,
|
|
||||||
FullscreenImageViewer,
|
FullscreenImageViewer,
|
||||||
PwaInstallOverlay,
|
PwaInstallOverlay,
|
||||||
} from "./components";
|
} from "./components";
|
||||||
@@ -46,7 +46,8 @@ import {
|
|||||||
import {
|
import {
|
||||||
deriveIsGuest,
|
deriveIsGuest,
|
||||||
} from "./chat-screen.helpers";
|
} from "./chat-screen.helpers";
|
||||||
import { useFirstRechargeOfferBanner } from "./hooks/use-first-recharge-offer-banner";
|
import { useChatSupportCta } from "./hooks/use-chat-support-cta";
|
||||||
|
import { useChatCommercialMessages } from "./hooks/use-chat-commercial-messages";
|
||||||
import { useChatUnlockCoordinator } from "./hooks/use-chat-unlock-coordinator";
|
import { useChatUnlockCoordinator } from "./hooks/use-chat-unlock-coordinator";
|
||||||
import { useChatGuestLogin } from "./hooks/use-chat-guest-login";
|
import { useChatGuestLogin } from "./hooks/use-chat-guest-login";
|
||||||
import { useChatMessageLimitBanner } from "./hooks/use-chat-message-limit-banner";
|
import { useChatMessageLimitBanner } from "./hooks/use-chat-message-limit-banner";
|
||||||
@@ -130,10 +131,15 @@ export function ChatScreen() {
|
|||||||
upgradeReason: state.upgradeReason,
|
upgradeReason: state.upgradeReason,
|
||||||
paymentGuidance: state.paymentGuidance,
|
paymentGuidance: state.paymentGuidance,
|
||||||
});
|
});
|
||||||
const firstRechargeOfferBanner = useFirstRechargeOfferBanner({
|
const supportCta = useChatSupportCta({
|
||||||
|
characterId: character.id,
|
||||||
historyLoaded: state.historyLoaded,
|
historyLoaded: state.historyLoaded,
|
||||||
loginStatus: authState.loginStatus,
|
loginStatus: authState.loginStatus,
|
||||||
});
|
});
|
||||||
|
useChatCommercialMessages({
|
||||||
|
characterId: character.id,
|
||||||
|
loginStatus: authState.loginStatus,
|
||||||
|
});
|
||||||
const shouldShowPwaInstall =
|
const shouldShowPwaInstall =
|
||||||
state.historyLoaded && state.historyMessages.length >= 10;
|
state.historyLoaded && state.historyMessages.length >= 10;
|
||||||
useChatGuestLogin({
|
useChatGuestLogin({
|
||||||
@@ -422,13 +428,13 @@ export function ChatScreen() {
|
|||||||
<ChatHeader
|
<ChatHeader
|
||||||
isGuest={isGuest}
|
isGuest={isGuest}
|
||||||
offerBanner={
|
offerBanner={
|
||||||
<FirstRechargeOfferBanner
|
supportCta.visible ? (
|
||||||
visible={firstRechargeOfferBanner.visible}
|
<ChatSupportButton
|
||||||
discountPercent={firstRechargeOfferBanner.discountPercent}
|
kind={supportCta.kind}
|
||||||
onClick={firstRechargeOfferBanner.claim}
|
label={supportCta.label}
|
||||||
onClose={firstRechargeOfferBanner.close}
|
onClick={supportCta.open}
|
||||||
variant="compact"
|
/>
|
||||||
/>
|
) : null
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { CommercialOfferSummary } from "@/data/schemas/payment";
|
||||||
|
|
||||||
|
export type ChatSupportCtaKind =
|
||||||
|
| "support"
|
||||||
|
| "firstRecharge"
|
||||||
|
| "commercialOffer";
|
||||||
|
|
||||||
|
export interface ChatSupportCtaView {
|
||||||
|
kind: ChatSupportCtaKind;
|
||||||
|
label: string;
|
||||||
|
commercialOfferId: string | null;
|
||||||
|
planId: string | null;
|
||||||
|
expiresAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveChatSupportCta(input: {
|
||||||
|
isFirstRecharge: boolean;
|
||||||
|
commercialOffer: CommercialOfferSummary | null;
|
||||||
|
nowMs: number;
|
||||||
|
}): ChatSupportCtaView {
|
||||||
|
if (input.isFirstRecharge) {
|
||||||
|
return {
|
||||||
|
kind: "firstRecharge",
|
||||||
|
label: "Support me · 50% OFF · First recharge",
|
||||||
|
commercialOfferId: null,
|
||||||
|
planId: null,
|
||||||
|
expiresAt: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const offer = input.commercialOffer;
|
||||||
|
const expiresAtMs = offer ? Date.parse(offer.expiresAt) : Number.NaN;
|
||||||
|
if (offer?.enabled && Number.isFinite(expiresAtMs) && expiresAtMs > input.nowMs) {
|
||||||
|
return {
|
||||||
|
kind: "commercialOffer",
|
||||||
|
label: `Support me · ${offer.discountPercent}% OFF · ${formatOfferCountdown(expiresAtMs, input.nowMs)}`,
|
||||||
|
commercialOfferId: offer.commercialOfferId,
|
||||||
|
planId: offer.planId,
|
||||||
|
expiresAt: offer.expiresAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
kind: "support",
|
||||||
|
label: "Support me",
|
||||||
|
commercialOfferId: null,
|
||||||
|
planId: null,
|
||||||
|
expiresAt: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatOfferCountdown(expiresAtMs: number, nowMs: number): string {
|
||||||
|
const totalSeconds = Math.max(
|
||||||
|
0,
|
||||||
|
Math.ceil((expiresAtMs - nowMs) / 1000) - 1,
|
||||||
|
);
|
||||||
|
const hours = Math.floor(totalSeconds / 3600);
|
||||||
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||||
|
const seconds = totalSeconds % 60;
|
||||||
|
return [hours, minutes, seconds]
|
||||||
|
.map((value) => String(value).padStart(2, "0"))
|
||||||
|
.join(":");
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Heart, Sparkles } from "lucide-react";
|
||||||
|
|
||||||
|
import type { ChatSupportCtaKind } from "../chat-support-cta";
|
||||||
|
|
||||||
|
export interface ChatSupportButtonProps {
|
||||||
|
kind: ChatSupportCtaKind;
|
||||||
|
label: string;
|
||||||
|
onClick: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChatSupportButton({
|
||||||
|
kind,
|
||||||
|
label,
|
||||||
|
onClick,
|
||||||
|
}: ChatSupportButtonProps) {
|
||||||
|
const Icon = kind === "support" ? Heart : Sparkles;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-analytics-key="chat.support_character"
|
||||||
|
data-support-state={kind}
|
||||||
|
className="inline-flex min-h-9 max-w-full items-center justify-center gap-1.5 rounded-full border border-[rgba(255,255,255,0.22)] bg-[linear-gradient(135deg,rgba(246,87,160,0.96),rgba(255,119,84,0.94))] px-3 py-1.5 text-center text-[12px] font-extrabold leading-tight text-white shadow-[0_8px_24px_rgba(246,87,160,0.3)] backdrop-blur-md transition active:scale-95"
|
||||||
|
aria-label={label}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<Icon className="shrink-0" size={14} strokeWidth={2.5} aria-hidden="true" />
|
||||||
|
<span className="whitespace-normal text-balance">{label}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ export * from "./chat-insufficient-credits-banner";
|
|||||||
export * from "./chat-input-bar";
|
export * from "./chat-input-bar";
|
||||||
export * from "./chat-input-text-field";
|
export * from "./chat-input-text-field";
|
||||||
export * from "./chat-send-button";
|
export * from "./chat-send-button";
|
||||||
|
export * from "./chat-support-button";
|
||||||
export * from "./chat-unlock-dialogs";
|
export * from "./chat-unlock-dialogs";
|
||||||
export * from "./date-header";
|
export * from "./date-header";
|
||||||
export * from "./first-recharge-offer-banner";
|
export * from "./first-recharge-offer-banner";
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";
|
|||||||
import { ArrowRight, CircleDollarSign, X } from "lucide-react";
|
import { ArrowRight, CircleDollarSign, X } from "lucide-react";
|
||||||
|
|
||||||
import type { PaymentGuidance } from "@/data/schemas/chat";
|
import type { PaymentGuidance } from "@/data/schemas/chat";
|
||||||
|
import type { PaymentAnalyticsTriggerReason } from "@/lib/analytics/payment_analytics_context";
|
||||||
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
|
import { recordChatActionEventById } from "@/lib/chat/chat_action_events";
|
||||||
import { useActiveCharacter } from "@/providers/character-provider";
|
import { useActiveCharacter } from "@/providers/character-provider";
|
||||||
import { useAppNavigator } from "@/router/use-app-navigator";
|
import { useAppNavigator } from "@/router/use-app-navigator";
|
||||||
@@ -15,6 +16,18 @@ export interface PaymentGuidanceCardProps {
|
|||||||
guidance: PaymentGuidance;
|
guidance: PaymentGuidance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function triggerReasonForGuidance(
|
||||||
|
scene: PaymentGuidance["scene"],
|
||||||
|
): PaymentAnalyticsTriggerReason {
|
||||||
|
if (scene === "supportCharacter" || scene === "vip" || scene === "purchaseOptions") {
|
||||||
|
return "vip_cta";
|
||||||
|
}
|
||||||
|
if (scene === "privateMessageLocked" || scene === "historyLocked") {
|
||||||
|
return "private_topic_limit";
|
||||||
|
}
|
||||||
|
return "insufficient_credits";
|
||||||
|
}
|
||||||
|
|
||||||
export function PaymentGuidanceCard({ guidance }: PaymentGuidanceCardProps) {
|
export function PaymentGuidanceCard({ guidance }: PaymentGuidanceCardProps) {
|
||||||
const character = useActiveCharacter();
|
const character = useActiveCharacter();
|
||||||
const navigator = useAppNavigator();
|
const navigator = useAppNavigator();
|
||||||
@@ -91,7 +104,7 @@ export function PaymentGuidanceCard({ guidance }: PaymentGuidanceCardProps) {
|
|||||||
chatActionId: guidance.guidanceId,
|
chatActionId: guidance.guidanceId,
|
||||||
analytics: {
|
analytics: {
|
||||||
entryPoint: "chat_input",
|
entryPoint: "chat_input",
|
||||||
triggerReason: "insufficient_credits",
|
triggerReason: triggerReasonForGuidance(guidance.scene),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
import { createChatWebSocket } from "@/core/net/chat-websocket";
|
||||||
|
import type { LoginStatus } from "@/data/schemas/auth";
|
||||||
|
import { getSessionAccessToken } from "@/lib/auth/auth_session";
|
||||||
|
import { useChatDispatch } from "@/stores/chat/chat-context";
|
||||||
|
|
||||||
|
export function useChatCommercialMessages(input: {
|
||||||
|
characterId: string;
|
||||||
|
loginStatus: LoginStatus;
|
||||||
|
}) {
|
||||||
|
const chatDispatch = useChatDispatch();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (input.loginStatus === "notLoggedIn" || input.loginStatus === "guest") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let disposed = false;
|
||||||
|
let socket: ReturnType<typeof createChatWebSocket> | null = null;
|
||||||
|
void getSessionAccessToken().then((token) => {
|
||||||
|
if (disposed || !token) return;
|
||||||
|
socket = createChatWebSocket(token);
|
||||||
|
socket.onCommercialMessage = (message) => {
|
||||||
|
if (message.characterId !== input.characterId) return;
|
||||||
|
chatDispatch({ type: "ChatCommercialMessageReceived", message });
|
||||||
|
};
|
||||||
|
socket.connect();
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
disposed = true;
|
||||||
|
socket?.disconnect();
|
||||||
|
};
|
||||||
|
}, [chatDispatch, input.characterId, input.loginStatus]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { shallowEqual } from "@xstate/react";
|
||||||
|
|
||||||
|
import type { LoginStatus } from "@/data/schemas/auth";
|
||||||
|
import { getDefaultPayChannelForCountryCode } from "@/lib/payment/default_pay_channel";
|
||||||
|
import { useAppNavigator } from "@/router/use-app-navigator";
|
||||||
|
import {
|
||||||
|
usePaymentDispatch,
|
||||||
|
usePaymentSelector,
|
||||||
|
} from "@/stores/payment/payment-context";
|
||||||
|
import { useUserSelector } from "@/stores/user/user-context";
|
||||||
|
|
||||||
|
import { deriveChatSupportCta } from "../chat-support-cta";
|
||||||
|
|
||||||
|
export function useChatSupportCta(input: {
|
||||||
|
characterId: string;
|
||||||
|
historyLoaded: boolean;
|
||||||
|
loginStatus: LoginStatus;
|
||||||
|
}) {
|
||||||
|
const navigator = useAppNavigator();
|
||||||
|
const paymentDispatch = usePaymentDispatch();
|
||||||
|
const initializedCharacterRef = useRef<string | null>(null);
|
||||||
|
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||||
|
const payment = usePaymentSelector(
|
||||||
|
(state) => ({
|
||||||
|
commercialOffer: state.context.commercialOffer,
|
||||||
|
isFirstRecharge: state.context.isFirstRecharge,
|
||||||
|
supportCharacterId: state.context.supportCharacterId,
|
||||||
|
}),
|
||||||
|
shallowEqual,
|
||||||
|
);
|
||||||
|
const countryCode = useUserSelector(
|
||||||
|
(state) => state.context.currentUser?.countryCode,
|
||||||
|
);
|
||||||
|
const isAuthenticated =
|
||||||
|
input.loginStatus !== "notLoggedIn" && input.loginStatus !== "guest";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAuthenticated) return;
|
||||||
|
if (initializedCharacterRef.current === input.characterId) return;
|
||||||
|
initializedCharacterRef.current = input.characterId;
|
||||||
|
paymentDispatch({
|
||||||
|
type: "PaymentInit",
|
||||||
|
characterId: input.characterId,
|
||||||
|
payChannel: getDefaultPayChannelForCountryCode(countryCode),
|
||||||
|
});
|
||||||
|
}, [countryCode, input.characterId, isAuthenticated, paymentDispatch]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!payment.commercialOffer) return;
|
||||||
|
const timer = window.setInterval(() => setNowMs(Date.now()), 1000);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [payment.commercialOffer]);
|
||||||
|
|
||||||
|
const cta = useMemo(
|
||||||
|
() =>
|
||||||
|
deriveChatSupportCta({
|
||||||
|
isFirstRecharge:
|
||||||
|
isAuthenticated && payment.supportCharacterId === input.characterId
|
||||||
|
? payment.isFirstRecharge
|
||||||
|
: false,
|
||||||
|
commercialOffer:
|
||||||
|
isAuthenticated && payment.supportCharacterId === input.characterId
|
||||||
|
? payment.commercialOffer
|
||||||
|
: null,
|
||||||
|
nowMs,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
input.characterId,
|
||||||
|
isAuthenticated,
|
||||||
|
nowMs,
|
||||||
|
payment.commercialOffer,
|
||||||
|
payment.isFirstRecharge,
|
||||||
|
payment.supportCharacterId,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const open = () => {
|
||||||
|
navigator.openSubscription({
|
||||||
|
type: cta.planId?.startsWith("dol_") ? "topup" : "vip",
|
||||||
|
returnTo: "chat",
|
||||||
|
...(cta.planId ? { planId: cta.planId } : {}),
|
||||||
|
...(cta.commercialOfferId
|
||||||
|
? { commercialOfferId: cta.commercialOfferId }
|
||||||
|
: {}),
|
||||||
|
analytics: {
|
||||||
|
entryPoint: "chat_offer_banner",
|
||||||
|
triggerReason:
|
||||||
|
cta.kind === "support" ? "vip_cta" : "commercial_offer",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return { ...cta, visible: input.historyLoaded, open };
|
||||||
|
}
|
||||||
@@ -189,6 +189,7 @@ export default function ExternalEntryPersist({
|
|||||||
authState.hasInitialized,
|
authState.hasInitialized,
|
||||||
authState.isLoading,
|
authState.isLoading,
|
||||||
authState.loginStatus,
|
authState.loginStatus,
|
||||||
|
character,
|
||||||
destination,
|
destination,
|
||||||
hasPersisted,
|
hasPersisted,
|
||||||
handoffCompleted,
|
handoffCompleted,
|
||||||
|
|||||||
@@ -34,14 +34,14 @@ describe("SubscriptionPage", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses Elio for missing source navigation context", async () => {
|
it("keeps the recipient empty when source navigation has no character", async () => {
|
||||||
const page = await SubscriptionPage({
|
const page = await SubscriptionPage({
|
||||||
searchParams: Promise.resolve({}),
|
searchParams: Promise.resolve({}),
|
||||||
});
|
});
|
||||||
|
|
||||||
renderToStaticMarkup(page);
|
renderToStaticMarkup(page);
|
||||||
expect(mocks.screenProps).toHaveBeenLastCalledWith(
|
expect(mocks.screenProps).toHaveBeenLastCalledWith(
|
||||||
expect.objectContaining({ sourceCharacterSlug: "elio" }),
|
expect.objectContaining({ sourceCharacterSlug: null }),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,16 @@ import { createRoot, type Root } from "react-dom/client";
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
const mocks = vi.hoisted(() => {
|
const mocks = vi.hoisted(() => {
|
||||||
|
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",
|
||||||
|
},
|
||||||
|
];
|
||||||
const payment = {
|
const payment = {
|
||||||
status: "ready",
|
status: "ready",
|
||||||
plans: [
|
plans: [
|
||||||
@@ -52,7 +62,17 @@ const mocks = vi.hoisted(() => {
|
|||||||
payment.selectedPlanId = event.planId;
|
payment.selectedPlanId = event.planId;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return { payment, paymentDispatch, planClick: vi.fn() };
|
return {
|
||||||
|
characterCatalog: {
|
||||||
|
characters,
|
||||||
|
getBySlug: (slug: string | null) =>
|
||||||
|
characters.find((character) => character.slug === slug) ?? null,
|
||||||
|
},
|
||||||
|
payment,
|
||||||
|
paymentDispatch,
|
||||||
|
paymentFlowInput: vi.fn(),
|
||||||
|
planClick: vi.fn(),
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.mock("@/app/_components", () => ({
|
vi.mock("@/app/_components", () => ({
|
||||||
@@ -83,6 +103,10 @@ vi.mock("@/stores/user/user-context", () => ({
|
|||||||
useUserState: () => ({ currentUser: { countryCode: "ID" } }),
|
useUserState: () => ({ currentUser: { countryCode: "ID" } }),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/providers/character-catalog-provider", () => ({
|
||||||
|
useCharacterCatalog: () => mocks.characterCatalog,
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/payment/payment_method", () => ({
|
vi.mock("@/lib/payment/payment_method", () => ({
|
||||||
getPaymentMethodConfig: () => ({
|
getPaymentMethodConfig: () => ({
|
||||||
initialPayChannel: "stripe",
|
initialPayChannel: "stripe",
|
||||||
@@ -97,13 +121,16 @@ vi.mock("@/lib/analytics", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../use-subscription-payment-flow", () => ({
|
vi.mock("../use-subscription-payment-flow", () => ({
|
||||||
useSubscriptionPaymentFlow: () => ({
|
useSubscriptionPaymentFlow: (input: unknown) => {
|
||||||
payment: mocks.payment,
|
mocks.paymentFlowInput(input);
|
||||||
paymentDispatch: mocks.paymentDispatch,
|
return {
|
||||||
showPaymentSuccessDialog: false,
|
payment: mocks.payment,
|
||||||
handleBackClick: vi.fn(),
|
paymentDispatch: mocks.paymentDispatch,
|
||||||
handlePaymentSuccessClose: vi.fn(),
|
showPaymentSuccessDialog: false,
|
||||||
}),
|
handleBackClick: vi.fn(),
|
||||||
|
handlePaymentSuccessClose: vi.fn(),
|
||||||
|
};
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../components", () => ({
|
vi.mock("../components", () => ({
|
||||||
@@ -170,8 +197,16 @@ describe("SubscriptionScreen payment selection flow", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
|
||||||
.IS_REACT_ACT_ENVIRONMENT = true;
|
.IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
mocks.payment.isFirstRecharge = false;
|
||||||
|
mocks.payment.commercialOffer = null;
|
||||||
|
for (const plan of mocks.payment.plans) {
|
||||||
|
delete (plan as Record<string, unknown>).isFirstRechargeOffer;
|
||||||
|
delete (plan as Record<string, unknown>).firstRechargeDiscountPercent;
|
||||||
|
delete (plan as Record<string, unknown>).promotionType;
|
||||||
|
}
|
||||||
mocks.payment.selectedPlanId = "vip_monthly";
|
mocks.payment.selectedPlanId = "vip_monthly";
|
||||||
mocks.paymentDispatch.mockClear();
|
mocks.paymentDispatch.mockClear();
|
||||||
|
mocks.paymentFlowInput.mockClear();
|
||||||
mocks.planClick.mockClear();
|
mocks.planClick.mockClear();
|
||||||
container = document.createElement("div");
|
container = document.createElement("div");
|
||||||
document.body.appendChild(container);
|
document.body.appendChild(container);
|
||||||
@@ -184,7 +219,7 @@ describe("SubscriptionScreen payment selection flow", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("confirms VIP selection before enabling the separate checkout button", () => {
|
it("confirms VIP selection before enabling the separate checkout button", () => {
|
||||||
act(() => root.render(<SubscriptionScreen />));
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
const checkout = container.querySelector<HTMLButtonElement>(
|
const checkout = container.querySelector<HTMLButtonElement>(
|
||||||
'[data-testid="checkout"]',
|
'[data-testid="checkout"]',
|
||||||
);
|
);
|
||||||
@@ -215,7 +250,7 @@ describe("SubscriptionScreen payment selection flow", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the original selection when VIP confirmation is cancelled", () => {
|
it("keeps the original selection when VIP confirmation is cancelled", () => {
|
||||||
act(() => root.render(<SubscriptionScreen />));
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
act(() => clickButton(container, "vip_quarterly"));
|
act(() => clickButton(container, "vip_quarterly"));
|
||||||
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
|
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
|
||||||
|
|
||||||
@@ -230,21 +265,21 @@ describe("SubscriptionScreen payment selection flow", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("requires VIP confirmation again after the page is remounted", () => {
|
it("requires VIP confirmation again after the page is remounted", () => {
|
||||||
act(() => root.render(<SubscriptionScreen />));
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
act(() => clickButton(container, "vip_monthly"));
|
act(() => clickButton(container, "vip_monthly"));
|
||||||
act(() => clickButton(container, "Confirm"));
|
act(() => clickButton(container, "Confirm"));
|
||||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||||
|
|
||||||
act(() => root.unmount());
|
act(() => root.unmount());
|
||||||
root = createRoot(container);
|
root = createRoot(container);
|
||||||
act(() => root.render(<SubscriptionScreen />));
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
act(() => clickButton(container, "vip_monthly"));
|
act(() => clickButton(container, "vip_monthly"));
|
||||||
|
|
||||||
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
|
expect(container.querySelector('[role="dialog"]')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("selects a coin package without showing the renewal dialog", () => {
|
it("selects a coin package without showing the renewal dialog", () => {
|
||||||
act(() => root.render(<SubscriptionScreen />));
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
act(() => clickButton(container, "coin_1000"));
|
act(() => clickButton(container, "coin_1000"));
|
||||||
|
|
||||||
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
expect(container.querySelector('[role="dialog"]')).toBeNull();
|
||||||
@@ -275,6 +310,81 @@ describe("SubscriptionScreen payment selection flow", () => {
|
|||||||
expect(guidance?.textContent).toContain("cannot continue");
|
expect(guidance?.textContent).toContain("cannot continue");
|
||||||
expect(guidance?.textContent).not.toContain("Elio");
|
expect(guidance?.textContent).not.toContain("Elio");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not render the first recharge banner on the subscription page", () => {
|
||||||
|
mocks.payment.isFirstRecharge = true;
|
||||||
|
Object.assign(mocks.payment.plans[0] as Record<string, unknown>, {
|
||||||
|
isFirstRechargeOffer: true,
|
||||||
|
firstRechargeDiscountPercent: 50,
|
||||||
|
promotionType: "first_recharge_half_price",
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => root.render(<SubscriptionScreen sourceCharacterSlug="elio" />));
|
||||||
|
|
||||||
|
expect(container.textContent).not.toContain("First Recharge Offer");
|
||||||
|
expect(container.textContent).not.toContain(
|
||||||
|
"Your first recharge price is already applied",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["elio", "maya", "nayeli"])(
|
||||||
|
"inherits the %s chat character without rendering a recipient selector",
|
||||||
|
(sourceCharacterSlug) => {
|
||||||
|
mocks.payment.selectedPlanId = "coin_1000";
|
||||||
|
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<SubscriptionScreen
|
||||||
|
subscriptionType="topup"
|
||||||
|
sourceCharacterSlug={sourceCharacterSlug}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkout = container.querySelector<HTMLButtonElement>(
|
||||||
|
'[data-testid="checkout"]',
|
||||||
|
);
|
||||||
|
expect(container.textContent).not.toContain("Supporting ");
|
||||||
|
expect(container.textContent).not.toContain(
|
||||||
|
"Choose who you want to support",
|
||||||
|
);
|
||||||
|
expect(container.textContent).not.toContain(
|
||||||
|
"Your VIP or credit purchase supports the character you choose",
|
||||||
|
);
|
||||||
|
expect(checkout?.disabled).toBe(false);
|
||||||
|
expect(mocks.paymentFlowInput).toHaveBeenLastCalledWith(
|
||||||
|
expect.objectContaining({ sourceCharacterSlug }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("does not invent a recipient when opened without a source character", () => {
|
||||||
|
mocks.payment.selectedPlanId = "coin_1000";
|
||||||
|
|
||||||
|
act(() =>
|
||||||
|
root.render(
|
||||||
|
<SubscriptionScreen
|
||||||
|
subscriptionType="topup"
|
||||||
|
sourceCharacterSlug={null}
|
||||||
|
/>,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkout = container.querySelector<HTMLButtonElement>(
|
||||||
|
'[data-testid="checkout"]',
|
||||||
|
);
|
||||||
|
expect(container.textContent).not.toContain("Supporting ");
|
||||||
|
expect(container.textContent).not.toContain(
|
||||||
|
"Choose who you want to support",
|
||||||
|
);
|
||||||
|
expect(container.textContent).not.toContain(
|
||||||
|
"Your VIP or credit purchase supports the character you choose",
|
||||||
|
);
|
||||||
|
expect(checkout?.disabled).toBe(true);
|
||||||
|
expect(mocks.paymentFlowInput).toHaveBeenLastCalledWith(
|
||||||
|
expect.objectContaining({ sourceCharacterSlug: null }),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function clickButton(root: ParentNode, label: string): void {
|
function clickButton(root: ParentNode, label: string): void {
|
||||||
|
|||||||
@@ -3,8 +3,12 @@ import { createRoot, type Root } from "react-dom/client";
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { Result } from "@/utils/result";
|
import { Result } from "@/utils/result";
|
||||||
|
import { ApiError } from "@/data/services/api/api_result";
|
||||||
|
|
||||||
import { SubscriptionPaymentIssueDialog } from "../subscription-payment-issue-dialog";
|
import {
|
||||||
|
getPaymentIssueSubmitErrorLogDetails,
|
||||||
|
SubscriptionPaymentIssueDialog,
|
||||||
|
} from "../subscription-payment-issue-dialog";
|
||||||
import { SubscriptionRenewalConfirmationDialog } from "../subscription-renewal-confirmation-dialog";
|
import { SubscriptionRenewalConfirmationDialog } from "../subscription-renewal-confirmation-dialog";
|
||||||
|
|
||||||
const mocks = vi.hoisted(() => ({
|
const mocks = vi.hoisted(() => ({
|
||||||
@@ -200,6 +204,28 @@ describe("subscription payment dialogs", () => {
|
|||||||
);
|
);
|
||||||
expect(onClose).toHaveBeenCalledOnce();
|
expect(onClose).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps HTTP status and backend error code in payment issue failure diagnostics", () => {
|
||||||
|
const failure = Result.err(
|
||||||
|
new ApiError("HTTP_ERROR", "Invalid feedback context", 400, {
|
||||||
|
detail: {
|
||||||
|
message: "Invalid feedback context",
|
||||||
|
errorCode: "INVALID_FEEDBACK_CONTEXT",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (failure.success) throw new Error("Expected failure result");
|
||||||
|
expect(getPaymentIssueSubmitErrorLogDetails(failure.error)).toMatchObject({
|
||||||
|
code: "UNKNOWN",
|
||||||
|
message: "Invalid feedback context",
|
||||||
|
causeName: "ApiError",
|
||||||
|
causeMessage: "Invalid feedback context",
|
||||||
|
httpStatus: 400,
|
||||||
|
apiCode: "HTTP_ERROR",
|
||||||
|
serverErrorCode: "INVALID_FEEDBACK_CONTEXT",
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function clickButton(root: ParentNode | null, label: string): void {
|
function clickButton(root: ParentNode | null, label: string): void {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ export interface SubscriptionCheckoutButtonProps {
|
|||||||
subscriptionType: "vip" | "topup";
|
subscriptionType: "vip" | "topup";
|
||||||
returnTo?: SubscriptionReturnTo;
|
returnTo?: SubscriptionReturnTo;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string;
|
||||||
|
countryCode?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SubscriptionCheckoutButton({
|
export function SubscriptionCheckoutButton({
|
||||||
@@ -31,6 +32,7 @@ export function SubscriptionCheckoutButton({
|
|||||||
subscriptionType,
|
subscriptionType,
|
||||||
returnTo = null,
|
returnTo = null,
|
||||||
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
||||||
|
countryCode = null,
|
||||||
}: SubscriptionCheckoutButtonProps) {
|
}: SubscriptionCheckoutButtonProps) {
|
||||||
const payment = usePaymentState();
|
const payment = usePaymentState();
|
||||||
const paymentDispatch = usePaymentDispatch();
|
const paymentDispatch = usePaymentDispatch();
|
||||||
@@ -42,6 +44,7 @@ export function SubscriptionCheckoutButton({
|
|||||||
returnTo: returnTo ?? undefined,
|
returnTo: returnTo ?? undefined,
|
||||||
characterSlug: sourceCharacterSlug,
|
characterSlug: sourceCharacterSlug,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
|
countryCode,
|
||||||
});
|
});
|
||||||
|
|
||||||
const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
|
const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
|
||||||
@@ -57,7 +60,6 @@ export function SubscriptionCheckoutButton({
|
|||||||
paymentLaunch.resetLaunchState();
|
paymentLaunch.resetLaunchState();
|
||||||
paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
|
paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SubscriptionCtaButton
|
<SubscriptionCtaButton
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { ModalPortal } from "@/app/_components/core/modal-portal";
|
|||||||
import { createFeedbackContext } from "@/app/feedback/feedback-context";
|
import { createFeedbackContext } from "@/app/feedback/feedback-context";
|
||||||
import type { PayChannel } from "@/data/schemas/payment";
|
import type { PayChannel } from "@/data/schemas/payment";
|
||||||
import { submitFeedback } from "@/lib/feedback";
|
import { submitFeedback } from "@/lib/feedback";
|
||||||
|
import { Logger } from "@/utils/logger";
|
||||||
|
|
||||||
import type { SubscriptionType } from "../subscription-screen.helpers";
|
import type { SubscriptionType } from "../subscription-screen.helpers";
|
||||||
import styles from "./subscription-dialog.module.css";
|
import styles from "./subscription-dialog.module.css";
|
||||||
@@ -33,6 +34,21 @@ const OTHER_DETAILS_MIN_LENGTH = 10;
|
|||||||
const OTHER_DETAILS_MAX_LENGTH = 2000;
|
const OTHER_DETAILS_MAX_LENGTH = 2000;
|
||||||
const SUCCESS_MESSAGE = "Thanks. Your payment issue has been submitted.";
|
const SUCCESS_MESSAGE = "Thanks. Your payment issue has been submitted.";
|
||||||
const FAILURE_MESSAGE = "Unable to submit. Please try again.";
|
const FAILURE_MESSAGE = "Unable to submit. Please try again.";
|
||||||
|
const log = new Logger("SubscriptionPaymentIssueDialog");
|
||||||
|
|
||||||
|
interface ErrorRecord {
|
||||||
|
readonly [key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaymentIssueSubmitErrorLogDetails {
|
||||||
|
code: string;
|
||||||
|
message: string;
|
||||||
|
causeName?: string;
|
||||||
|
causeMessage?: string;
|
||||||
|
httpStatus?: number;
|
||||||
|
apiCode?: string;
|
||||||
|
serverErrorCode?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SubscriptionPaymentIssueDialogProps {
|
export interface SubscriptionPaymentIssueDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -119,6 +135,19 @@ export function SubscriptionPaymentIssueDialog({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
|
log.error(
|
||||||
|
{
|
||||||
|
...getPaymentIssueSubmitErrorLogDetails(result.error),
|
||||||
|
paymentIssueReason: reason,
|
||||||
|
subscriptionType,
|
||||||
|
planId,
|
||||||
|
orderId,
|
||||||
|
payChannel,
|
||||||
|
countryCode,
|
||||||
|
characterId,
|
||||||
|
},
|
||||||
|
"Payment issue feedback submit failed",
|
||||||
|
);
|
||||||
setErrorMessage(FAILURE_MESSAGE);
|
setErrorMessage(FAILURE_MESSAGE);
|
||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
return;
|
return;
|
||||||
@@ -206,6 +235,32 @@ export function SubscriptionPaymentIssueDialog({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getPaymentIssueSubmitErrorLogDetails(
|
||||||
|
error: Error,
|
||||||
|
): PaymentIssueSubmitErrorLogDetails {
|
||||||
|
const errorRecord = toErrorRecord(error);
|
||||||
|
const cause = toErrorRecord(errorRecord?.cause);
|
||||||
|
const responseDetails = toErrorRecord(cause?.details);
|
||||||
|
const detail = toErrorRecord(responseDetails?.detail);
|
||||||
|
const causeName = stringValue(cause?.name);
|
||||||
|
const causeMessage = stringValue(cause?.message);
|
||||||
|
const httpStatus = numberValue(cause?.status);
|
||||||
|
const apiCode = stringValue(cause?.code);
|
||||||
|
const serverErrorCode =
|
||||||
|
stringValue(detail?.errorCode) ??
|
||||||
|
stringValue(responseDetails?.errorCode);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: stringValue(errorRecord?.code) ?? "UNKNOWN",
|
||||||
|
message: error.message,
|
||||||
|
...(causeName ? { causeName } : {}),
|
||||||
|
...(causeMessage ? { causeMessage } : {}),
|
||||||
|
...(httpStatus !== undefined ? { httpStatus } : {}),
|
||||||
|
...(apiCode ? { apiCode } : {}),
|
||||||
|
...(serverErrorCode ? { serverErrorCode } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function createIdempotencyKey(): string {
|
function createIdempotencyKey(): string {
|
||||||
const token =
|
const token =
|
||||||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||||||
@@ -213,3 +268,18 @@ function createIdempotencyKey(): string {
|
|||||||
: `${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
: `${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
||||||
return `payment_feedback_${token}`;
|
return `payment_feedback_${token}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toErrorRecord(value: unknown): ErrorRecord | null {
|
||||||
|
if (typeof value !== "object" || value === null) return null;
|
||||||
|
return value as ErrorRecord;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stringValue(value: unknown): string | undefined {
|
||||||
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberValue(value: unknown): number | undefined {
|
||||||
|
return typeof value === "number" && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,24 @@
|
|||||||
.shell {
|
.shell {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
height: var(--app-viewport-height, 100dvh);
|
||||||
min-height: var(--app-viewport-height, 100dvh);
|
min-height: var(--app-viewport-height, 100dvh);
|
||||||
|
overflow: hidden;
|
||||||
background:
|
background:
|
||||||
radial-gradient(circle at 8% 4%, rgba(255, 255, 255, 0.95) 0 90px, transparent 160px),
|
radial-gradient(circle at 8% 4%, rgba(255, 255, 255, 0.95) 0 90px, transparent 160px),
|
||||||
linear-gradient(180deg, #fff9fb 0%, #fcf3f4 52%, #fffefe 100%);
|
linear-gradient(180deg, #fff9fb 0%, #fcf3f4 52%, #fffefe 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrollArea {
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
overflow-y: auto;
|
||||||
|
overscroll-behavior: contain;
|
||||||
padding:
|
padding:
|
||||||
calc(var(--page-padding-y, 18px) + var(--app-safe-top, 0px))
|
calc(var(--page-padding-y, 18px) + var(--app-safe-top, 0px))
|
||||||
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
|
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
|
||||||
calc(104px + var(--app-safe-bottom, 0px))
|
var(--page-section-gap-lg, 22px)
|
||||||
calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
|
calc(var(--page-padding-x, 20px) + var(--app-safe-left, 0px));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,11 +201,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.ctaSlot {
|
.ctaSlot {
|
||||||
position: fixed;
|
position: relative;
|
||||||
z-index: 40;
|
z-index: 40;
|
||||||
right: 50%;
|
flex: 0 0 auto;
|
||||||
bottom: 0;
|
width: 100%;
|
||||||
width: min(100%, var(--app-max-width, 540px));
|
max-height: min(50dvh, 360px);
|
||||||
|
overflow-y: auto;
|
||||||
padding:
|
padding:
|
||||||
12px
|
12px
|
||||||
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
|
calc(var(--page-padding-x, 20px) + var(--app-safe-right, 0px))
|
||||||
@@ -209,5 +220,4 @@
|
|||||||
);
|
);
|
||||||
box-shadow: 0 -12px 30px rgba(87, 35, 59, 0.1);
|
box-shadow: 0 -12px 30px rgba(87, 35, 59, 0.1);
|
||||||
backdrop-filter: blur(16px);
|
backdrop-filter: blur(16px);
|
||||||
transform: translateX(50%);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
type PaymentSearchParams,
|
type PaymentSearchParams,
|
||||||
} from "@/lib/payment/payment_search_params";
|
} from "@/lib/payment/payment_search_params";
|
||||||
import {
|
import {
|
||||||
DEFAULT_CHARACTER_SLUG,
|
|
||||||
getCharacterBySlug,
|
getCharacterBySlug,
|
||||||
} from "@/data/constants/character";
|
} from "@/data/constants/character";
|
||||||
|
|
||||||
@@ -30,8 +29,7 @@ export default async function SubscriptionPage({
|
|||||||
getFirstPaymentSearchParam(query.type),
|
getFirstPaymentSearchParam(query.type),
|
||||||
);
|
);
|
||||||
const sourceCharacterSlug =
|
const sourceCharacterSlug =
|
||||||
getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ??
|
getCharacterBySlug(getFirstPaymentSearchParam(query.character))?.slug ?? null;
|
||||||
DEFAULT_CHARACTER_SLUG;
|
|
||||||
const initialPlanId = getFirstPaymentSearchParam(query.planId);
|
const initialPlanId = getFirstPaymentSearchParam(query.planId);
|
||||||
const commercialOfferId = getFirstPaymentSearchParam(
|
const commercialOfferId = getFirstPaymentSearchParam(
|
||||||
query.commercialOfferId,
|
query.commercialOfferId,
|
||||||
|
|||||||
@@ -8,11 +8,8 @@ import { usePaymentMethodSelection } from "@/app/_hooks/use-payment-method-selec
|
|||||||
import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics";
|
import { usePaymentPlanAnalytics } from "@/app/_hooks/use-payment-plan-analytics";
|
||||||
import type { PayChannel } from "@/data/schemas/payment";
|
import type { PayChannel } from "@/data/schemas/payment";
|
||||||
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
|
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
|
||||||
import {
|
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
|
||||||
DEFAULT_CHARACTER,
|
import { useCharacterCatalog } from "@/providers/character-catalog-provider";
|
||||||
DEFAULT_CHARACTER_SLUG,
|
|
||||||
getCharacterBySlug,
|
|
||||||
} from "@/data/constants/character";
|
|
||||||
import {
|
import {
|
||||||
behaviorAnalytics,
|
behaviorAnalytics,
|
||||||
getDefaultPaymentAnalyticsContext,
|
getDefaultPaymentAnalyticsContext,
|
||||||
@@ -51,7 +48,7 @@ export interface SubscriptionScreenProps {
|
|||||||
returnTo?: SubscriptionReturnTo;
|
returnTo?: SubscriptionReturnTo;
|
||||||
initialPayChannel?: PayChannel | null;
|
initialPayChannel?: PayChannel | null;
|
||||||
analyticsContext?: PaymentAnalyticsContext;
|
analyticsContext?: PaymentAnalyticsContext;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string | null;
|
||||||
initialPlanId?: string | null;
|
initialPlanId?: string | null;
|
||||||
commercialOfferId?: string | null;
|
commercialOfferId?: string | null;
|
||||||
resumeOrderId?: string | null;
|
resumeOrderId?: string | null;
|
||||||
@@ -64,7 +61,7 @@ export function SubscriptionScreen({
|
|||||||
returnTo = null,
|
returnTo = null,
|
||||||
initialPayChannel = null,
|
initialPayChannel = null,
|
||||||
analyticsContext: providedAnalyticsContext,
|
analyticsContext: providedAnalyticsContext,
|
||||||
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
sourceCharacterSlug = null,
|
||||||
initialPlanId = null,
|
initialPlanId = null,
|
||||||
commercialOfferId = null,
|
commercialOfferId = null,
|
||||||
resumeOrderId = null,
|
resumeOrderId = null,
|
||||||
@@ -78,9 +75,9 @@ export function SubscriptionScreen({
|
|||||||
const [paymentIssueNotice, setPaymentIssueNotice] = useState<string | null>(
|
const [paymentIssueNotice, setPaymentIssueNotice] = useState<string | null>(
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
const characterCatalog = useCharacterCatalog();
|
||||||
const userState = useUserState();
|
const userState = useUserState();
|
||||||
const sourceCharacter =
|
const sourceCharacter = characterCatalog.getBySlug(sourceCharacterSlug);
|
||||||
getCharacterBySlug(sourceCharacterSlug) ?? DEFAULT_CHARACTER;
|
|
||||||
const hasHydrated = useHasHydrated();
|
const hasHydrated = useHasHydrated();
|
||||||
const countryCode = userState.currentUser?.countryCode;
|
const countryCode = userState.currentUser?.countryCode;
|
||||||
const paymentMethodConfig = getPaymentMethodConfig({
|
const paymentMethodConfig = getPaymentMethodConfig({
|
||||||
@@ -100,7 +97,7 @@ export function SubscriptionScreen({
|
|||||||
subscriptionType,
|
subscriptionType,
|
||||||
shouldResumePendingOrder,
|
shouldResumePendingOrder,
|
||||||
returnTo,
|
returnTo,
|
||||||
sourceCharacterSlug,
|
sourceCharacterSlug: sourceCharacter?.slug ?? null,
|
||||||
initialPayChannel: paymentMethodConfig.initialPayChannel,
|
initialPayChannel: paymentMethodConfig.initialPayChannel,
|
||||||
initialPlanId,
|
initialPlanId,
|
||||||
commercialOfferId,
|
commercialOfferId,
|
||||||
@@ -131,14 +128,14 @@ export function SubscriptionScreen({
|
|||||||
});
|
});
|
||||||
}, [canSubscribeVip, directCoinsPlans, payment.plans, vipOfferPlans]);
|
}, [canSubscribeVip, directCoinsPlans, payment.plans, vipOfferPlans]);
|
||||||
usePaymentPlanAnalytics(displayedPlans, analyticsContext);
|
usePaymentPlanAnalytics(displayedPlans, analyticsContext);
|
||||||
const firstRechargeOffer = useMemo(
|
const hasFirstRechargeOffer = useMemo(
|
||||||
() =>
|
() =>
|
||||||
getFirstRechargeOfferView({
|
getFirstRechargeOfferView({
|
||||||
isFirstRecharge: payment.isFirstRecharge,
|
isFirstRecharge: payment.isFirstRecharge,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
vipPlans: vipOfferPlans,
|
vipPlans: vipOfferPlans,
|
||||||
coinPlans: directCoinsPlans,
|
coinPlans: directCoinsPlans,
|
||||||
}),
|
}) !== null,
|
||||||
[
|
[
|
||||||
directCoinsPlans,
|
directCoinsPlans,
|
||||||
payment.isFirstRecharge,
|
payment.isFirstRecharge,
|
||||||
@@ -160,6 +157,7 @@ export function SubscriptionScreen({
|
|||||||
(plan) => plan.id === payment.selectedPlanId,
|
(plan) => plan.id === payment.selectedPlanId,
|
||||||
);
|
);
|
||||||
const canActivate =
|
const canActivate =
|
||||||
|
sourceCharacter !== null &&
|
||||||
selectedPlan !== null &&
|
selectedPlan !== null &&
|
||||||
canCheckoutSubscriptionPlan({
|
canCheckoutSubscriptionPlan({
|
||||||
selectedPlanId: payment.selectedPlanId,
|
selectedPlanId: payment.selectedPlanId,
|
||||||
@@ -243,7 +241,8 @@ export function SubscriptionScreen({
|
|||||||
return (
|
return (
|
||||||
<MobileShell>
|
<MobileShell>
|
||||||
<div className={styles.shell}>
|
<div className={styles.shell}>
|
||||||
<header className={styles.header}>
|
<div className={styles.scrollArea}>
|
||||||
|
<header className={styles.header}>
|
||||||
<BackButton
|
<BackButton
|
||||||
className={styles.backSlot}
|
className={styles.backSlot}
|
||||||
onClick={handleBackClick}
|
onClick={handleBackClick}
|
||||||
@@ -260,7 +259,7 @@ export function SubscriptionScreen({
|
|||||||
>
|
>
|
||||||
Payment issue?
|
Payment issue?
|
||||||
</button>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{paymentIssueNotice ? (
|
{paymentIssueNotice ? (
|
||||||
<p className={styles.paymentIssueNotice} role="status">
|
<p className={styles.paymentIssueNotice} role="status">
|
||||||
@@ -268,7 +267,7 @@ export function SubscriptionScreen({
|
|||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{chatActionId ? (
|
{chatActionId && sourceCharacter ? (
|
||||||
<section
|
<section
|
||||||
className={styles.characterSupportBanner}
|
className={styles.characterSupportBanner}
|
||||||
aria-label={`Support ${sourceCharacter.displayName}`}
|
aria-label={`Support ${sourceCharacter.displayName}`}
|
||||||
@@ -284,31 +283,7 @@ export function SubscriptionScreen({
|
|||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{firstRechargeOffer ? (
|
{payment.commercialOffer && !hasFirstRechargeOffer && sourceCharacter ? (
|
||||||
<section
|
|
||||||
className={styles.firstRechargeBanner}
|
|
||||||
aria-label="First recharge offer"
|
|
||||||
>
|
|
||||||
<span className={styles.firstRechargeBadge}>
|
|
||||||
{firstRechargeOffer.badgeText}
|
|
||||||
</span>
|
|
||||||
<div className={styles.firstRechargeCopy}>
|
|
||||||
<h2 className={styles.firstRechargeTitle}>
|
|
||||||
{firstRechargeOffer.title}
|
|
||||||
</h2>
|
|
||||||
<p className={styles.firstRechargeSubtitle}>
|
|
||||||
{firstRechargeOffer.subtitle}
|
|
||||||
</p>
|
|
||||||
{firstRechargeOffer.renewalNotice ? (
|
|
||||||
<p className={styles.firstRechargeRenewalNotice}>
|
|
||||||
{firstRechargeOffer.renewalNotice}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{payment.commercialOffer && !firstRechargeOffer ? (
|
|
||||||
<section
|
<section
|
||||||
className={styles.firstRechargeBanner}
|
className={styles.firstRechargeBanner}
|
||||||
aria-label={`${sourceCharacter.shortName} private offer`}
|
aria-label={`${sourceCharacter.shortName} private offer`}
|
||||||
@@ -341,26 +316,28 @@ export function SubscriptionScreen({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<PaymentMethodSelector
|
<PaymentMethodSelector
|
||||||
config={renderedPaymentMethodConfig}
|
config={renderedPaymentMethodConfig}
|
||||||
value={payment.payChannel}
|
value={payment.payChannel}
|
||||||
disabled={isPaymentBusy}
|
disabled={payment.isCreatingOrder}
|
||||||
caption={
|
caption={
|
||||||
paymentMethodConfig.ezpayDisplayName === "QRIS"
|
paymentMethodConfig.ezpayDisplayName === "QRIS"
|
||||||
? "QRIS by default in Indonesia"
|
? "QRIS by default in Indonesia"
|
||||||
: "GCash by default in the Philippines"
|
: "GCash by default in the Philippines"
|
||||||
}
|
}
|
||||||
className={styles.paymentMethodSlot}
|
className={styles.paymentMethodSlot}
|
||||||
analyticsKey="subscription.payment_method"
|
analyticsKey="subscription.payment_method"
|
||||||
onChange={handlePaymentMethodChange}
|
onChange={handlePaymentMethodChange}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className={styles.ctaSlot}>
|
<div className={styles.ctaSlot}>
|
||||||
<SubscriptionCheckoutButton
|
<SubscriptionCheckoutButton
|
||||||
disabled={!canActivate}
|
disabled={!canActivate}
|
||||||
subscriptionType={subscriptionType}
|
subscriptionType={subscriptionType}
|
||||||
returnTo={returnTo}
|
returnTo={returnTo}
|
||||||
sourceCharacterSlug={sourceCharacterSlug}
|
sourceCharacterSlug={sourceCharacter?.slug ?? DEFAULT_CHARACTER_SLUG}
|
||||||
|
countryCode={countryCode}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -385,7 +362,7 @@ export function SubscriptionScreen({
|
|||||||
orderId={payment.currentOrderId}
|
orderId={payment.currentOrderId}
|
||||||
payChannel={payment.payChannel}
|
payChannel={payment.payChannel}
|
||||||
countryCode={countryCode}
|
countryCode={countryCode}
|
||||||
characterId={sourceCharacterSlug}
|
characterId={sourceCharacter?.id ?? ""}
|
||||||
onClose={() => setShowPaymentIssueDialog(false)}
|
onClose={() => setShowPaymentIssueDialog(false)}
|
||||||
onSubmitted={setPaymentIssueNotice}
|
onSubmitted={setPaymentIssueNotice}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -5,7 +5,10 @@ import { useRouter } from "next/navigation";
|
|||||||
|
|
||||||
import { usePaymentRouteFlow } from "@/app/_hooks/use-payment-route-flow";
|
import { usePaymentRouteFlow } from "@/app/_hooks/use-payment-route-flow";
|
||||||
import type { PayChannel } from "@/data/schemas/payment";
|
import type { PayChannel } from "@/data/schemas/payment";
|
||||||
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
|
import {
|
||||||
|
DEFAULT_CHARACTER,
|
||||||
|
getCharacterBySlug,
|
||||||
|
} from "@/data/constants/character";
|
||||||
import {
|
import {
|
||||||
consumeSubscriptionExitUrl,
|
consumeSubscriptionExitUrl,
|
||||||
resolveSubscriptionSuccessExitUrl,
|
resolveSubscriptionSuccessExitUrl,
|
||||||
@@ -19,7 +22,7 @@ export interface UseSubscriptionPaymentFlowInput {
|
|||||||
shouldResumePendingOrder: boolean;
|
shouldResumePendingOrder: boolean;
|
||||||
returnTo: SubscriptionReturnTo;
|
returnTo: SubscriptionReturnTo;
|
||||||
initialPayChannel: PayChannel;
|
initialPayChannel: PayChannel;
|
||||||
sourceCharacterSlug?: string;
|
sourceCharacterSlug?: string | null;
|
||||||
initialPlanId?: string | null;
|
initialPlanId?: string | null;
|
||||||
commercialOfferId?: string | null;
|
commercialOfferId?: string | null;
|
||||||
resumeOrderId?: string | null;
|
resumeOrderId?: string | null;
|
||||||
@@ -31,17 +34,20 @@ export function useSubscriptionPaymentFlow({
|
|||||||
shouldResumePendingOrder,
|
shouldResumePendingOrder,
|
||||||
returnTo,
|
returnTo,
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
|
sourceCharacterSlug = null,
|
||||||
initialPlanId = null,
|
initialPlanId = null,
|
||||||
commercialOfferId = null,
|
commercialOfferId = null,
|
||||||
resumeOrderId = null,
|
resumeOrderId = null,
|
||||||
chatActionId = null,
|
chatActionId = null,
|
||||||
}: UseSubscriptionPaymentFlowInput) {
|
}: UseSubscriptionPaymentFlowInput) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const supportCharacter = getCharacterBySlug(sourceCharacterSlug);
|
||||||
|
const exitCharacterSlug = supportCharacter?.slug ?? DEFAULT_CHARACTER.slug;
|
||||||
const { payment, paymentDispatch } = usePaymentRouteFlow({
|
const { payment, paymentDispatch } = usePaymentRouteFlow({
|
||||||
initialPayChannel,
|
initialPayChannel,
|
||||||
paymentType: subscriptionType,
|
paymentType: subscriptionType,
|
||||||
shouldResumePendingOrder,
|
shouldResumePendingOrder,
|
||||||
|
characterId: supportCharacter?.id,
|
||||||
initialPlanId,
|
initialPlanId,
|
||||||
commercialOfferId,
|
commercialOfferId,
|
||||||
resumeOrderId,
|
resumeOrderId,
|
||||||
@@ -62,7 +68,7 @@ export function useSubscriptionPaymentFlow({
|
|||||||
const handleBackClick = () => {
|
const handleBackClick = () => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
router.replace(
|
router.replace(
|
||||||
await consumeSubscriptionExitUrl(returnTo, sourceCharacterSlug),
|
await consumeSubscriptionExitUrl(returnTo, exitCharacterSlug),
|
||||||
);
|
);
|
||||||
})();
|
})();
|
||||||
};
|
};
|
||||||
@@ -74,7 +80,7 @@ export function useSubscriptionPaymentFlow({
|
|||||||
router.replace(
|
router.replace(
|
||||||
await resolveSubscriptionSuccessExitUrl(
|
await resolveSubscriptionSuccessExitUrl(
|
||||||
returnTo,
|
returnTo,
|
||||||
sourceCharacterSlug,
|
exitCharacterSlug,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export interface TipCheckoutButtonProps {
|
|||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
onOrder: () => void;
|
onOrder: () => void;
|
||||||
returnPath: string;
|
returnPath: string;
|
||||||
|
countryCode?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TipCheckoutButton({
|
export function TipCheckoutButton({
|
||||||
@@ -27,6 +28,7 @@ export function TipCheckoutButton({
|
|||||||
disabled = false,
|
disabled = false,
|
||||||
onOrder,
|
onOrder,
|
||||||
returnPath,
|
returnPath,
|
||||||
|
countryCode = null,
|
||||||
}: TipCheckoutButtonProps) {
|
}: TipCheckoutButtonProps) {
|
||||||
const character = useActiveCharacter();
|
const character = useActiveCharacter();
|
||||||
const payment = usePaymentState();
|
const payment = usePaymentState();
|
||||||
@@ -40,16 +42,17 @@ export function TipCheckoutButton({
|
|||||||
giftCategory,
|
giftCategory,
|
||||||
giftPlanId,
|
giftPlanId,
|
||||||
characterSlug: character.slug,
|
characterSlug: character.slug,
|
||||||
|
countryCode,
|
||||||
});
|
});
|
||||||
|
|
||||||
const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
|
const isLoading = payment.isCreatingOrder || payment.isPollingOrder;
|
||||||
const label = payment.isPollingOrder
|
const label = payment.isPollingOrder
|
||||||
? "Processing payment..."
|
? "Processing payment..."
|
||||||
: payment.isCreatingOrder
|
: payment.isCreatingOrder
|
||||||
? "Creating order..."
|
? "Creating order..."
|
||||||
: payment.isPaid
|
: payment.isPaid
|
||||||
? "Thanks for the coffee"
|
? "Thanks for the coffee"
|
||||||
: "Order and Buy";
|
: "Order and Buy";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -292,7 +292,7 @@ export function TipScreen({
|
|||||||
config={renderedPaymentMethodConfig}
|
config={renderedPaymentMethodConfig}
|
||||||
value={payment.payChannel}
|
value={payment.payChannel}
|
||||||
density="compact"
|
density="compact"
|
||||||
disabled={isPaymentBusy}
|
disabled={payment.isCreatingOrder}
|
||||||
className={styles.paymentMethodSlot}
|
className={styles.paymentMethodSlot}
|
||||||
analyticsKey="tip.payment_method"
|
analyticsKey="tip.payment_method"
|
||||||
onChange={handlePaymentMethodChange}
|
onChange={handlePaymentMethodChange}
|
||||||
@@ -305,6 +305,7 @@ export function TipScreen({
|
|||||||
disabled={!canCreateOrder}
|
disabled={!canCreateOrder}
|
||||||
onOrder={handleOrder}
|
onOrder={handleOrder}
|
||||||
returnPath={returnPath}
|
returnPath={returnPath}
|
||||||
|
countryCode={userState.currentUser?.countryCode}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -45,6 +45,27 @@ describe("ChatWebSocket payment guidance", () => {
|
|||||||
|
|
||||||
expect(onPaymentGuidance).not.toHaveBeenCalled();
|
expect(onPaymentGuidance).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("delivers a persisted commercial thank-you as a live role message", () => {
|
||||||
|
const socket = new ChatWebSocket("ws://example.test/chat", "token");
|
||||||
|
const onCommercialMessage = vi.fn();
|
||||||
|
socket.onCommercialMessage = onCommercialMessage;
|
||||||
|
|
||||||
|
receive(socket, {
|
||||||
|
type: "commercial_message",
|
||||||
|
messageId: "message-1",
|
||||||
|
message: "Thank you for supporting me.",
|
||||||
|
characterId: "maya-tan",
|
||||||
|
createdAt: "2026-07-28T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(onCommercialMessage).toHaveBeenCalledWith({
|
||||||
|
messageId: "message-1",
|
||||||
|
message: "Thank you for supporting me.",
|
||||||
|
characterId: "maya-tan",
|
||||||
|
createdAt: "2026-07-28T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function receive(socket: ChatWebSocket, payload: unknown): void {
|
function receive(socket: ChatWebSocket, payload: unknown): void {
|
||||||
|
|||||||
@@ -37,6 +37,13 @@ export interface PaywallStatusPayload {
|
|||||||
reason: string | null;
|
reason: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CommercialMessagePayload {
|
||||||
|
messageId: string;
|
||||||
|
message: string;
|
||||||
|
characterId: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class ChatWebSocket {
|
export class ChatWebSocket {
|
||||||
private ws: WebSocket | null = null;
|
private ws: WebSocket | null = null;
|
||||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -52,6 +59,7 @@ export class ChatWebSocket {
|
|||||||
onCommercialAction: ((action: CommercialAction) => void) | null = null;
|
onCommercialAction: ((action: CommercialAction) => void) | null = null;
|
||||||
onChatAction: ((action: ChatAction) => void) | null = null;
|
onChatAction: ((action: ChatAction) => void) | null = null;
|
||||||
onPaymentGuidance: ((guidance: PaymentGuidance) => void) | null = null;
|
onPaymentGuidance: ((guidance: PaymentGuidance) => void) | null = null;
|
||||||
|
onCommercialMessage: ((message: CommercialMessagePayload) => void) | null = null;
|
||||||
onError: ((errorMessage: string) => void) | null = null;
|
onError: ((errorMessage: string) => void) | null = null;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -149,6 +157,10 @@ export class ChatWebSocket {
|
|||||||
done?: boolean;
|
done?: boolean;
|
||||||
audioUrl?: string;
|
audioUrl?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
messageId?: string;
|
||||||
|
message?: string;
|
||||||
|
characterId?: string;
|
||||||
|
createdAt?: string;
|
||||||
data?: Record<string, unknown> & {
|
data?: Record<string, unknown> & {
|
||||||
image?: {
|
image?: {
|
||||||
type?: string | null;
|
type?: string | null;
|
||||||
@@ -163,6 +175,10 @@ export class ChatWebSocket {
|
|||||||
ruleId?: string;
|
ruleId?: string;
|
||||||
kind?: string;
|
kind?: string;
|
||||||
orderId?: string | null;
|
orderId?: string | null;
|
||||||
|
messageId?: string;
|
||||||
|
message?: string;
|
||||||
|
characterId?: string;
|
||||||
|
createdAt?: string;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
@@ -217,6 +233,25 @@ export class ChatWebSocket {
|
|||||||
if (guidance.success) this.onPaymentGuidance?.(guidance.data);
|
if (guidance.success) this.onPaymentGuidance?.(guidance.data);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "commercial_message": {
|
||||||
|
const commercialMessage = payload.data?.messageId
|
||||||
|
? payload.data
|
||||||
|
: payload;
|
||||||
|
if (
|
||||||
|
commercialMessage?.messageId &&
|
||||||
|
commercialMessage.message &&
|
||||||
|
commercialMessage.characterId &&
|
||||||
|
commercialMessage.createdAt
|
||||||
|
) {
|
||||||
|
this.onCommercialMessage?.({
|
||||||
|
messageId: commercialMessage.messageId,
|
||||||
|
message: commercialMessage.message,
|
||||||
|
characterId: commercialMessage.characterId,
|
||||||
|
createdAt: commercialMessage.createdAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "error":
|
case "error":
|
||||||
this.onError?.(payload.error ?? "Unknown error");
|
this.onError?.(payload.error ?? "Unknown error");
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -13,7 +13,10 @@ import type { Result } from "@/utils/result";
|
|||||||
|
|
||||||
export interface IPaymentRepository {
|
export interface IPaymentRepository {
|
||||||
/** 获取套餐列表。 */
|
/** 获取套餐列表。 */
|
||||||
getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>>;
|
getPlans(
|
||||||
|
commercialOfferId?: string,
|
||||||
|
supportCharacterId?: string,
|
||||||
|
): Promise<Result<PaymentPlansResponse>>;
|
||||||
|
|
||||||
/** 获取本地缓存套餐列表。 */
|
/** 获取本地缓存套餐列表。 */
|
||||||
getCachedPlans(): Promise<Result<PaymentPlansResponse | null>>;
|
getCachedPlans(): Promise<Result<PaymentPlansResponse | null>>;
|
||||||
|
|||||||
@@ -24,10 +24,18 @@ export class PaymentRepository implements IPaymentRepository {
|
|||||||
constructor(private readonly api: PaymentApi) {}
|
constructor(private readonly api: PaymentApi) {}
|
||||||
|
|
||||||
/** 获取套餐列表。 */
|
/** 获取套餐列表。 */
|
||||||
async getPlans(commercialOfferId?: string): Promise<Result<PaymentPlansResponse>> {
|
async getPlans(
|
||||||
|
commercialOfferId?: string,
|
||||||
|
supportCharacterId?: string,
|
||||||
|
): Promise<Result<PaymentPlansResponse>> {
|
||||||
return Result.wrap(async () => {
|
return Result.wrap(async () => {
|
||||||
const response = await this.api.getPlans(commercialOfferId);
|
const response = await this.api.getPlans(
|
||||||
if (!commercialOfferId) await PaymentPlansStorage.setPlans(response);
|
commercialOfferId,
|
||||||
|
supportCharacterId,
|
||||||
|
);
|
||||||
|
if (!commercialOfferId && !supportCharacterId) {
|
||||||
|
await PaymentPlansStorage.setPlans(response);
|
||||||
|
}
|
||||||
return response;
|
return response;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,16 @@ describe("payment guidance wire contract", () => {
|
|||||||
expect(PaymentGuidanceSchema.parse(guidance)).toEqual(guidance);
|
expect(PaymentGuidanceSchema.parse(guidance)).toEqual(guidance);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("accepts the supportCharacter guidance scene", () => {
|
||||||
|
expect(
|
||||||
|
PaymentGuidanceSchema.parse({
|
||||||
|
...guidance,
|
||||||
|
scene: "supportCharacter",
|
||||||
|
ruleId: "payment_guidance_supportCharacter",
|
||||||
|
}).scene,
|
||||||
|
).toBe("supportCharacter");
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps all backend lock facts instead of dropping hint and CTA", () => {
|
it("keeps all backend lock facts instead of dropping hint and CTA", () => {
|
||||||
expect(
|
expect(
|
||||||
ChatLockDetailSchema.parse({
|
ChatLockDetailSchema.parse({
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ export const PaymentGuidanceSceneSchema = z.enum([
|
|||||||
"privateZoneLocked",
|
"privateZoneLocked",
|
||||||
"unknownLock",
|
"unknownLock",
|
||||||
"whyPay",
|
"whyPay",
|
||||||
|
"supportCharacter",
|
||||||
"leavingAfterCredits",
|
"leavingAfterCredits",
|
||||||
"paymentIssue",
|
"paymentIssue",
|
||||||
"externalRisk",
|
"externalRisk",
|
||||||
|
|||||||
@@ -195,9 +195,11 @@ describe("PaymentPlansResponse", () => {
|
|||||||
|
|
||||||
it("parses one user-bound commercial offer and its discounted plan", () => {
|
it("parses one user-bound commercial offer and its discounted plan", () => {
|
||||||
const response = PaymentPlansResponseSchema.parse({
|
const response = PaymentPlansResponseSchema.parse({
|
||||||
commercialOffer: {
|
supportCharacterId: "maya-tan",
|
||||||
enabled: true,
|
commercialOffer: {
|
||||||
commercialOfferId: "offer-1",
|
enabled: true,
|
||||||
|
commercialOfferId: "offer-1",
|
||||||
|
characterId: "maya-tan",
|
||||||
planId: "vip_annual",
|
planId: "vip_annual",
|
||||||
discountPercent: 30,
|
discountPercent: 30,
|
||||||
pricePercent: 70,
|
pricePercent: 70,
|
||||||
@@ -225,6 +227,8 @@ describe("PaymentPlansResponse", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(response.commercialOffer?.commercialOfferId).toBe("offer-1");
|
expect(response.commercialOffer?.commercialOfferId).toBe("offer-1");
|
||||||
|
expect(response.supportCharacterId).toBe("maya-tan");
|
||||||
|
expect(response.commercialOffer?.characterId).toBe("maya-tan");
|
||||||
expect(response.plans[0]).toMatchObject({
|
expect(response.plans[0]).toMatchObject({
|
||||||
planId: "vip_annual",
|
planId: "vip_annual",
|
||||||
commercialOfferId: "offer-1",
|
commercialOfferId: "offer-1",
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ export const CommercialOfferSummarySchema = z
|
|||||||
.object({
|
.object({
|
||||||
enabled: booleanOrFalse,
|
enabled: booleanOrFalse,
|
||||||
commercialOfferId: z.string().min(1),
|
commercialOfferId: z.string().min(1),
|
||||||
|
characterId: stringOrEmpty,
|
||||||
planId: z.string().min(1),
|
planId: z.string().min(1),
|
||||||
discountPercent: numberOrZero,
|
discountPercent: numberOrZero,
|
||||||
pricePercent: numberOrZero,
|
pricePercent: numberOrZero,
|
||||||
@@ -36,6 +37,7 @@ export const CommercialOfferSummarySchema = z
|
|||||||
export const PaymentPlansResponseSchema = z
|
export const PaymentPlansResponseSchema = z
|
||||||
.object({
|
.object({
|
||||||
isFirstRecharge: booleanOrFalse,
|
isFirstRecharge: booleanOrFalse,
|
||||||
|
supportCharacterId: stringOrEmpty,
|
||||||
firstRechargeOffer: schemaOrNull(FirstRechargeOfferSchema),
|
firstRechargeOffer: schemaOrNull(FirstRechargeOfferSchema),
|
||||||
commercialOffer: schemaOrNull(CommercialOfferSummarySchema),
|
commercialOffer: schemaOrNull(CommercialOfferSummarySchema),
|
||||||
plans: arrayOrEmpty(PaymentPlanSchema),
|
plans: arrayOrEmpty(PaymentPlanSchema),
|
||||||
|
|||||||
@@ -26,9 +26,19 @@ import { ApiEnvelope, unwrap } from "./response_helper";
|
|||||||
|
|
||||||
export class PaymentApi {
|
export class PaymentApi {
|
||||||
/** 获取 VIP 与 Top-up 套餐列表。 */
|
/** 获取 VIP 与 Top-up 套餐列表。 */
|
||||||
async getPlans(commercialOfferId?: string): Promise<PaymentPlansResponse> {
|
async getPlans(
|
||||||
|
commercialOfferId?: string,
|
||||||
|
supportCharacterId?: string,
|
||||||
|
): Promise<PaymentPlansResponse> {
|
||||||
const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans, {
|
const env = await httpClient<ApiEnvelope<unknown>>(ApiPath.paymentPlans, {
|
||||||
...(commercialOfferId ? { query: { commercialOfferId } } : {}),
|
...(commercialOfferId || supportCharacterId
|
||||||
|
? {
|
||||||
|
query: {
|
||||||
|
...(commercialOfferId ? { commercialOfferId } : {}),
|
||||||
|
...(supportCharacterId ? { supportCharacterId } : {}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
return PaymentPlansResponseSchema.parse(
|
return PaymentPlansResponseSchema.parse(
|
||||||
unwrap(env) as Record<string, unknown>,
|
unwrap(env) as Record<string, unknown>,
|
||||||
|
|||||||
@@ -17,6 +17,17 @@ describe("payment analytics context", () => {
|
|||||||
entryPoint: "chat_unlock",
|
entryPoint: "chat_unlock",
|
||||||
triggerReason: "ad_landing",
|
triggerReason: "ad_landing",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
parsePaymentAnalyticsContext({
|
||||||
|
entryPoint: "chat_offer_banner",
|
||||||
|
triggerReason: "commercial_offer",
|
||||||
|
subscriptionType: "vip",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
entryPoint: "chat_offer_banner",
|
||||||
|
triggerReason: "commercial_offer",
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back independently for invalid query values", () => {
|
it("falls back independently for invalid query values", () => {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export type PaymentAnalyticsTriggerReason =
|
|||||||
| "insufficient_credits"
|
| "insufficient_credits"
|
||||||
| "profile_recharge"
|
| "profile_recharge"
|
||||||
| "vip_cta"
|
| "vip_cta"
|
||||||
|
| "commercial_offer"
|
||||||
| "ad_landing"
|
| "ad_landing"
|
||||||
| "manual_recharge"
|
| "manual_recharge"
|
||||||
| "unknown";
|
| "unknown";
|
||||||
@@ -47,6 +48,7 @@ const TRIGGER_REASONS = new Set<PaymentAnalyticsTriggerReason>([
|
|||||||
"insufficient_credits",
|
"insufficient_credits",
|
||||||
"profile_recharge",
|
"profile_recharge",
|
||||||
"vip_cta",
|
"vip_cta",
|
||||||
|
"commercial_offer",
|
||||||
"ad_landing",
|
"ad_landing",
|
||||||
"manual_recharge",
|
"manual_recharge",
|
||||||
"unknown",
|
"unknown",
|
||||||
|
|||||||
@@ -9,6 +9,21 @@ import {
|
|||||||
shouldBindExternalFacebookIdentity,
|
shouldBindExternalFacebookIdentity,
|
||||||
} from "../external_entry";
|
} from "../external_entry";
|
||||||
|
|
||||||
|
const facebookBusinessEntryCases = [
|
||||||
|
["private-space", "elio", "chat", null, null, getCharacterRoutes("elio").chat, null],
|
||||||
|
["private-space", "maya", "chat", null, null, getCharacterRoutes("maya").chat, null],
|
||||||
|
["private-space", "nayeli", "chat", null, null, getCharacterRoutes("nayeli").chat, null],
|
||||||
|
["voice", "elio", "chat", "promotion", "voice", getCharacterRoutes("elio").chat, "voice"],
|
||||||
|
["voice", "maya", "chat", "promotion", "voice", getCharacterRoutes("maya").chat, "voice"],
|
||||||
|
["voice", "nayeli", "chat", "promotion", "voice", getCharacterRoutes("nayeli").chat, "voice"],
|
||||||
|
["image-pack", "elio", "private-zone", null, null, getCharacterRoutes("elio").privateZone, null],
|
||||||
|
["image-pack", "maya", "private-zone", null, null, getCharacterRoutes("maya").privateZone, null],
|
||||||
|
["image-pack", "nayeli", "private-zone", null, null, getCharacterRoutes("nayeli").privateZone, null],
|
||||||
|
["coffee", "elio", "tip", null, null, getCharacterRoutes("elio").tip, null],
|
||||||
|
["coffee", "maya", "tip", null, null, getCharacterRoutes("maya").tip, null],
|
||||||
|
["coffee", "nayeli", "tip", null, null, getCharacterRoutes("nayeli").tip, null],
|
||||||
|
] as const;
|
||||||
|
|
||||||
describe("external entry navigation", () => {
|
describe("external entry navigation", () => {
|
||||||
it("defaults to chat", () => {
|
it("defaults to chat", () => {
|
||||||
expect(resolveExternalEntryTarget({})).toBe(ROUTES.chat);
|
expect(resolveExternalEntryTarget({})).toBe(ROUTES.chat);
|
||||||
@@ -62,6 +77,26 @@ describe("external entry navigation", () => {
|
|||||||
).toBe(getCharacterRoutes("elio").privateZone);
|
).toBe(getCharacterRoutes("elio").privateZone);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(facebookBusinessEntryCases)(
|
||||||
|
"routes Facebook business entry %s for %s",
|
||||||
|
(
|
||||||
|
_entry,
|
||||||
|
character,
|
||||||
|
target,
|
||||||
|
mode,
|
||||||
|
promotionType,
|
||||||
|
expectedDestination,
|
||||||
|
expectedPromotionType,
|
||||||
|
) => {
|
||||||
|
expect(resolveExternalEntryDestination({ target, character })).toBe(
|
||||||
|
expectedDestination,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
resolveExternalEntryPromotionType({ mode, promotionType }),
|
||||||
|
).toBe(expectedPromotionType);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
["chat", "elio", getCharacterRoutes("elio").chat],
|
["chat", "elio", getCharacterRoutes("elio").chat],
|
||||||
["chat", "maya", getCharacterRoutes("maya").chat],
|
["chat", "maya", getCharacterRoutes("maya").chat],
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
getPaymentUrl,
|
getPaymentUrl,
|
||||||
|
getPaymentUrlHostname,
|
||||||
getStripeClientSecret,
|
getStripeClientSecret,
|
||||||
isEzpayPayment,
|
isEzpayPayment,
|
||||||
launchEzpayRedirect,
|
launchEzpayRedirect,
|
||||||
@@ -43,36 +44,103 @@ describe("payment launch helpers", () => {
|
|||||||
).toBeNull();
|
).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resolves Ezpay URL and QR launch parameters without treating QR data as a URL", () => {
|
it("prioritizes a hosted GCash URL for Philippine checkout", () => {
|
||||||
expect(
|
expect(
|
||||||
resolveEzpayLaunchTarget({
|
resolveEzpayLaunchTarget({
|
||||||
provider: "ezpay",
|
provider: "ezpay",
|
||||||
channelType: "URL",
|
channelType: "URL",
|
||||||
payData: "https://pay.example/qris",
|
payData: "https://pay.example/gcash",
|
||||||
}),
|
}, { countryCode: "PH", currency: "PHP" }),
|
||||||
).toEqual({ kind: "url", paymentUrl: "https://pay.example/qris" });
|
).toEqual({ kind: "url", paymentUrl: "https://pay.example/gcash" });
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
resolveEzpayLaunchTarget({
|
resolveEzpayLaunchTarget({
|
||||||
provider: "ezpay",
|
provider: "ezpay",
|
||||||
channelType: "QR",
|
channelType: "QR",
|
||||||
payData: "00020101021226670016COM.NOBUBANK.WWW",
|
payData: "000201010212ph-qr-payload",
|
||||||
}),
|
cashierUrl: "https://pay.example/gcash-hosted",
|
||||||
|
}, { countryCode: "PH" }),
|
||||||
|
).toEqual({
|
||||||
|
kind: "url",
|
||||||
|
paymentUrl: "https://pay.example/gcash-hosted",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a usable QR Ph fallback without calling it QRIS", () => {
|
||||||
|
expect(
|
||||||
|
resolveEzpayLaunchTarget(
|
||||||
|
{
|
||||||
|
provider: "ezpay",
|
||||||
|
channelType: "QR",
|
||||||
|
payData: "000201010212ph-qr-payload",
|
||||||
|
},
|
||||||
|
{ currency: "PHP" },
|
||||||
|
),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
kind: "qr",
|
kind: "qr",
|
||||||
|
experience: "gcashQrPh",
|
||||||
|
qrData: "000201010212ph-qr-payload",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
resolveEzpayLaunchTarget(
|
||||||
|
{
|
||||||
|
provider: "ezpay",
|
||||||
|
payData: "000201010212ph-qr-payload",
|
||||||
|
},
|
||||||
|
{ countryCode: "PH" },
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
kind: "qr",
|
||||||
|
experience: "gcashQrPh",
|
||||||
|
qrData: "000201010212ph-qr-payload",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps Indonesian QRIS ahead of an optional hosted URL", () => {
|
||||||
|
expect(
|
||||||
|
resolveEzpayLaunchTarget(
|
||||||
|
{
|
||||||
|
provider: "ezpay",
|
||||||
|
channelType: "QR",
|
||||||
|
payData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
|
cashierUrl: "https://pay.example/indonesia",
|
||||||
|
},
|
||||||
|
{ countryCode: "ID", currency: "IDR" },
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
kind: "qr",
|
||||||
|
experience: "qris",
|
||||||
qrData: "00020101021226670016COM.NOBUBANK.WWW",
|
qrData: "00020101021226670016COM.NOBUBANK.WWW",
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a regional error only when both URL and QR data are absent", () => {
|
||||||
expect(
|
expect(
|
||||||
resolveEzpayLaunchTarget({
|
resolveEzpayLaunchTarget(
|
||||||
provider: "ezpay",
|
{
|
||||||
channelType: "QR",
|
provider: "ezpay",
|
||||||
payData: "",
|
channelType: "QR",
|
||||||
}),
|
payData: "",
|
||||||
|
},
|
||||||
|
{ countryCode: "PH" },
|
||||||
|
),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
kind: "error",
|
kind: "error",
|
||||||
errorMessage: "QRIS payment data is missing. Please try again.",
|
errorMessage:
|
||||||
|
"GCash / QR Ph payment data is missing. Please try again.",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps diagnostics to the payment URL hostname", () => {
|
||||||
|
expect(
|
||||||
|
getPaymentUrlHostname(
|
||||||
|
"https://pay.example/gcash?token=must-not-appear-in-logs",
|
||||||
|
),
|
||||||
|
).toBe("pay.example");
|
||||||
|
expect(getPaymentUrlHostname("not-a-url")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("rejects VA and unknown Ezpay channel types with explicit errors", () => {
|
it("rejects VA and unknown Ezpay channel types with explicit errors", () => {
|
||||||
expect(
|
expect(
|
||||||
resolveEzpayLaunchTarget({ provider: "ezpay", channelType: "VA" }),
|
resolveEzpayLaunchTarget({ provider: "ezpay", channelType: "VA" }),
|
||||||
|
|||||||
@@ -13,9 +13,20 @@ const log = new Logger("LibPaymentPaymentLaunch");
|
|||||||
|
|
||||||
export type EzpayLaunchTarget =
|
export type EzpayLaunchTarget =
|
||||||
| { kind: "url"; paymentUrl: string }
|
| { kind: "url"; paymentUrl: string }
|
||||||
| { kind: "qr"; qrData: string }
|
| {
|
||||||
|
kind: "qr";
|
||||||
|
experience: EzpayQrExperience;
|
||||||
|
qrData: string;
|
||||||
|
}
|
||||||
| { kind: "error"; errorMessage: string };
|
| { kind: "error"; errorMessage: string };
|
||||||
|
|
||||||
|
export type EzpayQrExperience = "gcashQrPh" | "qris" | "paymentQr";
|
||||||
|
|
||||||
|
export interface ResolveEzpayLaunchContext {
|
||||||
|
countryCode?: string | null;
|
||||||
|
currency?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
function getNonEmptyString(
|
function getNonEmptyString(
|
||||||
payParams: Record<string, unknown>,
|
payParams: Record<string, unknown>,
|
||||||
...keys: string[]
|
...keys: string[]
|
||||||
@@ -41,6 +52,12 @@ function getHttpPaymentUrl(value: string | null): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getPaymentUrlHostname(value: string | null): string | null {
|
||||||
|
const paymentUrl = getHttpPaymentUrl(value);
|
||||||
|
if (!paymentUrl) return null;
|
||||||
|
return new URL(paymentUrl).hostname;
|
||||||
|
}
|
||||||
|
|
||||||
export function getPaymentUrl(payParams: Record<string, unknown>): string | null {
|
export function getPaymentUrl(payParams: Record<string, unknown>): string | null {
|
||||||
const keys = [
|
const keys = [
|
||||||
"cashierUrl",
|
"cashierUrl",
|
||||||
@@ -71,6 +88,7 @@ export function isEzpayPayment(payParams: Record<string, unknown>): boolean {
|
|||||||
|
|
||||||
export function resolveEzpayLaunchTarget(
|
export function resolveEzpayLaunchTarget(
|
||||||
payParams: Record<string, unknown>,
|
payParams: Record<string, unknown>,
|
||||||
|
context: ResolveEzpayLaunchContext = {},
|
||||||
): EzpayLaunchTarget {
|
): EzpayLaunchTarget {
|
||||||
const rawChannelType = getNonEmptyString(
|
const rawChannelType = getNonEmptyString(
|
||||||
payParams,
|
payParams,
|
||||||
@@ -79,13 +97,33 @@ export function resolveEzpayLaunchTarget(
|
|||||||
);
|
);
|
||||||
const channelType = rawChannelType?.toUpperCase() ?? null;
|
const channelType = rawChannelType?.toUpperCase() ?? null;
|
||||||
const payData = getNonEmptyString(payParams, "payData", "pay_data");
|
const payData = getNonEmptyString(payParams, "payData", "pay_data");
|
||||||
|
const payDataUrl = getHttpPaymentUrl(payData);
|
||||||
|
const namedPaymentUrl = getHttpPaymentUrl(getPaymentUrl(payParams));
|
||||||
|
const paymentUrl = payDataUrl ?? namedPaymentUrl;
|
||||||
|
const qrData = payData && !payDataUrl ? payData : null;
|
||||||
|
const region = resolveEzpayRegion(payParams, context);
|
||||||
|
|
||||||
|
if (
|
||||||
|
region === "ph" &&
|
||||||
|
paymentUrl &&
|
||||||
|
(channelType === "QR" || channelType === "URL" || channelType === null)
|
||||||
|
) {
|
||||||
|
return { kind: "url", paymentUrl };
|
||||||
|
}
|
||||||
|
|
||||||
if (channelType === "QR") {
|
if (channelType === "QR") {
|
||||||
return payData
|
if (qrData) {
|
||||||
? { kind: "qr", qrData: payData }
|
return {
|
||||||
|
kind: "qr",
|
||||||
|
experience: resolveEzpayQrExperience(region),
|
||||||
|
qrData,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return paymentUrl
|
||||||
|
? { kind: "url", paymentUrl }
|
||||||
: {
|
: {
|
||||||
kind: "error",
|
kind: "error",
|
||||||
errorMessage: "QRIS payment data is missing. Please try again.",
|
errorMessage: regionalQrMissingMessage(region),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,8 +135,6 @@ export function resolveEzpayLaunchTarget(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (channelType === "URL") {
|
if (channelType === "URL") {
|
||||||
const paymentUrl =
|
|
||||||
getHttpPaymentUrl(payData) ?? getHttpPaymentUrl(getPaymentUrl(payParams));
|
|
||||||
return paymentUrl
|
return paymentUrl
|
||||||
? { kind: "url", paymentUrl }
|
? { kind: "url", paymentUrl }
|
||||||
: {
|
: {
|
||||||
@@ -114,14 +150,66 @@ export function resolveEzpayLaunchTarget(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const legacyPaymentUrl = getHttpPaymentUrl(getPaymentUrl(payParams));
|
if (paymentUrl) return { kind: "url", paymentUrl };
|
||||||
return legacyPaymentUrl
|
if (qrData && region !== null) {
|
||||||
? { kind: "url", paymentUrl: legacyPaymentUrl }
|
return {
|
||||||
: {
|
kind: "qr",
|
||||||
kind: "error",
|
experience: resolveEzpayQrExperience(region),
|
||||||
errorMessage:
|
qrData,
|
||||||
"Ezpay payment parameters did not include a supported URL or QRIS code.",
|
};
|
||||||
};
|
}
|
||||||
|
return {
|
||||||
|
kind: "error",
|
||||||
|
errorMessage:
|
||||||
|
"Ezpay payment parameters did not include a supported URL or payment QR code.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveEzpayRegion(
|
||||||
|
payParams: Record<string, unknown>,
|
||||||
|
context: ResolveEzpayLaunchContext,
|
||||||
|
): "ph" | "id" | null {
|
||||||
|
const currency = (
|
||||||
|
context.currency ?? getNonEmptyString(payParams, "currency")
|
||||||
|
)
|
||||||
|
?.trim()
|
||||||
|
.toUpperCase();
|
||||||
|
if (currency === "PHP") return "ph";
|
||||||
|
if (currency === "IDR") return "id";
|
||||||
|
|
||||||
|
const countryCode = (
|
||||||
|
context.countryCode ??
|
||||||
|
getNonEmptyString(
|
||||||
|
payParams,
|
||||||
|
"purchaseCountryCode",
|
||||||
|
"purchase_country_code",
|
||||||
|
"countryCode",
|
||||||
|
"country_code",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
?.trim()
|
||||||
|
.toUpperCase();
|
||||||
|
if (countryCode === "PH") return "ph";
|
||||||
|
if (countryCode === "ID") return "id";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveEzpayQrExperience(
|
||||||
|
region: "ph" | "id" | null,
|
||||||
|
): EzpayQrExperience {
|
||||||
|
if (region === "ph") return "gcashQrPh";
|
||||||
|
if (region === "id") return "qris";
|
||||||
|
return "paymentQr";
|
||||||
|
}
|
||||||
|
|
||||||
|
function regionalQrMissingMessage(region: "ph" | "id" | null): string {
|
||||||
|
if (region === "ph") {
|
||||||
|
return "GCash / QR Ph payment data is missing. Please try again.";
|
||||||
|
}
|
||||||
|
if (region === "id") {
|
||||||
|
return "QRIS payment data is missing. Please try again.";
|
||||||
|
}
|
||||||
|
return "Payment QR data is missing. Please try again.";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getStripeClientSecret(
|
export function getStripeClientSecret(
|
||||||
@@ -166,18 +254,19 @@ export async function launchEzpayRedirect({
|
|||||||
onOpened,
|
onOpened,
|
||||||
onFailed,
|
onFailed,
|
||||||
}: LaunchEzpayRedirectInput): Promise<void> {
|
}: LaunchEzpayRedirectInput): Promise<void> {
|
||||||
|
const paymentUrlHost = getPaymentUrlHostname(paymentUrl);
|
||||||
log.debug("[payment-launch] launchEzpayRedirect START", {
|
log.debug("[payment-launch] launchEzpayRedirect START", {
|
||||||
hasOrderId: Boolean(orderId),
|
hasOrderId: Boolean(orderId),
|
||||||
orderId,
|
orderId,
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
paymentUrl,
|
paymentUrlHost,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!orderId) {
|
if (!orderId) {
|
||||||
const errorMessage = "Missing order id before opening Ezpay.";
|
const errorMessage = "Missing order id before opening Ezpay.";
|
||||||
log.error("[payment-launch] pending ezpay order save skipped", {
|
log.error("[payment-launch] pending ezpay order save skipped", {
|
||||||
subscriptionType,
|
subscriptionType,
|
||||||
paymentUrl,
|
paymentUrlHost,
|
||||||
errorMessage,
|
errorMessage,
|
||||||
});
|
});
|
||||||
onFailed(errorMessage);
|
onFailed(errorMessage);
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ export interface OpenSubscriptionInput {
|
|||||||
replace?: boolean;
|
replace?: boolean;
|
||||||
analytics?: PaymentAnalyticsContext;
|
analytics?: PaymentAnalyticsContext;
|
||||||
chatActionId?: string;
|
chatActionId?: string;
|
||||||
|
planId?: string;
|
||||||
|
commercialOfferId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StartMessageUnlockInput {
|
export interface StartMessageUnlockInput {
|
||||||
|
|||||||
@@ -80,6 +80,8 @@ export function useGlobalAppNavigator(): GlobalAppNavigator {
|
|||||||
replace: shouldReplace = false,
|
replace: shouldReplace = false,
|
||||||
analytics = getDefaultPaymentAnalyticsContext(type),
|
analytics = getDefaultPaymentAnalyticsContext(type),
|
||||||
chatActionId,
|
chatActionId,
|
||||||
|
planId,
|
||||||
|
commercialOfferId,
|
||||||
}: OpenGlobalSubscriptionInput): void => {
|
}: OpenGlobalSubscriptionInput): void => {
|
||||||
const target = ROUTE_BUILDERS.subscription(type, {
|
const target = ROUTE_BUILDERS.subscription(type, {
|
||||||
payChannel,
|
payChannel,
|
||||||
@@ -87,6 +89,8 @@ export function useGlobalAppNavigator(): GlobalAppNavigator {
|
|||||||
sourceCharacterSlug,
|
sourceCharacterSlug,
|
||||||
analytics,
|
analytics,
|
||||||
chatActionId,
|
chatActionId,
|
||||||
|
planId,
|
||||||
|
commercialOfferId,
|
||||||
});
|
});
|
||||||
|
|
||||||
behaviorAnalytics.rechargeModalOpen(analytics);
|
behaviorAnalytics.rechargeModalOpen(analytics);
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { appendCommercialMessage } from "../helper/commercial-message";
|
||||||
|
|
||||||
|
describe("chat commercial message", () => {
|
||||||
|
const incoming = {
|
||||||
|
messageId: "payment-thanks-1",
|
||||||
|
message: "Thank you for supporting me.",
|
||||||
|
characterId: "maya-tan",
|
||||||
|
createdAt: "2026-07-28T08:30:00.000Z",
|
||||||
|
};
|
||||||
|
|
||||||
|
it("appends one persisted payment thank-you to the matching character chat", () => {
|
||||||
|
const messages = appendCommercialMessage([], "maya-tan", incoming);
|
||||||
|
|
||||||
|
expect(messages).toHaveLength(1);
|
||||||
|
expect(messages[0]).toMatchObject({
|
||||||
|
remoteId: "payment-thanks-1",
|
||||||
|
content: "Thank you for supporting me.",
|
||||||
|
isFromAI: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores duplicate delivery and a message for another character", () => {
|
||||||
|
const messages = appendCommercialMessage([], "maya-tan", incoming);
|
||||||
|
|
||||||
|
expect(appendCommercialMessage(messages, "maya-tan", incoming)).toEqual(
|
||||||
|
messages,
|
||||||
|
);
|
||||||
|
expect(appendCommercialMessage(messages, "elio", incoming)).toEqual(
|
||||||
|
messages,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -116,7 +116,7 @@ describe("sendResponseToUiMessage", () => {
|
|||||||
copy: "Buy me a coffee?",
|
copy: "Buy me a coffee?",
|
||||||
ctaLabel: "View gifts",
|
ctaLabel: "View gifts",
|
||||||
target: "giftCatalog",
|
target: "giftCatalog",
|
||||||
ruleId: "coffee_support_question",
|
ruleId: "coffee_after_thanks",
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -127,7 +127,7 @@ describe("sendResponseToUiMessage", () => {
|
|||||||
copy: "Buy me a coffee?",
|
copy: "Buy me a coffee?",
|
||||||
ctaLabel: "View gifts",
|
ctaLabel: "View gifts",
|
||||||
target: "giftCatalog",
|
target: "giftCatalog",
|
||||||
ruleId: "coffee_support_question",
|
ruleId: "coffee_after_thanks",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,15 @@ export type ChatEvent =
|
|||||||
}
|
}
|
||||||
| { type: "ChatOlderHistoryLoadFailed"; error: unknown }
|
| { type: "ChatOlderHistoryLoadFailed"; error: unknown }
|
||||||
| { type: "ChatHistoryRefreshRequested" }
|
| { type: "ChatHistoryRefreshRequested" }
|
||||||
|
| {
|
||||||
|
type: "ChatCommercialMessageReceived";
|
||||||
|
message: {
|
||||||
|
messageId: string;
|
||||||
|
message: string;
|
||||||
|
characterId: string;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
// Chat domain events.
|
// Chat domain events.
|
||||||
| { type: "ChatSendMessage"; content: string }
|
| { type: "ChatSendMessage"; content: string }
|
||||||
| { type: "ChatSendImage"; imageBase64: string }
|
| { type: "ChatSendImage"; imageBase64: string }
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { createRemoteUiMessageIdentity, type UiMessage } from "../ui-message";
|
||||||
|
import { todayString } from "@/utils/date";
|
||||||
|
|
||||||
|
export interface IncomingCommercialMessage {
|
||||||
|
messageId: string;
|
||||||
|
message: string;
|
||||||
|
characterId: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appendCommercialMessage(
|
||||||
|
messages: readonly UiMessage[],
|
||||||
|
activeCharacterId: string,
|
||||||
|
incoming: IncomingCommercialMessage,
|
||||||
|
): UiMessage[] {
|
||||||
|
if (incoming.characterId !== activeCharacterId) return [...messages];
|
||||||
|
if (messages.some((message) => message.remoteId === incoming.messageId)) {
|
||||||
|
return [...messages];
|
||||||
|
}
|
||||||
|
const createdAt = new Date(incoming.createdAt);
|
||||||
|
return [
|
||||||
|
...messages,
|
||||||
|
{
|
||||||
|
...createRemoteUiMessageIdentity(incoming.messageId, true),
|
||||||
|
content: incoming.message,
|
||||||
|
isFromAI: true,
|
||||||
|
date: todayString(Number.isNaN(createdAt.getTime()) ? new Date() : createdAt),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createChatPromotionState } from "../helper/promotion";
|
import { createChatPromotionState } from "../helper/promotion";
|
||||||
|
import { appendCommercialMessage } from "../helper/commercial-message";
|
||||||
import { shouldPromptUnlockHistory } from "../helper/unlock";
|
import { shouldPromptUnlockHistory } from "../helper/unlock";
|
||||||
import { createInitialChatState } from "../chat-state";
|
import { createInitialChatState } from "../chat-state";
|
||||||
import {
|
import {
|
||||||
@@ -53,6 +54,19 @@ const injectPromotionAction = unlockMachineSetup.assign(({ event }) => {
|
|||||||
|
|
||||||
const clearPromotionAction = unlockMachineSetup.assign({ promotion: null });
|
const clearPromotionAction = unlockMachineSetup.assign({ promotion: null });
|
||||||
|
|
||||||
|
const appendCommercialMessageAction = unlockMachineSetup.assign(
|
||||||
|
({ context, event }) => {
|
||||||
|
if (event.type !== "ChatCommercialMessageReceived") return {};
|
||||||
|
return {
|
||||||
|
messages: appendCommercialMessage(
|
||||||
|
context.messages,
|
||||||
|
context.characterId,
|
||||||
|
event.message,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
export const chatMachineSetup = unlockMachineSetup.extend({
|
export const chatMachineSetup = unlockMachineSetup.extend({
|
||||||
actions: {
|
actions: {
|
||||||
startGuestSession: startGuestSessionAction,
|
startGuestSession: startGuestSessionAction,
|
||||||
@@ -60,6 +74,7 @@ export const chatMachineSetup = unlockMachineSetup.extend({
|
|||||||
clearChatSession: clearChatSessionAction,
|
clearChatSession: clearChatSessionAction,
|
||||||
injectPromotion: injectPromotionAction,
|
injectPromotion: injectPromotionAction,
|
||||||
clearPromotion: clearPromotionAction,
|
clearPromotion: clearPromotionAction,
|
||||||
|
appendCommercialMessage: appendCommercialMessageAction,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -258,6 +273,7 @@ export const chatRootStateConfig = chatMachineSetup.createStateConfig({
|
|||||||
on: {
|
on: {
|
||||||
ChatPromotionInjected: { actions: "injectPromotion" },
|
ChatPromotionInjected: { actions: "injectPromotion" },
|
||||||
ChatPromotionCleared: { actions: "clearPromotion" },
|
ChatPromotionCleared: { actions: "clearPromotion" },
|
||||||
|
ChatCommercialMessageReceived: { actions: "appendCommercialMessage" },
|
||||||
},
|
},
|
||||||
states: {
|
states: {
|
||||||
idle: idleState,
|
idle: idleState,
|
||||||
|
|||||||
@@ -105,6 +105,29 @@ describe("payment order flow", () => {
|
|||||||
actor.stop();
|
actor.stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(["elio", "maya-tan", "nayeli-cervantes"])(
|
||||||
|
"binds a default VIP or credit order to the source chat character %s",
|
||||||
|
async (characterId) => {
|
||||||
|
const createOrderSpy = vi.fn<CreateOrderSpy>();
|
||||||
|
const actor = createActor(
|
||||||
|
createTestPaymentMachine({ createOrderSpy }),
|
||||||
|
).start();
|
||||||
|
actor.send({ type: "PaymentInit", characterId });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||||
|
|
||||||
|
actor.send({ type: "PaymentCreateOrderSubmitted" });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("paid"));
|
||||||
|
|
||||||
|
expect(createOrderSpy).toHaveBeenCalledWith({
|
||||||
|
planId: "vip_monthly",
|
||||||
|
payChannel: "stripe",
|
||||||
|
autoRenew: true,
|
||||||
|
recipientCharacterId: characterId,
|
||||||
|
});
|
||||||
|
actor.stop();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it("carries the originating chat action into order creation", async () => {
|
it("carries the originating chat action into order creation", async () => {
|
||||||
const createOrderSpy = vi.fn<CreateOrderSpy>();
|
const createOrderSpy = vi.fn<CreateOrderSpy>();
|
||||||
const actor = createActor(
|
const actor = createActor(
|
||||||
@@ -278,6 +301,37 @@ describe("payment order flow", () => {
|
|||||||
actor.stop();
|
actor.stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("can abandon a pending QRIS order and switch to Stripe", async () => {
|
||||||
|
const createOrderSpy = vi.fn<CreateOrderSpy>();
|
||||||
|
const actor = createActor(
|
||||||
|
createTestPaymentMachine({ createOrderSpy, orderStatus: "pending" }),
|
||||||
|
).start();
|
||||||
|
await initialize(actor);
|
||||||
|
actor.send({ type: "PaymentPayChannelChanged", payChannel: "ezpay" });
|
||||||
|
actor.send({ type: "PaymentCreateOrderSubmitted" });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("waitingForPayment"));
|
||||||
|
|
||||||
|
actor.send({ type: "PaymentPayChannelChanged", payChannel: "stripe" });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
|
||||||
|
|
||||||
|
expect(actor.getSnapshot().context).toMatchObject({
|
||||||
|
payChannel: "stripe",
|
||||||
|
currentOrderId: null,
|
||||||
|
payParams: null,
|
||||||
|
orderStatus: null,
|
||||||
|
orderPollingStartedAt: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
actor.send({ type: "PaymentCreateOrderSubmitted" });
|
||||||
|
await waitFor(actor, (snapshot) => snapshot.matches("waitingForPayment"));
|
||||||
|
expect(createOrderSpy).toHaveBeenNthCalledWith(2, {
|
||||||
|
planId: "vip_monthly",
|
||||||
|
payChannel: "stripe",
|
||||||
|
autoRenew: true,
|
||||||
|
});
|
||||||
|
actor.stop();
|
||||||
|
});
|
||||||
|
|
||||||
it("moves to failed when polling reports failure", async () => {
|
it("moves to failed when polling reports failure", async () => {
|
||||||
const actor = createActor(
|
const actor = createActor(
|
||||||
createTestPaymentMachine({ orderStatus: "failed" }),
|
createTestPaymentMachine({ orderStatus: "failed" }),
|
||||||
|
|||||||
@@ -136,12 +136,20 @@ export function consumeFirstRechargeState(
|
|||||||
context: PaymentState,
|
context: PaymentState,
|
||||||
): Pick<
|
): Pick<
|
||||||
PaymentState,
|
PaymentState,
|
||||||
"plans" | "isFirstRecharge" | "selectedPlanId" | "autoRenew" | "errorMessage"
|
| "plans"
|
||||||
|
| "isFirstRecharge"
|
||||||
|
| "commercialOffer"
|
||||||
|
| "commercialOfferId"
|
||||||
|
| "selectedPlanId"
|
||||||
|
| "autoRenew"
|
||||||
|
| "errorMessage"
|
||||||
> {
|
> {
|
||||||
const plans = context.plans.map(consumeFirstRechargePlan);
|
const plans = context.plans.map(consumeFirstRechargePlan);
|
||||||
return {
|
return {
|
||||||
...refreshPlansState(plans, context.selectedPlanId),
|
...refreshPlansState(plans, context.selectedPlanId),
|
||||||
isFirstRecharge: false,
|
isFirstRecharge: false,
|
||||||
|
commercialOffer: null,
|
||||||
|
commercialOfferId: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import type { PaymentPlanCatalog } from "../../payment-state";
|
|||||||
|
|
||||||
export const loadCachedPaymentPlansActor = fromPromise<
|
export const loadCachedPaymentPlansActor = fromPromise<
|
||||||
PaymentPlansResponse | null,
|
PaymentPlansResponse | null,
|
||||||
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null }
|
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null; supportCharacterId?: string | null }
|
||||||
>(async ({ input }) => {
|
>(async ({ input }) => {
|
||||||
if (input.catalog === "tip" || input.commercialOfferId) return null;
|
if (input.catalog === "tip" || input.commercialOfferId || input.supportCharacterId) return null;
|
||||||
const result = await getPaymentRepository().getCachedPlans();
|
const result = await getPaymentRepository().getCachedPlans();
|
||||||
if (Result.isErr(result)) throw result.error;
|
if (Result.isErr(result)) throw result.error;
|
||||||
return result.data;
|
return result.data;
|
||||||
@@ -18,13 +18,16 @@ export const loadCachedPaymentPlansActor = fromPromise<
|
|||||||
|
|
||||||
export const refreshPaymentPlansActor = fromPromise<
|
export const refreshPaymentPlansActor = fromPromise<
|
||||||
PaymentPlansResponse,
|
PaymentPlansResponse,
|
||||||
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null }
|
{ catalog: PaymentPlanCatalog; commercialOfferId?: string | null; supportCharacterId?: string | null }
|
||||||
>(async ({ input }) => {
|
>(async ({ input }) => {
|
||||||
const paymentRepo = getPaymentRepository();
|
const paymentRepo = getPaymentRepository();
|
||||||
if (input.catalog === "tip") {
|
if (input.catalog === "tip") {
|
||||||
throw new Error("Gift catalogs must use the gift products actor.");
|
throw new Error("Gift catalogs must use the gift products actor.");
|
||||||
}
|
}
|
||||||
const result = await paymentRepo.getPlans(input.commercialOfferId ?? undefined);
|
const result = await paymentRepo.getPlans(
|
||||||
|
input.commercialOfferId ?? undefined,
|
||||||
|
input.supportCharacterId ?? undefined,
|
||||||
|
);
|
||||||
if (Result.isErr(result)) throw result.error;
|
if (Result.isErr(result)) throw result.error;
|
||||||
return result.data;
|
return result.data;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,8 +29,14 @@ function initializeCatalogState(
|
|||||||
planCatalog === "tip"
|
planCatalog === "tip"
|
||||||
? (event.characterId ?? context.giftCharacterId)
|
? (event.characterId ?? context.giftCharacterId)
|
||||||
: null;
|
: null;
|
||||||
|
const supportCharacterId =
|
||||||
|
planCatalog === "default"
|
||||||
|
? (event.characterId ?? context.supportCharacterId)
|
||||||
|
: null;
|
||||||
const catalogChanged = planCatalog !== context.planCatalog;
|
const catalogChanged = planCatalog !== context.planCatalog;
|
||||||
const characterChanged = giftCharacterId !== context.giftCharacterId;
|
const characterChanged =
|
||||||
|
giftCharacterId !== context.giftCharacterId ||
|
||||||
|
supportCharacterId !== context.supportCharacterId;
|
||||||
const selectionChanged =
|
const selectionChanged =
|
||||||
planCatalog === "tip" &&
|
planCatalog === "tip" &&
|
||||||
((event.category ?? null) !== context.selectedGiftCategory ||
|
((event.category ?? null) !== context.selectedGiftCategory ||
|
||||||
@@ -45,6 +51,7 @@ function initializeCatalogState(
|
|||||||
planCatalog,
|
planCatalog,
|
||||||
...(event.payChannel ? { payChannel: event.payChannel } : {}),
|
...(event.payChannel ? { payChannel: event.payChannel } : {}),
|
||||||
giftCharacterId,
|
giftCharacterId,
|
||||||
|
supportCharacterId,
|
||||||
commercialOfferId,
|
commercialOfferId,
|
||||||
chatActionId,
|
chatActionId,
|
||||||
requestedGiftCategory:
|
requestedGiftCategory:
|
||||||
@@ -219,6 +226,7 @@ export const loadingCachedPlansState =
|
|||||||
input: ({ context }) => ({
|
input: ({ context }) => ({
|
||||||
catalog: context.planCatalog,
|
catalog: context.planCatalog,
|
||||||
commercialOfferId: context.commercialOfferId,
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
supportCharacterId: context.supportCharacterId,
|
||||||
}),
|
}),
|
||||||
onDone: [
|
onDone: [
|
||||||
{
|
{
|
||||||
@@ -235,9 +243,10 @@ export const loadingCachedPlansState =
|
|||||||
export const loadingPlansState = catalogMachineSetup.createStateConfig({
|
export const loadingPlansState = catalogMachineSetup.createStateConfig({
|
||||||
invoke: {
|
invoke: {
|
||||||
src: "refreshPlans",
|
src: "refreshPlans",
|
||||||
input: ({ context }) => ({
|
input: ({ context }) => ({
|
||||||
catalog: context.planCatalog,
|
catalog: context.planCatalog,
|
||||||
commercialOfferId: context.commercialOfferId,
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
supportCharacterId: context.supportCharacterId,
|
||||||
}),
|
}),
|
||||||
onDone: {
|
onDone: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
@@ -256,6 +265,7 @@ export const refreshingPlansState = catalogMachineSetup.createStateConfig({
|
|||||||
input: ({ context }) => ({
|
input: ({ context }) => ({
|
||||||
catalog: context.planCatalog,
|
catalog: context.planCatalog,
|
||||||
commercialOfferId: context.commercialOfferId,
|
commercialOfferId: context.commercialOfferId,
|
||||||
|
supportCharacterId: context.supportCharacterId,
|
||||||
}),
|
}),
|
||||||
onDone: {
|
onDone: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
|
|||||||
@@ -192,8 +192,14 @@ const creatingOrderState = paymentMachineSetup.createStateConfig({
|
|||||||
payChannel: context.payChannel,
|
payChannel: context.payChannel,
|
||||||
autoRenew: context.autoRenew,
|
autoRenew: context.autoRenew,
|
||||||
...(event.type === "PaymentCreateOrderSubmitted" &&
|
...(event.type === "PaymentCreateOrderSubmitted" &&
|
||||||
event.recipientCharacterId
|
(event.recipientCharacterId || context.supportCharacterId || context.giftCharacterId)
|
||||||
? { recipientCharacterId: event.recipientCharacterId }
|
? {
|
||||||
|
recipientCharacterId:
|
||||||
|
event.recipientCharacterId ||
|
||||||
|
context.supportCharacterId ||
|
||||||
|
context.giftCharacterId ||
|
||||||
|
undefined,
|
||||||
|
}
|
||||||
: {}),
|
: {}),
|
||||||
...(context.commercialOfferId
|
...(context.commercialOfferId
|
||||||
? { commercialOfferId: context.commercialOfferId }
|
? { commercialOfferId: context.commercialOfferId }
|
||||||
@@ -259,6 +265,10 @@ const pollingOrderState = paymentMachineSetup.createStateConfig({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
on: {
|
on: {
|
||||||
|
PaymentPayChannelChanged: {
|
||||||
|
target: "ready",
|
||||||
|
actions: "changePayChannel",
|
||||||
|
},
|
||||||
PaymentReset: {
|
PaymentReset: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
actions: "resetOrder",
|
actions: "resetOrder",
|
||||||
@@ -271,6 +281,10 @@ const waitingForPaymentState = paymentMachineSetup.createStateConfig({
|
|||||||
[POLL_DELAY_MS]: "pollingOrder",
|
[POLL_DELAY_MS]: "pollingOrder",
|
||||||
},
|
},
|
||||||
on: {
|
on: {
|
||||||
|
PaymentPayChannelChanged: {
|
||||||
|
target: "ready",
|
||||||
|
actions: "changePayChannel",
|
||||||
|
},
|
||||||
PaymentReset: {
|
PaymentReset: {
|
||||||
target: "ready",
|
target: "ready",
|
||||||
actions: "resetOrder",
|
actions: "resetOrder",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ export interface PaymentState {
|
|||||||
giftCategories: readonly GiftCategory[];
|
giftCategories: readonly GiftCategory[];
|
||||||
giftProducts: readonly GiftProduct[];
|
giftProducts: readonly GiftProduct[];
|
||||||
giftCharacterId: string | null;
|
giftCharacterId: string | null;
|
||||||
|
supportCharacterId: string | null;
|
||||||
selectedGiftCategory: string | null;
|
selectedGiftCategory: string | null;
|
||||||
requestedGiftCategory: string | null;
|
requestedGiftCategory: string | null;
|
||||||
requestedGiftPlanId: string | null;
|
requestedGiftPlanId: string | null;
|
||||||
@@ -45,6 +46,7 @@ export const initialState: PaymentState = {
|
|||||||
giftCategories: [],
|
giftCategories: [],
|
||||||
giftProducts: [],
|
giftProducts: [],
|
||||||
giftCharacterId: null,
|
giftCharacterId: null,
|
||||||
|
supportCharacterId: null,
|
||||||
selectedGiftCategory: null,
|
selectedGiftCategory: null,
|
||||||
requestedGiftCategory: null,
|
requestedGiftCategory: null,
|
||||||
requestedGiftPlanId: null,
|
requestedGiftPlanId: null,
|
||||||
|
|||||||
Reference in New Issue
Block a user