Compare commits
4 Commits
131823ca12
...
iteration/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e084cdeb90 | ||
|
|
b5f89b744c | ||
|
|
33f3b37be0 | ||
|
|
f7cb28febf |
@@ -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 }}
|
||||
|
||||
|
||||
@@ -3,24 +3,30 @@ 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,
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
1754
docs/2026-10-26-轮询按运营商账户限流-前端接口变更说明.md
Normal file
1754
docs/2026-10-26-轮询按运营商账户限流-前端接口变更说明.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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" /> -->
|
||||
@@ -205,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,
|
||||
@@ -284,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([]);
|
||||
@@ -305,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';
|
||||
@@ -337,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) {
|
||||
@@ -396,25 +399,25 @@
|
||||
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 onRenewalVisibilityChange = (visible) => {
|
||||
@@ -730,6 +733,7 @@
|
||||
};
|
||||
|
||||
const onSync = async () => {
|
||||
if (syncing.value) return;
|
||||
const identifier = userStore.state.identifier;
|
||||
if (!identifier) {
|
||||
uni.showToast({
|
||||
@@ -739,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
|
||||
@@ -751,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({
|
||||
@@ -771,6 +779,7 @@
|
||||
}
|
||||
}).catch((e) => {
|
||||
uni.hideLoading();
|
||||
if (!isCurrentSession(context)) return;
|
||||
console.error('同步数据失败', e);
|
||||
|
||||
if (e.msg && e.msg.includes('冷却')) {
|
||||
@@ -785,7 +794,7 @@
|
||||
icon: 'none'
|
||||
});
|
||||
}
|
||||
});
|
||||
}).finally(() => { syncing.value = false; });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1001,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();
|
||||
@@ -1018,6 +1030,7 @@
|
||||
});
|
||||
onHide(() => {
|
||||
homeEntryId++;
|
||||
assetRequestId++;
|
||||
homeActive.value = false;
|
||||
shownExpiryReminder.value = null;
|
||||
notificationPopupShow.value = false;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 () => {
|
||||
@@ -231,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');
|
||||
@@ -578,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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user