6 Commits

Author SHA1 Message Date
luo
e084cdeb90 fix: some
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 2m14s
2026-10-26 15:00:05 +08:00
luo
b5f89b744c ci: switch production deployment to iteration/october
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 2m3s
2026-10-26 14:29:18 +08:00
luo
33f3b37be0 fix: some
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 12m12s
2026-10-26 14:24:59 +08:00
luo
f7cb28febf fix: some
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 2m16s
2026-10-14 13:40:55 +08:00
luo
131823ca12 fix: some
All checks were successful
构建并部署前端到生产环境 / build-and-deploy (push) Successful in 3m40s
2026-10-14 11:04:41 +08:00
luo
a7b1156ac1 fix: some 2026-10-14 09:56:09 +08:00
21 changed files with 2536 additions and 224 deletions

View File

@@ -3,7 +3,7 @@ name: 构建并部署前端到生产环境
on:
push:
branches:
- iteration/august
- iteration/october
- dev
- test
@@ -28,7 +28,7 @@ jobs:
- name: 设置镜像标签
id: tag
run: |
if [ "${{ github.ref }}" = "refs/heads/iteration/august" ]; then
if [ "${{ github.ref }}" = "refs/heads/iteration/october" ]; then
echo "tag=latest" >> $GITHUB_OUTPUT
elif [ "${{ github.ref }}" = "refs/heads/dev" ]; then
echo "tag=dev" >> $GITHUB_OUTPUT
@@ -52,8 +52,8 @@ jobs:
docker push ${{ env.IMAGE_NAME }}:${{ steps.tag.outputs.tag }}
docker push ${{ env.IMAGE_NAME }}:${{ github.sha }}
- name: 部署到本地(仅 iteration/august 分支)
if: github.ref == 'refs/heads/iteration/august'
- name: 部署到本地(仅 iteration/october 分支)
if: github.ref == 'refs/heads/iteration/october'
run: |
mkdir -p ${{ env.DEPLOY_DIR }}

View File

@@ -3,29 +3,35 @@ import { useAssetStore } from '@/store/asset.js';
import { useUserStore } from '@/store/user.js';
import { getSessionContext, isCurrentSession } from '@/utils/session-context.js';
export const normalizeAssetInfo = (data = {}) => ({
...data,
allowed_payment_methods: Array.isArray(data.allowed_payment_methods)
? data.allowed_payment_methods
: [],
real_name_status: data.real_name_status === undefined || data.real_name_status === null
? data.real_name_status
: Number(data.real_name_status),
realname_required: data.realname_required === undefined || data.realname_required === null
? data.realname_required
: data.realname_required === true || data.realname_required === 1,
days_until_final_expiry: data.days_until_final_expiry === null || data.days_until_final_expiry === undefined
? data.days_until_final_expiry
: Number(data.days_until_final_expiry),
is_expiring: data.is_expiring === undefined || data.is_expiring === null
? data.is_expiring
: data.is_expiring === true || data.is_expiring === 1
});
let assetInfoRequestId = 0;
export const normalizeAssetInfo = (data = {}) => {
// 保护期已下线:不向展示和业务判断透传废弃字段,兼容 none 或字段缺失。
const { device_protect_status, ...info } = data;
return {
...info,
allowed_payment_methods: Array.isArray(data.allowed_payment_methods)
? data.allowed_payment_methods
: [],
real_name_status: data.real_name_status === undefined || data.real_name_status === null
? data.real_name_status
: Number(data.real_name_status),
realname_required: data.realname_required === undefined || data.realname_required === null
? data.realname_required
: data.realname_required === true || data.realname_required === 1,
days_until_final_expiry: data.days_until_final_expiry === null || data.days_until_final_expiry === undefined
? data.days_until_final_expiry
: Number(data.days_until_final_expiry),
is_expiring: data.is_expiring === undefined || data.is_expiring === null
? data.is_expiring
: data.is_expiring === true || data.is_expiring === 1
};
};
const normalizePackageHistoryNode = (node = {}) => ({
...node,
children: Array.isArray(node.children)
? node.children.map(normalizePackageHistoryNode)
? node.children.filter(child => Number(child?.status) !== 4).map(normalizePackageHistoryNode)
: [],
expand_by_default: node.expand_by_default === true || node.expand_by_default === 1
});
@@ -33,7 +39,7 @@ const normalizePackageHistoryNode = (node = {}) => ({
export const normalizeAssetPackageHistory = (data = {}) => ({
...data,
items: Array.isArray(data.items)
? data.items.map(normalizePackageHistoryNode)
? data.items.filter(node => Number(node?.status) !== 4).map(normalizePackageHistoryNode)
: [],
page: Number(data.page),
size: Number(data.size),
@@ -59,9 +65,17 @@ export const hasActiveOrPendingPackage = async (identifier) => {
export const assetApi = {
getInfo(identifier) {
identifier = typeof identifier === 'string' ? identifier.trim() : '';
if (!identifier) {
return Promise.reject({ msg: '缺少资产标识,请重新输入或扫码登录' });
}
const context = getSessionContext();
const userStore = useUserStore();
if (userStore.state.loginPending || !context.token) {
return Promise.reject({ msg: '登录和微信配置尚未完成,请稍后重试' });
}
const phoneRevision = userStore.state.phoneRevision;
const requestId = identifier === context.identifier ? ++assetInfoRequestId : null;
return request({
url: '/api/c/v1/asset/info',
method: 'GET',
@@ -69,7 +83,10 @@ export const assetApi = {
}).then((response) => {
const data = normalizeAssetInfo(response);
if (identifier === context.identifier && isCurrentSession(context)) {
useAssetStore().receiveExpiryReminder(context, data.expiry_reminder);
const assetStore = useAssetStore();
// 替换整个快照,不合并旧轮询开关;迟到的旧请求不得覆盖新状态。
if (requestId === assetInfoRequestId) assetStore.setAssetInfo(data);
assetStore.receiveExpiryReminder(context, data.expiry_reminder);
if (phoneRevision === userStore.state.phoneRevision && typeof data.bound_phone === 'string') {
userStore.setCustomerPhone(data.bound_phone);
}

View File

@@ -31,7 +31,7 @@ export const notificationApi = {
markAllRead() {
return request({
url: '/api/c/v1/notifications/read-all',
method: 'POST'
method: 'PUT'
});
}
};

View File

@@ -15,7 +15,8 @@
<text class="expiry-value">{{ formatShanghaiExpiry(reminder.expires_at) }}</text>
</view>
<view class="reminder-description">为避免套餐到期影响使用,请及时续费。</view>
<button class="reminder-confirm" @tap="$emit('close')">我知道了</button>
<button class="reminder-confirm" @tap="$emit('renew')">立即续费</button>
<button class="reminder-later" @tap="$emit('close')">我知道了</button>
</view>
</view>
</view>
@@ -24,7 +25,7 @@
<script setup>
import { formatShanghaiExpiry } from '@/utils/expiry-reminder.js';
defineProps({ reminder: { type: Object, required: true } });
defineEmits(['close']);
defineEmits(['close', 'renew']);
</script>
<style scoped lang="scss">
@@ -69,7 +70,7 @@
color: var(--text-tertiary);
background: transparent;
}
.reminder-close::after, .reminder-confirm::after { border: none; }
.reminder-close::after, .reminder-confirm::after, .reminder-later::after { border: none; }
.clock-halo {
display: flex;
align-items: center;
@@ -127,6 +128,7 @@
background: var(--reminder-color);
}
.expiry-red { --reminder-color: #d94040; --reminder-tint: rgba(217, 64, 64, 0.08); }
.reminder-later { margin: 12rpx 0 0; padding: 14rpx; font-size: 24rpx; line-height: 1.5; color: var(--text-tertiary); background: transparent; }
.expiry-purple { --reminder-color: #8850c4; --reminder-tint: rgba(136, 80, 196, 0.08); }
.expiry-pink { --reminder-color: #ce4878; --reminder-tint: rgba(206, 72, 120, 0.08); }
</style>

View File

@@ -42,7 +42,7 @@
</template>
<script setup>
import { ref, computed } from 'vue';
import { ref, computed, watch } from 'vue';
import { assetApi, isAssetRealNameCompleted, orderApi } from '@/api/index.js';
import {
handlePaymentError,
@@ -63,8 +63,9 @@
paymentRefreshTarget: { type: String, default: PAYMENT_REFRESH_TARGETS.ORDER_LIST }
});
const emit = defineEmits(['completed']);
const emit = defineEmits(['completed', 'visibility-change']);
const show = ref(false);
watch(show, (value) => emit('visibility-change', value), { flush: 'sync' });
const submitting = ref(false);
const packageIds = ref([]);
const packageNames = ref([]);

View File

@@ -40,32 +40,23 @@
<script setup>
import {
ref,
computed,
watch
computed
} from 'vue';
import {
assetApi
} from '@/api/index.js';
import {
useUserStore
} from '@/store/index.js';
const props = defineProps({
identifier: {
type: String,
default: ''
assetInfo: {
type: Object,
default: null
}
});
const emit = defineEmits(['packageLoaded']);
const userStore = useUserStore();
// 流量数据
const usedMB = ref(0);
const totalMB = ref(0);
const remainMB = ref(0);
// 和首页共用最新资产快照,不保留只在首次进入时加载的套餐缓存。
const metrics = computed(() => props.assetInfo?.current_package_usage_id
? getTrafficMetrics(props.assetInfo)
: { used: 0, total: 0, remain: 0 });
const usedMB = computed(() => metrics.value.used);
const totalMB = computed(() => metrics.value.total);
const remainMB = computed(() => metrics.value.remain);
const toMB = (value) => Number(value) || 0;
@@ -125,39 +116,6 @@
};
};
// 加载套餐流量数据
const loadPackageData = async () => {
const identifier = props.identifier || userStore.state.identifier;
if (!identifier) return;
try {
const data = await assetApi.getInfo(identifier);
if (data.current_package_usage_id) {
const metrics = getTrafficMetrics(data);
usedMB.value = metrics.used;
totalMB.value = metrics.total;
remainMB.value = metrics.remain;
emit('packageLoaded', data);
} else {
usedMB.value = 0;
totalMB.value = 0;
remainMB.value = 0;
emit('packageLoaded', null);
}
} catch (e) {
console.error('加载套餐流量数据失败', e);
}
};
// 监听 identifier 变化
watch(() => props.identifier || userStore.state.identifier, (newVal) => {
if (newVal) {
loadPackageData();
}
}, {
immediate: true
});
</script>
<style scoped lang="scss">

View File

@@ -23,8 +23,8 @@
{{ networkStatus == 1 ? '正常' : '停机' }}
</view>
</view>
<up-button v-if="hasPackageName" class="renew-button" type="primary" size="small"
@tap.stop="emit('renew')">立即续费</up-button>
<!-- <up-button v-if="hasPackageName" class="renew-button" type="primary" size="small"
@tap.stop="emit('renew')">立即续费</up-button> -->
</view>
</template>

File diff suppressed because it is too large Load Diff

View File

@@ -8,21 +8,22 @@
- 四种绑定模式使用原 bind-phone 入参;资产首次绑号可输入与客户号不同的号码,1192 提示管理员并禁用当前提交,1184 保留后端错误。按用户最新确认,强制绑定成功保留有效 token 和资产标识,直接进入首页,不再要求重登。
- 客户换号只更新后端确认的客户号码,不改资产关联;归属事实失效,下一次真实登录重新确认。换号的原号来源不再放进 URL。
- asset/info 的共享返回入口接收一次性临期提醒,首页按最新要求使用居中、可关闭弹窗,已移除旧横幅组件。0 天正常显示,使用服务器等级和上海时区;与风险换货/运营候选、普通通知依次展示。绑定页预填收到的提醒留在当前会话,进入首页展示。
- 旧首页通知弹窗排除临期项,通知中心保留。全部已读改 POST,单条已读保持 PUT;成功后重新读取列表和计数,失败不乐观清空,延迟响应不能覆盖新的资产上下文。
- 旧首页通知弹窗排除临期项,通知中心保留。全部已读按用户 2026-10-14 最新确认恢复为 PUT,单条已读也保持 PUT;成功后重新读取列表和计数,失败不乐观清空,延迟响应不能覆盖新的资产上下文。
- 临期弹窗不再展示等级文字标签,仅使用等级配色;新增“立即续费”,先关闭提醒再打开首页原有续费窗口,复用当前套餐 ID/名称/价格和全部原有支付校验,准备和展示期间暂停其他通知。
- 通知卡片移除左侧未读强调边框和小圆点,标题右侧显示“未读/已读”小按钮。点击卡片或按钮成功标记后更新,失败仍显示未读。
## 验证证据
| 证据 | 结果 | 说明 |
|---|---|---|
| `npm run test:h5-integration` | 17/17 通过 | 实际 store/API 模块及页面 setup,使用 Vue 响应性;原生 API、生命周期和后端响应为模拟 |
| `npm run test:h5-integration` | 19/19 通过 | 实际 store/API 模块及页面 setup,使用 Vue 响应性;原生 API、生命周期和后端响应为模拟 |
| `npm run build:h5` | 通过 | uni-app H5 开发配置构建 |
| `npm run build:h5:production` | 通过 | uni-app H5 生产配置构建 |
| `openspec validate update-october-batch1-h5-integration --strict` | 通过 | 提案、需求和场景结构校验 |
| `git diff --check` | 通过 | 默认 Git 换行配置下未发现补丁空白错误;Windows 换行提示不影响构建 |
| 本地浏览器,390×844 / 320×640 | 通过 | 居中临期弹窗、0 天/上海时间、关闭、通知标题右侧未读按钮、点击卡片变已读;此前绑定表单及 1192 检查保留,无页面运行错误 |
测试文件:[tests/october-h5.test.mjs](../../../tests/october-h5.test.mjs)。覆盖绑定模式/成功后的分类更新、登录提示开关、状态持久化/隔离、换号不迁移资产、1192/1184、强制绑定直接进入首页且 token/客户信息/提醒保留、预填失败、共享接收/并发、0~15 天/上海边界、旧弹窗过滤、POST/PUT 请求方法、通知失败与切换、模拟 A/B 全部已读以及 401 状态清理。
测试文件:[tests/october-h5.test.mjs](../../../tests/october-h5.test.mjs)。覆盖绑定模式/成功后的分类更新、登录提示开关、状态持久化/隔离、换号不迁移资产、1192/1184、强制绑定直接进入首页且 token/客户信息/提醒保留、预填失败、共享接收/并发、0~15 天/上海边界、旧弹窗过滤、PUT 已读请求、通知失败与切换、模拟 A/B 全部已读、401 状态清理以及临期弹窗续费复用/队列暂停。
本次修订删除了绑定成功后的登录态清理和“绑定手机号成功,请重新登录”提示,替代旧手动重登提案;真正的退出或 401 登录过期处理不变。
@@ -51,7 +52,7 @@ agent-browser --session october-h5-ui close
1. 微信公众号真实登录应返回三个布尔字段;尤其验证客户无号/资产有号时只给客户绑定,以及客户已有号时资产可绑定不同号码。
2. 确认 asset/info.bound_phone 仍表示当前客户手机号,与登录布尔事实区分;换号后资产号码保持原值。若实际响应与对接文档冲突,先确认契约,不猜测接口。
3. 同客户 A/B 两个临期资产分别扫码进入,确认服务器每天只返回一次、临期列表/未读数仅计当前资产,以及 A 上 POST 全部已读不改变 B 的临期通知。
3. 同客户 A/B 两个临期资产分别扫码进入,确认服务器每天只返回一次、临期列表/未读数仅计当前资产,以及 A 上 PUT 全部已读不改变 B 的临期通知。
4. 完整回归真实支付、实名认证、套餐订购以及运营/风险换货候选弹窗。本次没有修改这些接口或候选组件,构建成功不替代真实业务验收。
完成结果已按实际验证范围回写 [tasks.md](tasks.md),真实联调项保留未勾选;不归档历史提案。

View File

@@ -12,7 +12,7 @@
| `pages/change-phone/change-phone.vue` 把 `newPhone` 写入资产缓存 | 与新文档“只换客户手机号”冲突 | 仅更新客户手机号,保留资产关联 |
| 首页、TrafficCard、绑定页等分别请求 `asset/info` | 一次性提醒可能先被非展示调用方取走 | 在 API 返回入口集中接收,再由资产信息区展示 |
| 首页 `loadUnreadNotifications` 展示所有未读项 | 仍以旧临期通知触发弹窗 | 从旧弹窗来源排除临期项,通知中心不删除 |
| `api/modules/notification.js` 的 `markAllRead` 使用 PUT | 与新文档方法不一致 | 明确切换 POST,不影响 `markRead` 的 PUT |
| `api/modules/notification.js` 的 `markAllRead` 方法约定曾冲突 | 用户最新确认应为 PUT | 保持 PUT,不采用此前 POST 约定 |
## Goals / Non-Goals
@@ -54,12 +54,14 @@
### 4. 一次性临期提醒使用弹窗及共享接收
首页就是当前 H5 的资产信息展示页,本次不新增资产详情路由。按用户最新要求,移除横幅,使用 `ExpiryReminderPopup` 居中弹窗:等级色、小型时钟图形、突出显示剩余天数和预计到期时间,提供右上关闭及“我知道了”操作。
首页就是当前 H5 的资产信息展示页,本次不新增资产详情路由。按用户最新要求,移除横幅,使用 `ExpiryReminderPopup` 居中弹窗:等级配色、小型时钟图形、突出显示剩余天数和预计到期时间;不展示 level_name 标签。提供“立即续费”、右上关闭及“我知道了”操作。
首页按现有风险换货/运营候选 → 临期提醒 → 普通通知的顺序展示,一次只显示一个。asset/info 和候选请求未完成时不消费待展示提醒;通知已显示时才收到临期提醒,则等通知关闭后显示。候选按钮立即导航时保持提醒待展示;候选组件卸载后的异步响应不得回调新页面。临期关闭不再占首页布局,也不因此创建新的业务请求。
原样保留 `expiry_reminder.remaining_days`、`expires_at`、`level`、`level_name`;使用服务端等级映射 red / purple / pink 的样式,保留文本提示,不能只靠颜色传达紧急程度。`remaining_days=0` 必须正常展示。日期展示遵循 Asia/Shanghai,不能用客户端当前时区重算剩余自然日或等级。
“立即续费”先关闭临期弹窗且不推进其他通知,再调用与首页按钮相同的 startHomepageRenewal,使用当前套餐 ID、名称和续费价格。续费窗口准备中/可见时暂停其他提醒,关闭后继续排队。无可续费套餐或无支付方式时沿用原提示,不新增下单接口,也不在点击提醒按钮时自动创建订单。
`assetApi.getInfo` 成功返回处集中接收非空提醒并交给共享状态,同次资产进入期间的并发响应不允许用“未返回字段”的响应覆盖已经接收的提醒。共享状态隔离当前客户上下文与 identifier,避免切换资产/退出后显示旧资产或他人的提醒。提醒到达时若资产信息区尚不可见,应先暂存,待对应资产可见时再展示,不能静默丢弃。
后端负责“客户 + 资产 + 上海自然日”的每日一次;前端只防止同一次接收被多个组件重复展示,不增加每日定时推送、补发请求或长期缓存复播。关闭/已展示的提醒在当天后续无字段响应时不得重新出现。审核所有 `asset/info` 调用方,特别是绑定前预填及首页 TrafficCard 的请求顺序;绑定成功使用同一 token,提醒无需跨登录传递。真实退出、登录过期或切换上下文仍清理旧提醒。
@@ -72,7 +74,7 @@
列表、未读数保持原入参,不增加文档未定义的 identifier/asset_id;后端基于当前认证资产过滤临期通知,并非所有通知都只属于当前资产。切换资产后刷新列表和计数,不将 A 的未读结果拼接到 B。
全部已读使用 POST,保留通知中心主动触发;失败不提前清除未读状态。成功后以刷新结果对齐本地列表/未读数,不能把其他资产的临期通知置已读。单条已读继续 PUT。风险换货、运营及临期弹窗均不得自动调用全部已读。
全部已读按用户最新确认使用 PUT,保留通知中心主动触发;失败不提前清除未读状态。成功后以刷新结果对齐本地列表/未读数,不能把其他资产的临期通知置已读。单条已读继续 PUT。风险换货、运营及临期弹窗均不得自动调用全部已读。
通知卡片保留常规边框,移除左侧未读强调边框和小圆点。标题右侧显示绿色“未读”或灰色“已读”小按钮;点击整张卡片或状态按钮调用现有单条 PUT,成功后显示“已读”并刷新计数,失败保留“未读”。按钮阻止事件冒泡,避免一次点击触发两次标记。
@@ -87,7 +89,7 @@
1. 提案批准后,先完成状态拆分及旧缓存失效,再调整绑定/换号行为。
2. 加入临期提醒共享接收和居中弹窗及排队显示,排除首页旧临期通知弹窗来源,调整通知阅读状态按钮。
3. 切换全部已读为 POST,回归当前资产的列表与未读数。
3. 保持全部已读为 PUT,回归当前资产的列表与未读数。
4. 完成任务中的场景验证及 H5 构建,记录实际结果;不以静态构建代替真实接口联调。
5. 需要回退时只回退本次前端改动;服务端新契约不变,不能恢复“客户换号即资产迁移”的旧假设作为兼容策略。

View File

@@ -13,15 +13,15 @@
- 对 `bind-phone` 的 `1192` 提示“该资产已绑定手机号,如需更换请联系管理员”,不提供重试当前绑定请求的操作;保留 `1184` 的既有错误处理。
- 绑定成功保留有效 token 和资产标识;登录引导的绑定页直接进入首页,不再清除登录态、提示或要求重新登录。普通绑定成功仍返回上一页。
- **BREAKING(替代旧前端假设)**:`change-phone` 只修改客户手机号,不更新任何资产手机号关联;停止将新客户手机号写入资产绑定缓存。
- 接收 `asset/info.expiry_reminder`,在首页展示居中、可关闭的临期弹窗,展示后端提供的剩余天数、到期时间和等级;无字段时不自行计算或补发提醒。
- 接收 `asset/info.expiry_reminder`,在首页展示居中、可关闭的临期弹窗,显示剩余天数、到期时间及等级配色,不显示等级名称标签;“立即续费”复用首页已有续费流程。无字段时不自行计算或补发提醒。
- 统一接收各 `asset/info` 调用返回的一次性提醒,防止首页子组件或其他调用方先获得字段后将其丢弃;不为提醒新增轮询或额外请求。
- 首页旧未读通知弹窗不再以临期通知作为弹窗依据;临期通知仍保留在通知中心,其他通知和既有运营/风险换货弹窗不变。
- 临期弹窗与风险换货/运营、普通通知弹窗依次展示,不叠加;通知卡片去掉左侧未读边框,标题右侧使用“未读/已读”小按钮,点击卡片或按钮后按单条已读响应更新。
- **BREAKING(请求方法切换)**:全部已读改为 `POST /api/c/v1/notifications/read-all`,不再发送旧 `PUT` 或自动回退;通知列表和未读数沿用现有入参,由后端过滤当前资产的临期通知。
- 全部已读保持 `PUT /api/c/v1/notifications/read-all`,以用户 2026-10-14 最新确认覆盖此前 POST 约定;通知列表和未读数沿用现有入参,由后端过滤当前资产的临期通知。
## Scope and confirmed decisions
用户于 2026-10-13 确认:不处理代理注册;手机号行为以当前对接说明为准;全部已读以新文档的 `POST` 为准。
用户确认:不处理代理注册;手机号行为以当前对接说明为准。全部已读以 2026-10-14 最新确认的 `PUT` 为准,不采用此前文档中的 POST。
后续用户补充确认:绑定手机号不会使 token 失效,绑定成功不得再跳转登录页。本次修订覆盖旧强制绑定后手动重登流程。
@@ -35,7 +35,7 @@
| `GET /api/c/v1/asset/info` | 接收一次性 `expiry_reminder`,区分手机号用途 | 原资产、套餐、实名、支付字段 |
| `GET /api/c/v1/notifications` | 回归当前资产临期通知的可见性 | 分页、排序、通知中心展示 |
| `GET /api/c/v1/notifications/unread-count` | 使用后端当前上下文计数 | 原请求参数、未读入口 |
| `POST /api/c/v1/notifications/read-all` | 从旧 PUT 切换为 POST | 用户主动点击“全部已读”的入口 |
| `PUT /api/c/v1/notifications/read-all` | 保持 PUT,撤销此前 POST 改动 | 用户主动点击“全部已读”的入口 |
明确排除:
@@ -57,7 +57,7 @@
- [update-phone-bind-association-flow](../update-phone-bind-association-flow/proposal.md):其“不同于客户主号则拒绝”“换号迁移全部资产关联”“用 bound_phone 判断资产关联”的旧约定,被本提案的 F1 约定替代;不覆盖其历史文件及完成标记。
- [update-post-bind-wechat-login-recheck](../update-post-bind-wechat-login-recheck/proposal.md):根据用户最新确认,替代其“强制绑定后清除 token 并要求手动重登”的约定;改为保留登录态直接进入首页,不改写历史提案。
- [update-july-h5-c-iteration](../update-july-h5-c-iteration/proposal.md):仅替代临期通知作为首页弹窗来源的约定,保留通知中心、其他通知和套餐到期信息展示。
- [add-personal-notifications](../add-personal-notifications/proposal.md):仅切换全部已读方法及遵循当前资产临期通知范围,不把单条已读的 PUT 一并改为 POST。
- [add-personal-notifications](../add-personal-notifications/proposal.md):保持单条/全部已读的 PUT,遵循当前资产临期通知范围及最新卡片样式。
- [add-h5-popup-candidate-flow](../add-h5-popup-candidate-flow/proposal.md):保留候选弹窗与单条已读链路;候选结束后再显示临期弹窗,不调用全部已读来关闭任何弹窗。
技术选择、字段依据及风险见 [design.md](design.md),执行及验收清单见 [tasks.md](tasks.md)。

View File

@@ -2,7 +2,7 @@
### Requirement: Expiry reminders SHALL use the optional asset-info response
H5 SHALL 仅以 `GET /api/c/v1/asset/info` 返回的可选 `expiry_reminder` 作为本次临期主动提醒来源,在首页展示居中、可关闭的临期弹窗,而不是内联横幅。剩余天数、到期时间、等级及等级名称 SHALL 使用 `remaining_days`、`expires_at`、`level`、`level_name`,SHALL NOT 用旧未读临期通知或客户端计算补发提醒。
H5 SHALL 仅以 `GET /api/c/v1/asset/info` 返回的可选 `expiry_reminder` 作为本次临期主动提醒来源,在首页展示居中、可关闭的临期弹窗,而不是内联横幅。剩余天数、到期时间及配色 SHALL 使用 `remaining_days`、`expires_at`、`level`;SHALL NOT 展示 level_name 等级标签,也 SHALL NOT 用旧未读临期通知或客户端计算补发提醒。
#### Scenario: Asset info includes a reminder
@@ -75,3 +75,18 @@ H5 SHALL 在风险换货/运营候选结束后展示待处理临期提醒,再
- **WHEN** 普通通知弹窗正在显示,随后收到 expiry_reminder
- **THEN** H5 SHALL 暂存临期提醒,等通知关闭后再展示
### Requirement: Expiry popup renewal SHALL reuse the homepage renewal flow
H5 SHALL 在临期弹窗提供“立即续费”,点击后先关闭提醒,再调用首页已有续费入口,使用当前套餐 ID、名称及价格。续费窗口准备/展示期间 SHALL 暂停其他通知弹窗,窗口关闭后再恢复;SHALL NOT 在提醒中另建下单或支付实现。
#### Scenario: User taps renew in an expiry popup
- **WHEN** 当前资产有可续费套餐,用户点击临期弹窗“立即续费”
- **THEN** 临期弹窗 SHALL 关闭,首页原有续费窗口 SHALL 打开
- **AND** 其他排队通知 SHALL 不与续费窗口重叠
#### Scenario: Current asset has no renewable package
- **WHEN** 用户点击“立即续费”,但当前套餐 ID 或名称无效
- **THEN** H5 SHALL 使用首页原有“当前资产暂无可续费套餐”提示,不创建订单

View File

@@ -15,25 +15,25 @@ H5 SHALL 保持 `GET /api/c/v1/notifications` 与 `GET /api/c/v1/notifications/u
- **WHEN** 当前认证资产由 A 切换为 B
- **THEN** H5 SHALL 刷新列表和未读数,防止 A 的延迟响应覆盖 B
### Requirement: Mark-all-read SHALL use POST and preserve other assets' expiry notifications
### Requirement: Mark-all-read SHALL use PUT and preserve other assets' expiry notifications
H5 SHALL 在用户主动点击通知中心“全部已读”时调用 `POST /api/c/v1/notifications/read-all`,SHALL NOT 使用或自动回退旧 PUT。其他资产的临期通知 SHALL 由后端保留未读;客户端成功后 SHALL 按服务端刷新结果更新当前视图,失败 SHALL 保留未读状态。单条已读 SHALL 继续使用 `PUT /api/c/v1/notifications/{id}/read`。
H5 SHALL 在用户主动点击通知中心“全部已读”时调用 `PUT /api/c/v1/notifications/read-all`,SHALL NOT 发送 POST 或用不同方法重试。其他资产的临期通知 SHALL 由后端保留未读;客户端成功后 SHALL 按服务端刷新结果更新当前视图,失败 SHALL 保留未读状态。单条已读 SHALL 继续使用 `PUT /api/c/v1/notifications/{id}/read`。
#### Scenario: User marks all notifications read on asset A
- **WHEN** 客户在 A 上主动执行全部已读
- **THEN** H5 SHALL 发送 POST 并对齐当前视图
- **THEN** H5 SHALL 发送 PUT 并对齐当前视图
- **AND** 资产 B 的临期通知 SHALL 保持未读
#### Scenario: Mark-all-read fails
- **WHEN** POST 全部已读请求失败
- **THEN** H5 SHALL 不提前清空未读计数或把本地项全部标成已读,也不改用 PUT 重试
- **WHEN** PUT 全部已读请求失败
- **THEN** H5 SHALL 不提前清空未读计数或把本地项全部标成已读,也不改用 POST 重试
#### Scenario: User reads one notification
- **WHEN** 用户执行单条已读操作
- **THEN** H5 SHALL 继续发送对应通知的 PUT 请求,不受 read-all 方法切换影响
- **THEN** H5 SHALL 继续发送对应通知的 PUT 请求
#### Scenario: Reminder or popup is displayed

View File

@@ -25,7 +25,7 @@
## 4. 当前资产通知与全部已读
- [x] 4.1 将 markAllRead 切换为 POST /api/c/v1/notifications/read-all,不回退 PUT;单条已读继续 PUT。
- [x] 4.1 按用户最新确认,将 markAllRead 恢复为 PUT /api/c/v1/notifications/read-all,不发送 POST;单条已读继续 PUT。
- [x] 4.2 保持列表/未读数入参不变,切换资产后刷新相关结果,禁止旧资产结果覆盖新资产。
- [x] 4.3 全部已读成功后按服务端结果对齐当前列表/计数,失败保留未读状态;不在任何提醒/弹窗展示链路调用 read-all。
@@ -36,12 +36,13 @@
- [x] 5.3 通过自动/模拟测试验证换号只更新客户、资产关联保持、归属失效及旧缓存/账号/资产隔离。
- [x] 5.4 通过自动/模拟测试验证字段缺省、0/3/4/7/8/15 天及等级、上海日期边界、重复进入和 A/B 上下文;浏览器检查 0 天弹窗及关闭行为。
- [x] 5.5 通过共享接收和首页脚本测试验证并发/其他调用方先返回提醒不丢失,以及旧首页弹窗只排除临期通知。
- [ ] 5.6 用同一客户的 A/B 两资产验证列表、未读数与 A 上 POST 全部已读;B 的临期通知仍保持未读,普通通知范围不被前端扩大过滤。
- [ ] 5.6 用同一客户的 A/B 两资产验证列表、未读数与 A 上 PUT 全部已读;B 的临期通知仍保持未读,普通通知范围不被前端扩大过滤。
- [ ] 5.7 验证单条已读仍 PUT、read-all 失败不提前清空、运营/风险换货弹窗和支付/实名/套餐展示不回归。
- [x] 5.8 执行 npm run build:h5、npm run build:h5:production,均通过;实施记录明确区分模拟验证与待真实联调场景。
- [x] 5.9 执行 openspec validate update-october-batch1-h5-integration --strict,校验通过;仅按实际完成结果更新本任务清单。
- [x] 5.10 新增并执行 npm run test:h5-integration,17 组自动/模拟测试全部通过,覆盖强制绑定、token 保留、弹窗排队、通知未读按钮及失败状态。
- [x] 5.10 新增并执行 npm run test:h5-integration,19 组自动/模拟测试通过,覆盖强制绑定、token 保留、弹窗排队、续费复用、PUT 全部已读及通知状态。
- [x] 5.11 使用本地模拟预览检查移动端居中临期弹窗、绑定表单预填/不同号输入及 1192 弹窗/禁用操作;不发送真实业务请求。
- [x] 5.12 去掉通知卡片左侧未读边框,改为标题右侧未读/已读小按钮;验证点击卡片成功后更新、失败不提前显示已读。
- [x] 5.13 移除临期弹窗等级文字标签,新增“立即续费”并复用首页入口;续费窗口打开时不推进其他通知。
5.6 的客户端 A/B 隔离逻辑、5.7 的单条 PUT 和失败不提前清空均已模拟测试通过;真实后端范围及完整支付/实名/候选弹窗回归未完成,不勾选。

View File

@@ -46,24 +46,28 @@
if (loading.value || (append && noMore.value)) return;
loading.value = true;
const requestedPage = page.value;
try {
const data = await assetApi.getPackageHistory(
userStore.state.identifier,
requestedPage,
pageSize
);
const groups = data.items;
const responsePage = Number.isInteger(data.page) && data.page > 0
? data.page
: requestedPage;
const responseSize = Number.isInteger(data.size) && data.size > 0
? data.size
: pageSize;
const responseTotal = Number.isFinite(data.total) && data.total >= 0
? data.total
: 0;
let groups;
do {
const requestedPage = page.value;
const data = await assetApi.getPackageHistory(
userStore.state.identifier,
requestedPage,
pageSize
);
groups = data.items;
const responsePage = Number.isInteger(data.page) && data.page > 0
? Math.max(data.page, requestedPage)
: requestedPage;
const responseSize = Number.isInteger(data.size) && data.size > 0
? data.size
: pageSize;
total.value = Number.isFinite(data.total) && data.total >= 0 ? data.total : 0;
// Total and pagination describe the unfiltered backend pages. Skip a
// page containing only invalidated records so later records stay reachable.
noMore.value = responsePage * responseSize >= total.value;
page.value = responsePage + 1;
} while (groups.length === 0 && !noMore.value);
if (append) {
packageList.value.push(...groups);
@@ -71,9 +75,6 @@
packageList.value = groups;
}
total.value = responseTotal;
noMore.value = responsePage * responseSize >= total.value;
page.value = responsePage + 1;
} catch (error) {
// The shared request layer handles the API's unified error response and authentication errors.
console.error('加载套餐历史失败', error);

View File

@@ -10,7 +10,7 @@
<!-- <VoiceCard v-if="!userInfo.isDevice" :voiceStats="voiceStats" :dateRangeText="dateRangeText"
@openDatePicker="openDateRangePicker" /> -->
<TrafficCard :identifier="userStore.state.identifier" />
<TrafficCard :assetInfo="assetStore.state.assetInfo" />
<!-- <WhitelistCard v-if="!userInfo.isDevice" :whitelistData="whitelistData" @refresh="refreshWhitelist"
@add="showAddWhitelistDialog" @showSms="showSmsCodeDialog" /> -->
@@ -98,14 +98,14 @@
<view class="bottom-spacer"></view>
<ExpiryReminderPopup v-if="visibleExpiryReminder" :reminder="visibleExpiryReminder"
@close="closeExpiryReminder" />
@close="closeExpiryReminder" @renew="renewFromExpiryReminder" />
<NotificationPopup :show="notificationPopupShow" :items="notificationItems"
:current="notificationPopupCurrent" @change="onNotificationChange" @close="closeNotificationPopup"
@renew="startHomepageRenewal" />
<RenewalPaymentPopup ref="renewalPopupRef" :identifier="userStore.state.identifier"
paymentRefreshTarget="home" @completed="loadAssetInfo" />
paymentRefreshTarget="home" @completed="loadAssetInfo" @visibility-change="onRenewalVisibilityChange" />
<PopupCandidate v-if='popupCandidateShow' page='home' :identifier='userStore.state.identifier'
@close='onPopupCandidateClose' />
@@ -162,6 +162,8 @@
const homeActive = ref(false);
const shownExpiryReminder = ref(null);
const awaitingHomeReminders = ref(false);
const renewalOpening = ref(false);
const renewalVisible = ref(false);
let notificationFallbackPending = false;
let notificationQueued = false;
let homeEntryId = 0;
@@ -172,18 +174,18 @@
});
const showPendingExpiryReminder = () => {
const entry = assetStore.state.expiryReminder;
if (!homeActive.value || awaitingHomeReminders.value || popupCandidateShow.value || notificationPopupShow.value ||
if (!homeActive.value || awaitingHomeReminders.value || renewalOpening.value || renewalVisible.value || popupCandidateShow.value || notificationPopupShow.value ||
visibleExpiryReminder.value || !entry || entry.shown || !isCurrentSession(entry) || entry.day !== getShanghaiDay()) return;
shownExpiryReminder.value = { ...entry };
assetStore.markExpiryReminderShown();
};
const closeExpiryReminder = () => {
const closeExpiryReminder = (resumeQueue = true) => {
shownExpiryReminder.value = null;
assetStore.dismissExpiryReminder();
advanceHomePopupQueue();
if (resumeQueue) advanceHomePopupQueue();
};
const advanceHomePopupQueue = () => {
if (!homeActive.value || awaitingHomeReminders.value || popupCandidateShow.value ||
if (!homeActive.value || awaitingHomeReminders.value || renewalOpening.value || renewalVisible.value || popupCandidateShow.value ||
visibleExpiryReminder.value || notificationPopupShow.value) return;
showPendingExpiryReminder();
if (visibleExpiryReminder.value) return;
@@ -203,6 +205,8 @@
let recoverShow = ref(false);
let logoutShow = ref(false);
let loading = ref(false);
let syncing = ref(false);
let assetRequestId = 0;
let userInfo = reactive({
isDevice: true,
@@ -282,7 +286,6 @@
let showSmsCode = ref(false);
let smsCodePhone = ref('');
let smsCode = ref('');
let indexEntryChecking = ref(false);
let notificationUnreadCount = ref(0);
let notificationPopupShow = ref(false);
let notificationItems = ref([]);
@@ -303,14 +306,16 @@
};
const loadAssetInfo = async () => {
const identifier = userStore.state.identifier;
const identifier = String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim();
if (!identifier) return;
if (userStore.state.identifier !== identifier) userStore.setIdentifier(identifier);
const context = getSessionContext();
const requestId = ++assetRequestId;
loading.value = true;
try {
const data = await assetApi.getInfo(identifier);
if (!isCurrentSession(context)) return null;
if (!isCurrentSession(context) || requestId !== assetRequestId) return null;
// 基本信息
userInfo.isDevice = data.asset_type === 'device';
@@ -335,7 +340,7 @@
effectiveRealnamePolicy.value = data.effective_realname_policy || 'none';
userStore.setRealNameStatus(data.real_name_status);
// 流量信息已由 TrafficCard 组件独立获取,这里不再处理
// 流量卡片消费同一次 asset/info 快照,支付和有效期变化后一起更新。
// 当前卡信息
if (data.cards && data.cards.length > 0) {
@@ -394,28 +399,33 @@
console.error('加载资产信息失败', e);
return null;
} finally {
loading.value = false;
if (requestId === assetRequestId) loading.value = false;
}
};
const handleIndexEntry = async () => {
if (userStore.state.loginPending) return;
const token = uni.getStorageSync('token');
if (!token) {
const identifier = String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim();
if (!token || !identifier) {
if (token && !identifier) {
userStore.clearUser();
uni.showToast({ title: '缺少资产标识,请重新输入或扫码登录', icon: 'none' });
}
uni.reLaunch({ url: '/pages/login/login' });
return;
}
if (userStore.state.identifier !== identifier) userStore.setIdentifier(identifier);
if (indexEntryChecking.value) return;
indexEntryChecking.value = true;
try {
await loadAssetInfo();
} finally {
indexEntryChecking.value = false;
}
await loadAssetInfo();
};
const startHomepageRenewal = () => {
const onRenewalVisibilityChange = (visible) => {
renewalVisible.value = visible;
if (!visible) advanceHomePopupQueue();
};
const startHomepageRenewal = async () => {
if (renewalOpening.value || renewalVisible.value) return;
const packageId = Number(deviceInfo.currentPackageId || 0);
const packageName = String(deviceInfo.packageName || '').trim();
if (!packageId || !packageName || packageName === '-') {
@@ -423,7 +433,19 @@
return;
}
renewalPopupRef.value?.open([packageId], [packageName], deviceInfo.renewalPrice);
renewalOpening.value = true;
try {
await renewalPopupRef.value?.open([packageId], [packageName], deviceInfo.renewalPrice);
} finally {
renewalOpening.value = false;
advanceHomePopupQueue();
}
};
const renewFromExpiryReminder = async () => {
if (!visibleExpiryReminder.value || renewalOpening.value || renewalVisible.value) return;
closeExpiryReminder(false);
await startHomepageRenewal();
advanceHomePopupQueue();
};
const modifyWifi = () => {
@@ -711,6 +733,7 @@
};
const onSync = async () => {
if (syncing.value) return;
const identifier = userStore.state.identifier;
if (!identifier) {
uni.showToast({
@@ -720,11 +743,13 @@
return;
}
const context = getSessionContext();
uni.showModal({
title: '确认同步',
content: '确定要同步运营商数据吗?',
content: '确定要同步运营商数据吗?受理不代表同步或停复机已执行完成,结果以稍后读取的实际状态为准。',
success: (res) => {
if (!res.confirm) return;
if (!res.confirm || syncing.value || !isCurrentSession(context)) return;
syncing.value = true;
uni.showLoading({
title: '同步中...',
mask: true
@@ -732,17 +757,19 @@
assetApi.refresh(identifier).then((data) => {
uni.hideLoading();
if (!isCurrentSession(context)) return;
if (data.accepted) {
if (data?.accepted === true || data?.accepted === 1) {
const refreshTypeText = data.refresh_type === 'device' ? '设备' : '卡';
uni.showToast({
title: `${refreshTypeText}数据同步成功`,
icon: 'success',
duration: 2000
title: `${refreshTypeText}同步请求已受理,请稍后查看状态`,
icon: 'none',
duration: 3000
});
loadAssetInfo();
setTimeout(() => {
loadAssetInfo();
if (homeActive.value && isCurrentSession(context)) loadAssetInfo();
}, 2000);
} else {
uni.showToast({
@@ -752,6 +779,7 @@
}
}).catch((e) => {
uni.hideLoading();
if (!isCurrentSession(context)) return;
console.error('同步数据失败', e);
if (e.msg && e.msg.includes('冷却')) {
@@ -766,7 +794,7 @@
icon: 'none'
});
}
});
}).finally(() => { syncing.value = false; });
}
});
};
@@ -982,14 +1010,17 @@
awaitingHomeReminders.value = true;
notificationFallbackPending = false;
notificationQueued = false;
if (!getSessionContext().token) {
if (userStore.state.loginPending) {
awaitingHomeReminders.value = false;
return;
}
if (!getSessionContext().token || !String(userStore.state.identifier || uni.getStorageSync('identifier') || '').trim()) {
awaitingHomeReminders.value = false;
handleIndexEntry();
return;
}
if (consumePendingPaymentRefresh(PAYMENT_REFRESH_TARGETS.HOME)) {
loadAssetInfo();
}
// 每次返回首页都重新读取实际状态,支付返回不再重复发起两次请求。
consumePendingPaymentRefresh(PAYMENT_REFRESH_TARGETS.HOME);
loadNotificationUnreadCount();
runPopupCandidate();
await handleIndexEntry();
@@ -999,6 +1030,7 @@
});
onHide(() => {
homeEntryId++;
assetRequestId++;
homeActive.value = false;
shownExpiryReminder.value = null;
notificationPopupShow.value = false;

View File

@@ -71,7 +71,14 @@
import { useUserStore } from '@/store/index.js';
import { initWxConfig, wxScan, isInWechat } from '@/utils/wxsdk.js';
const WECHAT_LOGIN_CONTEXT_KEY = 'wechatLoginContext';
const userStore = useUserStore();
// Close the asset-request gate synchronously, before cached homepage
// components can react to the callback's old token or saved identifier.
if (new URLSearchParams(window.location.search).get('code') && sessionStorage.getItem('assetToken')) {
userStore.setLoginPending(true);
}
const identifier = ref(uni.getStorageSync('identifier') || '');
const loading = ref(false);
const agreed = ref(true);
@@ -82,6 +89,24 @@
const resetLoadingState = () => {
loading.value = false;
};
const initializeLoginSdk = async () => {
if (isInWechat()) await initWxConfig();
};
const resumeStoredSession = async (assetIdentifier) => {
userStore.setLoginPending(true);
loading.value = true;
try {
userStore.setIdentifier(assetIdentifier);
await initializeLoginSdk();
sessionStorage.removeItem('assetToken');
sessionStorage.removeItem(WECHAT_LOGIN_CONTEXT_KEY);
userStore.setLoginPending(false);
uni.reLaunch({ url: '/pages/index/index' });
} catch (e) {
uni.showToast({ title: e?.msg || e?.message || '微信初始化失败,请重新登录', icon: 'none' });
loading.value = false;
}
};
onMounted(async () => {
// Remove the obsolete post-bind re-login notice from older client builds.
@@ -89,13 +114,19 @@
const urlIdentifier = getPathDeviceId();
const token = uni.getStorageSync('token');
const storedIdentifier = uni.getStorageSync('identifier') || '';
// Complete OAuth first. An existing token or the callback's identifier
// must not bypass the callback or start another authorization round.
if (getCode() && sessionStorage.getItem('assetToken')) {
await handleWechatCallback();
return;
}
// 从外部链接进入时,链接中的资产标识优先于本地登录态。
// 只有相同资产才能复用已登录的会话,避免将上一台设备的数据带到新链接中。
if (urlIdentifier) {
identifier.value = urlIdentifier;
if (token && urlIdentifier === storedIdentifier) {
uni.reLaunch({ url: '/pages/index/index' });
await resumeStoredSession(urlIdentifier);
return;
}
@@ -103,16 +134,15 @@
userStore.clearUser();
}
doLogin();
await doLogin();
return;
}
if (token) {
uni.reLaunch({ url: '/pages/index/index' });
if (token && storedIdentifier.trim()) {
await resumeStoredSession(storedIdentifier.trim());
return;
}
handleWechatCallback();
if (token) userStore.clearUser();
// 初始化微信 SDK (仅在微信浏览器内执行)
// #ifdef H5
@@ -163,10 +193,13 @@
return wechatAppId.value;
};
const redirectToWxAuth = async (assetToken) => {
const redirectToWxAuth = async (assetToken, assetIdentifier) => {
sessionStorage.setItem('assetToken', assetToken);
sessionStorage.setItem(WECHAT_LOGIN_CONTEXT_KEY, JSON.stringify({ assetToken, identifier: assetIdentifier }));
const appId = await getWechatAppId();
const redirectUri = encodeURIComponent(window.location.origin + window.location.pathname);
const callbackUrl = new URL(window.location.pathname, window.location.origin);
callbackUrl.searchParams.set('identifier', assetIdentifier);
const redirectUri = encodeURIComponent(callbackUrl.toString());
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=wechat_auth#wechat_redirect`;
window.location.href = url;
};
@@ -290,19 +323,23 @@
const doLogin = async () => {
loading.value = true;
userStore.setLoginPending(true);
// 丢弃上一轮未完成授权留下的临时凭证,避免校验失败时继续复用。
if (typeof sessionStorage !== 'undefined') {
sessionStorage.removeItem('assetToken');
sessionStorage.removeItem(WECHAT_LOGIN_CONTEXT_KEY);
}
try {
const enteredIdentifier = identifier.value;
const enteredIdentifier = String(identifier.value || '').trim();
if (!enteredIdentifier) throw { msg: '请输入有效的资产标识' };
const { verifyData, verifiedIdentifier } = await verifyAssetWithIccidRetry(enteredIdentifier);
userStore.setAssetToken(verifyData.asset_token);
userStore.setIdentifier(verifiedIdentifier);
await redirectToWxAuth(verifyData.asset_token);
await redirectToWxAuth(verifyData.asset_token, verifiedIdentifier);
} catch (e) {
userStore.setLoginPending(false);
console.error('登录失败', e);
uni.showToast({
title: e?.msg || e?.message || '资产校验失败,请稍后重试',
@@ -318,15 +355,38 @@
const assetToken = sessionStorage.getItem('assetToken');
if (!code || !assetToken) return;
userStore.setLoginPending(true);
let loginContext = null;
try {
loginContext = JSON.parse(sessionStorage.getItem(WECHAT_LOGIN_CONTEXT_KEY) || 'null');
} catch (e) {
// Old clients may only have the legacy assetToken and saved identifier.
}
const contextIdentifier = loginContext?.assetToken === assetToken && typeof loginContext.identifier === 'string'
? loginContext.identifier.trim() : '';
const loginIdentifier = contextIdentifier || getPathDeviceId() ||
String(uni.getStorageSync('identifier') || userStore.state.identifier || identifier.value || '').trim();
if (!loginIdentifier) {
clearCode();
sessionStorage.removeItem('assetToken');
sessionStorage.removeItem(WECHAT_LOGIN_CONTEXT_KEY);
userStore.clearUser();
uni.showToast({ title: '缺少资产标识,请重新输入或扫码登录', icon: 'none' });
loading.value = false;
return;
}
loading.value = true;
clearCode();
try {
const loginData = await authApi.wechatLogin(assetToken, code);
// Restore the verified identifier before publishing the login state or
// mounting homepage components that immediately request asset/info.
userStore.setIdentifier(loginIdentifier);
userStore.setToken(loginData.token);
userStore.setLoginPhoneState(loginData);
uni.setStorageSync('identifier', userStore.state.identifier);
identifier.value = loginIdentifier;
// #ifdef H5
if (loginData.user_info) {
@@ -337,6 +397,13 @@
}
// #endif
// Keep the gate closed while JSSDK config/ready is still pending.
// Homepage and bind-page asset/info requests only start afterwards.
await initializeLoginSdk();
sessionStorage.removeItem('assetToken');
sessionStorage.removeItem(WECHAT_LOGIN_CONTEXT_KEY);
userStore.setLoginPending(false);
if (userStore.state.needBindPhone === true) {
uni.redirectTo({ url: '/pages/bind/bind?fromLogin=true' });
} else {

View File

@@ -67,14 +67,14 @@
</view>
<RenewalPaymentPopup ref="renewalPopupRef" :identifier="userStore.state.identifier"
paymentRefreshTarget="order-list" @completed="resetOrderListAndLoad" />
paymentRefreshTarget="order-list" @completed="refreshOrderState" />
</view>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ref, reactive, computed } from 'vue';
import { onReachBottom, onShow } from '@dcloudio/uni-app';
import { orderApi } from '@/api/index.js';
import { assetApi, orderApi } from '@/api/index.js';
import RenewalPaymentPopup from '@/components/RenewalPaymentPopup.vue';
import { useUserStore } from '@/store/index.js';
import {
@@ -121,17 +121,25 @@
loadOrderList();
};
const refreshOrderState = () => {
resetOrderListAndLoad();
// 订单支付、退款及套餐生效后,读取后端实际轮询状态,不推测已恢复。
return assetApi.getInfo(userStore.state.identifier).catch(error => {
console.error('刷新订单关联资产状态失败', error);
});
};
const scheduleOrderStatusRefresh = () => {
uni.showToast({
title: '正在同步支付状态',
icon: 'none'
});
resetOrderListAndLoad();
refreshOrderState();
setTimeout(() => {
resetOrderListAndLoad();
}, 1500);
setTimeout(() => {
resetOrderListAndLoad();
refreshOrderState();
}, 3000);
};
@@ -232,16 +240,13 @@
onShow(() => {
if (!consumePendingPaymentRefresh(PAYMENT_REFRESH_TARGETS.ORDER_LIST)) {
refreshOrderState();
return;
}
scheduleOrderStatusRefresh();
});
onMounted(() => {
loadOrderList();
});
onReachBottom(() => {
loadMore();
});

View File

@@ -102,7 +102,7 @@
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ref, reactive, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { assetApi, isAssetRealNameCompleted, orderApi, walletApi } from '@/api/index.js';
import { useUserStore } from '@/store/index.js';
@@ -121,6 +121,7 @@
import { getPaymentErrorMessage, isUnknownPaymentResult } from '@/utils/payment-attempt.js';
import { formatMoney } from '@/utils/display.js';
import { getDefaultPaymentMethod, getPaymentMethodOptions, normalizePaymentMethods } from '@/utils/payment-methods.js';
import { getSessionContext, isCurrentSession } from '@/utils/session-context.js';
const userStore = useUserStore();
const popupCandidateShow = ref(false);
@@ -147,7 +148,7 @@
{ label: '正式套餐', value: 'formal' },
{ label: '加油包', value: 'addon' }
];
let assetTypePromise = null;
let assetRequestId = 0;
let packageRequestId = 0;
const paymentMethodOptions = computed(() => getPaymentMethodOptions(allowedPaymentMethods.value));
@@ -177,22 +178,19 @@
const loadAssetType = async () => {
if (!userStore.state.identifier) return;
if (assetTypePromise) return assetTypePromise;
assetTypePromise = assetApi.getInfo(userStore.state.identifier)
.then((data) => {
assetInfo.value = data;
allowedPaymentMethods.value = normalizePaymentMethods(data.allowed_payment_methods);
normalizePaymentMethod();
})
.catch((error) => {
console.error('加载资产类型失败', error);
})
.finally(() => {
assetTypePromise = null;
});
return assetTypePromise;
const context = getSessionContext();
const requestId = ++assetRequestId;
try {
const data = await assetApi.getInfo(userStore.state.identifier);
if (!isCurrentSession(context) || requestId !== assetRequestId) return null;
assetInfo.value = data;
allowedPaymentMethods.value = normalizePaymentMethods(data.allowed_payment_methods);
normalizePaymentMethod();
return data;
} catch (error) {
console.error('加载资产类型失败', error);
return null;
}
};
const loadPackages = async (packageType = activePackageType.value) => {
@@ -261,12 +259,21 @@
};
const syncPackagePageState = async () => {
await loadAssetType();
if (!await loadAssetType()) return;
await Promise.all([loadPackages(), loadWalletBalance()]);
};
const refreshAfterPayment = async () => {
const context = getSessionContext();
await syncPackagePageState();
// 充值自动购包可能稍后生效,再确认一次,仍以实际响应为准。
setTimeout(() => {
if (isCurrentSession(context)) syncPackagePageState();
}, 1500);
};
const buyPackage = async (item) => {
await loadAssetType();
if (!await loadAssetType()) return;
if (assetInfo.value.effective_realname_policy === 'before_order' &&
assetInfo.value.realname_required && !isAssetRealNameCompleted(assetInfo.value)) {
uni.showModal({
@@ -309,9 +316,7 @@
} else {
showPaymentToast(true, isForceRecharge ? '充值成功,套餐将自动购买' : '支付成功');
}
setTimeout(() => {
loadWalletBalance();
}, 1500);
await refreshAfterPayment();
} catch (error) {
handlePaymentError(error);
}
@@ -464,9 +469,7 @@
} catch (error) {
showPaymentToast(false, '支付结果确认失败,请稍后查看订单');
}
setTimeout(() => {
loadWalletBalance();
}, 1500);
await refreshAfterPayment();
return;
}
@@ -505,11 +508,12 @@
};
onShow(() => {
// 后台也可能修改套餐有效期,返回页面时始终重读,不只处理支付宝返回。
syncPackagePageState();
if (!consumePendingPaymentRefresh(PAYMENT_REFRESH_TARGETS.PACKAGE_ORDER)) {
return;
}
syncPackagePageState();
uni.showModal({
title: '支付状态确认',
content: '已返回页面,支付结果以订单状态为准。是否前往我的订单查看最新状态?',
@@ -539,9 +543,6 @@
popupCandidateShow.value = true;
});
onMounted(() => {
syncPackagePageState();
});
</script>
<style lang="scss" scoped>

View File

@@ -12,6 +12,8 @@ const emptyPhoneState = () => ({
const savedPhoneState = uni.getStorageSync(PHONE_STATE_KEY);
const token = uni.getStorageSync('token') || '';
const identifier = uni.getStorageSync('identifier') || '';
const isOAuthCallback = typeof window !== 'undefined' && typeof sessionStorage !== 'undefined' &&
!!new URLSearchParams(window.location.search).get('code') && !!sessionStorage.getItem('assetToken');
const phoneState = savedPhoneState?.token === token && savedPhoneState?.identifier === identifier && token
? {
customerPhone: typeof savedPhoneState.customerPhone === 'string' ? savedPhoneState.customerPhone : null,
@@ -25,6 +27,7 @@ const state = reactive({
token,
assetToken: '',
identifier,
loginPending: isOAuthCallback,
...phoneState,
phoneRevision: 0,
isDevice: false,
@@ -36,6 +39,7 @@ const state = reactive({
});
export const useUserStore = () => {
const setLoginPending = (pending) => { state.loginPending = pending === true; };
const persistPhoneState = () => {
uni.setStorageSync(PHONE_STATE_KEY, {
token: state.token, identifier: state.identifier,
@@ -111,6 +115,7 @@ export const useUserStore = () => {
const clearUser = () => {
resetContext();
state.token = '';
state.loginPending = false;
state.assetToken = '';
state.identifier = '';
state.isDevice = false;
@@ -124,6 +129,7 @@ export const useUserStore = () => {
return {
state,
setToken,
setLoginPending,
setAssetToken,
setIdentifier,
setIsDevice,

View File

@@ -29,6 +29,15 @@ function runtime(initial = {}) {
const timers = [];
const sessionStorage = new Map();
const api = {};
const props = vue.reactive({});
const payment = {
consumePendingPaymentRefresh: () => false,
PAYMENT_REFRESH_TARGETS: { HOME: 'home', PACKAGE_ORDER: 'package-order', ORDER_LIST: 'order-list', MY_WALLET: 'my-wallet' },
handlePaymentError() {}, isValidAlipayPaymentLink: () => false, isValidWechatPayConfig: () => false,
markPendingPaymentRefresh() {}, openAlipayPayment: async () => {}, showPaymentToast() {}, wechatH5Pay: async () => {}
};
let inWechat = false;
let sdkInit = async () => {};
let options = {};
const uni = {
getStorageSync: key => storage.get(key) ?? '',
@@ -38,20 +47,22 @@ function runtime(initial = {}) {
request: request => { requests.push(request); },
showToast: value => calls.push({ kind: 'toast', ...value }),
showModal: value => calls.push({ kind: 'modal', ...value }),
showLoading: value => calls.push({ kind: 'loading', ...value }),
hideLoading: () => calls.push({ kind: 'hideLoading' }),
reLaunch: value => calls.push({ kind: 'reLaunch', ...value }),
redirectTo: value => calls.push({ kind: 'redirectTo', ...value }),
navigateTo: value => calls.push({ kind: 'navigateTo', ...value }),
navigateBack: () => calls.push({ kind: 'navigateBack' })
};
const context = vm.createContext({
uni, Intl, Date, URLSearchParams,
uni, Intl, Date, URLSearchParams, URL,
console: { log() {}, error() {}, warn() {} },
setTimeout: callback => { timers.push(callback); return timers.length; },
setInterval: () => 1, clearInterval() {},
getCurrentPages: () => [{ options }],
sessionStorage: { getItem: key => sessionStorage.get(key) || '', removeItem: key => sessionStorage.delete(key), setItem: (key, value) => sessionStorage.set(key, value) },
window: { location: { search: '', pathname: '/', hash: '' }, history: { replaceState() {} } },
defineProps: () => ({}), defineEmits: () => () => {}
window: { location: { search: '', pathname: '/', hash: '', origin: 'https://example.invalid' }, history: { replaceState() {} } },
defineProps: () => props, defineEmits: () => () => {}, defineExpose() {}
});
const cache = new Map();
const synthetic = (key, values) => {
@@ -79,16 +90,17 @@ function runtime(initial = {}) {
onMounted: cb => mounted.push(cb), onUnmounted: cb => unmounted.push(cb)
});
if (specifier === '@dcloudio/uni-app') return synthetic('uni-app', {
onShow: cb => shown.push(cb), onHide: cb => hidden.push(cb), onUnload: cb => unmounted.push(cb)
onShow: cb => shown.push(cb), onHide: cb => hidden.push(cb), onUnload: cb => unmounted.push(cb),
onLoad() {}, onReachBottom() {}
});
if (specifier === '@/api/index.js') return synthetic('api-index', {
...api, deviceApi: {}, hasActiveOrPendingPackage: async () => true
});
if (specifier === '@/utils/payment.js') return synthetic('payment', {
consumePendingPaymentRefresh: () => false, PAYMENT_REFRESH_TARGETS: { HOME: 'home' }
...payment, consumePendingPaymentRefresh: (...args) => payment.consumePendingPaymentRefresh(...args)
});
if (specifier === '@/utils/wxsdk.js') return synthetic('wxsdk', {
initWxConfig: async () => {}, wxScan: async () => {}, isInWechat: () => false
initWxConfig: () => sdkInit(), wxScan: async () => {}, isInWechat: () => inWechat
});
if (specifier === './env.js') return synthetic('env', { BASE_URL: 'https://example.invalid' });
if (specifier.endsWith('.vue')) return synthetic(specifier, { default: {} });
@@ -104,8 +116,9 @@ function runtime(initial = {}) {
const reply = (request, data = {}, code = 0, statusCode = 200, msg = 'success') => {
request.success({ statusCode, data: { code, msg, data } });
};
return { storage, sessionStorage, context, calls, requests, mounted, shown, hidden, unmounted, timers, api, load, reply,
setOptions: value => { options = value; }, tick: () => vue.nextTick() };
return { storage, sessionStorage, context, calls, requests, mounted, shown, hidden, unmounted, timers, api, props, payment, load, reply,
setOptions: value => { options = value; }, tick: () => vue.nextTick(),
setWechatSdk: init => { inWechat = true; sdkInit = init; } };
}
test('phone binding modes and success updates distinguish all four cases', async () => {
@@ -124,6 +137,70 @@ test('phone binding modes and success updates distinguish all four cases', async
assert.equal(success({}, '13900000002', 'customer-asset').assetPhoneBound, true);
});
test('package history hides numeric/string status 4 recursively without changing pagination', async () => {
const r = runtime();
const { normalizeAssetPackageHistory } = await r.load('api/modules/asset.js');
const input = {
page: 1, size: 10, total: 30,
items: [
{ package_usage_id: 1, status: 4 },
{ package_usage_id: 2, status: '4' },
{ package_usage_id: 3, status: 1, expand_by_default: 1, children: [
{ package_usage_id: 4, status: 4 },
{ package_usage_id: 5, status: 2, children: [
{ package_usage_id: 6, status: '4' }, { package_usage_id: 7, status: 0 }
] }
] },
{ package_usage_id: 8, status: 3 }
]
};
const result = normalizeAssetPackageHistory(input);
assert.deepEqual(plain(result.items).map(item => item.package_usage_id), [3, 8]);
assert.deepEqual(plain(result.items[0].children).map(item => item.package_usage_id), [5]);
assert.deepEqual(plain(result.items[0].children[0].children).map(item => item.package_usage_id), [7]);
assert.equal(result.items[0].expand_by_default, true);
assert.equal(result.total, 30);
assert.equal(result.page, 1);
assert.equal(input.items.length, 4);
assert.equal(input.items[2].children.length, 2);
});
test('package-history page skips all-invalid pages and keeps subsequent pages reachable', async () => {
const r = runtime();
const { normalizeAssetPackageHistory } = await r.load('api/modules/asset.js');
const requestedPages = [];
r.api.assetApi = { getPackageHistory: async (identifier, page) => {
assert.equal(identifier, 'A'); requestedPages.push(page);
return normalizeAssetPackageHistory({ page, size: 10, total: 40,
items: [{ package_usage_id: page, status: page === 2 || page === 4 ? 1 : 4 }] });
} };
const page = await r.load('pages/asset-package-history/asset-package-history.vue', ['loadPackageList', 'packageList', 'noMore']);
await page.loadPackageList();
assert.deepEqual(requestedPages, [1, 2]);
assert.deepEqual(plain(page.packageList.value).map(item => item.package_usage_id), [2]);
assert.equal(page.noMore.value, false);
await page.loadPackageList(true);
assert.deepEqual(requestedPages, [1, 2, 3, 4]);
assert.deepEqual(plain(page.packageList.value).map(item => item.package_usage_id), [2, 4]);
assert.equal(page.noMore.value, true);
});
test('package history with only invalidated records ends with an empty state', async () => {
const r = runtime();
const { normalizeAssetPackageHistory } = await r.load('api/modules/asset.js');
const requestedPages = [];
r.api.assetApi = { getPackageHistory: async (identifier, page) => {
requestedPages.push(page);
return normalizeAssetPackageHistory({ page, size: 10, total: 20, items: [{ status: 4 }] });
} };
const page = await r.load('pages/asset-package-history/asset-package-history.vue', ['loadPackageList', 'packageList', 'noMore', 'historyLoaded']);
await page.loadPackageList();
assert.deepEqual(requestedPages, [1, 2]);
assert.equal(page.packageList.value.length, 0);
assert.equal(page.noMore.value, true);
assert.equal(page.historyLoaded.value, true);
});
test('login facts are persisted per token/asset; customer phone changes never migrate assets', async () => {
const r = runtime({ phoneBindStatus: { A: { bound: true, phone: '13900000002' } } });
const user = (await r.load('store/user.js')).useUserStore();
@@ -167,6 +244,152 @@ test('login routing honors server guidance even with a phone bound to someone el
}
});
test('OAuth round trip carries the verified identifier without relying on localStorage', async () => {
const r = runtime({ token: '', identifier: '' });
r.api.authApi = { verifyAsset: async id => { assert.equal(id, 'B'); return { asset_token: 'asset-token-B' }; } };
r.api.wechatApi = { getAppId: async () => ({ app_id: 'mock-app-id' }) };
const page = await r.load('pages/login/login.vue', ['identifier', 'doLogin']);
page.identifier.value = ' B ';
await page.doLogin();
assert.equal(r.storage.get('identifier'), 'B');
assert.deepEqual(JSON.parse(r.sessionStorage.get('wechatLoginContext')), { assetToken: 'asset-token-B', identifier: 'B' });
const authUrl = new URL(r.context.window.location.href);
assert.equal(new URL(authUrl.searchParams.get('redirect_uri')).searchParams.get('identifier'), 'B');
});
test('OAuth callback restores its own asset identifier before entering home', async () => {
const r = runtime({ token: 'old-token', identifier: 'old-asset' });
r.sessionStorage.set('assetToken', 'asset-token-B');
r.sessionStorage.set('wechatLoginContext', JSON.stringify({ assetToken: 'asset-token-B', identifier: 'B' }));
r.context.window.location.search = '?code=mock-code&identifier=B';
r.api.authApi = { wechatLogin: async () => ({ token: 'new-token', need_bind_phone: false }) };
r.api.wechatApi = {};
await r.load('pages/login/login.vue');
await r.mounted[0]();
const user = (await r.load('store/user.js')).useUserStore();
assert.equal(user.state.identifier, 'B');
assert.equal(r.storage.get('identifier'), 'B');
assert.equal(user.state.token, 'new-token');
assert.equal(r.calls.find(call => call.kind === 'redirectTo').url, '/pages/index/index');
assert.equal(r.sessionStorage.has('assetToken'), false);
const { assetApi } = await r.load('api/modules/asset.js');
const info = assetApi.getInfo(user.state.identifier);
assert.deepEqual(plain(r.requests[0].data), { identifier: 'B' });
r.reply(r.requests[0], { identifier: 'B' }); await info;
});
test('callback can recover a verified identifier from session even if localStorage is empty', async () => {
const r = runtime({ token: '', identifier: '' });
r.sessionStorage.set('assetToken', 'asset-token-B');
r.sessionStorage.set('wechatLoginContext', JSON.stringify({ assetToken: 'asset-token-B', identifier: 'B' }));
r.context.window.location.search = '?code=mock-code';
r.api.authApi = { wechatLogin: async () => ({ token: 'new-token', need_bind_phone: true }) };
r.api.wechatApi = {};
const page = await r.load('pages/login/login.vue', ['handleWechatCallback']);
await page.handleWechatCallback();
assert.equal(r.storage.get('identifier'), 'B');
assert.equal(r.calls.find(call => call.kind === 'redirectTo').url, '/pages/bind/bind?fromLogin=true');
});
test('callback falls back to URL/saved identifiers, but never enters home without one', async () => {
for (const source of ['url', 'storage', 'missing']) {
const r = runtime({ token: '', identifier: '' });
r.sessionStorage.set('assetToken', 'mock-asset-token');
r.context.window.location.search = source === 'url' ? '?code=mock-code&identifier=B' : '?code=mock-code';
if (source === 'storage') r.storage.set('identifier', 'B');
let logins = 0;
r.api.wechatApi = {};
r.api.authApi = { wechatLogin: async () => { logins++; return { token: 'new-token', need_bind_phone: false }; } };
const page = await r.load('pages/login/login.vue', ['handleWechatCallback']);
await page.handleWechatCallback();
if (source === 'missing') {
assert.equal(logins, 0);
assert.equal(r.calls.some(call => call.kind === 'redirectTo'), false);
assert.match(r.calls.find(call => call.kind === 'toast').title, /缺少资产标识/);
} else {
assert.equal(r.storage.get('identifier'), 'B');
assert.equal(logins, 1);
}
}
});
test('asset-info API rejects empty identifiers without a network request', async () => {
const r = runtime();
const { assetApi } = await r.load('api/modules/asset.js');
for (const value of ['', ' ', undefined, null]) {
await assert.rejects(assetApi.getInfo(value));
}
assert.equal(r.requests.length, 0);
const request = assetApi.getInfo(' A ');
assert.deepEqual(plain(r.requests[0].data), { identifier: 'A' });
r.reply(r.requests[0], {}); await request;
});
test('asset info waits until both wechat-login and JSSDK readiness complete', async () => {
const r = runtime({ token: 'old-token', identifier: 'old-asset' });
r.sessionStorage.set('assetToken', 'asset-token-B');
r.sessionStorage.set('wechatLoginContext', JSON.stringify({ assetToken: 'asset-token-B', identifier: 'B' }));
r.context.window.location.search = '?code=mock-code';
const login = deferred();
const sdk = deferred();
const events = [];
r.api.authApi = { wechatLogin: () => { events.push('login'); return login.promise; } };
r.api.wechatApi = {};
r.setWechatSdk(() => { events.push('jssdk'); return sdk.promise; });
await r.load('pages/login/login.vue');
const { assetApi } = await r.load('api/modules/asset.js');
const pending = r.mounted[0]();
await assert.rejects(assetApi.getInfo('old-asset'));
assert.equal(r.requests.length, 0);
assert.deepEqual(events, ['login']);
login.resolve({ token: 'new-token', need_bind_phone: false });
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(events, ['login', 'jssdk']);
assert.equal(r.calls.some(call => call.kind === 'redirectTo'), false);
await assert.rejects(assetApi.getInfo('B'));
assert.equal(r.requests.length, 0);
sdk.resolve(); await pending;
const user = (await r.load('store/user.js')).useUserStore();
assert.equal(user.state.loginPending, false);
assert.equal(r.calls.find(call => call.kind === 'redirectTo').url, '/pages/index/index');
const info = assetApi.getInfo(user.state.identifier);
assert.deepEqual(plain(r.requests[0].data), { identifier: 'B' });
assert.equal(r.requests[0].header.Authorization, 'Bearer new-token');
r.reply(r.requests[0], {}); await info;
});
test('JSSDK failure does not enter the homepage or release asset requests', async () => {
const r = runtime({ token: '', identifier: 'A' });
r.sessionStorage.set('assetToken', 'asset-token-A');
r.context.window.location.search = '?code=mock-code';
r.api.authApi = { wechatLogin: async () => ({ token: 'new-token', need_bind_phone: false }) };
r.api.wechatApi = {};
r.setWechatSdk(async () => { throw new Error('JSSDK failed'); });
const page = await r.load('pages/login/login.vue', ['handleWechatCallback']);
await page.handleWechatCallback();
assert.equal(r.calls.some(call => call.kind === 'redirectTo'), false);
const { assetApi } = await r.load('api/modules/asset.js');
await assert.rejects(assetApi.getInfo('A'));
assert.equal(r.requests.length, 0);
});
test('returning login session initializes JSSDK before re-entering homepage', async () => {
const r = runtime();
r.api.authApi = {}; r.api.wechatApi = {};
const sdk = deferred();
r.setWechatSdk(() => sdk.promise);
await r.load('pages/login/login.vue');
const pending = r.mounted[0]();
const { assetApi } = await r.load('api/modules/asset.js');
await assert.rejects(assetApi.getInfo('A'));
assert.equal(r.calls.some(call => call.kind === 'reLaunch'), false);
sdk.resolve(); await pending;
assert.equal(r.calls.find(call => call.kind === 'reLaunch').url, '/pages/index/index');
const info = assetApi.getInfo('A');
assert.equal(r.requests.length, 1);
r.reply(r.requests[0], {}); await info;
});
test('expiry boundaries and Shanghai rendering preserve server values, including zero', async () => {
const r = runtime();
const { normalizeExpiryReminder, getShanghaiDay, formatShanghaiExpiry } = await r.load('utils/expiry-reminder.js');
@@ -225,11 +448,11 @@ test('shared asset-info receiver keeps a child-first reminder and rejects stale
assert.equal(asset.state.expiryReminder.identifier, 'B');
});
test('notification APIs use POST read-all and retain PUT single-read without new parameters', async () => {
test('notification APIs use PUT for read-all and single-read without new parameters', async () => {
const r = runtime();
const { notificationApi } = await r.load('api/modules/notification.js');
const all = notificationApi.markAllRead();
assert.equal(r.requests[0].method, 'POST');
assert.equal(r.requests[0].method, 'PUT');
assert.match(r.requests[0].url, /\/notifications\/read-all$/);
r.reply(r.requests[0]); await all;
const one = notificationApi.markRead(12);
@@ -398,6 +621,38 @@ test('expiry popup waits for an open notification and closing it does not mark e
assert.equal(page.visibleExpiryReminder.value, null);
});
test('expiry renewal reuses homepage renewal and keeps queued notifications behind payment', async () => {
const r = runtime();
r.api.assetApi = { getInfo: async () => ({ identifier: 'A', current_package_id: 12, current_package: '月套餐', renewal_price: 990 }) };
r.api.notificationApi = {
getList: async () => ({ items: [{ id: 2, category: 'approval', is_read: false }] }),
getUnreadCount: async () => ({ count: 1 }), markRead: async () => {}
};
const asset = (await r.load('store/asset.js')).useAssetStore();
asset.receiveExpiryReminder({ token: 'session-A', identifier: 'A' }, { remaining_days: 0, level: 'red' });
const page = await r.load('pages/index/index.vue', ['visibleExpiryReminder', 'notificationPopupShow', 'onPopupCandidateClose', 'loadUnreadNotifications', 'renewalPopupRef', 'onRenewalVisibilityChange', 'renewFromExpiryReminder', 'startHomepageRenewal']);
await r.shown[0](); page.onPopupCandidateClose('empty');
await page.loadUnreadNotifications();
assert.equal(page.visibleExpiryReminder.value.remaining_days, 0);
const opens = [];
page.renewalPopupRef.value = { open: async (...args) => {
assert.equal(page.visibleExpiryReminder.value, null);
assert.equal(page.notificationPopupShow.value, false);
opens.push(plain(args));
page.onRenewalVisibilityChange(true);
} };
await page.renewFromExpiryReminder();
assert.deepEqual(opens, [[[12], ['月套餐'], 990]]);
assert.equal(page.notificationPopupShow.value, false);
page.onRenewalVisibilityChange(false);
assert.equal(page.notificationPopupShow.value, true);
page.notificationPopupShow.value = false;
await page.startHomepageRenewal();
assert.deepEqual(opens[1], opens[0]);
const source = readFileSync(resolve(root, 'components/ExpiryReminderPopup.vue'), 'utf8');
assert.match(source, /@tap="\$emit\('renew'\)">立即续费/);
});
test('notification center refreshes server scope after read-all; failures keep unread items', async () => {
for (const fail of [false, true]) {
const r = runtime();
@@ -482,3 +737,197 @@ test('401 clears phone/reminder state, but late 401 cannot log out a new session
assert.equal(user.state.assetPhoneBound, null);
assert.equal(r.storage.has('customerAssetPhoneState'), false);
});
test('asset info ignores deprecated protection values and preserves actual polling states', async () => {
const r = runtime();
const { normalizeAssetInfo } = await r.load('api/modules/asset.js');
for (const protection of [undefined, 'none', 'protecting']) {
const input = { enable_polling: false, network_status: 0, cards: [{ enable_polling: false }] };
if (protection !== undefined) input.device_protect_status = protection;
const result = normalizeAssetInfo(input);
assert.equal(Object.hasOwn(result, 'device_protect_status'), false);
assert.equal(result.enable_polling, false);
assert.equal(result.network_status, 0);
assert.equal(result.cards[0].enable_polling, false);
}
assert.equal(normalizeAssetInfo({}).enable_polling, undefined);
for (const path of ['pages/index/index.vue', 'components/UserInfoCard.vue', 'components/DeviceStatusCard.vue', 'components/TrafficCard.vue']) {
assert.doesNotMatch(readFileSync(resolve(root, path), 'utf8'), /device_protect_status|保护期/);
}
});
test('fresh asset snapshots replace polling cache and late responses cannot roll it back', async () => {
const r = runtime();
const { assetApi } = await r.load('api/modules/asset.js');
const asset = (await r.load('store/asset.js')).useAssetStore();
asset.setAssetInfo({ enable_polling: false, current_package_id: 1 });
const old = assetApi.getInfo('A');
const fresh = assetApi.getInfo('A');
r.reply(r.requests[1], { enable_polling: true, current_package_id: 2, cards: [{ enable_polling: true }] });
await fresh;
r.reply(r.requests[0], { enable_polling: false, current_package_id: 1 });
await old;
assert.equal(asset.state.assetInfo.enable_polling, true);
assert.equal(asset.state.assetInfo.current_package_id, 2);
assert.equal(asset.state.assetInfo.cards[0].enable_polling, true);
const missing = assetApi.getInfo('A');
r.reply(r.requests[2], { current_package_id: 3 }); await missing;
assert.equal(asset.state.assetInfo.enable_polling, undefined);
assert.equal(asset.state.assetInfo.cards, undefined);
const late = assetApi.getInfo('A');
(await r.load('store/user.js')).useUserStore().setIdentifier('B');
r.reply(r.requests[3], { enable_polling: true }); await late;
assert.equal(asset.state.assetInfo, null);
const b = assetApi.getInfo('B');
r.reply(r.requests[4], { enable_polling: false }); await b;
assert.equal(asset.state.assetInfo.enable_polling, false);
});
test('traffic uses the same fresh asset snapshot and clears expired or missing package data', async () => {
const r = runtime();
const card = await r.load('components/TrafficCard.vue', ['usedMB', 'totalMB', 'remainMB']);
assert.equal(card.totalMB.value, 0);
r.props.assetInfo = { current_package_usage_id: 1, real_used_mb: 100, real_total_mb: 1000 };
assert.equal(card.usedMB.value, 100);
assert.equal(card.remainMB.value, 900);
r.props.assetInfo = { current_package_usage_id: 2, real_used_mb: 200, virtual_used_mb: 150, enable_virtual_data: true, real_total_mb: 2000 };
assert.equal(card.usedMB.value, 150);
assert.equal(card.totalMB.value, 2000);
assert.equal(card.remainMB.value, 1850);
r.props.assetInfo = { real_used_mb: 200, real_total_mb: 2000 };
assert.equal(card.usedMB.value, 0);
assert.equal(card.totalMB.value, 0);
r.props.assetInfo = null;
assert.equal(card.remainMB.value, 0);
assert.equal(r.requests.length, 0);
});
test('returning home reloads actual polling, network and expiry with one asset request per entry', async () => {
const r = runtime();
r.api.assetApi = (await r.load('api/modules/asset.js')).assetApi;
r.api.notificationApi = { getUnreadCount: async () => ({ count: 0 }) };
r.payment.consumePendingPaymentRefresh = () => true;
const page = await r.load('pages/index/index.vue', ['deviceInfo']);
const first = r.shown[0]();
assert.equal(r.requests.length, 1);
r.reply(r.requests[0], { enable_polling: false, network_status: 0, estimated_final_expires_at: '2026-10-26T00:00:00Z' });
await first;
const asset = (await r.load('store/asset.js')).useAssetStore();
assert.equal(asset.state.assetInfo.enable_polling, false);
r.hidden[0]();
const next = r.shown[0]();
assert.equal(r.requests.length, 2);
r.reply(r.requests[1], { enable_polling: true, network_status: 1, estimated_final_expires_at: '2026-11-26T00:00:00Z' });
await next;
assert.equal(asset.state.assetInfo.enable_polling, true);
assert.equal(page.deviceInfo.network_status, 1);
assert.equal(page.deviceInfo.expireDate, '2026-11-26');
});
test('home rejects an old asset request after a new refresh or hide-and-return', async () => {
const r = runtime();
r.api.notificationApi = {};
const old = deferred();
const fresh = deferred();
let reads = 0;
r.api.assetApi = { getInfo: () => (++reads === 1 ? old.promise : fresh.promise) };
const page = await r.load('pages/index/index.vue', ['loadAssetInfo', 'deviceInfo']);
const a = page.loadAssetInfo();
r.hidden[0]();
const b = page.loadAssetInfo();
fresh.resolve({ network_status: 0, current_package: '新套餐' }); await b;
old.resolve({ network_status: 1, current_package: '旧套餐' }); await a;
assert.equal(page.deviceInfo.network_status, 0);
assert.equal(page.deviceInfo.packageName, '新套餐');
});
test('sync acceptance is not completion and never optimistically resumes the network', async () => {
for (const accepted of [true, false, undefined, 'false']) {
const r = runtime();
r.api.notificationApi = {};
let reads = 0;
r.api.assetApi = {
refresh: async () => ({ accepted, refresh_type: 'device' }),
getInfo: async () => { reads++; return { network_status: 0 }; }
};
const page = await r.load('pages/index/index.vue', ['onSync', 'deviceInfo', 'homeActive']);
page.homeActive.value = true;
await page.onSync();
const modal = r.calls.find(call => call.kind === 'modal');
assert.match(modal.content, /受理不代表.*停复机已执行完成/);
modal.success({ confirm: true });
await new Promise(resolve => setImmediate(resolve));
const toast = r.calls.find(call => call.kind === 'toast');
assert.equal(toast.icon, 'none');
assert.doesNotMatch(toast.title, /同步成功|复机成功|停机成功/);
assert.equal(reads, accepted === true ? 1 : 0);
if (accepted === true) {
assert.match(toast.title, /已受理/);
assert.equal(page.deviceInfo.network_status, 0);
await r.timers[0]();
assert.equal(reads, 2);
(await r.load('store/user.js')).useUserStore().setIdentifier('B');
await r.timers[0]();
assert.equal(reads, 2);
}
}
});
test('package page reloads asset state on every entry, after wallet payment and after wechat payment', async () => {
for (const method of ['wallet', 'wechat']) {
const r = runtime();
let polling = false;
let reads = 0;
r.api.assetApi = {
getInfo: async () => { reads++; return { enable_polling: polling, allowed_payment_methods: [method] }; },
getPackages: async () => ({ packages: [] })
};
r.api.isAssetRealNameCompleted = () => true;
r.api.walletApi = { getDetail: async () => ({ balance: 0 }) };
r.api.orderApi = {
create: async () => ({ order: { order_id: 12, payment_status: 2 } }),
pay: async () => ({}), getDetail: async () => ({ payment_status: 2 })
};
const page = await r.load('pages/package-order/package-order.vue', ['syncPackagePageState', 'confirmPay', 'currentPackage', 'paymentMethod', 'assetInfo', 'handleWechatPay']);
await page.syncPackagePageState();
assert.equal(page.assetInfo.value.enable_polling, false);
polling = true;
if (method === 'wallet') {
page.currentPackage.value = { package_id: 1 };
page.paymentMethod.value = 'wallet';
await page.confirmPay();
} else {
await page.handleWechatPay({}, false, 12);
}
assert.equal(page.assetInfo.value.enable_polling, true);
assert.equal(reads, 2);
polling = false;
await r.timers[0]();
await new Promise(resolve => setImmediate(resolve));
assert.equal(page.assetInfo.value.enable_polling, false);
polling = true;
r.shown[0]();
await new Promise(resolve => setImmediate(resolve));
assert.equal(page.assetInfo.value.enable_polling, true);
assert.equal(reads, 4);
}
});
test('order completion and payment return reread actual asset state, not a presumed polling value', async () => {
const r = runtime();
let reads = 0;
r.api.assetApi = { getInfo: async () => { reads++; return { enable_polling: false }; } };
r.api.orderApi = { getList: async () => ({ items: [] }) };
const page = await r.load('pages/order-list/order-list.vue', ['refreshOrderState']);
await page.refreshOrderState();
assert.equal(reads, 1);
r.shown[0]();
await new Promise(resolve => setImmediate(resolve));
assert.equal(reads, 2);
r.payment.consumePendingPaymentRefresh = () => true;
r.shown[0]();
await new Promise(resolve => setImmediate(resolve));
assert.equal(reads, 3);
await r.timers[1]();
assert.equal(reads, 4);
});