Commit 1517c05d authored by zengqiang's avatar zengqiang

Merge branch 'feature/2026-05-08-wechat-transfer' into 'master'

Feature/2026 05 08 wechat transfer See merge request wykolor/mall-webview!29
parents 5a6324b0 43714e68
...@@ -24,3 +24,16 @@ npm run lint ...@@ -24,3 +24,16 @@ npm run lint
### Customize configuration ### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/). See [Configuration Reference](https://cli.vuejs.org/config/).
### 变更记录
本次更新主要围绕微信商家转账升级,主要变更包括:
- 新增确认收款中间页
- 新增处理中状态展示
- 新增提现状态枚举展示
### 页面说明
**提现相关页面:**
- **确认收款页**: 用户发起提现后,需在此页确认收款。通过 JSBridge 调用原生能力调起微信确认。
- **提现记录列表**: 展示提现记录,支持新的提现状态枚举(处理中、待确认收款、已成功、失败)。
...@@ -6,6 +6,7 @@ module.exports = { ...@@ -6,6 +6,7 @@ module.exports = {
'@babel/plugin-proposal-logical-assignment-operators', '@babel/plugin-proposal-logical-assignment-operators',
'@babel/plugin-proposal-optional-chaining' '@babel/plugin-proposal-optional-chaining'
] ]
}] }],
'@babel/preset-typescript'
] ]
} }
module.exports = {
testEnvironment: 'jsdom',
moduleFileExtensions: [
'js',
'ts',
'json',
'vue',
],
transform: {
'^.+\.ts$': 'ts-jest',
'^.+\.js$': 'babel-jest',
'.*\.(vue)$' : '@vue/vue3-jest',
},
testMatch: [
'**/__tests__/**/*.spec.[jt]s?(x)',
'**/__tests__/**/*.test.[jt]s?(x)',
'**/src/**/*.spec.[jt]s?(x)',
'**/src/**/*.test.[jt]s?(x)',
],
moduleNameMapper: {
'^@/(.*)$' : '<rootDir>/src/$1'
},
};
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -6,7 +6,9 @@ ...@@ -6,7 +6,9 @@
"build": "vue-cli-service build", "build": "vue-cli-service build",
"serve": "vue-cli-service serve", "serve": "vue-cli-service serve",
"dev": "vue-cli-service serve", "dev": "vue-cli-service serve",
"lint": "vue-cli-service lint --fix" "lint": "vue-cli-service lint --fix",
"test": "vue-cli-service test:unit",
"test:unit": "vue-cli-service test:unit"
}, },
"dependencies": { "dependencies": {
"amfe-flexible": "^2.2.1", "amfe-flexible": "^2.2.1",
...@@ -15,11 +17,13 @@ ...@@ -15,11 +17,13 @@
"js-cookie": "^2.2.1", "js-cookie": "^2.2.1",
"vant": "^3.0.9", "vant": "^3.0.9",
"vconsole": "^3.4.0", "vconsole": "^3.4.0",
"version-compare": "^3.12.0",
"vue": "^3.2.13", "vue": "^3.2.13",
"vue-router": "^4.2.4", "vue-router": "^4.2.4",
"vuex": "^4.0.2" "vuex": "^4.0.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-typescript": "^7.28.5",
"@geek/webpack-upload-assets-plugin": "^1.0.1", "@geek/webpack-upload-assets-plugin": "^1.0.1",
"@types/js-cookie": "^3.0.3", "@types/js-cookie": "^3.0.3",
"@typescript-eslint/eslint-plugin": "^5.4.0", "@typescript-eslint/eslint-plugin": "^5.4.0",
...@@ -28,11 +32,14 @@ ...@@ -28,11 +32,14 @@
"@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0", "@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-typescript": "~5.0.0", "@vue/cli-plugin-typescript": "~5.0.0",
"@vue/cli-plugin-unit-jest": "^5.0.9",
"@vue/cli-plugin-vuex": "~5.0.0", "@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0", "@vue/cli-service": "~5.0.0",
"@vue/eslint-config-standard": "^6.1.0", "@vue/eslint-config-standard": "^6.1.0",
"@vue/eslint-config-typescript": "^9.1.0", "@vue/eslint-config-typescript": "^9.1.0",
"@vue/preload-webpack-plugin": "^2.0.0", "@vue/preload-webpack-plugin": "^2.0.0",
"@vue/test-utils": "^2.4.0-alpha.2",
"@vue/vue3-jest": "^27.0.0",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.3", "eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0", "eslint-plugin-node": "^11.1.0",
...@@ -44,6 +51,7 @@ ...@@ -44,6 +51,7 @@
"sass": "^1.32.7", "sass": "^1.32.7",
"sass-loader": "^12.0.0", "sass-loader": "^12.0.0",
"ts-import-plugin": "^1.6.7", "ts-import-plugin": "^1.6.7",
"ts-jest": "^27.1.5",
"typescript": "~4.5.5", "typescript": "~4.5.5",
"webpack-merge": "^5.7.3" "webpack-merge": "^5.7.3"
} }
......
...@@ -42,7 +42,12 @@ export enum ErrCode { ...@@ -42,7 +42,12 @@ export enum ErrCode {
// 提现记录状态 // 提现记录状态
export enum WithdrawStatus { export enum WithdrawStatus {
WITHDRAWING = 'WITHDRAWING', WITHDRAWING = 'WITHDRAWING', // 提现中
RECEIVED = 'RECEIVED', RECEIVED = 'RECEIVED', // 已到账
FAILED = 'FAILED' FAILED = 'FAILED', // 提现失败
WAIT_CONFIRM = 'WAIT_CONFIRM', // 待用户确认收款
TRANSFERING = 'TRANSFERING', // 转账中
ACCEPTED = 'ACCEPTED', // 已受理
CANCELING = 'CANCELING', // 撤销中
CANCELLED = 'CANCELLED' // 已撤销
} }
...@@ -65,7 +65,9 @@ export interface WithdrawListResponse { ...@@ -65,7 +65,9 @@ export interface WithdrawListResponse {
withdrawApplyTime: string; withdrawApplyTime: string;
withdrawAmount: number; withdrawAmount: number;
withdrawPayTime: string; withdrawPayTime: string;
status: string; status: string; // 显示状态 (WithdrawDisplayStatusEnum)
withdrawStatus?: string; // 原始提现状态 (WithdrawStatusEnum)
withdrawNo?: string; // 提现流水号
expectedPayTime: string; expectedPayTime: string;
failTime: string; failTime: string;
reason: string; reason: string;
...@@ -85,10 +87,14 @@ export interface WithdrawParams { ...@@ -85,10 +87,14 @@ export interface WithdrawParams {
export interface WithdrawResponse { export interface WithdrawResponse {
serialNo: string; serialNo: string;
withdrawNo: string;
withdrawAccount: string; withdrawAccount: string;
amount: number; amount: number;
withdrawApplyTime: string; withdrawApplyTime: string;
expectedPayTime: string; expectedPayTime: string;
packageInfo?: string;
mchId?: string;
appId?: string;
} }
export interface WithdrawRiskResponse { export interface WithdrawRiskResponse {
......
...@@ -25,6 +25,16 @@ const routes: Array<RouteRecordRaw> = [ ...@@ -25,6 +25,16 @@ const routes: Array<RouteRecordRaw> = [
path: '/test/paging', path: '/test/paging',
name: 'test-paging', name: 'test-paging',
component: () => import('../views/test/paging.vue') component: () => import('../views/test/paging.vue')
},
{
path: '/withdraw/confirm-receipt',
name: 'WithdrawConfirmReceipt',
component: () => import('../views/withdraw/ConfirmReceipt.vue')
},
{
path: '/withdraw/processing-status',
name: 'WithdrawProcessingStatus',
component: () => import('../views/withdraw/ProcessingStatus.vue')
} }
] ]
......
import { invokeNativeMethod } from '@/util/use-native-bridge';
interface NativeMerchantTransferResponse {
errMsg: string; // e.g., 'requestMerchantTransfer:ok' or an error message
// Add other fields if the native method returns more data
}
/**
* Calls the native JSBridge to request merchant transfer (similar to wx.requestMerchantTransfer).
* @param {string} packageInfo - The package information received from the backend for native transfer.
* @returns {Promise<NativeMerchantTransferResponse>}
*/
export function requestNativeMerchantTransfer(packageInfo: string): Promise<NativeMerchantTransferResponse> {
return invokeNativeMethod<NativeMerchantTransferResponse, string>({
type: 'requestMerchantTransfer', // Assuming the native app exposes this method type
data: packageInfo,
});
}
import { get } from '../request'
interface WithdrawStatusResponseData {
withdrawNo: string;
amount: string;
withdrawStatus: string;
failReason?: string;
withdrawApplyTime: string;
withdrawPayTime: string;
}
interface WithdrawPackageInfoResponseData {
packageInfo: string;
mchId: string;
appId: string;
}
/**
* 查询提现明细
* @param {string} withdrawNo - 提现流水号
* @returns {Promise<WithdrawStatusResponseData>}
*/
export function queryWithdrawStatus (withdrawNo: string): Promise<WithdrawStatusResponseData> {
return get(
`/api-jksxb-app/v1/withdraw/detail?withdrawNo=${withdrawNo}`
)
}
/**
* 获取提现确认参数
* @param {string} withdrawNo - 提现流水号
* @returns {Promise<WithdrawPackageInfoResponseData>}
*/
export function getWithdrawPackageInfo (withdrawNo: string): Promise<WithdrawPackageInfoResponseData> {
return get(
`/api-jksxb-app/v1/withdraw/packageInfo?withdrawNo=${withdrawNo}`
)
}
...@@ -22,7 +22,8 @@ window.$geek_excuteJS = function (args: any) { ...@@ -22,7 +22,8 @@ window.$geek_excuteJS = function (args: any) {
try { try {
const params = JSON.parse(args) const params = JSON.parse(args)
eventBus.emit<NativeInvokeFuncParams>(GEEK_NATIVE_NAME, params) eventBus.emit<NativeInvokeFuncParams>(GEEK_NATIVE_NAME, params)
} catch (error) { } catch (error: any) {
console.log('error in $geek_excuteJS', error.message, error.stack)
eventBus.emit<NativeInvokeFuncParams>(GEEK_NATIVE_NAME, args) eventBus.emit<NativeInvokeFuncParams>(GEEK_NATIVE_NAME, args)
} }
} }
...@@ -87,20 +88,25 @@ export { useNativeBridge } ...@@ -87,20 +88,25 @@ export { useNativeBridge }
const INVOKE_NATIVE_METHOD_TIMEOUT = 10000 const INVOKE_NATIVE_METHOD_TIMEOUT = 10000
function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }): Promise<T> { function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }, timeout = INVOKE_NATIVE_METHOD_TIMEOUT): Promise<T> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const callbackName = `${arg.type}_callback_${Math.random()}`.replace(/\./, '') const callbackName = `${arg.type}_callback_${Math.random()}`.replace(/\./, '')
let timer: ReturnType<typeof setTimeout> | null = null
const timer = setTimeout(() => { // 如果 timeout 大于 0,则设置一个定时器,如果超时则拒绝请求
reject(new Error(`invoke ${arg.type} timeout`)) if (timeout > 0) {
eventBus.off(GEEK_NATIVE_NAME, onCallback) timer = setTimeout(() => {
}, INVOKE_NATIVE_METHOD_TIMEOUT) reject(new Error(`invoke ${arg.type} timeout`))
eventBus.off(GEEK_NATIVE_NAME, onCallback)
}, timeout)
}
eventBus.on(GEEK_NATIVE_NAME, onCallback) eventBus.on(GEEK_NATIVE_NAME, onCallback)
function onCallback (params?: NativeInvokeFuncParams) { function onCallback (params?: NativeInvokeFuncParams) {
if (params?.method === callbackName) { if (params?.method === callbackName) {
clearTimeout(timer) if (timer) {
clearTimeout(timer)
}
if (params.error) { if (params.error) {
reject(new Error(params.error)) reject(new Error(params.error))
} else { } else {
...@@ -114,6 +120,8 @@ function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }): ...@@ -114,6 +120,8 @@ function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }):
}) })
} }
export { invokeNativeMethod }
/** /**
* 微信登录 * 微信登录
*/ */
...@@ -135,3 +143,35 @@ export function makeCall (phone: string) { ...@@ -135,3 +143,35 @@ export function makeCall (phone: string) {
export function goHome () { export function goHome () {
return invokeNativeMethod<null, null>({ type: 'goHome' }) return invokeNativeMethod<null, null>({ type: 'goHome' })
} }
export interface RequestMerchantTransferParams {
/** 商户号,与发起转账接口 mchid 一致 */
mchId: string;
/** 开放平台移动应用 appid,与发起转账一致 */
appId: string;
/** 发起转账应答中的 package_info(单据为 WAIT_USER_CONFIRM 时返回) */
package: string;
}
export function requestMerchantTransfer (params: RequestMerchantTransferParams) {
return invokeNativeMethod<string, RequestMerchantTransferParams>({ type: 'requestMerchantTransfer', data: params }, -1)
}
export function getDeviceInfo () {
return invokeNativeMethod<{ appVersion: string, buildVersion: string, os: string }>({ type: 'getDeviceInfo' })
}
export interface OpenLinkParams {
title?: string;
/**
* jksxbapp://platformapi/launchMini?appId=xxxx&path=encodeURIComponent(path)&miniProgramType=0
* @example
* jksxbapp://platformapi/launchMini?appId=gh_0066abe06cc6&path=%2FsubPackages%2Freward-day%2Fland-page%2Findex%3Frefer%3Dapp&miniProgramType=2
*/
url: string;
from?: string;
}
export function openLink (params: OpenLinkParams) {
return invokeNativeMethod<null, OpenLinkParams>({ type: 'openLink', data: params })
}
import { mount, flushPromises } from '@vue/test-utils';
import { defineComponent } from 'vue';
import WithdrawList from '../withdraw-list.vue';
import { getWithdrawList } from '@/server/api/bonus';
import { WithdrawStatus } from '@/model/bonus/constant';
import { createStore } from 'vuex';
// Mock PullRefreshList component
const PullRefreshListStub = defineComponent({
template: `
<div class="pull-refresh-list-stub">
<slot :list="mockedList"></slot>
</div>
`,
props: {
request: { type: Function, required: true },
paramsFn: { type: Function, required: true },
},
data() {
return {
mockedList: [] as any[],
};
},
watch: {
request: {
immediate: true,
async handler(this: any, newVal: Function) {
if (newVal) {
try {
const res = await newVal(this.paramsFn());
this.mockedList = res.data.list;
} catch (error) {
console.error('Error fetching withdraw list:', error);
}
}
},
},
},
});
// Mock API
jest.mock('@/server/api/bonus', () => ({
getWithdrawList: jest.fn(),
}));
describe('WithdrawList.vue', () => {
let store: ReturnType<typeof createStore>;
beforeEach(() => {
jest.clearAllMocks();
store = createStore({
state: {
bonus: {
studentId: 'testStudent123',
},
},
});
});
it('renders an empty list initially', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: { list: [], total: 0 },
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
expect(wrapper.findAll('.withdraw-list')).toHaveLength(0);
expect(getWithdrawList).toHaveBeenCalledWith({ studentId: 'testStudent123' });
});
it('renders a list with "提现中" (WITHDRAWING) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 1,
status: WithdrawStatus.WITHDRAWING,
accountName: '张三',
withdrawAmount: 100.00,
withdrawApplyTime: '2024-01-01 10:00:00',
expectedPayTime: '2024-01-02 10:00:00',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现中');
expect(withdrawItem.find('.header-status label').text()).toBe('请耐心等候~');
expect(withdrawItem.find('.apply-money').text()).toBe('¥100.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-shijian');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:张三');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 10:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('预计时间:2024-01-02 10:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').exists()).toBe(false); // No 到账时间
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(5)').exists()).toBe(false); // No 失败时间
});
it('renders a list with "提现成功" (RECEIVED) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 2,
status: WithdrawStatus.RECEIVED,
accountName: '李四',
withdrawAmount: 50.00,
withdrawApplyTime: '2024-01-01 09:00:00',
withdrawPayTime: '2024-01-01 11:00:00',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现成功');
expect(withdrawItem.find('.header-status label').exists()).toBe(false); // No 请耐心等候
expect(withdrawItem.find('.apply-money').text()).toBe('-¥50.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-jindutiaoqiandai');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:李四');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 09:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('到账时间:2024-01-01 11:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').exists()).toBe(false); // No 失败时间
});
it('renders a list with "提现失败" (FAILED) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 3,
status: WithdrawStatus.FAILED,
accountName: '王五',
withdrawAmount: 200.00,
withdrawApplyTime: '2024-01-01 08:00:00',
failTime: '2024-01-01 08:30:00',
reason: '银行卡信息有误',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现失败');
expect(withdrawItem.find('.header-status label').exists()).toBe(false); // No 请耐心等候
expect(withdrawItem.find('.apply-money').text()).toBe('¥200.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-xiazaishibai');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:王五');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 08:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('失败时间:2024-01-01 08:30:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').text()).toBe('失败原因:银行卡信息有误');
});
it('handles API error gracefully', async () => {
(getWithdrawList as jest.Mock).mockRejectedValue(new Error('API error'));
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith('Error fetching withdraw list:', expect.any(Error));
consoleErrorSpy.mockRestore();
});
});
...@@ -62,6 +62,7 @@ ...@@ -62,6 +62,7 @@
.van-button { .van-button {
height: 56px; height: 56px;
width: 160px; width: 160px;
white-space: nowrap; // 禁止文字换行
} }
} }
.withdrawable-money { .withdrawable-money {
...@@ -74,6 +75,7 @@ ...@@ -74,6 +75,7 @@
.van-button { .van-button {
height: 56px; height: 56px;
width: 120px; width: 120px;
white-space: nowrap; // 禁止文字换行
} }
} }
.bonus-record { .bonus-record {
......
...@@ -5,33 +5,14 @@ ...@@ -5,33 +5,14 @@
<div class="header-status"> <div class="header-status">
<i <i
class="iconfont" class="iconfont"
:class=" :class="getStatusIconClass(item.withdrawStatus || item.status)"
item.status === WithdrawStatus.WITHDRAWING :style="{ color: getStatusIconColor(item.withdrawStatus || item.status) }"
? 'icon-shijian'
: item.status === WithdrawStatus.RECEIVED
? 'icon-jindutiaoqiandai'
: 'icon-xiazaishibai'
"
:style="{
color:
item.status === WithdrawStatus.WITHDRAWING
? '#46BB36'
: item.status === WithdrawStatus.RECEIVED
? '#027AFF'
: '#F1551E'
}"
></i> ></i>
<span>{{ <span>{{ getStatusText(item.withdrawStatus || item.status) }}</span>
item.status === WithdrawStatus.WITHDRAWING <label v-if="isProcessingStatus(item.withdrawStatus || item.status)">请耐心等候~</label>
? "提现中"
: item.status === WithdrawStatus.RECEIVED
? "提现成功"
: "提现失败"
}}</span>
<label v-if="item.status === WithdrawStatus.WITHDRAWING">请耐心等候~</label>
</div> </div>
<p class="apply-money"> <p class="apply-money">
{{ item.status === WithdrawStatus.RECEIVED ? "-" : "" }}¥{{ {{ item.status === 'RECEIVED' ? "-" : "" }}¥{{
item.withdrawAmount.toFixed(2) item.withdrawAmount.toFixed(2)
}} }}
</p> </p>
...@@ -39,38 +20,115 @@ ...@@ -39,38 +20,115 @@
<ul class="withdraw-list-detail"> <ul class="withdraw-list-detail">
<li>微信提现:{{ item.accountName }}</li> <li>微信提现:{{ item.accountName }}</li>
<li>申请时间:{{ item.withdrawApplyTime }}</li> <li>申请时间:{{ item.withdrawApplyTime }}</li>
<li v-if="item.status === WithdrawStatus.WITHDRAWING"> <li v-if="isProcessingStatus(item.withdrawStatus || item.status)">
预计时间:{{ item.expectedPayTime }} 预计时间:{{ item.expectedPayTime }}
</li> </li>
<li v-if="item.status === WithdrawStatus.RECEIVED">到账时间:{{ item.withdrawPayTime }}</li> <li v-if="item.status === 'RECEIVED'">到账时间:{{ item.withdrawPayTime }}</li>
<li v-if="item.status === WithdrawStatus.FAILED">失败时间:{{ item.failTime }}</li> <li v-if="item.status === 'FAILED'">失败时间:{{ item.failTime }}</li>
<li v-if="item.status === WithdrawStatus.FAILED">失败原因:{{ item.reason }}</li> <li v-if="item.status === 'FAILED'">失败原因:{{ item.reason }}</li>
</ul> </ul>
<van-button class="action-btn" v-if="needConfirmAction(item.withdrawStatus) && item.withdrawNo" round type="primary" color="#07c160" block @click="handleConfirmReceipt(item)">去确认收款</van-button>
<div class="action-hint" v-if="needConfirmAction(item.withdrawStatus) && !item.withdrawNo">
<span class="hint-text">请在微信中确认收款</span>
</div>
</div> </div>
</pull-refresh-list> </pull-refresh-list>
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent, computed } from 'vue' import { defineComponent, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex' import { useStore } from 'vuex'
import { Button } from 'vant'
import { getWithdrawList } from '@/server/api/bonus' import { getWithdrawList } from '@/server/api/bonus'
import { WithdrawStatus } from '@/model/bonus/constant'
import PullRefreshList from './components/pull-pefresh-list.vue' import PullRefreshList from './components/pull-pefresh-list.vue'
export default defineComponent({ export default defineComponent({
components: { components: {
PullRefreshList PullRefreshList,
[Button.name]: Button
}, },
setup () { setup () {
const store = useStore() const store = useStore()
const router = useRouter()
const bonusStoreState = computed(() => store.state.bonus) const bonusStoreState = computed(() => store.state.bonus)
const paramsFn = () => ({ const paramsFn = () => ({
studentId: bonusStoreState.value.studentId studentId: bonusStoreState.value.studentId
}) })
return { WithdrawStatus, getWithdrawList, paramsFn } // 处理中的状态
const processingStatuses = ['APPROVING', 'TRANSFERING', 'WITHDRAWING', 'WAIT_CONFIRM']
const isProcessingStatus = (status: string) => processingStatuses.includes(status)
// 判断是否需要显示"去确认收款"按钮
const needConfirmAction = (withdrawStatus: string) => {
return withdrawStatus === 'WAIT_CONFIRM' || withdrawStatus === 'APPROVING'
}
// 获取状态图标类名
const getStatusIconClass = (status: string) => {
const classMap: Record<string, string> = {
APPROVING: 'icon-shijian',
TRANSFERING: 'icon-shijian',
WITHDRAWING: 'icon-shijian',
WAIT_CONFIRM: 'icon-shijian',
RECEIVED: 'icon-jindutiaoqiandai',
FAILED: 'icon-xiazaishibai'
}
return classMap[status] || 'icon-shijian'
}
// 获取状态图标颜色
const getStatusIconColor = (status: string) => {
const colorMap: Record<string, string> = {
APPROVING: '#46BB36',
TRANSFERING: '#46BB36',
WITHDRAWING: '#46BB36',
WAIT_CONFIRM: '#46BB36',
RECEIVED: '#027AFF',
FAILED: '#F1551E'
}
return colorMap[status] || '#46BB36'
}
// 获取状态文本
const getStatusText = (status: string) => {
const textMap: Record<string, string> = {
APPROVING: '提现中',
TRANSFERING: '提现中',
WITHDRAWING: '提现中',
WAIT_CONFIRM: '提现中',
RECEIVED: '提现成功',
FAILED: '提现失败'
}
return textMap[status] || '处理中'
}
// 去确认收款
const handleConfirmReceipt = (item: any) => {
router.push({
path: '/withdraw/confirm-receipt',
query: {
withdrawNo: item.withdrawNo,
amount: item.withdrawAmount?.toFixed(2) || '0.00',
withdrawAccount: encodeURIComponent(item.accountName || '')
}
})
}
return {
getWithdrawList,
paramsFn,
isProcessingStatus,
needConfirmAction,
getStatusIconClass,
getStatusIconColor,
getStatusText,
handleConfirmReceipt
}
} }
}) })
</script> </script>
...@@ -119,5 +177,18 @@ export default defineComponent({ ...@@ -119,5 +177,18 @@ export default defineComponent({
line-height: 1.6em; line-height: 1.6em;
} }
} }
.action-btn {
margin-top: 20px;
height: 44px;
font-size: 16px;
}
.action-hint {
margin-top: 40rpx;
text-align: center;
.hint-text {
color: #fa8c16;
font-size: 28rpx;
}
}
} }
</style> </style>
...@@ -53,17 +53,12 @@ ...@@ -53,17 +53,12 @@
:withdraw-account="withdrawAccount" :withdraw-account="withdrawAccount"
@withdraw-success="withdrawSuccess" @withdraw-success="withdrawSuccess"
/> />
<!-- 提现成功弹窗 -->
<WithdrawSuccessDialog
v-model:show="showWithdrawSuccess"
:withdraw-response="withdrawResponse"
/>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
import { computed, defineComponent, onMounted, reactive, toRefs } from 'vue' import { computed, defineComponent, onMounted, reactive, toRefs } from 'vue'
import { useRoute } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex' import { useStore } from 'vuex'
import { Button, Cell, Dialog, Field, Toast } from 'vant' import { Button, Cell, Dialog, Field, Toast } from 'vant'
...@@ -71,7 +66,6 @@ import { Button, Cell, Dialog, Field, Toast } from 'vant' ...@@ -71,7 +66,6 @@ import { Button, Cell, Dialog, Field, Toast } from 'vant'
import { sendNativeMessage } from '@/util/use-native-bridge' import { sendNativeMessage } from '@/util/use-native-bridge'
import { getWithdrawRisk } from '@/server/api/bonus' import { getWithdrawRisk } from '@/server/api/bonus'
import { WithdrawResponse } from '@/model/bonus' import { WithdrawResponse } from '@/model/bonus'
import WithdrawSuccessDialog from './withdraw-success-dialog.vue'
import WithdrawDialog from './withdraw-dialog.vue' import WithdrawDialog from './withdraw-dialog.vue'
interface State { interface State {
...@@ -86,11 +80,11 @@ const Withdraw = defineComponent({ ...@@ -86,11 +80,11 @@ const Withdraw = defineComponent({
[Cell.name]: Cell, [Cell.name]: Cell,
[Field.name]: Field, [Field.name]: Field,
[Dialog.Component.name]: Dialog.Component, [Dialog.Component.name]: Dialog.Component,
WithdrawSuccessDialog,
WithdrawDialog WithdrawDialog
}, },
setup () { setup () {
const route = useRoute() const route = useRoute()
const router = useRouter()
const store = useStore() const store = useStore()
const bonusStoreState = computed(() => store.state.bonus) const bonusStoreState = computed(() => store.state.bonus)
...@@ -99,7 +93,6 @@ const Withdraw = defineComponent({ ...@@ -99,7 +93,6 @@ const Withdraw = defineComponent({
withdrawableTotal: 0, withdrawableTotal: 0,
maxWithDraw: 0, maxWithDraw: 0,
showWithdraw: false, showWithdraw: false,
showWithdrawSuccess: false,
withdrawAccount: '', withdrawAccount: '',
withdrawAccountId: '', withdrawAccountId: '',
withdrawResponse: {}, withdrawResponse: {},
...@@ -134,9 +127,34 @@ const Withdraw = defineComponent({ ...@@ -134,9 +127,34 @@ const Withdraw = defineComponent({
} }
// 提现成功 // 提现成功
const withdrawSuccess = (data: any) => { const withdrawSuccess = (data: WithdrawResponse) => {
state.withdrawResponse = data state.withdrawResponse = data
state.showWithdrawSuccess = true
// 新版流程:根据是否有 packageInfo 决定跳转
if (data.packageInfo) {
// 跳转到确认收款页
router.replace({
path: '/withdraw/confirm-receipt',
query: {
withdrawNo: data.withdrawNo || data.serialNo,
amount: data.amount.toFixed(2),
withdrawAccount: encodeURIComponent(data.withdrawAccount),
packageInfo: encodeURIComponent(data.packageInfo),
mchId: data.mchId || '',
appId: data.appId || ''
}
})
} else {
// 无需确认,直接跳转到处理状态页
router.replace({
path: '/withdraw/processing-status',
query: {
status: 'TRANSFERING',
withdrawNo: data.withdrawNo || data.serialNo,
amount: data.amount.toFixed(2)
}
})
}
} }
// 获取风控值 // 获取风控值
......
...@@ -169,7 +169,15 @@ export default defineComponent({ ...@@ -169,7 +169,15 @@ export default defineComponent({
} }
const data = await withdraw(params) const data = await withdraw(params)
context.emit('update:show', false) context.emit('update:show', false)
context.emit('withdrawSuccess', data)
// 新版流程:判断是否有 packageInfo
if (data.packageInfo) {
// 跳转到确认收款页
context.emit('withdrawSuccess', data)
} else {
// 无需确认,直接跳转到处理状态页
context.emit('withdrawSuccess', data)
}
} catch (err: any) { } catch (err: any) {
Toast(err) Toast(err)
} finally { } finally {
......
<template>
<div class="confirm-page">
<!-- 加载中 -->
<div class="loading" v-if="loading">
<span>加载中...</span>
</div>
<template v-else>
<div class="confirm-icon">💰</div>
<div class="confirm-title">提现申请已提交</div>
<div class="confirm-amount">¥{{ amount }}</div>
<div class="confirm-card">
<p>请在微信中确认收款</p>
<p>转账金额将在您确认后实时到账微信零钱</p>
<p class="to-account" v-if="withdrawAccount">提现至:{{ withdrawAccount }}</p>
<p class="timeout-hint">⏰ 请在24小时内确认,超时将自动退回</p>
</div>
<button class="btn-confirm" @click="handleConfirm">👆 确认收款</button>
<button class="btn-back" @click="handleBack">返回奖励金首页</button>
<div class="confirm-faq">
<span class="faq-icon">?</span>
<span>点击后没反应?请更新微信至最新版本</span>
</div>
</template>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { Toast, Dialog } from 'vant'
import versionCompare from 'version-compare'
import { getWithdrawPackageInfo } from '@/server/api/withdrawService'
import { requestMerchantTransfer, getDeviceInfo, openLink } from '@/util/use-native-bridge'
const MIN_APP_VERSION = '5.0.0'
const MINI_PROGRAM_APP_ID = 'gh_160e85b41006'
const MINI_PROGRAM_PATH = '/pages/main/main'
export default defineComponent({
name: 'ConfirmReceipt',
data () {
return {
amount: '0.00',
withdrawNo: '',
withdrawAccount: '',
packageInfo: '',
mchId: '',
appId: '',
loading: true
}
},
async created () {
const query = this.$route.query
this.amount = (query.amount as string) || '0.00'
this.withdrawNo = (query.withdrawNo as string) || ''
this.withdrawAccount = query.withdrawAccount ? decodeURIComponent(query.withdrawAccount as string) : ''
if (query.packageInfo) {
// 场景1:从提现表单页进入,已有 packageInfo
this.packageInfo = decodeURIComponent(query.packageInfo as string)
this.mchId = (query.mchId as string) || ''
this.appId = (query.appId as string) || ''
this.loading = false
} else if (this.withdrawNo) {
// 场景2:从列表页进入,需要查询 packageInfo
await this.fetchPackageInfo()
} else {
this.loading = false
}
},
methods: {
async fetchPackageInfo () {
try {
console.log('fetchPackageInfo called, withdrawNo:', this.withdrawNo)
const res = await getWithdrawPackageInfo(this.withdrawNo)
console.log('packageInfo response:', JSON.stringify(res))
if (res) {
this.packageInfo = res.packageInfo || ''
this.mchId = res.mchId || ''
this.appId = res.appId || ''
console.log('packageInfo:', this.packageInfo, 'mchId:', this.mchId, 'appId:', this.appId)
} else {
console.log('no data in response')
Toast.fail('获取提现信息失败')
}
} catch (error) {
console.error('fetchPackageInfo error:', error)
Toast.fail('网络请求失败')
} finally {
this.loading = false
}
},
async handleConfirm () {
if (!this.packageInfo || !this.mchId || !this.appId) {
console.error('Missing params:', { packageInfo: this.packageInfo, mchId: this.mchId, appId: this.appId })
Toast.fail('缺少必要参数,无法确认收款')
return
}
try {
const { appVersion } = await getDeviceInfo()
if (versionCompare(appVersion, MIN_APP_VERSION) < 0) {
Dialog.confirm({
message: 'App版本过低,请升级APP或前往小程序确认收款',
confirmButtonText: '前往小程序'
})
.then(() => {
const url = `jksxbapp://platformapi/launchMini?appId=${MINI_PROGRAM_APP_ID}&path=${encodeURIComponent(MINI_PROGRAM_PATH)}&miniProgramType=0`
openLink({ url })
})
.catch(() => undefined)
return
}
} catch (error) {
Toast.fail('请在APP内确认收款')
console.warn('getDeviceInfo failed, continue with native transfer', error)
}
try {
// 调用原生方法唤起微信确认收款
const result = await requestMerchantTransfer({
mchId: this.mchId,
appId: this.appId,
package: this.packageInfo
})
console.log('requestMerchantTransfer result:', result)
// 成功:跳转到处理状态页面
this.$router.replace({
path: '/withdraw/processing-status',
query: {
status: 'TRANSFERING',
withdrawNo: this.withdrawNo,
amount: this.amount
}
})
} catch (error: any) {
console.error('requestMerchantTransfer error:', error)
// 用户取消
if (error.message === 'cancel') {
Toast('用户取消')
} else {
Toast.fail('操作失败')
}
}
},
handleBack () {
this.$router.back()
}
}
})
</script>
<style scoped>
.confirm-page {
display: flex;
flex-direction: column;
align-items: center;
padding: 12vw 4vw;
text-align: center;
background: #ffffff;
min-height: 100vh;
box-sizing: border-box;
}
.loading {
display: flex;
align-items: center;
justify-content: center;
min-height: 50vh;
color: #999;
font-size: 4vw;
}
.confirm-icon {
font-size: 10vw;
margin-bottom: 4vw;
}
.confirm-title {
font-size: 5vw;
font-weight: 600;
color: #212121;
margin-bottom: 1vw;
}
.confirm-amount {
font-size: 9vw;
font-weight: 700;
color: #212121;
margin-bottom: 8vw;
letter-spacing: -0.02em;
}
.confirm-card {
width: 100%;
background: #f5f5f5;
border-radius: 3vw;
padding: 4vw;
margin-bottom: 4vw;
box-sizing: border-box;
text-align: left;
}
.confirm-card p {
font-size: 3.5vw;
color: #616161;
line-height: 1.8;
margin: 0;
}
.confirm-card .to-account {
font-size: 3.2vw;
color: #9e9e9e;
margin-top: 2vw;
}
.confirm-card .timeout-hint {
color: #fa8c16;
font-weight: 500;
margin-top: 2vw;
}
.btn-confirm {
width: 100%;
padding: 4.5vw;
background: linear-gradient(135deg, #07c160 0%, #38cd7f 100%);
color: white;
border: none;
border-radius: 3vw;
font-size: 4vw;
font-weight: 600;
margin-bottom: 3vw;
box-sizing: border-box;
cursor: pointer;
}
.btn-back {
width: 100%;
padding: 3.5vw;
background: #f5f5f5;
color: #757575;
border: none;
border-radius: 3vw;
font-size: 3.5vw;
font-weight: 500;
box-sizing: border-box;
cursor: pointer;
}
.confirm-faq {
width: 100%;
text-align: left;
margin-top: 4vw;
font-size: 3vw;
color: #9e9e9e;
display: flex;
align-items: center;
gap: 1vw;
}
.confirm-faq .faq-icon {
width: 4vw;
height: 4vw;
background: #fa8c16;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 2.5vw;
font-weight: bold;
}
</style>
<template>
<div class="processing-page">
<!-- Spinner -->
<div class="spinner" v-if="!isFinalStatus"></div>
<!-- 标题 -->
<div class="processing-title">
{{ getTitleText }}
</div>
<!-- 金额 -->
<div class="processing-amount">¥{{ amount }}</div>
<!-- 卡片 -->
<div class="processing-card">
<template v-if="isFinalStatus">
<template v-if="status === 'RECEIVED'">
<p>提现金额已到账微信零钱</p>
<p class="to-account">感谢您的使用</p>
</template>
<template v-else>
<p class="fail-text">{{ failReason || '提现失败' }}</p>
<p class="to-account">奖励金已退回账户余额</p>
</template>
</template>
<template v-else>
<p>您已确认收款</p>
<p>资金正在转入微信零钱,请稍候...</p>
<div class="progress-bar">
<div class="progress-fill"></div>
</div>
</template>
</div>
<!-- 提示 -->
<div class="processing-hint" v-if="!isFinalStatus">
自动查询状态中,请勿关闭
</div>
<!-- 按钮 -->
<button class="btn-back" @click="handleBackHome">返回首页</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { queryWithdrawStatus } from '@/server/api/withdrawService'
export default defineComponent({
name: 'ProcessingStatus',
data () {
return {
status: 'TRANSFERING',
withdrawNo: '',
amount: '0.00',
failReason: '',
packageInfo: '',
mchId: '',
pollingInterval: null as ReturnType<typeof setInterval> | null,
pollingCount: 0,
maxPollingAttempts: 10
}
},
computed: {
isFinalStatus (): boolean {
return ['RECEIVED', 'FAILED', 'CANCELLED'].includes(this.status)
},
getTitleText (): string {
if (this.isFinalStatus) {
return this.status === 'RECEIVED' ? '提现成功' : '提现失败'
}
return '提现处理中'
}
},
created () {
const query = this.$route.query
this.withdrawNo = (query.withdrawNo as string) || ''
this.amount = (query.amount as string) || '0.00'
this.status = (query.status as string) || 'TRANSFERING'
this.packageInfo = query.packageInfo ? decodeURIComponent(query.packageInfo as string) : ''
this.mchId = (query.mchId as string) || ''
},
mounted () {
this.startPolling()
},
beforeUnmount () {
this.stopPolling()
},
methods: {
startPolling () {
this.stopPolling()
this.pollingInterval = setInterval(async () => {
this.pollingCount++
if (this.pollingCount > this.maxPollingAttempts) {
this.stopPolling()
console.warn('Max polling attempts reached.')
return
}
await this.queryWithdrawStatus()
}, 5000)
},
stopPolling () {
if (this.pollingInterval) {
clearInterval(this.pollingInterval)
this.pollingInterval = null
}
},
async queryWithdrawStatus () {
if (!this.withdrawNo) {
console.error('No withdrawNo available.')
this.stopPolling()
return
}
console.log('Polling status for withdrawNo:', this.withdrawNo, 'attempt:', this.pollingCount)
try {
const res = await queryWithdrawStatus(this.withdrawNo)
if (res && res.withdrawStatus) {
const newStatus = res.withdrawStatus
this.status = newStatus
if (res.amount) {
this.amount = res.amount
}
if (res.failReason) {
this.failReason = res.failReason
}
if (['RECEIVED', 'FAILED', 'CANCELLED'].includes(newStatus)) {
this.stopPolling()
}
}
} catch (error) {
console.error('Error querying status:', error)
}
},
handleBackHome () {
this.$router.back()
}
}
})
</script>
<style scoped>
/* P3b 处理中页样式 - 基于 features/withdraw/prd/frontend-design/index.html */
.processing-page {
display: flex;
flex-direction: column;
align-items: center;
padding: 12vw 4vw;
text-align: center;
background: #ffffff;
min-height: 100vh;
box-sizing: border-box;
}
.spinner {
width: 14vw;
height: 14vw;
border: 1vw solid #eeeeee;
border-top-color: #07c160;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 6vw;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.processing-title {
font-size: 5vw;
font-weight: 600;
color: #212121;
margin-bottom: 1vw;
}
.processing-amount {
font-size: 9vw;
font-weight: 700;
color: #212121;
margin-bottom: 8vw;
letter-spacing: -0.02em;
}
.processing-card {
width: 100%;
background: #fafafa;
border-radius: 3vw;
padding: 6vw;
margin-bottom: 6vw;
box-sizing: border-box;
}
.processing-card p {
font-size: 3.5vw;
color: #616161;
line-height: 1.8;
margin: 0;
}
.processing-card .to-account {
font-size: 3.2vw;
color: #9e9e9e;
margin-top: 2vw;
}
.processing-card .fail-text {
color: #ff4d4f;
font-weight: 500;
}
.progress-bar {
height: 1.5vw;
background: #eeeeee;
border-radius: 9999px;
margin-top: 4vw;
overflow: hidden;
}
.progress-fill {
height: 100%;
width: 30%;
background: linear-gradient(90deg, #07c160, #38cd7f);
border-radius: 9999px;
animation: progress 2s ease-in-out infinite;
}
@keyframes progress {
0% { transform: translateX(0); width: 30%; }
50% { width: 70%; }
100% { transform: translateX(200%); width: 30%; }
}
.processing-hint {
font-size: 3vw;
color: #9e9e9e;
margin-bottom: 6vw;
display: flex;
align-items: center;
justify-content: center;
gap: 1vw;
}
.processing-hint::before {
content: '';
width: 1.5vw;
height: 1.5vw;
background: #07c160;
border-radius: 50%;
animation: pulse 1s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(1.2); }
}
.btn-back {
width: 100%;
padding: 3.5vw;
background: #f5f5f5;
color: #757575;
border: none;
border-radius: 3vw;
font-size: 3.5vw;
font-weight: 500;
box-sizing: border-box;
cursor: pointer;
}
</style>
import { mount } from '@vue/test-utils';
import ConfirmReceipt from '../ConfirmReceipt.vue';
// Mock vue-router
const mockRouter = {
replace: jest.fn(),
};
const mockRoute = {
query: {
amount: '100.00',
withdrawNo: 'WD123456',
withdrawAccount: encodeURIComponent('微信用户'),
packageInfo: encodeURIComponent('test_package'),
mchId: 'test_mch_id',
},
};
describe('ConfirmReceipt.vue', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('renders correctly with initial data from route query', () => {
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
expect(wrapper.find('.confirm-amount').text()).toBe('¥100.00');
expect(wrapper.find('.confirm-title').text()).toBe('提现申请已提交');
});
it('shows alert and navigates to processing-status on confirm click', () => {
const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.btn-confirm').trigger('click');
expect(alertSpy).toHaveBeenCalled();
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/processing-status',
query: {
status: 'WAIT_CONFIRM',
withdrawNo: 'WD123456',
amount: '100.00',
},
});
alertSpy.mockRestore();
});
it('navigates back on back button click', () => {
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.btn-back').trigger('click');
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/bonus/withdraw',
});
});
});
import { mount, flushPromises } from '@vue/test-utils';
import ProcessingStatus from '../ProcessingStatus.vue';
import { queryWithdrawStatus } from '@/server/api/withdrawService';
// Mock vue-router
const mockRouter = {
replace: jest.fn(),
};
const mockRoute = {
query: {
withdrawNo: 'WD123456',
amount: '100.00',
status: 'TRANSFERING',
},
};
jest.mock('@/server/api/withdrawService');
describe('ProcessingStatus.vue', () => {
let setIntervalSpy: jest.SpyInstance;
let clearIntervalSpy: jest.SpyInstance;
beforeEach(() => {
jest.clearAllMocks();
setIntervalSpy = jest.spyOn(window, 'setInterval').mockReturnValue(123 as any);
clearIntervalSpy = jest.spyOn(window, 'clearInterval');
});
afterEach(() => {
setIntervalSpy.mockRestore();
clearIntervalSpy.mockRestore();
});
it('renders correctly with initial data', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
expect(wrapper.find('.processing-title').text()).toBe('提现处理中');
expect(wrapper.find('.processing-amount').text()).toBe('¥100.00');
expect(wrapper.find('.spinner').exists()).toBe(true);
});
it('shows success state without spinner', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { withdrawNo: 'WD123456', amount: '100.00', status: 'RECEIVED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.processing-title').text()).toBe('提现成功');
expect(wrapper.find('.spinner').exists()).toBe(false);
});
it('shows failed state without spinner', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { withdrawNo: 'WD123456', amount: '100.00', status: 'FAILED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.processing-title').text()).toBe('提现失败');
expect(wrapper.find('.spinner').exists()).toBe(false);
});
it('starts polling on mount', () => {
mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
expect(setIntervalSpy).toHaveBeenCalledTimes(1);
});
it('stops polling on unmount', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.unmount();
expect(clearIntervalSpy).toHaveBeenCalled();
});
it('updates status on API response', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { withdrawStatus: 'RECEIVED', amount: '100.00' },
});
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
await (wrapper.vm as any).queryWithdrawStatus();
await flushPromises();
expect(wrapper.vm.status).toBe('RECEIVED');
});
it('navigates back to withdraw page on button click', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.btn-back').trigger('click');
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/bonus/withdraw',
});
});
});
...@@ -13,7 +13,8 @@ ...@@ -13,7 +13,8 @@
"sourceMap": true, "sourceMap": true,
"baseUrl": ".", "baseUrl": ".",
"types": [ "types": [
"webpack-env" "webpack-env",
"jest"
], ],
"paths": { "paths": {
"@/*": [ "@/*": [
......
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment