Commit c894835e by 张立顺

feat 功能开发

1 parent 8c815586
...@@ -4,9 +4,9 @@ MODE = 'production' ...@@ -4,9 +4,9 @@ MODE = 'production'
# 发布路径 # 发布路径
PUBLISH_PATH = '/' PUBLISH_PATH = '/'
# ── API 地址(正式版 release 锁定)──────────────────────────────────────────── # ── API 地址(未知 AppId 的正式版回退)────────────────────────────────────────
# 正式版(envVersion=release)始终使用本文件构建注入的 VITE_APP_API_*,不走运行时映射。 # 开发版、体验版、正式版优先按真实小程序 AppId 自动选择 test/prod。
# 体验版(trial)/ 开发版(develop)按小程序 AppId 自动选 test/prod,无需改注释切换。 # 仅当正式版无法识别 AppId 时,才使用本文件构建注入的 VITE_APP_API_*。
# 开发者工具联调请改 src/config/activeDevApiEnv.ts。 # 开发者工具联调请改 src/config/activeDevApiEnv.ts。
# 详见 docs/API_ENV_RUNTIME.md # 详见 docs/API_ENV_RUNTIME.md
# ──────────────────────────────────────────────────────────────────────────── # ────────────────────────────────────────────────────────────────────────────
......
...@@ -26,12 +26,14 @@ flowchart LR ...@@ -26,12 +26,14 @@ flowchart LR
| 优先级 | 条件 | 结果 | `source` 日志值 | | 优先级 | 条件 | 结果 | `source` 日志值 |
|--------|------|------|-----------------| |--------|------|------|-----------------|
| P0 | `import.meta.env.DEV` 且 `platform === 'devtools'` | [`activeDevApiEnv.ts`](src/config/activeDevApiEnv.ts) 中的 `ACTIVE_DEV_API_ENV` | `devtools` | | P0 | 开发者工具且选择 `local-*` | 使用 `activeDevApiEnv.ts` 本地联调地址 | `devtools` |
| P1 | 构建产物 + `envVersion === 'release'` | **锁定** `.env.production` 的 `VITE_APP_API_*` | `build-env` | | P1 | 微信小程序且 AppId 已登记 | 开发版、体验版、正式版统一按 AppId 映射 | `appId` |
| P2 | 构建产物 + `envVersion === 'trial'` | 按 AppId 映射 | `appId` | | P2 | 正式版且 AppId 未登记 | 使用 `.env.production` 构建注入值 | `build-env` |
| P3 | 构建产物 + `envVersion === 'develop'` | 按 AppId 映射 | `appId` | | P3 | 开发者工具且无已知 AppId | 使用 `activeDevApiEnv.ts` | `devtools` |
| P4 | 其他(H5、未知 AppId 等) | 回退 `.env` 默认值 | `fallback` | | P4 | 其他(H5、未知 AppId 等) | 回退 `.env` 默认值 | `fallback` |
> **注意**:同一个已登记 AppId 在 `develop`、`trial`、`release` 中始终连接同一套 API,避免体验版正常而正式版切换到其他后端。
## AppId 映射 ## AppId 映射
| 小程序 AppId | API 环境 | 接口域名 | | 小程序 AppId | API 环境 | 接口域名 |
...@@ -93,8 +95,9 @@ VITE_APP_API_BASE_URL = 'https://aus.glsx.com.cn/app/' ...@@ -93,8 +95,9 @@ VITE_APP_API_BASE_URL = 'https://aus.glsx.com.cn/app/'
| 现象 | 可能原因 | 处理 | | 现象 | 可能原因 | 处理 |
|------|----------|------| |------|----------|------|
| 体验版连错环境 | 打开了错误 AppId 的小程序 | 检查上传账号对应 AppId 与期望环境 | | 体验版连错环境 | 打开了错误 AppId 的小程序 | 检查上传账号对应 AppId 与期望环境 |
| 开发者工具仍连旧地址 | 未刷新或 `ACTIVE_DEV_API_ENV` 未保存 | 保存后重新编译;看 `[runtime] API` 中 `source=devtools` | | 开发者工具仍连生产(build 预览) | 旧 dist 缓存 / 工具项目 AppId 与目录不一致 | 重新 `npm run build:mp-weixin`;**关闭旧项目**,重新导入 `dist\build\mp-weixin`;看日志 `source=appId envKey=test` |
| 正式版连测试服 | `.env.production` 构建值错误 | 改 `.env.production` 后重新 build | | `appId` 为 `touristappid` | 未绑定真实小程序 | 确认 `project.config.json` 中 `appid` 为 `wx568d02f6352efd49` |
| 正式版连错环境 | AppId 未登记,且 `.env.production` 构建值错误 | 补充 `APP_ID_TO_ENV` 映射,并修正 `.env.production` 后重新 build |
| `source=fallback` | 非微信小程序或 AppId 未登记 | 检查运行平台;在 `APP_ID_TO_ENV` 补充映射 | | `source=fallback` | 非微信小程序或 AppId 未登记 | 检查运行平台;在 `APP_ID_TO_ENV` 补充映射 |
| 登录与接口环境不一致 | 少见;登录用运行时 `getAccountInfoSync().appId` | 两者应一致;检查日志中的 AppId | | 登录与接口环境不一致 | 少见;登录用运行时 `getAccountInfoSync().appId` | 两者应一致;检查日志中的 AppId |
......
...@@ -11,8 +11,8 @@ import type { ApiEnvKey } from "@/config/apiEnvironments"; ...@@ -11,8 +11,8 @@ import type { ApiEnvKey } from "@/config/apiEnvironments";
* *
* **无需**修改 `.env.development`,**无需**重启 `npm run dev:mp-weixin`。 * **无需**修改 `.env.development`,**无需**重启 `npm run dev:mp-weixin`。
* *
* 体验版 / 正式包由运行时 AppId 与 envVersion 自动决定,不受本常量影响。 * 开发版 / 体验版 / 正式版优先按运行时 AppId 自动决定环境,不受本常量影响。
* 正式版(release)锁定 `.env.production` 构建值。 * 只有无法识别 AppId 的正式版(release)才回退 `.env.production` 构建值。
* *
* ## 快速切换(改等号右侧字符串后保存) * ## 快速切换(改等号右侧字符串后保存)
* *
...@@ -32,4 +32,4 @@ import type { ApiEnvKey } from "@/config/apiEnvironments"; ...@@ -32,4 +32,4 @@ import type { ApiEnvKey } from "@/config/apiEnvironments";
// export const ACTIVE_DEV_API_ENV: ApiEnvKey = "local-125"; // export const ACTIVE_DEV_API_ENV: ApiEnvKey = "local-125";
/** 开发者工具联调环境 key,可选值见上方注释与 `apiEnvironments.ts` */ /** 开发者工具联调环境 key,可选值见上方注释与 `apiEnvironments.ts` */
export const ACTIVE_DEV_API_ENV: ApiEnvKey = "test"; export const ACTIVE_DEV_API_ENV: ApiEnvKey = "prod";
...@@ -13,7 +13,6 @@ export interface MiniProgramRuntimeContext { ...@@ -13,7 +13,6 @@ export interface MiniProgramRuntimeContext {
} }
const TOURIST_APP_ID = 'touristappid'; const TOURIST_APP_ID = 'touristappid';
const DEFAULT_PROD_APP_ID = 'wxa719209ed933d667';
function emptyContext(): MiniProgramRuntimeContext { function emptyContext(): MiniProgramRuntimeContext {
return { return {
...@@ -27,8 +26,9 @@ function emptyContext(): MiniProgramRuntimeContext { ...@@ -27,8 +26,9 @@ function emptyContext(): MiniProgramRuntimeContext {
function normalizeAppId(appId: string): string { function normalizeAppId(appId: string): string {
const normalized = appId?.trim() ?? ''; const normalized = appId?.trim() ?? '';
// touristappid 无法映射环境,留空以回退 activeDevApiEnv / .env
if (normalized === TOURIST_APP_ID) { if (normalized === TOURIST_APP_ID) {
return DEFAULT_PROD_APP_ID; return '';
} }
return normalized; return normalized;
} }
......
/** /**
* @file 按优先级链解析 API 环境 key。 * @file 按优先级链解析 API 环境 key。
* *
* P0: 开发态 + 开发者工具 → `activeDevApiEnv.ts` * P0: 开发者工具本地环境覆盖 → `activeDevApiEnv.ts`
* P1: 构建产物 + release → 锁定 `.env.production`(返回 build-env) * P1: 已知微信小程序 AppId → 统一映射 test/prod(含 release)
* P2/P3: 构建产物 + trial/develop → AppId 映射 * P2: 未知 AppId 的正式版 → 回退 `.env.production`
* P4: 回退 `.env` 默认值 * P3: 开发者工具无已知 AppId → `activeDevApiEnv.ts`
* P4: 其他平台 → 回退 `.env` 默认值
*/ */
import {ACTIVE_DEV_API_ENV} from '@/config/activeDevApiEnv'; import {ACTIVE_DEV_API_ENV} from '@/config/activeDevApiEnv';
...@@ -29,27 +30,26 @@ export function resolveApiEnvKeyFromContext( ...@@ -29,27 +30,26 @@ export function resolveApiEnvKeyFromContext(
isDev: boolean, isDev: boolean,
devtoolsEnvKey: ApiEnvKey = ACTIVE_DEV_API_ENV, devtoolsEnvKey: ApiEnvKey = ACTIVE_DEV_API_ENV,
): ResolvedApiEnvKey { ): ResolvedApiEnvKey {
if (isDev && runtime.isDevtools) { // 开发者工具允许显式覆盖到本地联调地址。
const isLocalOverride = devtoolsEnvKey.startsWith('local-'); if (runtime.isDevtools && devtoolsEnvKey.startsWith('local-')) {
if (isLocalOverride) { return {source: 'devtools', envKey: devtoolsEnvKey};
return {source: 'devtools', envKey: devtoolsEnvKey}; }
}
// 同一个小程序 AppId 在开发版、体验版和正式版中必须解析到同一环境。
if (runtime.isWeixinMp) {
const envKeyFromAppId = resolveEnvKeyFromAppId(runtime.appId); const envKeyFromAppId = resolveEnvKeyFromAppId(runtime.appId);
if (envKeyFromAppId) { if (envKeyFromAppId) {
return {source: 'appId', envKey: envKeyFromAppId}; return {source: 'appId', envKey: envKeyFromAppId};
} }
return {source: 'devtools', envKey: devtoolsEnvKey};
} }
// 无法识别 AppId 的正式版才使用构建时 .env.production 作为安全回退。
if (!isDev && runtime.envVersion === 'release') { if (!isDev && runtime.envVersion === 'release') {
return {source: 'build-env'}; return {source: 'build-env'};
} }
if (!isDev && runtime.isWeixinMp && (runtime.envVersion === 'trial' || runtime.envVersion === 'develop')) { if (runtime.isDevtools) {
const envKey = resolveEnvKeyFromAppId(runtime.appId); return {source: 'devtools', envKey: devtoolsEnvKey};
if (envKey) {
return {source: 'appId', envKey};
}
} }
return {source: 'fallback'}; return {source: 'fallback'};
......
...@@ -36,8 +36,8 @@ ...@@ -36,8 +36,8 @@
"quickapp": {}, "quickapp": {},
/* 小程序特有相关 */ /* 小程序特有相关 */
"mp-weixin": { "mp-weixin": {
// "appid": "wxa719209ed933d667", "appid": "wxa719209ed933d667",
"appid": "wx568d02f6352efd49", // "appid": "wx568d02f6352efd49",
"setting": { "setting": {
"urlCheck": false, "urlCheck": false,
"es6": true, "es6": true,
......
<template> <template>
<view class="upload-transfer-page"> <view class="upload-transfer-page">
<view class="page-content" :style="{ paddingBottom: contentBottomPadding + 'px' }"> <view v-if="isLoadingData" class="page-state">
<text class="page-state-title">资料加载中...</text>
</view>
<view v-else-if="loadError" class="page-state">
<text class="page-state-title">过户资料加载失败</text>
<text class="page-state-message">{{ loadError }}</text>
<button class="page-state-retry" @click="loadData">重新加载</button>
</view>
<view v-else class="page-content" :style="{ paddingBottom: contentBottomPadding + 'px' }">
<!-- 顶部导航栏 --> <!-- 顶部导航栏 -->
<van-notice-bar v-if="order?.auditState==='REJECTED'" left-icon="info" :scrollable="false" wrapable text="审核失败,原因:行驶证照片模糊,无法识别信息,请重新上传。" background="#EB4E4E19"/> <van-notice-bar v-if="order?.auditState==='REJECTED'" left-icon="info" :scrollable="false" wrapable text="审核失败,原因:行驶证照片模糊,无法识别信息,请重新上传。" background="#EB4E4E19"/>
<van-notice-bar v-else left-icon="info" :scrollable="false" wrapable text="请确保上传的照片清晰、完整,以便平台快速审核。" background="#FF8D1A19"> <van-notice-bar v-else left-icon="info" :scrollable="false" wrapable text="请确保上传的照片清晰、完整,以便平台快速审核。" background="#FF8D1A19">
...@@ -136,10 +144,10 @@ ...@@ -136,10 +144,10 @@
</view> </view>
<!-- 底部提交按钮 --> <!-- 底部提交按钮 -->
<view class="submit-section"> <view v-if="!isLoadingData && !loadError" class="submit-section">
<van-button type="primary" hairline round :disabled="!canSubmit" @click="submitReview" block>提交审核</van-button> <van-button type="primary" hairline round :disabled="!canSubmit" @click="submitReview" block>提交审核</van-button>
</view> </view>
<plate-input v-if="showPlateKeyboard" :plate="newLicensePlate" @export="setPlate" @close="showPlateKeyboard=false"/> <plate-input v-if="!isLoadingData && !loadError && showPlateKeyboard" :plate="newLicensePlate" @export="setPlate" @close="showPlateKeyboard=false"/>
</view> </view>
</template> </template>
<script lang="ts"> <script lang="ts">
...@@ -192,6 +200,8 @@ export default class UploadTransferPage extends Vue { ...@@ -192,6 +200,8 @@ export default class UploadTransferPage extends Vue {
uploadQueue: string[] = []; uploadQueue: string[] = [];
uploadQueueRunning = false; uploadQueueRunning = false;
isLoadingData = true; isLoadingData = true;
loadRequestRunning = false;
loadError = '';
isSubmitting = false; isSubmitting = false;
// 新车牌号 // 新车牌号
newLicensePlate = ''; newLicensePlate = '';
...@@ -216,7 +226,7 @@ export default class UploadTransferPage extends Vue { ...@@ -216,7 +226,7 @@ export default class UploadTransferPage extends Vue {
created(): void { created(): void {
onLoad((option) => { onLoad((option) => {
this.orderId = Number(option.orderId); this.orderId = Number(option.orderId);
this.loadData(); void this.loadData();
}); });
onReady(() => { onReady(() => {
this.measureFooterHeight(); this.measureFooterHeight();
...@@ -240,21 +250,38 @@ export default class UploadTransferPage extends Vue { ...@@ -240,21 +250,38 @@ export default class UploadTransferPage extends Vue {
.exec(); .exec();
} }
loadData(): void { async loadData(): Promise<void> {
if (this.uploadQueueRunning) { if (this.uploadQueueRunning) {
uni.showToast({title: '图片上传中,请稍候', icon: 'none'}); uni.showToast({title: '图片上传中,请稍候', icon: 'none'});
return; return;
} }
if (this.loadRequestRunning) {
return;
}
this.loadRequestRunning = true;
this.isLoadingData = true; this.isLoadingData = true;
AuctionOrderController.getAuctionOrderDetailById(this.axios, this.orderId).then(res => { this.loadError = '';
let loadedSuccessfully = false;
try {
if (!Number.isFinite(this.orderId) || this.orderId <= 0) {
throw new Error('订单参数无效');
}
const res = await AuctionOrderController.getAuctionOrderDetailById(this.axios, this.orderId);
if (this.uploadQueueRunning || this.uploadQueue.length > 0) { if (this.uploadQueueRunning || this.uploadQueue.length > 0) {
return; return;
} }
this.order = res.data; const order = res?.data;
this.newLicensePlate = this.order.newPlateNumber; if (!order) {
throw new Error('未获取到订单资料');
}
this.order = order;
this.newLicensePlate = order.newPlateNumber ?? '';
let invalidStoredFileCount = 0; let invalidStoredFileCount = 0;
const nextRegistrationItems: TransferUploadItem[] = []; const nextRegistrationItems: TransferUploadItem[] = [];
(this.order.registrationCertificate ?? []).forEach((file, index) => { const registrationFiles = Array.isArray(order.registrationCertificate)
? order.registrationCertificate
: [];
registrationFiles.forEach((file, index) => {
try { try {
nextRegistrationItems.push(createLoadedUploadItem( nextRegistrationItems.push(createLoadedUploadItem(
'registration', 'registration',
...@@ -268,7 +295,10 @@ export default class UploadTransferPage extends Vue { ...@@ -268,7 +295,10 @@ export default class UploadTransferPage extends Vue {
this.registrationItems = nextRegistrationItems; this.registrationItems = nextRegistrationItems;
this.licenseMainItem = null; this.licenseMainItem = null;
const licenseMainFile = this.order.vehicleLicense?.[0]; const vehicleLicenseFiles = Array.isArray(order.vehicleLicense)
? order.vehicleLicense
: [];
const licenseMainFile = vehicleLicenseFiles[0];
if (licenseMainFile) { if (licenseMainFile) {
try { try {
this.licenseMainItem = createLoadedUploadItem( this.licenseMainItem = createLoadedUploadItem(
...@@ -282,7 +312,7 @@ export default class UploadTransferPage extends Vue { ...@@ -282,7 +312,7 @@ export default class UploadTransferPage extends Vue {
} }
this.licenseSubItem = null; this.licenseSubItem = null;
const licenseSubFile = this.order.vehicleLicense?.[1]; const licenseSubFile = vehicleLicenseFiles[1];
if (licenseSubFile) { if (licenseSubFile) {
try { try {
this.licenseSubItem = createLoadedUploadItem( this.licenseSubItem = createLoadedUploadItem(
...@@ -302,15 +332,21 @@ export default class UploadTransferPage extends Vue { ...@@ -302,15 +332,21 @@ export default class UploadTransferPage extends Vue {
duration: 3000, duration: 3000,
}); });
} }
}).catch((error) => { loadedSuccessfully = true;
} catch (error) {
this.loadError = getUploadErrorMessage(error, '过户资料加载失败');
uni.showToast({ uni.showToast({
title: getUploadErrorMessage(error, '过户资料加载失败'), title: this.loadError,
icon: 'none', icon: 'none',
duration: 3000, duration: 3000,
}); });
}).finally(() => { } finally {
this.loadRequestRunning = false;
this.isLoadingData = false; this.isLoadingData = false;
}); if (loadedSuccessfully) {
this.$nextTick(() => this.measureFooterHeight());
}
}
} }
chooseRegistrationImage(): void { chooseRegistrationImage(): void {
...@@ -560,6 +596,7 @@ export default class UploadTransferPage extends Vue { ...@@ -560,6 +596,7 @@ export default class UploadTransferPage extends Vue {
get canSubmit(): boolean { get canSubmit(): boolean {
return !this.isLoadingData return !this.isLoadingData
&& !this.loadError
&& !this.isSubmitting && !this.isSubmitting
&& this.order?.orderState === 'TRANSFERRING' && this.order?.orderState === 'TRANSFERRING'
&& this.newLicensePlate?.length >= 7 && this.newLicensePlate?.length >= 7
...@@ -652,6 +689,45 @@ export default class UploadTransferPage extends Vue { ...@@ -652,6 +689,45 @@ export default class UploadTransferPage extends Vue {
box-sizing: border-box; box-sizing: border-box;
} }
.page-state {
min-height: 60vh;
padding: 80rpx 40rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
box-sizing: border-box;
text-align: center;
}
.page-state-title {
color: #333;
font-size: 32rpx;
font-weight: 500;
}
.page-state-message {
margin-top: 20rpx;
color: #999;
font-size: 26rpx;
line-height: 1.6;
}
.page-state-retry {
min-width: 220rpx;
margin-top: 36rpx;
padding: 0 36rpx;
color: #fff;
background-color: #185EFE;
border-radius: 44rpx;
font-size: 28rpx;
line-height: 80rpx;
}
.page-state-retry::after {
border: none;
}
/* 资料上传区域 */ /* 资料上传区域 */
......
...@@ -105,12 +105,29 @@ assert.deepEqual( ...@@ -105,12 +105,29 @@ assert.deepEqual(
{source: 'devtools', envKey: 'local-125'}, {source: 'devtools', envKey: 'local-125'},
); );
// P1: release locks build env // A known release AppId must use the same environment as trial/develop.
assert.deepEqual( assert.deepEqual(
resolveApiEnvKeyFromContext( resolveApiEnvKeyFromContext(
runtime({envVersion: 'release', isWeixinMp: true, appId: 'wx568d02f6352efd49'}), runtime({envVersion: 'release', isWeixinMp: true, appId: 'wx568d02f6352efd49'}),
false, false,
), ),
{source: 'appId', envKey: 'test'},
);
assert.deepEqual(
resolveApiEnvKeyFromContext(
runtime({envVersion: 'release', isWeixinMp: true, appId: 'wxa719209ed933d667'}),
false,
),
{source: 'appId', envKey: 'prod'},
);
// Unknown release AppIds retain the build-time fallback.
assert.deepEqual(
resolveApiEnvKeyFromContext(
runtime({envVersion: 'release', isWeixinMp: true, appId: 'wx-unknown'}),
false,
),
{source: 'build-env'}, {source: 'build-env'},
); );
...@@ -156,13 +173,37 @@ assert.deepEqual( ...@@ -156,13 +173,37 @@ assert.deepEqual(
{source: 'fallback'}, {source: 'fallback'},
); );
// dev build on real device (not devtools) falls back // P0: build preview in devtools + release envVersion still uses AppId (not build-env lock)
assert.deepEqual(
resolveApiEnvKeyFromContext(
runtime({
isDevtools: true,
envVersion: 'release',
isWeixinMp: true,
appId: 'wx568d02f6352efd49',
}),
false,
'test',
),
{source: 'appId', envKey: 'test'},
);
// Real-device release also follows the known AppId mapping.
assert.deepEqual(
resolveApiEnvKeyFromContext(
runtime({envVersion: 'release', isWeixinMp: true, appId: 'wx568d02f6352efd49'}),
false,
),
{source: 'appId', envKey: 'test'},
);
// A dev build on a real mini-program device still follows its known AppId.
assert.deepEqual( assert.deepEqual(
resolveApiEnvKeyFromContext( resolveApiEnvKeyFromContext(
runtime({envVersion: 'develop', isWeixinMp: true, appId: 'wx568d02f6352efd49'}), runtime({envVersion: 'develop', isWeixinMp: true, appId: 'wx568d02f6352efd49'}),
true, true,
), ),
{source: 'fallback'}, {source: 'appId', envKey: 'test'},
); );
console.log('resolve-api-env-key.test.cjs: all tests passed'); console.log('resolve-api-env-key.test.cjs: all tests passed');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ts = require('typescript');
const {parse} = require('@vue/compiler-sfc');
const pagePath = path.resolve(
__dirname,
'..',
'src/module/order/transfer/UploadTransferPage.vue',
);
const pageSource = fs.readFileSync(pagePath, 'utf8');
const parsed = parse(pageSource, {filename: pagePath});
assert.equal(parsed.errors.length, 0, `SFC parse errors: ${parsed.errors.join('\n')}`);
const scriptSource = parsed.descriptor.script.content;
const compiled = ts.transpileModule(scriptSource, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2020,
experimentalDecorators: true,
esModuleInterop: true,
},
fileName: pagePath,
}).outputText;
let detailRequest;
class Vue {
$nextTick(callback) {
callback();
}
}
const moduleStubs = {
'vue-facing-decorator': {
Component: () => (target) => target,
Vue,
},
'lib/src/entity/auction/entity/AuctionOrder': {
AuctionOrder: class AuctionOrder {},
},
'@dcloudio/uni-app': {
onLoad: () => {},
onReady: () => {},
},
'@/api/AuctionOrderController': {
AuctionOrderController: {
getAuctionOrderDetailById: (...args) => detailRequest(...args),
},
},
'@/common/UploadHelper': {
getUploadErrorMessage: (error, fallback = '图片上传失败') =>
error instanceof Error && error.message ? error.message : fallback,
uploadFiles: () => Promise.reject(new Error('not used by loading tests')),
},
'@/components/uni-plate-input/uni-plate-input.vue': {},
'@/common/TransferUploadState': {
buildTransferUploadPayload: () => ({}),
canSelectTransferImages: () => true,
cancelUploadItem: () => null,
canSubmitTransferUploads: () => false,
createLoadedUploadItem: (slot, fileInfo, clientId) => ({
slot,
fileInfo,
clientId,
status: 'uploaded',
previewUrl: fileInfo.url || fileInfo.filePath,
errorMessage: '',
}),
createQueuedUploadItem: () => ({}),
markUploadFailed: () => ({}),
markUploadStarted: () => ({}),
markUploadSucceeded: () => ({}),
remainingRegistrationSlots: () => 10,
retryUploadItem: () => ({}),
},
};
const loadedModule = {exports: {}};
const localRequire = (request) => {
if (Object.prototype.hasOwnProperty.call(moduleStubs, request)) {
return moduleStubs[request];
}
return require(request);
};
const evaluate = new Function('module', 'exports', 'require', compiled);
evaluate(loadedModule, loadedModule.exports, localRequire);
const UploadTransferPage = loadedModule.exports.default;
global.uni = {
showToast: () => {},
createSelectorQuery: () => ({
in() { return this; },
select() { return this; },
boundingClientRect() { return this; },
exec() {},
}),
};
function createPage(orderId) {
const page = new UploadTransferPage();
page.orderId = orderId;
page.axios = {};
return page;
}
async function run() {
let requestCount = 0;
detailRequest = () => {
requestCount += 1;
return Promise.resolve({data: {}});
};
const invalidPage = createPage(Number.NaN);
const invalidResult = invalidPage.loadData();
assert.ok(invalidResult instanceof Promise, 'loadData must expose its async completion');
await invalidResult;
assert.equal(requestCount, 0, 'invalid order IDs must not reach the API');
assert.equal(invalidPage.loadError, '订单参数无效');
assert.equal(invalidPage.isLoadingData, false);
detailRequest = () => Promise.reject(new Error('正式订单读取失败'));
const failedPage = createPage(123);
await failedPage.loadData();
assert.equal(failedPage.loadError, '正式订单读取失败');
assert.equal(failedPage.isLoadingData, false);
let resolveConcurrentRequest;
const concurrentResponse = new Promise((resolve) => {
resolveConcurrentRequest = resolve;
});
let concurrentRequestCount = 0;
detailRequest = () => {
concurrentRequestCount += 1;
return concurrentResponse;
};
const concurrentPage = createPage(123);
const firstLoad = concurrentPage.loadData();
const duplicateLoad = concurrentPage.loadData();
assert.equal(concurrentRequestCount, 1, 'duplicate retries must not start another request');
resolveConcurrentRequest({
data: {
orderState: 'TRANSFERRING',
newPlateNumber: '粤B12345',
registrationCertificate: [],
vehicleLicense: [],
},
});
await Promise.all([firstLoad, duplicateLoad]);
detailRequest = () => Promise.resolve({data: null});
const emptyPage = createPage(123);
await emptyPage.loadData();
assert.equal(emptyPage.loadError, '未获取到订单资料');
assert.equal(emptyPage.isLoadingData, false);
detailRequest = () => Promise.resolve({
data: {
orderState: 'TRANSFERRING',
newPlateNumber: '粤B12345',
registrationCertificate: [],
vehicleLicense: [],
},
});
const successfulPage = createPage(123);
let footerMeasureCount = 0;
successfulPage.measureFooterHeight = () => {
footerMeasureCount += 1;
};
successfulPage.loadError = '旧错误';
await successfulPage.loadData();
assert.equal(successfulPage.loadError, '');
assert.equal(successfulPage.isLoadingData, false);
assert.equal(successfulPage.newLicensePlate, '粤B12345');
assert.equal(footerMeasureCount, 1, 'successful loading must remeasure the rendered footer');
process.stdout.write('PASS transfer page loading states\n');
}
run().catch((error) => {
process.stderr.write(`${error.stack || error}\n`);
process.exitCode = 1;
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!